subharness 0.0.10 → 0.0.11-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/adapters/cursor-rpc.d.ts +2 -1
- package/dist/adapters/cursor-rpc.js +18 -9
- package/dist/adapters/cursor-rpc.js.map +1 -1
- package/dist/adapters/fx-rpc.d.ts +3 -0
- package/dist/adapters/fx-rpc.js +16 -3
- package/dist/adapters/fx-rpc.js.map +1 -1
- package/dist/adapters/fx-tools.d.ts +12 -9
- package/dist/adapters/fx-tools.js +54 -8
- package/dist/adapters/fx-tools.js.map +1 -1
- package/dist/adapters/fx.d.ts +3 -1
- package/dist/adapters/fx.js +234 -97
- package/dist/adapters/fx.js.map +1 -1
- package/dist/adapters/types.d.ts +4 -0
- package/dist/adapters/types.js.map +1 -1
- package/dist/cli/output.js +1 -0
- package/dist/cli/output.js.map +1 -1
- package/dist/events/content.d.ts +1 -0
- package/dist/events/content.js +11 -0
- package/dist/events/content.js.map +1 -1
- package/dist/events/validate.js +18 -1
- package/dist/events/validate.js.map +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/runtime/access-errors.js +2 -0
- package/dist/runtime/access-errors.js.map +1 -1
- package/dist/runtime/capture.js +9 -0
- package/dist/runtime/capture.js.map +1 -1
- package/dist/runtime/coordinator.d.ts +9 -0
- package/dist/runtime/coordinator.js +143 -35
- package/dist/runtime/coordinator.js.map +1 -1
- package/dist/runtime/event-owner.d.ts +3 -1
- package/dist/runtime/event-owner.js +28 -17
- package/dist/runtime/event-owner.js.map +1 -1
- package/dist/runtime/sdk-projection.d.ts +2 -2
- package/dist/runtime/sdk-projection.js +3 -3
- package/dist/runtime/sdk-projection.js.map +1 -1
- package/dist/runtime/select-native.d.ts +5 -1
- package/dist/runtime/select-native.js +58 -12
- package/dist/runtime/select-native.js.map +1 -1
- package/dist/runtime/selection-label.d.ts +2 -0
- package/dist/runtime/selection-label.js +14 -0
- package/dist/runtime/selection-label.js.map +1 -0
- package/dist/runtime/selection.d.ts +13 -0
- package/dist/runtime/selection.js +29 -0
- package/dist/runtime/selection.js.map +1 -0
- package/dist/runtime/service.js +2 -1
- package/dist/runtime/service.js.map +1 -1
- package/dist/runtime/snapshots.d.ts +4 -5
- package/dist/runtime/snapshots.js.map +1 -1
- package/dist/runtime/types.d.ts +6 -2
- package/dist/runtime/types.js.map +1 -1
- package/dist/runtime/worker-client.js +11 -0
- package/dist/runtime/worker-client.js.map +1 -1
- package/dist/runtime/worker-event-protocol.d.ts +4 -0
- package/dist/runtime/worker-event-protocol.js.map +1 -1
- package/dist/runtime/worker-server.js +19 -2
- package/dist/runtime/worker-server.js.map +1 -1
- package/dist/sdk/event-types.d.ts +9 -1
- package/dist/sdk/event-types.js.map +1 -1
- package/dist/sdk/execution-driver.js +23 -3
- package/dist/sdk/execution-driver.js.map +1 -1
- package/dist/sdk/execution-types.d.ts +2 -1
- package/dist/sdk/execution-types.js.map +1 -1
- package/dist/sdk/execution.d.ts +1 -1
- package/dist/sdk/execution.js.map +1 -1
- package/package.json +1 -1
- package/sdk/adapter-contract.md +2 -2
- package/sdk/cli/index.md +1 -1
- package/sdk/cli/output.md +3 -1
- package/sdk/diagnostics.md +2 -0
- package/sdk/distribution.md +41 -8
- package/sdk/events.md +13 -3
- package/sdk/execution.md +24 -6
- package/sdk/fx.md +17 -3
- package/sdk/harnesses.md +11 -3
- package/sdk/message-delivery.md +3 -3
- package/sdk/pr-integration.md +1 -1
- package/sdk/project-team.md +13 -13
- package/sdk/sessions.md +1 -1
- package/sdk/v1-runtime.md +1 -1
package/README.md
CHANGED
|
@@ -274,7 +274,7 @@ This checkout includes ten [repository roles](sdk/project-team.md): the Astra `a
|
|
|
274
274
|
|
|
275
275
|
The local coordinator retains sessions and responses across command exits, but does not restore queues after coordinator or environment loss. External assistant reactivation depends on that assistant's host. Supported native permission requests return structured schemas and keep the original operation pending. The caller answers with `subharness respond <request-id> --content <json>` and observes the same task. See [permission request examples](sdk/approvals.md). Unsupported interactive input still fails with actionable `INPUT_REQUIRED`; no request is automatically approved. CLI delegation requires the native shell to reach the coordinator over loopback HTTP; a sandbox that blocks local networking must be configured by the caller.
|
|
276
276
|
|
|
277
|
-
`resume`
|
|
277
|
+
After a recoverable [fx process exit](sdk/fx.md#reconnecting-after-process-loss), the next send or `resume` reconnects the same native conversation without changing the failed task. Otherwise, adapters report `RECOVERY_UNSUPPORTED` when prompt-free native recovery is unavailable. Failed work is not automatically replayed or migrated.
|
|
278
278
|
|
|
279
279
|
Live subscription checks with Codex and Claude Code cover execution, conversation follow-ups, custom tools, and queuing. Codex native steering and interruption preserve queued work. Claude's `steer` fallback also interrupts the active task, runs its replacement, and preserves queued work.
|
|
280
280
|
|
|
@@ -44,7 +44,8 @@ export class CursorRpc {
|
|
|
44
44
|
child;
|
|
45
45
|
pending = new Map();
|
|
46
46
|
sequence = 0;
|
|
47
|
-
buffer =
|
|
47
|
+
buffer = [];
|
|
48
|
+
bufferedBytes = 0;
|
|
48
49
|
started = false;
|
|
49
50
|
closing = false;
|
|
50
51
|
closed = false;
|
|
@@ -187,15 +188,18 @@ export class CursorRpc {
|
|
|
187
188
|
read(chunk) {
|
|
188
189
|
if (this.failure)
|
|
189
190
|
return;
|
|
190
|
-
|
|
191
|
+
let start = 0;
|
|
191
192
|
let newline;
|
|
192
|
-
while ((newline =
|
|
193
|
-
const
|
|
194
|
-
this.
|
|
193
|
+
while ((newline = chunk.indexOf("\n", start)) >= 0) {
|
|
194
|
+
const end = chunk.slice(start, newline);
|
|
195
|
+
if (this.bufferedBytes + Buffer.byteLength(end, "utf8") > MAX_FRAME_BYTES)
|
|
196
|
+
return this.invalid();
|
|
197
|
+
const line = this.buffer.length ? `${this.buffer.join("")}${end}` : end;
|
|
198
|
+
this.buffer.length = 0;
|
|
199
|
+
this.bufferedBytes = 0;
|
|
200
|
+
start = newline + 1;
|
|
195
201
|
if (!line.trim())
|
|
196
202
|
continue;
|
|
197
|
-
if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES)
|
|
198
|
-
return this.invalid();
|
|
199
203
|
let message;
|
|
200
204
|
try {
|
|
201
205
|
message = JSON.parse(line);
|
|
@@ -230,7 +234,12 @@ export class CursorRpc {
|
|
|
230
234
|
else
|
|
231
235
|
pending.resolve(message.result);
|
|
232
236
|
}
|
|
233
|
-
|
|
237
|
+
const tail = chunk.slice(start);
|
|
238
|
+
if (!tail)
|
|
239
|
+
return;
|
|
240
|
+
this.buffer.push(tail);
|
|
241
|
+
this.bufferedBytes += Buffer.byteLength(tail, "utf8");
|
|
242
|
+
if (this.bufferedBytes > MAX_FRAME_BYTES)
|
|
234
243
|
this.invalid();
|
|
235
244
|
}
|
|
236
245
|
invalid() {
|
|
@@ -247,7 +256,7 @@ export class CursorRpc {
|
|
|
247
256
|
this.closed = true;
|
|
248
257
|
if (this.closing)
|
|
249
258
|
return this.rejectPending(closedError());
|
|
250
|
-
this.fail(this.buffer.trim()
|
|
259
|
+
this.fail(this.buffer.some(chunk => chunk.trim())
|
|
251
260
|
? protocolError()
|
|
252
261
|
: new AgentError("HARNESS_FAILED", "Cursor ACP exited before the native operation completed."));
|
|
253
262
|
void this.close().catch(() => { });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cursor-rpc.js","sourceRoot":"","sources":["../../src/adapters/cursor-rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACzC,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,aAAa,GAAG,KAAK,C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B,CAAC,CAAC,aAAa,EAAE;YACjB,CAAC,CAAC,IAAI,UAAU,CAAC,gBAAgB,EAAE,0DAA0D,CAAC,CAAC,CAAC;QAClG,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACpC,CAAC;IAEO,aAAa,CAAC,KAAiB;QACrC,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;YAC5C,IAAI,OAAO,CAAC,KAAK;gBAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC/C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;IAEO,IAAI,CAAC,KAAiB;QAC5B,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { AgentError } from \"../errors.js\";\n\nconst MAX_FRAME_BYTES = 16 * 1024 * 1024;\nconst CONTROL_TIMEOUT_MS = 15_000;\nconst GRACEFUL_CLOSE_MS = 100;\nconst TERM_CLOSE_MS = 250;\nconst KILL_CLOSE_MS = 1_000;\nconst protocolError = () => new AgentError(\"PROTOCOL_ERROR\", \"Cursor returned invalid ACP protocol data.\");\nconst closedError = () => new AgentError(\"SESSION_CLOSED\", \"The Cursor ACP transport is closed.\");\nconst cancellationError = () => new AgentError(\"CANCELLATION_FAILED\", \"Cursor ACP process termination could not be confirmed.\");\n\nexport type CursorRpcEnvelope = {\n jsonrpc?: \"2.0\";\n id?: string | number;\n method?: string;\n params?: unknown;\n result?: unknown;\n error?: unknown;\n};\n\nexport class CursorRpcNativeError extends AgentError {\n constructor(public readonly nativeCode: number) {\n super(\"NATIVE_ERROR\", \"Cursor ACP request failed.\");\n this.name = \"CursorRpcNativeError\";\n }\n}\n\ntype Pending = { timer?: NodeJS.Timeout; resolve(value: unknown): void; reject(error: Error): void };\n\nconst validId = (value: unknown): value is string | number =>\n typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n\nfunction validEnvelope(value: unknown): value is CursorRpcEnvelope {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const message = value as CursorRpcEnvelope;\n if (message.jsonrpc !== \"2.0\") return false;\n const hasId = Object.hasOwn(message, \"id\");\n const hasMethod = Object.hasOwn(message, \"method\");\n const hasResult = Object.hasOwn(message, \"result\");\n const hasError = Object.hasOwn(message, \"error\");\n if (hasMethod) {\n return typeof message.method === \"string\" && (!hasId || validId(message.id)) && !hasResult && !hasError;\n }\n if (!hasId || !validId(message.id) || hasResult === hasError || Object.hasOwn(message, \"params\")) return false;\n if (!hasError) return true;\n const error = message.error;\n return !!error && typeof error === \"object\" && !Array.isArray(error)\n && Number.isInteger((error as { code?: unknown }).code)\n && typeof (error as { message?: unknown }).message === \"string\";\n}\n\n/** Newline-delimited JSON-RPC 2.0 transport for Cursor's native ACP process. */\nexport class CursorRpc {\n private readonly child: ChildProcessWithoutNullStreams;\n private readonly pending = new Map<number, Pending>();\n private sequence = 0;\n private buffer = \"\";\n private started = false;\n private closing = false;\n private closed = false;\n private closePromise?: Promise<void>;\n private failure?: AgentError;\n private failureHandler: (error: AgentError) => void = () => {};\n onMessage: (message: CursorRpcEnvelope) => void = () => {};\n\n constructor(executable: string, args: string[], cwd: string, env: NodeJS.ProcessEnv) {\n if (process.platform === \"win32\") {\n throw new AgentError(\"UNSUPPORTED_OPTION\", \"Cursor subscription access is supported only on macOS and Linux.\");\n }\n this.child = spawn(executable, args, { cwd, env, detached: true, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n this.child.once(\"spawn\", () => { this.started = true; });\n this.child.stdout.setEncoding(\"utf8\");\n this.child.stdout.on(\"data\", chunk => this.read(chunk));\n this.child.stderr.resume();\n this.child.stdin.on(\"error\", () => this.handleInputFailure());\n this.child.stdin.on(\"close\", () => this.handleInputFailure());\n this.child.once(\"error\", () => {\n this.fail(new AgentError(\"HARNESS_UNAVAILABLE\", \"Cannot start the Cursor ACP executable.\"));\n void this.close().catch(() => {});\n });\n this.child.once(\"close\", () => this.handleExit());\n }\n\n request(method: string, params: unknown, timeoutMs?: number): Promise<unknown> {\n if (this.failure) return Promise.reject(this.failure);\n if (this.closing) return Promise.reject(closedError());\n const timeout = timeoutMs ?? (method === \"session/prompt\" ? undefined : CONTROL_TIMEOUT_MS);\n if (timeout !== undefined && (!Number.isSafeInteger(timeout) || timeout <= 0)) {\n return Promise.reject(new AgentError(\"INVALID_ARGUMENT\", \"Cursor ACP request timeout must be a positive safe integer.\"));\n }\n const id = ++this.sequence;\n return new Promise((resolve, reject) => {\n const pending: Pending = { resolve, reject };\n if (timeout !== undefined) {\n pending.timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new AgentError(\"HARNESS_FAILED\", \"Cursor ACP request timed out.\"));\n }, timeout);\n pending.timer.unref();\n }\n this.pending.set(id, pending);\n try { this.send({ id, method, params }); }\n catch (error) {\n this.pending.delete(id);\n if (pending.timer) clearTimeout(pending.timer);\n reject(error);\n }\n });\n }\n\n send(envelope: CursorRpcEnvelope): void {\n if (this.failure) throw this.failure;\n if (this.closing) throw closedError();\n let frame: string;\n try {\n frame = JSON.stringify({ jsonrpc: \"2.0\", ...envelope });\n if (Buffer.byteLength(frame, \"utf8\") > MAX_FRAME_BYTES || !validEnvelope(JSON.parse(frame))) throw protocolError();\n } catch {\n throw protocolError();\n }\n try {\n this.child.stdin.write(`${frame}\\n`);\n } catch {\n const error = new AgentError(\"HARNESS_FAILED\", \"The Cursor ACP input connection closed.\");\n this.fail(error);\n void this.close().catch(() => {});\n throw error;\n }\n }\n\n setFailureHandler(handler: (error: AgentError) => void): void {\n this.failureHandler = handler;\n if (this.failure) handler(this.failure);\n }\n\n close(): Promise<void> {\n this.closePromise ??= this.closeOwnedProcess();\n return this.closePromise;\n }\n\n private async closeOwnedProcess(): Promise<void> {\n this.closing = true;\n this.rejectPending(this.failure ?? closedError());\n if (!this.closed) {\n try { this.child.stdin.end(); } catch {}\n }\n if (await this.waitForRetirement(GRACEFUL_CLOSE_MS)) return;\n this.signal(\"SIGTERM\");\n if (await this.waitForRetirement(TERM_CLOSE_MS)) return;\n this.signal(\"SIGKILL\");\n if (await this.waitForRetirement(KILL_CLOSE_MS)) return;\n const error = cancellationError();\n this.fail(error);\n throw error;\n }\n\n private signal(signal: NodeJS.Signals): void {\n try { if (this.child.pid !== undefined) process.kill(-this.child.pid, signal); }\n catch {}\n }\n\n private async waitForRetirement(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (this.retired()) return true;\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n return this.retired();\n }\n\n private retired(): boolean {\n if (!this.closed) return false;\n if (this.child.pid === undefined) return true;\n try {\n process.kill(-this.child.pid, 0);\n return false;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ESRCH\";\n }\n }\n\n private read(chunk: string): void {\n if (this.failure) return;\n this.buffer += chunk;\n let newline: number;\n while ((newline = this.buffer.indexOf(\"\\n\")) >= 0) {\n const line = this.buffer.slice(0, newline);\n this.buffer = this.buffer.slice(newline + 1);\n if (!line.trim()) continue;\n if (Buffer.byteLength(line, \"utf8\") > MAX_FRAME_BYTES) return this.invalid();\n let message: unknown;\n try { message = JSON.parse(line); }\n catch { return this.invalid(); }\n if (!validEnvelope(message)) return this.invalid();\n if (typeof message.method === \"string\") {\n try { this.onMessage(message); }\n catch {\n this.fail(new AgentError(\"HARNESS_FAILED\", \"Cursor ACP message handling failed.\"));\n void this.close().catch(() => {});\n }\n continue;\n }\n if (typeof message.id !== \"number\") continue;\n const pending = this.pending.get(message.id);\n if (!pending) continue;\n this.pending.delete(message.id);\n if (pending.timer) clearTimeout(pending.timer);\n if (Object.hasOwn(message, \"error\")) {\n const nativeCode = (message.error as { code: number }).code;\n pending.reject(new CursorRpcNativeError(nativeCode as number));\n }\n else pending.resolve(message.result);\n }\n if (Buffer.byteLength(this.buffer, \"utf8\") > MAX_FRAME_BYTES) this.invalid();\n }\n\n private invalid(): void {\n this.fail(protocolError());\n void this.close().catch(() => {});\n }\n\n private handleInputFailure(): void {\n if (!this.started || this.closing || this.closed) return;\n this.fail(new AgentError(\"HARNESS_FAILED\", \"The Cursor ACP input connection closed.\"));\n void this.close().catch(() => {});\n }\n\n private handleExit(): void {\n this.closed = true;\n if (this.closing) return this.rejectPending(closedError());\n this.fail(this.buffer.trim()\n ? protocolError()\n : new AgentError(\"HARNESS_FAILED\", \"Cursor ACP exited before the native operation completed.\"));\n void this.close().catch(() => {});\n }\n\n private rejectPending(error: AgentError): void {\n for (const pending of this.pending.values()) {\n if (pending.timer) clearTimeout(pending.timer);\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n private fail(error: AgentError): void {\n if (this.failure) return;\n this.failure = error;\n this.rejectPending(error);\n this.failureHandler(error);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cursor-rpc.js","sourceRoot":"","sources":["../../src/adapters/cursor-rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACzC,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,MAAM,aAAa,GAAG,GAAG,EAAE,CAAC,IAAI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"node:child_process\";\nimport { AgentError } from \"../errors.js\";\n\nconst MAX_FRAME_BYTES = 16 * 1024 * 1024;\nconst CONTROL_TIMEOUT_MS = 15_000;\nconst GRACEFUL_CLOSE_MS = 100;\nconst TERM_CLOSE_MS = 250;\nconst KILL_CLOSE_MS = 1_000;\nconst protocolError = () => new AgentError(\"PROTOCOL_ERROR\", \"Cursor returned invalid ACP protocol data.\");\nconst closedError = () => new AgentError(\"SESSION_CLOSED\", \"The Cursor ACP transport is closed.\");\nconst cancellationError = () => new AgentError(\"CANCELLATION_FAILED\", \"Cursor ACP process termination could not be confirmed.\");\n\nexport type CursorRpcEnvelope = {\n jsonrpc?: \"2.0\";\n id?: string | number;\n method?: string;\n params?: unknown;\n result?: unknown;\n error?: unknown;\n};\n\nexport class CursorRpcNativeError extends AgentError {\n constructor(public readonly nativeCode: number) {\n super(\"NATIVE_ERROR\", \"Cursor ACP request failed.\");\n this.name = \"CursorRpcNativeError\";\n }\n}\n\ntype Pending = { timer?: NodeJS.Timeout; resolve(value: unknown): void; reject(error: Error): void };\n\nconst validId = (value: unknown): value is string | number =>\n typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n\nfunction validEnvelope(value: unknown): value is CursorRpcEnvelope {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const message = value as CursorRpcEnvelope;\n if (message.jsonrpc !== \"2.0\") return false;\n const hasId = Object.hasOwn(message, \"id\");\n const hasMethod = Object.hasOwn(message, \"method\");\n const hasResult = Object.hasOwn(message, \"result\");\n const hasError = Object.hasOwn(message, \"error\");\n if (hasMethod) {\n return typeof message.method === \"string\" && (!hasId || validId(message.id)) && !hasResult && !hasError;\n }\n if (!hasId || !validId(message.id) || hasResult === hasError || Object.hasOwn(message, \"params\")) return false;\n if (!hasError) return true;\n const error = message.error;\n return !!error && typeof error === \"object\" && !Array.isArray(error)\n && Number.isInteger((error as { code?: unknown }).code)\n && typeof (error as { message?: unknown }).message === \"string\";\n}\n\n/** Newline-delimited JSON-RPC 2.0 transport for Cursor's native ACP process. */\nexport class CursorRpc {\n private readonly child: ChildProcessWithoutNullStreams;\n private readonly pending = new Map<number, Pending>();\n private sequence = 0;\n private readonly buffer: string[] = [];\n private bufferedBytes = 0;\n private started = false;\n private closing = false;\n private closed = false;\n private closePromise?: Promise<void>;\n private failure?: AgentError;\n private failureHandler: (error: AgentError) => void = () => {};\n onMessage: (message: CursorRpcEnvelope) => void = () => {};\n\n constructor(executable: string, args: string[], cwd: string, env: NodeJS.ProcessEnv) {\n if (process.platform === \"win32\") {\n throw new AgentError(\"UNSUPPORTED_OPTION\", \"Cursor subscription access is supported only on macOS and Linux.\");\n }\n this.child = spawn(executable, args, { cwd, env, detached: true, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n this.child.once(\"spawn\", () => { this.started = true; });\n this.child.stdout.setEncoding(\"utf8\");\n this.child.stdout.on(\"data\", chunk => this.read(chunk));\n this.child.stderr.resume();\n this.child.stdin.on(\"error\", () => this.handleInputFailure());\n this.child.stdin.on(\"close\", () => this.handleInputFailure());\n this.child.once(\"error\", () => {\n this.fail(new AgentError(\"HARNESS_UNAVAILABLE\", \"Cannot start the Cursor ACP executable.\"));\n void this.close().catch(() => {});\n });\n this.child.once(\"close\", () => this.handleExit());\n }\n\n request(method: string, params: unknown, timeoutMs?: number): Promise<unknown> {\n if (this.failure) return Promise.reject(this.failure);\n if (this.closing) return Promise.reject(closedError());\n const timeout = timeoutMs ?? (method === \"session/prompt\" ? undefined : CONTROL_TIMEOUT_MS);\n if (timeout !== undefined && (!Number.isSafeInteger(timeout) || timeout <= 0)) {\n return Promise.reject(new AgentError(\"INVALID_ARGUMENT\", \"Cursor ACP request timeout must be a positive safe integer.\"));\n }\n const id = ++this.sequence;\n return new Promise((resolve, reject) => {\n const pending: Pending = { resolve, reject };\n if (timeout !== undefined) {\n pending.timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new AgentError(\"HARNESS_FAILED\", \"Cursor ACP request timed out.\"));\n }, timeout);\n pending.timer.unref();\n }\n this.pending.set(id, pending);\n try { this.send({ id, method, params }); }\n catch (error) {\n this.pending.delete(id);\n if (pending.timer) clearTimeout(pending.timer);\n reject(error);\n }\n });\n }\n\n send(envelope: CursorRpcEnvelope): void {\n if (this.failure) throw this.failure;\n if (this.closing) throw closedError();\n let frame: string;\n try {\n frame = JSON.stringify({ jsonrpc: \"2.0\", ...envelope });\n if (Buffer.byteLength(frame, \"utf8\") > MAX_FRAME_BYTES || !validEnvelope(JSON.parse(frame))) throw protocolError();\n } catch {\n throw protocolError();\n }\n try {\n this.child.stdin.write(`${frame}\\n`);\n } catch {\n const error = new AgentError(\"HARNESS_FAILED\", \"The Cursor ACP input connection closed.\");\n this.fail(error);\n void this.close().catch(() => {});\n throw error;\n }\n }\n\n setFailureHandler(handler: (error: AgentError) => void): void {\n this.failureHandler = handler;\n if (this.failure) handler(this.failure);\n }\n\n close(): Promise<void> {\n this.closePromise ??= this.closeOwnedProcess();\n return this.closePromise;\n }\n\n private async closeOwnedProcess(): Promise<void> {\n this.closing = true;\n this.rejectPending(this.failure ?? closedError());\n if (!this.closed) {\n try { this.child.stdin.end(); } catch {}\n }\n if (await this.waitForRetirement(GRACEFUL_CLOSE_MS)) return;\n this.signal(\"SIGTERM\");\n if (await this.waitForRetirement(TERM_CLOSE_MS)) return;\n this.signal(\"SIGKILL\");\n if (await this.waitForRetirement(KILL_CLOSE_MS)) return;\n const error = cancellationError();\n this.fail(error);\n throw error;\n }\n\n private signal(signal: NodeJS.Signals): void {\n try { if (this.child.pid !== undefined) process.kill(-this.child.pid, signal); }\n catch {}\n }\n\n private async waitForRetirement(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (this.retired()) return true;\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n return this.retired();\n }\n\n private retired(): boolean {\n if (!this.closed) return false;\n if (this.child.pid === undefined) return true;\n try {\n process.kill(-this.child.pid, 0);\n return false;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ESRCH\";\n }\n }\n\n private read(chunk: string): void {\n if (this.failure) return;\n let start = 0;\n let newline: number;\n while ((newline = chunk.indexOf(\"\\n\", start)) >= 0) {\n const end = chunk.slice(start, newline);\n if (this.bufferedBytes + Buffer.byteLength(end, \"utf8\") > MAX_FRAME_BYTES) return this.invalid();\n const line = this.buffer.length ? `${this.buffer.join(\"\")}${end}` : end;\n this.buffer.length = 0;\n this.bufferedBytes = 0;\n start = newline + 1;\n if (!line.trim()) continue;\n let message: unknown;\n try { message = JSON.parse(line); }\n catch { return this.invalid(); }\n if (!validEnvelope(message)) return this.invalid();\n if (typeof message.method === \"string\") {\n try { this.onMessage(message); }\n catch {\n this.fail(new AgentError(\"HARNESS_FAILED\", \"Cursor ACP message handling failed.\"));\n void this.close().catch(() => {});\n }\n continue;\n }\n if (typeof message.id !== \"number\") continue;\n const pending = this.pending.get(message.id);\n if (!pending) continue;\n this.pending.delete(message.id);\n if (pending.timer) clearTimeout(pending.timer);\n if (Object.hasOwn(message, \"error\")) {\n const nativeCode = (message.error as { code: number }).code;\n pending.reject(new CursorRpcNativeError(nativeCode as number));\n }\n else pending.resolve(message.result);\n }\n const tail = chunk.slice(start);\n if (!tail) return;\n this.buffer.push(tail);\n this.bufferedBytes += Buffer.byteLength(tail, \"utf8\");\n if (this.bufferedBytes > MAX_FRAME_BYTES) this.invalid();\n }\n\n private invalid(): void {\n this.fail(protocolError());\n void this.close().catch(() => {});\n }\n\n private handleInputFailure(): void {\n if (!this.started || this.closing || this.closed) return;\n this.fail(new AgentError(\"HARNESS_FAILED\", \"The Cursor ACP input connection closed.\"));\n void this.close().catch(() => {});\n }\n\n private handleExit(): void {\n this.closed = true;\n if (this.closing) return this.rejectPending(closedError());\n this.fail(this.buffer.some(chunk => chunk.trim())\n ? protocolError()\n : new AgentError(\"HARNESS_FAILED\", \"Cursor ACP exited before the native operation completed.\"));\n void this.close().catch(() => {});\n }\n\n private rejectPending(error: AgentError): void {\n for (const pending of this.pending.values()) {\n if (pending.timer) clearTimeout(pending.timer);\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n private fail(error: AgentError): void {\n if (this.failure) return;\n this.failure = error;\n this.rejectPending(error);\n this.failureHandler(error);\n }\n}\n"]}
|
|
@@ -16,10 +16,13 @@ export declare class FxRpc {
|
|
|
16
16
|
private buffer;
|
|
17
17
|
private failure?;
|
|
18
18
|
private closing;
|
|
19
|
+
private restoreCapable;
|
|
20
|
+
private inputFailed;
|
|
19
21
|
private readonly exited;
|
|
20
22
|
private failureHandler;
|
|
21
23
|
onMessage: (message: AcpEnvelope) => void;
|
|
22
24
|
constructor(cwd: string, env: NodeJS.ProcessEnv, model?: string);
|
|
25
|
+
markRestoreCapable(): void;
|
|
23
26
|
request(method: string, params: unknown): Promise<any>;
|
|
24
27
|
send(message: AcpEnvelope): void;
|
|
25
28
|
abort(error: AgentError): void;
|
package/dist/adapters/fx-rpc.js
CHANGED
|
@@ -11,6 +11,8 @@ export class FxRpc {
|
|
|
11
11
|
buffer = "";
|
|
12
12
|
failure;
|
|
13
13
|
closing = false;
|
|
14
|
+
restoreCapable = false;
|
|
15
|
+
inputFailed = false;
|
|
14
16
|
exited;
|
|
15
17
|
failureHandler = () => { };
|
|
16
18
|
onMessage = () => { };
|
|
@@ -20,9 +22,10 @@ export class FxRpc {
|
|
|
20
22
|
this.child.stdout.on("data", chunk => this.read(chunk));
|
|
21
23
|
this.child.stderr.resume();
|
|
22
24
|
this.child.stdin.on("error", () => setImmediate(() => {
|
|
23
|
-
if (
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
if (this.closing || this.child.exitCode !== null || this.child.signalCode !== null || this.failure)
|
|
26
|
+
return;
|
|
27
|
+
this.inputFailed = true;
|
|
28
|
+
void terminateFxRpcProcess(this.child, this.exited);
|
|
26
29
|
}));
|
|
27
30
|
this.child.on("error", () => this.fail(new AgentError("HARNESS_UNAVAILABLE", "Cannot start fx. Install fx 0.0.9 or a compatible release and make it available on PATH.")));
|
|
28
31
|
this.exited = new Promise(resolve => this.child.once("close", (code, signal) => {
|
|
@@ -32,12 +35,22 @@ export class FxRpc {
|
|
|
32
35
|
else
|
|
33
36
|
this.fail(this.closedError());
|
|
34
37
|
}
|
|
38
|
+
else if (this.inputFailed) {
|
|
39
|
+
this.fail(new AgentError("HARNESS_FAILED", "The fx ACP input connection closed."));
|
|
40
|
+
}
|
|
41
|
+
else if (this.restoreCapable) {
|
|
42
|
+
this.fail(new AgentError("FX_PROCESS_EXITED", `The established fx ACP process exited unexpectedly${processExitDescription(code, signal)}.`));
|
|
43
|
+
}
|
|
35
44
|
else {
|
|
36
45
|
this.fail(new AgentError("HARNESS_FAILED", `fx exited before the native operation completed${processExitDescription(code, signal)}.`));
|
|
37
46
|
}
|
|
38
47
|
resolve();
|
|
39
48
|
}));
|
|
40
49
|
}
|
|
50
|
+
markRestoreCapable() {
|
|
51
|
+
if (!this.failure && !this.closing)
|
|
52
|
+
this.restoreCapable = true;
|
|
53
|
+
}
|
|
41
54
|
request(method, params) {
|
|
42
55
|
if (this.failure)
|
|
43
56
|
return Promise.reject(this.failure);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fx-rpc.js","sourceRoot":"","sources":["../../src/adapters/fx-rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AAYrD,MAAM,kBAAkB,GAAG,KAAK,CAAC;AAEjC,oEAAoE;AACpE,MAAM,OAAO,KAAK;IACC,KAAK,CAAiC;IACtC,OAAO,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC9C,QAAQ,GAAG,CAAC,CAAC;IACb,MAAM,GAAG,EAAE,CAAC;IACZ,OAAO,C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CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAClC,CAAC;QACH,CAAC;IACH,CAAC;IAEO,OAAO;QACb,IAAI,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,gBAAgB,EAAE,wCAAwC,CAAC,CAAC,CAAC;QACtF,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAEO,IAAI,CAAC,KAAiB;QAC5B,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAEO,WAAW;QACjB,OAAO,IAAI,UAAU,CAAC,gBAAgB,EAAE,2BAA2B,CAAC,CAAC;IACvE,CAAC;CACF;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,KAA+E,EAC/E,MAAqB;IAErB,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IACxE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACtB,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,kBAAkB,CAAC,CAAC;IAC1E,KAAK,CAAC,KAAK,EAAE,CAAC;IACd,MAAM,MAAM,CAAC;IACb,YAAY,CAAC,KAAK,CAAC,CAAC;AACtB,CAAC","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { AgentError } from \"../errors.js\";\nimport { processExitDescription } from \"../process-diagnostics.js\";\nimport { nativeRpcErrorDescription } from \"./rpc.js\";\n\nexport type AcpEnvelope = {\n jsonrpc?: string;\n id?: string | number;\n method?: string;\n params?: any;\n result?: any;\n error?: unknown;\n};\n\ntype Pending = { method: string; resolve(value: any): void; reject(error: Error): void };\nconst terminationGraceMs = 5_000;\n\n/** A JSON-RPC 2.0 newline transport for fx's native ACP process. */\nexport class FxRpc {\n private readonly child: ChildProcessWithoutNullStreams;\n private readonly pending = new Map<number, Pending>();\n private sequence = 0;\n private buffer = \"\";\n private failure?: AgentError;\n private closing = false;\n private readonly exited: Promise<void>;\n private failureHandler: (error: AgentError) => void = () => {};\n onMessage: (message: AcpEnvelope) => void = () => {};\n\n constructor(cwd: string, env: NodeJS.ProcessEnv, model?: string) {\n this.child = spawn(\"fx\", model ? [\"acp\", \"--model\", model] : [\"acp\"], { cwd, env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n this.child.stdout.setEncoding(\"utf8\");\n this.child.stdout.on(\"data\", chunk => this.read(chunk));\n this.child.stderr.resume();\n this.child.stdin.on(\"error\", () => setImmediate(() => {\n if (!this.closing && this.child.exitCode === null && this.child.signalCode === null) {\n this.fail(new AgentError(\"HARNESS_FAILED\", \"The fx ACP input connection closed.\"));\n }\n }));\n this.child.on(\"error\", () => this.fail(new AgentError(\"HARNESS_UNAVAILABLE\", \"Cannot start fx. Install fx 0.0.9 or a compatible release and make it available on PATH.\")));\n this.exited = new Promise(resolve => this.child.once(\"close\", (code, signal) => {\n if (this.closing) {\n if (this.pending.size > 0) this.fail(new AgentError(\"HARNESS_FAILED\",\"The fx session closed before the native operation completed.\"));\n else this.fail(this.closedError());\n } else {\n this.fail(new AgentError(\"HARNESS_FAILED\",\n `fx exited before the native operation completed${processExitDescription(code, signal)}.`));\n }\n resolve();\n }));\n }\n\n request(method: string, params: unknown): Promise<any> {\n if (this.failure) return Promise.reject(this.failure);\n if (this.closing) return Promise.reject(this.closedError());\n const id = ++this.sequence;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n this.send({ id, method, params });\n });\n }\n\n send(message: AcpEnvelope): void {\n if (this.failure) throw this.failure;\n if (this.closing) throw this.closedError();\n this.child.stdin.write(`${JSON.stringify({ jsonrpc: \"2.0\", ...message })}\\n`);\n }\n\n abort(error: AgentError): void {\n this.fail(error);\n void this.close();\n }\n\n setFailureHandler(handler: (error: AgentError) => void): void {\n this.failureHandler = handler;\n if (this.failure) handler(this.failure);\n }\n\n async close(): Promise<void> {\n if (this.child.exitCode !== null || this.child.signalCode !== null) return this.exited;\n this.closing = true;\n await terminateFxRpcProcess(this.child, this.exited);\n }\n\n private read(chunk: string): void {\n this.buffer += chunk;\n if (this.buffer.length > 16 * 1024 * 1024) return this.invalid();\n let newline: number;\n while ((newline = this.buffer.indexOf(\"\\n\")) >= 0) {\n const line = this.buffer.slice(0, newline);\n this.buffer = this.buffer.slice(newline + 1);\n if (!line.trim()) continue;\n let message: AcpEnvelope;\n try { message = JSON.parse(line); } catch { return this.invalid(); }\n if (!message || typeof message !== \"object\" || Array.isArray(message) || message.jsonrpc !== \"2.0\") return this.invalid();\n if (typeof message.method === \"string\") {\n if (Object.hasOwn(message, \"result\") || Object.hasOwn(message, \"error\")) return this.invalid();\n this.onMessage(message);\n continue;\n }\n if (typeof message.id !== \"number\") return this.invalid();\n const hasResult = Object.hasOwn(message, \"result\");\n const hasError = Object.hasOwn(message, \"error\");\n if (hasResult === hasError) return this.invalid();\n if (hasError) {\n const error = message.error;\n if (!error || typeof error !== \"object\" || Array.isArray(error)\n || !Number.isInteger((error as { code?: unknown }).code)\n || typeof (error as { message?: unknown }).message !== \"string\") return this.invalid();\n }\n const pending = this.pending.get(message.id);\n if (!pending) continue;\n this.pending.delete(message.id);\n if (hasError) {\n const nativeCode = (message.error as { code?: unknown } | null)?.code;\n const unsupported = pending.method === \"session/set_config_option\" && (nativeCode === -32601 || nativeCode === -32602);\n const code = unsupported ? \"UNSUPPORTED_OPTION\" : \"NATIVE_ERROR\";\n const diagnostic = `fx rejected ${pending.method}${nativeRpcErrorDescription(message.error)}.`;\n pending.reject(new AgentError(code, code === \"UNSUPPORTED_OPTION\"\n ? `${diagnostic} The requested session option is unsupported.`\n : diagnostic));\n } else {\n pending.resolve(message.result);\n }\n }\n }\n\n private invalid(): void {\n this.fail(new AgentError(\"PROTOCOL_ERROR\", \"fx returned invalid ACP protocol data.\"));\n void this.close();\n }\n\n private fail(error: AgentError): void {\n if (this.failure) return;\n this.failure = error;\n for (const pending of this.pending.values()) pending.reject(error);\n this.pending.clear();\n this.failureHandler(error);\n }\n\n private closedError(): AgentError {\n return new AgentError(\"HARNESS_FAILED\", \"The fx session is closed.\");\n }\n}\n\nexport async function terminateFxRpcProcess(\n child: Pick<ChildProcessWithoutNullStreams, \"exitCode\" | \"signalCode\" | \"kill\">,\n exited: Promise<void>,\n): Promise<void> {\n if (child.exitCode !== null || child.signalCode !== null) return exited;\n child.kill(\"SIGTERM\");\n const timer = setTimeout(() => child.kill(\"SIGKILL\"), terminationGraceMs);\n timer.unref();\n await exited;\n clearTimeout(timer);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fx-rpc.js","sourceRoot":"","sources":["../../src/adapters/fx-rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AAYrD,MAAM,kBAAkB,GAAG,KAAK,CAAC;AAEjC,oEAAoE;AACpE,MAAM,OAAO,KAAK;IACC,KAAK,CAAiC;IACtC,OAAO,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC9C,QAAQ,GAAG,CAAC,CAAC;IACb,MAAM,GAAG,EAAE,CAAC;IACZ,OAAO,CAAc;IACrB,OAAO,GAAG,KAAK,CAAC;IAChB,cAAc,GAAG,KAAK,CAAC;IACvB,WAAW,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,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IACxE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACtB,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,kBAAkB,CAAC,CAAC;IAC1E,KAAK,CAAC,KAAK,EAAE,CAAC;IACd,MAAM,MAAM,CAAC;IACb,YAAY,CAAC,KAAK,CAAC,CAAC;AACtB,CAAC","sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { AgentError } from \"../errors.js\";\nimport { processExitDescription } from \"../process-diagnostics.js\";\nimport { nativeRpcErrorDescription } from \"./rpc.js\";\n\nexport type AcpEnvelope = {\n jsonrpc?: string;\n id?: string | number;\n method?: string;\n params?: any;\n result?: any;\n error?: unknown;\n};\n\ntype Pending = { method: string; resolve(value: any): void; reject(error: Error): void };\nconst terminationGraceMs = 5_000;\n\n/** A JSON-RPC 2.0 newline transport for fx's native ACP process. */\nexport class FxRpc {\n private readonly child: ChildProcessWithoutNullStreams;\n private readonly pending = new Map<number, Pending>();\n private sequence = 0;\n private buffer = \"\";\n private failure?: AgentError;\n private closing = false;\n private restoreCapable = false;\n private inputFailed = false;\n private readonly exited: Promise<void>;\n private failureHandler: (error: AgentError) => void = () => {};\n onMessage: (message: AcpEnvelope) => void = () => {};\n\n constructor(cwd: string, env: NodeJS.ProcessEnv, model?: string) {\n this.child = spawn(\"fx\", model ? [\"acp\", \"--model\", model] : [\"acp\"], { cwd, env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n this.child.stdout.setEncoding(\"utf8\");\n this.child.stdout.on(\"data\", chunk => this.read(chunk));\n this.child.stderr.resume();\n this.child.stdin.on(\"error\", () => setImmediate(() => {\n if (this.closing || this.child.exitCode !== null || this.child.signalCode !== null || this.failure) return;\n this.inputFailed = true;\n void terminateFxRpcProcess(this.child, this.exited);\n }));\n this.child.on(\"error\", () => this.fail(new AgentError(\"HARNESS_UNAVAILABLE\", \"Cannot start fx. Install fx 0.0.9 or a compatible release and make it available on PATH.\")));\n this.exited = new Promise(resolve => this.child.once(\"close\", (code, signal) => {\n if (this.closing) {\n if (this.pending.size > 0) this.fail(new AgentError(\"HARNESS_FAILED\",\"The fx session closed before the native operation completed.\"));\n else this.fail(this.closedError());\n } else if (this.inputFailed) {\n this.fail(new AgentError(\"HARNESS_FAILED\", \"The fx ACP input connection closed.\"));\n } else if (this.restoreCapable) {\n this.fail(new AgentError(\"FX_PROCESS_EXITED\",\n `The established fx ACP process exited unexpectedly${processExitDescription(code, signal)}.`));\n } else {\n this.fail(new AgentError(\"HARNESS_FAILED\",\n `fx exited before the native operation completed${processExitDescription(code, signal)}.`));\n }\n resolve();\n }));\n }\n\n markRestoreCapable(): void {\n if (!this.failure && !this.closing) this.restoreCapable = true;\n }\n\n request(method: string, params: unknown): Promise<any> {\n if (this.failure) return Promise.reject(this.failure);\n if (this.closing) return Promise.reject(this.closedError());\n const id = ++this.sequence;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n this.send({ id, method, params });\n });\n }\n\n send(message: AcpEnvelope): void {\n if (this.failure) throw this.failure;\n if (this.closing) throw this.closedError();\n this.child.stdin.write(`${JSON.stringify({ jsonrpc: \"2.0\", ...message })}\\n`);\n }\n\n abort(error: AgentError): void {\n this.fail(error);\n void this.close();\n }\n\n setFailureHandler(handler: (error: AgentError) => void): void {\n this.failureHandler = handler;\n if (this.failure) handler(this.failure);\n }\n\n async close(): Promise<void> {\n if (this.child.exitCode !== null || this.child.signalCode !== null) return this.exited;\n this.closing = true;\n await terminateFxRpcProcess(this.child, this.exited);\n }\n\n private read(chunk: string): void {\n this.buffer += chunk;\n if (this.buffer.length > 16 * 1024 * 1024) return this.invalid();\n let newline: number;\n while ((newline = this.buffer.indexOf(\"\\n\")) >= 0) {\n const line = this.buffer.slice(0, newline);\n this.buffer = this.buffer.slice(newline + 1);\n if (!line.trim()) continue;\n let message: AcpEnvelope;\n try { message = JSON.parse(line); } catch { return this.invalid(); }\n if (!message || typeof message !== \"object\" || Array.isArray(message) || message.jsonrpc !== \"2.0\") return this.invalid();\n if (typeof message.method === \"string\") {\n if (Object.hasOwn(message, \"result\") || Object.hasOwn(message, \"error\")) return this.invalid();\n this.onMessage(message);\n continue;\n }\n if (typeof message.id !== \"number\") return this.invalid();\n const hasResult = Object.hasOwn(message, \"result\");\n const hasError = Object.hasOwn(message, \"error\");\n if (hasResult === hasError) return this.invalid();\n if (hasError) {\n const error = message.error;\n if (!error || typeof error !== \"object\" || Array.isArray(error)\n || !Number.isInteger((error as { code?: unknown }).code)\n || typeof (error as { message?: unknown }).message !== \"string\") return this.invalid();\n }\n const pending = this.pending.get(message.id);\n if (!pending) continue;\n this.pending.delete(message.id);\n if (hasError) {\n const nativeCode = (message.error as { code?: unknown } | null)?.code;\n const unsupported = pending.method === \"session/set_config_option\" && (nativeCode === -32601 || nativeCode === -32602);\n const code = unsupported ? \"UNSUPPORTED_OPTION\" : \"NATIVE_ERROR\";\n const diagnostic = `fx rejected ${pending.method}${nativeRpcErrorDescription(message.error)}.`;\n pending.reject(new AgentError(code, code === \"UNSUPPORTED_OPTION\"\n ? `${diagnostic} The requested session option is unsupported.`\n : diagnostic));\n } else {\n pending.resolve(message.result);\n }\n }\n }\n\n private invalid(): void {\n this.fail(new AgentError(\"PROTOCOL_ERROR\", \"fx returned invalid ACP protocol data.\"));\n void this.close();\n }\n\n private fail(error: AgentError): void {\n if (this.failure) return;\n this.failure = error;\n for (const pending of this.pending.values()) pending.reject(error);\n this.pending.clear();\n this.failureHandler(error);\n }\n\n private closedError(): AgentError {\n return new AgentError(\"HARNESS_FAILED\", \"The fx session is closed.\");\n }\n}\n\nexport async function terminateFxRpcProcess(\n child: Pick<ChildProcessWithoutNullStreams, \"exitCode\" | \"signalCode\" | \"kill\">,\n exited: Promise<void>,\n): Promise<void> {\n if (child.exitCode !== null || child.signalCode !== null) return exited;\n child.kill(\"SIGTERM\");\n const timer = setTimeout(() => child.kill(\"SIGKILL\"), terminationGraceMs);\n timer.unref();\n await exited;\n clearTimeout(timer);\n}\n"]}
|
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
import { AgentError } from "../errors.js";
|
|
2
2
|
import type { ExecutionDefinition } from "./types.js";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
type FxToolDescriptor = {
|
|
4
|
+
type: "http";
|
|
5
|
+
name: string;
|
|
6
|
+
url: string;
|
|
7
|
+
headers: {
|
|
6
8
|
name: string;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
};
|
|
9
|
+
value: string;
|
|
10
|
+
}[];
|
|
11
|
+
};
|
|
12
|
+
export type FxToolEndpoint = {
|
|
13
|
+
readonly descriptor?: FxToolDescriptor;
|
|
13
14
|
onFailure(handler: (error: AgentError) => void): void;
|
|
14
15
|
beginTurn(): void;
|
|
15
16
|
stopAdmission(): void;
|
|
16
17
|
drain(): Promise<void>;
|
|
18
|
+
rotate(): Promise<void>;
|
|
17
19
|
close(): Promise<void>;
|
|
18
20
|
};
|
|
19
21
|
export declare function startFxTools(agent: Pick<ExecutionDefinition, "tools">): Promise<FxToolEndpoint>;
|
|
22
|
+
export {};
|
|
@@ -11,12 +11,59 @@ export async function startFxTools(agent) {
|
|
|
11
11
|
return emptyEndpoint();
|
|
12
12
|
for (const [, definition] of definitions)
|
|
13
13
|
toolJsonSchema(definition);
|
|
14
|
+
let generation = 1;
|
|
15
|
+
let closed = false;
|
|
16
|
+
let failureHandler;
|
|
17
|
+
const createBinding = (ownGeneration) => startFxToolBinding(definitions, error => {
|
|
18
|
+
if (!closed && generation === ownGeneration)
|
|
19
|
+
failureHandler?.(error);
|
|
20
|
+
});
|
|
21
|
+
let current = await createBinding(generation);
|
|
22
|
+
return {
|
|
23
|
+
get descriptor() { return current.descriptor; },
|
|
24
|
+
onFailure(handler) {
|
|
25
|
+
failureHandler = handler;
|
|
26
|
+
if (current.failure)
|
|
27
|
+
handler(current.failure);
|
|
28
|
+
},
|
|
29
|
+
beginTurn() { current.beginTurn(); },
|
|
30
|
+
stopAdmission() { current.stopAdmission(); },
|
|
31
|
+
async drain() { await current.drain(); },
|
|
32
|
+
async rotate() {
|
|
33
|
+
if (closed)
|
|
34
|
+
throw new AgentError("HARNESS_FAILED", "The private fx tool endpoint is closed.");
|
|
35
|
+
const previous = current;
|
|
36
|
+
const nextGeneration = ++generation;
|
|
37
|
+
previous.stopAdmission();
|
|
38
|
+
await previous.close();
|
|
39
|
+
if (closed)
|
|
40
|
+
throw new AgentError("HARNESS_FAILED", "The private fx tool endpoint is closed.");
|
|
41
|
+
const replacement = await createBinding(nextGeneration);
|
|
42
|
+
if (closed) {
|
|
43
|
+
await replacement.close();
|
|
44
|
+
throw new AgentError("HARNESS_FAILED", "The private fx tool endpoint is closed.");
|
|
45
|
+
}
|
|
46
|
+
current = replacement;
|
|
47
|
+
if (current.failure) {
|
|
48
|
+
failureHandler?.(current.failure);
|
|
49
|
+
throw current.failure;
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
async close() {
|
|
53
|
+
if (closed)
|
|
54
|
+
return;
|
|
55
|
+
closed = true;
|
|
56
|
+
generation++;
|
|
57
|
+
await current.close();
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async function startFxToolBinding(definitions, onFailure) {
|
|
14
62
|
const token = randomBytes(32).toString("base64url");
|
|
15
63
|
const namespace = `subharness_${randomUUID().replaceAll("-", "")}`;
|
|
16
64
|
const pending = new Set();
|
|
17
65
|
let accepting = false;
|
|
18
|
-
let
|
|
19
|
-
let failureHandler;
|
|
66
|
+
let failure;
|
|
20
67
|
const mcp = new McpServer({ name: namespace, version: "1.0.0" });
|
|
21
68
|
for (const [name, definition] of definitions) {
|
|
22
69
|
mcp.registerTool(name, { description: definition.description, inputSchema: definition.inputSchema }, async (input) => {
|
|
@@ -47,11 +94,11 @@ export async function startFxTools(agent) {
|
|
|
47
94
|
await closeHttp(http);
|
|
48
95
|
})();
|
|
49
96
|
const failEndpoint = () => {
|
|
50
|
-
if (
|
|
97
|
+
if (failure)
|
|
51
98
|
return;
|
|
52
|
-
|
|
99
|
+
failure = new AgentError("HARNESS_FAILED", "The private fx tool endpoint failed.");
|
|
53
100
|
accepting = false;
|
|
54
|
-
|
|
101
|
+
onFailure(failure);
|
|
55
102
|
void closeEndpoint();
|
|
56
103
|
};
|
|
57
104
|
try {
|
|
@@ -87,8 +134,7 @@ export async function startFxTools(agent) {
|
|
|
87
134
|
}
|
|
88
135
|
return {
|
|
89
136
|
descriptor: { type: "http", name: namespace, url: `http://127.0.0.1:${address.port}/mcp`, headers: [{ name: "Authorization", value: `Bearer ${token}` }] },
|
|
90
|
-
|
|
91
|
-
handler(endpointFailure); },
|
|
137
|
+
get failure() { return failure; },
|
|
92
138
|
beginTurn() { accepting = true; },
|
|
93
139
|
stopAdmission() { accepting = false; },
|
|
94
140
|
async drain() { accepting = false; await Promise.allSettled([...pending]); },
|
|
@@ -106,7 +152,7 @@ function toolError(text) {
|
|
|
106
152
|
return { isError: true, content: [{ type: "text", text }] };
|
|
107
153
|
}
|
|
108
154
|
function emptyEndpoint() {
|
|
109
|
-
return { onFailure() { }, beginTurn() { }, stopAdmission() { }, async drain() { }, async close() { } };
|
|
155
|
+
return { onFailure() { }, beginTurn() { }, stopAdmission() { }, async drain() { }, async rotate() { }, async close() { } };
|
|
110
156
|
}
|
|
111
157
|
async function closeHttp(server) {
|
|
112
158
|
if (!server.listening)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fx-tools.js","sourceRoot":"","sources":["../../src/adapters/fx-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACvE,OAA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AAC,IAAI,CAAC,UAAU,KAAK,EAAE,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACnC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,IAAI,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AACvE,CAAC;AAED,SAAS,aAAa;IACpB,OAAO,EAAE,SAAS,KAAI,CAAC,EAAE,SAAS,KAAI,CAAC,EAAE,aAAa,KAAI,CAAC,EAAE,KAAK,CAAC,KAAK,KAAI,CAAC,EAAE,KAAK,CAAC,KAAK,KAAI,CAAC,EAAE,CAAC;AACpG,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,MAAkB;IACzC,IAAI,CAAC,MAAM,CAAC,SAAS;QAAE,OAAO;IAC9B,MAAM,IAAI,OAAO,CAAO,OAAO,CAAC,EAAE;QAChC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9B,MAAM,CAAC,mBAAmB,EAAE,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { randomBytes, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { createServer, type Server as HttpServer } from \"node:http\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { AgentError } from \"../errors.js\";\nimport { executeTool, toolJsonSchema } from \"../sdk/tools.js\";\nimport type { ExecutionDefinition } from \"./types.js\";\nimport { mcpToolContent } from \"./mcp-tool-content.js\";\n\nexport type FxToolEndpoint = {\n descriptor?: { type: \"http\"; name: string; url: string; headers: { name: string; value: string }[] };\n onFailure(handler: (error: AgentError) => void): void;\n beginTurn(): void;\n stopAdmission(): void;\n drain(): Promise<void>;\n close(): Promise<void>;\n};\n\nexport async function startFxTools(agent: Pick<ExecutionDefinition, \"tools\">): Promise<FxToolEndpoint> {\n const definitions = Object.entries(agent.tools ?? {});\n if (definitions.length === 0) return emptyEndpoint();\n for (const [, definition] of definitions) toolJsonSchema(definition);\n\n const token = randomBytes(32).toString(\"base64url\");\n const namespace = `subharness_${randomUUID().replaceAll(\"-\", \"\")}`;\n const pending = new Set<Promise<unknown>>();\n let accepting = false;\n let endpointFailure: AgentError | undefined;\n let failureHandler: ((error: AgentError) => void) | undefined;\n const mcp = new McpServer({ name: namespace, version: \"1.0.0\" });\n for (const [name, definition] of definitions) {\n mcp.registerTool(name, { description: definition.description, inputSchema: definition.inputSchema }, async (input: unknown) => {\n if (!accepting) return toolError(\"The task is not accepting tool calls.\");\n const execution = executeTool(definition, input);\n pending.add(execution);\n try {\n return { content: mcpToolContent(await execution) };\n } catch (error) {\n return toolError(error instanceof AgentError ? `Tool failed (${error.code}).` : \"The custom tool failed.\");\n } finally {\n pending.delete(execution);\n }\n });\n }\n\n const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, enableJsonResponse: true });\n await mcp.connect(transport);\n let http: HttpServer | undefined;\n let closing: Promise<void> | undefined;\n const closeEndpoint = (): Promise<void> => closing ??= (async () => {\n accepting = false;\n await Promise.allSettled([...pending]);\n await mcp.close().catch(() => {});\n if (http) await closeHttp(http);\n })();\n const failEndpoint = () => {\n if (endpointFailure) return;\n endpointFailure = new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint failed.\");\n accepting = false;\n failureHandler?.(endpointFailure);\n void closeEndpoint();\n };\n try {\n http = createServer((request, response) => {\n if (request.url !== \"/mcp\" || !authorized(request.headers.authorization, token)) {\n response.writeHead(401, { \"content-type\": \"application/json\" });\n response.end(JSON.stringify({ error: \"unauthorized\" }));\n return;\n }\n void transport.handleRequest(request, response).catch(() => {\n if (!response.headersSent) response.writeHead(500);\n response.end();\n });\n });\n await new Promise<void>((resolve, reject) => {\n http!.once(\"error\", reject);\n http!.listen(0, \"127.0.0.1\", () => {\n http!.off(\"error\", reject);\n http!.on(\"error\", failEndpoint);\n resolve();\n });\n });\n } catch (error) {\n await closeEndpoint();\n throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint could not start.\");\n }\n const address = http.address();\n if (!address || typeof address === \"string\") {\n await closeEndpoint();\n throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint did not bind to loopback.\");\n }\n\n return {\n descriptor: { type: \"http\", name: namespace, url: `http://127.0.0.1:${address.port}/mcp`, headers: [{ name: \"Authorization\", value: `Bearer ${token}` }] },\n onFailure(handler) { failureHandler = handler; if (endpointFailure) handler(endpointFailure); },\n beginTurn() { accepting = true; },\n stopAdmission() { accepting = false; },\n async drain() { accepting = false; await Promise.allSettled([...pending]); },\n close: closeEndpoint,\n };\n}\n\nfunction authorized(header: string | undefined, token: string): boolean {\n if (typeof header !== \"string\") return false;\n const expected = Buffer.from(`Bearer ${token}`);\n const actual = Buffer.from(header);\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n}\n\nfunction toolError(text: string) {\n return { isError: true, content: [{ type: \"text\" as const, text }] };\n}\n\nfunction emptyEndpoint(): FxToolEndpoint {\n return { onFailure() {}, beginTurn() {}, stopAdmission() {}, async drain() {}, async close() {} };\n}\n\nasync function closeHttp(server: HttpServer): Promise<void> {\n if (!server.listening) return;\n await new Promise<void>(resolve => {\n server.close(() => resolve());\n server.closeAllConnections();\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fx-tools.js","sourceRoot":"","sources":["../../src/adapters/fx-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,YAAY,EAA6B,MAAM,WAAW,CAAC;AACpE,OAAO,E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B,MAAM,CAAC,mBAAmB,EAAE,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { randomBytes, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { createServer, type Server as HttpServer } from \"node:http\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { AgentError } from \"../errors.js\";\nimport { executeTool, toolJsonSchema } from \"../sdk/tools.js\";\nimport type { ExecutionDefinition } from \"./types.js\";\nimport { mcpToolContent } from \"./mcp-tool-content.js\";\n\ntype FxToolDescriptor = { type: \"http\"; name: string; url: string; headers: { name: string; value: string }[] };\ntype FxToolDefinitions = [string, NonNullable<ExecutionDefinition[\"tools\"]>[string]][];\n\ntype FxToolBinding = {\n readonly descriptor: FxToolDescriptor;\n readonly failure?: AgentError;\n beginTurn(): void;\n stopAdmission(): void;\n drain(): Promise<void>;\n close(): Promise<void>;\n};\n\nexport type FxToolEndpoint = {\n readonly descriptor?: FxToolDescriptor;\n onFailure(handler: (error: AgentError) => void): void;\n beginTurn(): void;\n stopAdmission(): void;\n drain(): Promise<void>;\n rotate(): Promise<void>;\n close(): Promise<void>;\n};\n\nexport async function startFxTools(agent: Pick<ExecutionDefinition, \"tools\">): Promise<FxToolEndpoint> {\n const definitions = Object.entries(agent.tools ?? {});\n if (definitions.length === 0) return emptyEndpoint();\n for (const [, definition] of definitions) toolJsonSchema(definition);\n\n let generation = 1;\n let closed = false;\n let failureHandler: ((error: AgentError) => void) | undefined;\n const createBinding = (ownGeneration: number) => startFxToolBinding(definitions, error => {\n if (!closed && generation === ownGeneration) failureHandler?.(error);\n });\n let current = await createBinding(generation);\n\n return {\n get descriptor() { return current.descriptor; },\n onFailure(handler) {\n failureHandler = handler;\n if (current.failure) handler(current.failure);\n },\n beginTurn() { current.beginTurn(); },\n stopAdmission() { current.stopAdmission(); },\n async drain() { await current.drain(); },\n async rotate() {\n if (closed) throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint is closed.\");\n const previous = current;\n const nextGeneration = ++generation;\n previous.stopAdmission();\n await previous.close();\n if (closed) throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint is closed.\");\n const replacement = await createBinding(nextGeneration);\n if (closed) {\n await replacement.close();\n throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint is closed.\");\n }\n current = replacement;\n if (current.failure) {\n failureHandler?.(current.failure);\n throw current.failure;\n }\n },\n async close() {\n if (closed) return;\n closed = true;\n generation++;\n await current.close();\n },\n };\n}\n\nasync function startFxToolBinding(\n definitions: FxToolDefinitions,\n onFailure: (error: AgentError) => void,\n): Promise<FxToolBinding> {\n const token = randomBytes(32).toString(\"base64url\");\n const namespace = `subharness_${randomUUID().replaceAll(\"-\", \"\")}`;\n const pending = new Set<Promise<unknown>>();\n let accepting = false;\n let failure: AgentError | undefined;\n const mcp = new McpServer({ name: namespace, version: \"1.0.0\" });\n for (const [name, definition] of definitions) {\n mcp.registerTool(name, { description: definition.description, inputSchema: definition.inputSchema }, async (input: unknown) => {\n if (!accepting) return toolError(\"The task is not accepting tool calls.\");\n const execution = executeTool(definition, input);\n pending.add(execution);\n try {\n return { content: mcpToolContent(await execution) };\n } catch (error) {\n return toolError(error instanceof AgentError ? `Tool failed (${error.code}).` : \"The custom tool failed.\");\n } finally {\n pending.delete(execution);\n }\n });\n }\n\n const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: randomUUID, enableJsonResponse: true });\n await mcp.connect(transport);\n let http: HttpServer | undefined;\n let closing: Promise<void> | undefined;\n const closeEndpoint = (): Promise<void> => closing ??= (async () => {\n accepting = false;\n await Promise.allSettled([...pending]);\n await mcp.close().catch(() => {});\n if (http) await closeHttp(http);\n })();\n const failEndpoint = () => {\n if (failure) return;\n failure = new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint failed.\");\n accepting = false;\n onFailure(failure);\n void closeEndpoint();\n };\n try {\n http = createServer((request, response) => {\n if (request.url !== \"/mcp\" || !authorized(request.headers.authorization, token)) {\n response.writeHead(401, { \"content-type\": \"application/json\" });\n response.end(JSON.stringify({ error: \"unauthorized\" }));\n return;\n }\n void transport.handleRequest(request, response).catch(() => {\n if (!response.headersSent) response.writeHead(500);\n response.end();\n });\n });\n await new Promise<void>((resolve, reject) => {\n http!.once(\"error\", reject);\n http!.listen(0, \"127.0.0.1\", () => {\n http!.off(\"error\", reject);\n http!.on(\"error\", failEndpoint);\n resolve();\n });\n });\n } catch (error) {\n await closeEndpoint();\n throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint could not start.\");\n }\n const address = http.address();\n if (!address || typeof address === \"string\") {\n await closeEndpoint();\n throw new AgentError(\"HARNESS_FAILED\", \"The private fx tool endpoint did not bind to loopback.\");\n }\n\n return {\n descriptor: { type: \"http\", name: namespace, url: `http://127.0.0.1:${address.port}/mcp`, headers: [{ name: \"Authorization\", value: `Bearer ${token}` }] },\n get failure() { return failure; },\n beginTurn() { accepting = true; },\n stopAdmission() { accepting = false; },\n async drain() { accepting = false; await Promise.allSettled([...pending]); },\n close: closeEndpoint,\n };\n}\n\nfunction authorized(header: string | undefined, token: string): boolean {\n if (typeof header !== \"string\") return false;\n const expected = Buffer.from(`Bearer ${token}`);\n const actual = Buffer.from(header);\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n}\n\nfunction toolError(text: string) {\n return { isError: true, content: [{ type: \"text\" as const, text }] };\n}\n\nfunction emptyEndpoint(): FxToolEndpoint {\n return { onFailure() {}, beginTurn() {}, stopAdmission() {}, async drain() {}, async rotate() {}, async close() {} };\n}\n\nasync function closeHttp(server: HttpServer): Promise<void> {\n if (!server.listening) return;\n await new Promise<void>(resolve => {\n server.close(() => resolve());\n server.closeAllConnections();\n });\n}\n"]}
|
package/dist/adapters/fx.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import { FxRpc } from "./fx-rpc.js";
|
|
2
2
|
import type { AdapterOptions, NativeSession } from "./types.js";
|
|
3
|
-
|
|
3
|
+
type CreateFxRpc = (cwd: string, env: NodeJS.ProcessEnv, model?: string) => FxRpc;
|
|
4
|
+
export declare function openFx(options: AdapterOptions, createRpc?: CreateFxRpc): Promise<NativeSession>;
|
|
5
|
+
export {};
|