Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Reconnect connectors on their own when the connection drops (#114)
Dias3472c134e938
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a45337c..e22863a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht- **A thread opens at its latest message,** like in Slack, instead of at the message that started it: a long thread no longer has to be scrolled all the way down to see where it is. Scrolling up still stays put when a reply comes in.- **Claude replies finish about 2 seconds sooner, at times 10.** After each reply Claude Code made one more model call, a summary of the turn that Tucano never reads, and only then said it was done and exited. That call is now off for the Claude Code that Tucano runs, so a reply ends when its text does, and what waits on it (the next agent in line, a team's report) starts right away. Your own Claude Code in the terminal isn't touched.- **Agents see what a connector returns, even when it's long.** A result over Claude Code's own cut (about 50 KB, like the comments of a big merge request) was saved to a file the agent can't read, so it called again and again and answered without the data. Tucano now cuts a result at 40 KB, counted in bytes so accents don't push it over, and tells the agent to ask again with pagination or a filter if it needs the rest.+- **Connectors stay connected.** A local connector whose process ended (a crash, or one that quits when idle) stayed **Disconnected** for good, and its tools went away from the agents, so nothing ever brought it back; and a remote one whose server forgot an idle session failed every call while still showing **Connected**. Now a connection that drops on its own comes back by itself, after a wait that grows from 2 seconds to 5 minutes, and a call on a forgotten session opens a new one and goes through. A connector that's only reconnecting keeps its tools; one that needs you (a refused token, a sign-in to finish) doesn't, and isn't retried.## [0.2.10] - 2026-11-04diff --git a/src/core/connectors.ts b/src/core/connectors.tsindex 6bbfd16..e198bee 100644--- a/src/core/connectors.ts+++ b/src/core/connectors.ts@@ -21,6 +21,9 @@ const CALL_TIMEOUT_MS = 120_000// A server that doesn't answer the handshake shows an error instead of "conectando…" for a minute.const CONNECT_TIMEOUT_MS = 20_000const MAX_STDIO_FAILURES = 3+// A connection that dropped on its own (the server's process ended, the network went), or an attempt that+// failed for a passing reason, is tried again after these waits; then it waits for a call or the button.+const RECONNECT_DELAYS_MS = [2_000, 5_000, 15_000, 60_000, 300_000]// The authorization page sent the browser back without a code: why, and what to do.export function notAuthorized(url: URL): string {@@ -55,8 +58,17 @@ interface Live {error?: stringfailures: numberconnecting?: Promise<void>+ retry?: NodeJS.Timeout // the next try after a drop+ retries?: number // tries since it last worked+ passing?: boolean // the last attempt failed for a reason that may go away by itself (network, timeout)}+// The call never ran, so it can go again on a new connection: the server forgot this session (it expired+// while idle), or the client had no connection to send it on. Not "Connection closed": the SDK gives that to+// every call already sent when the connection drops, which the server may have run (a write would go twice).+export const staleSession = (e: unknown): boolean =>+ (e instanceof StreamableHTTPError && e.code === 404) || (e instanceof Error && /session not found|no valid session|invalid session id|^not connected$/i.test(e.message))+const key = (id: string, what: string): string => `connector:${id}:${what}`export class ConnectorManager {@@ -64,6 +76,7 @@ export class ConnectorManager {private oauthStates = new Map<string, { connectorId: string; transport: StreamableHTTPClientTransport }>()private authUrls = new Map<string, string>() // a connector's last authorization pageprivate doneStates = new Set<string>() // finished already (the callback got there first): not an expired one+ private closing = false // the app is quitting: nothing reconnectsconstructor(private deps: ConnectorDeps) {}@@ -127,6 +140,7 @@ export class ConnectorManager {}async remove(id: string): Promise<void> {+ clearTimeout(this.live.get(id)?.retry)await this.disconnect(id)this.live.delete(id)this.deps.db.removeConnector(id)@@ -143,6 +157,8 @@ export class ConnectorManager {}async closeAll(): Promise<void> {+ this.closing = true+ for (const l of this.live.values()) clearTimeout(l.retry)await Promise.all([...this.live.keys()].map((id) => this.disconnect(id)))}@@ -228,8 +244,12 @@ export class ConnectorManager {} else if (e instanceof Error && /timed out/i.test(e.message)) {await client.close().catch(() => {})this.setStatus(id, 'error', L(`O servidor não respondeu em ${CONNECT_TIMEOUT_MS / 1000} s. Confira o endereço e a sua rede.`, `The server didn't answer in ${CONNECT_TIMEOUT_MS / 1000} s. Check the address and your network.`))+ this.live.get(id)!.passing = true+ this.reconnectLater(id)} else {this.setStatus(id, 'error', connectError(e))+ this.live.get(id)!.passing = true+ this.reconnectLater(id)}return}@@ -237,10 +257,14 @@ export class ConnectorManager {l.client = clientl.transport = transportl.failures = 0+ l.retries = 0+ l.passing = false+ // Closed by us (disconnect clears the client first) it stays closed; closed on its own, it comes back.transport.onclose = () => {if (this.live.get(id)?.client === client) {l.client = undefinedthis.setStatus(id, 'disconnected')+ this.reconnectLater(id)}}try {@@ -251,6 +275,25 @@ export class ConnectorManager {}}+ // Connects again after a wait that grows with each try, while the connector exists and nothing else has+ // brought it back. A failure that won't pass by itself (a refused token, a sign-in to finish) stops it.+ private reconnectLater(id: string): void {+ const l = this.live.get(id)+ if (!l || l.retry || this.closing) return+ const attempt = l.retries ?? 0+ if (attempt >= RECONNECT_DELAYS_MS.length) return+ l.retry = setTimeout(() => {+ l.retry = undefined+ if (this.closing || !this.deps.db.connector(id) || this.live.get(id)?.client) return+ l.retries = attempt + 1+ void this.connect(id).then(() => {+ const now = this.live.get(id)+ if (now && !now.client && (now.status === 'disconnected' || now.passing)) this.reconnectLater(id)+ })+ }, RECONNECT_DELAYS_MS[attempt])+ l.retry.unref?.()+ }+private async refreshTools(id: string): Promise<void> {const client = this.live.get(id)?.clientif (!client) return@@ -281,6 +324,11 @@ export class ConnectorManager {l.failures = 0return r} catch (e) {+ if (staleSession(e)) {+ await this.connect(id)+ const again = this.live.get(id)?.client+ if (again) return (await again.callTool({ name, arguments: args }, undefined, { timeout: CALL_TIMEOUT_MS })) as CallToolResult+ }const c = this.deps.db.connector(id)if (c?.kind === 'stdio' && ++l.failures >= MAX_STDIO_FAILURES) this.setStatus(id, 'error', L(`Falhou ${l.failures} vezes seguidas.`, `Failed ${l.failures} times in a row.`))throw ediff --git a/src/core/runs.ts b/src/core/runs.tsindex d2e4c62..b362f77 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -639,7 +639,9 @@ export class Runner {const exposed = new Map<string, Exposed>()const taken = new Set<string>([ASK_USER.name, ACCESS_REQUEST, ABRIR_PR, LEMBRAR.name, BUSCAR_THREADS.name, LER_THREAD.name, ...COMPUTER_TOOL_NAMES, ...BROWSER_TOOL_NAMES, ...APP_TOOL_NAMES, ...ROUTINE_TOOL_NAMES, ...SKILL_TOOL_NAMES])for (const c of this.deps.connectors?.list() ?? []) {- if (c.status !== 'connected') continue+ // Dropped for a moment, its tools stay: the next call connects again. An error that needs the person+ // (a refused token, a sign-in to finish) takes them away.+ if (c.status !== 'connected' && c.status !== 'disconnected' && c.status !== 'connecting') continuefor (const t of db.tools(c.id)) if (allowed(t, agent.grants[c.id])) exposed.set(exposedName(c, t.name, taken), { connector: c, tool: t })}// pedir_acesso: the connectors this agent could get more of; I decide, like any approval.@@ -1185,7 +1187,7 @@ export class Runner {hasComputer: !!computers,browser: !!browser,apps: apps ? agent.apps : undefined,- offline: (this.deps.connectors?.list() ?? []).filter((c) => c.status !== 'connected' && (agent.grants[c.id] ?? 'none') !== 'none').map((c) => c.name),+ offline: (this.deps.connectors?.list() ?? []).filter((c) => (c.status === 'error' || c.status === 'needs_auth') && (agent.grants[c.id] ?? 'none') !== 'none').map((c) => c.name),macFolder: computers?.mac && agent.computerKind === 'mac' ? computers.mac.cwd(agent) : undefined,web: agent.web !== false,routines: routines?.forAgent(agent.id),diff --git a/test/connector-reconnect.test.ts b/test/connector-reconnect.test.tsnew file mode 100644index 0000000..8c16ca0--- /dev/null+++ b/test/connector-reconnect.test.ts@@ -0,0 +1,124 @@+import { randomUUID } from 'node:crypto'+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import { mkdtempSync, writeFileSync } from 'node:fs'+import type { AddressInfo } from 'node:net'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { Server as McpServer } from '@modelcontextprotocol/sdk/server/index.js'+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'+import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'+import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js'+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'+import { ConnectorManager, staleSession } from '../src/core/connectors'+import { Db } from '../src/core/db'+import { plainCipher, Secrets } from '../src/core/secrets'++const sdk = pathToFileURL(resolve('node_modules/@modelcontextprotocol/sdk/dist/esm')).href+const tools = [{ name: 'ping', description: 'Responde pong.', inputSchema: { type: 'object' as const, properties: {} } }, { name: 'sair', description: 'Encerra o servidor.', inputSchema: { type: 'object' as const, properties: {} } }]++let db: Db+let connectors: ConnectorManager++const until = async (ok: () => boolean, ms = 8000): Promise<void> => {+ for (let i = 0; i < ms / 20 && !ok(); i++) await new Promise((r) => setTimeout(r, 20))+ expect(ok()).toBe(true)+}+const status = (id: string): string | undefined => connectors.get(id)?.status+const text = (r: { content: { type: string; text?: string }[] }): string => r.content.map((c) => c.text ?? '').join('')++beforeEach(() => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'tucano-reconnect-')), 'test.db'))+ connectors = new ConnectorManager({ db, secrets: new Secrets(db, plainCipher), emit: () => {}, openUrl: () => {}, oauthCallbackUrl: () => 'http://127.0.0.1:1/oauth/callback' })+})+afterEach(async () => {+ await connectors.closeAll()+ db.close()+})++describe('a local (stdio) connector whose process ends', () => {+ it('comes back by itself, and its tools work again', async () => {+ // A server that answers "ping" and ends its own process on "sair", like one that crashes or quits when idle.+ const script = join(mkdtempSync(join(tmpdir(), 'tucano-stdio-')), 'server.mjs')+ writeFileSync(+ script,+ `const { Server } = await import('${sdk}/server/index.js')+const { StdioServerTransport } = await import('${sdk}/server/stdio.js')+const { ListToolsRequestSchema, CallToolRequestSchema } = await import('${sdk}/types.js')+const s = new Server({ name: 't', version: '1' }, { capabilities: { tools: {} } })+s.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ${JSON.stringify(tools)} }))+s.setRequestHandler(CallToolRequestSchema, async (r) => {+ if (r.params.name === 'sair') setTimeout(() => process.exit(0), 50)+ return { content: [{ type: 'text', text: r.params.name === 'ping' ? 'pong' : 'tchau' }] }+})+await s.connect(new StdioServerTransport())`+ )+ const id = await connectors.add({ name: 'Local', kind: 'stdio', command: process.execPath, args: [script] })+ await until(() => status(id) === 'connected')++ await connectors.call(id, 'sair', {})+ await until(() => status(id) === 'disconnected')+ await until(() => status(id) === 'connected') // about 2 s later, on its own+ expect(text((await connectors.call(id, 'ping', {})) as never)).toBe('pong')+ }, 20_000)+})++describe('a remote connector whose server forgets the session', () => {+ let server: Server+ let url: string+ const sessions = new Map<string, StreamableHTTPServerTransport>()++ beforeEach(async () => {+ sessions.clear()+ server = createServer((req: IncomingMessage, res: ServerResponse) => {+ void (async () => {+ const sid = req.headers['mcp-session-id'] as string | undefined+ let transport = sid ? sessions.get(sid) : undefined+ if (sid && !transport) {+ res.writeHead(404, { 'content-type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32001, message: 'Session not found' }, id: null }))+ return+ }+ if (!transport) {+ const t = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), enableJsonResponse: true, onsessioninitialized: (s) => void sessions.set(s, t) })+ const mcp = new McpServer({ name: 'r', version: '1' }, { capabilities: { tools: {} } })+ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }))+ mcp.setRequestHandler(CallToolRequestSchema, async () => ({ content: [{ type: 'text', text: 'pong' }] }))+ await mcp.connect(t)+ transport = t+ }+ await transport.handleRequest(req, res)+ })()+ })+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))+ url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`+ })+ afterEach(async () => {+ server.closeAllConnections()+ await new Promise((r) => server.close(r))+ })++ it('a call after the session expired opens a new one and goes through', async () => {+ const id = await connectors.add({ name: 'Remoto', kind: 'remote', url, auth: 'none' })+ await until(() => status(id) === 'connected')+ expect(text((await connectors.call(id, 'ping', {})) as never)).toBe('pong')++ sessions.clear() // idle too long: the server forgot it+ expect(text((await connectors.call(id, 'ping', {})) as never)).toBe('pong')+ expect(status(id)).toBe('connected')+ expect(sessions.size).toBe(1) // a new session, once+ })+})++describe('which failed calls go again on a new connection', () => {+ it("only those that never ran: a forgotten session, or no connection to send them on", () => {+ expect(staleSession(new StreamableHTTPError(404, 'Session not found'))).toBe(true)+ expect(staleSession(new Error('Bad Request: No valid session ID provided'))).toBe(true)+ expect(staleSession(new Error('Not connected'))).toBe(true)+ })++ it('not a call cut by a dropped connection: the server may have run it, and a write would go twice', () => {+ expect(staleSession(McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'))).toBe(false)+ expect(staleSession(new StreamableHTTPError(500, 'Internal error'))).toBe(false)+ })+})