@qlairoslabs/acp-client 0.13.7-e-alpha.1 → 0.13.8-e-alpha.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.7e-alpha.1",
3
+ "version": "0.13.8e-alpha.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -4,6 +4,7 @@ import type { ConversationPermissionEvent } from "./permissions/conversation.ts"
4
4
  import type { OperationActivity } from "./operations/contracts.ts";
5
5
  import type { ItemsReceipt, TurnCause } from "./conversation-controller/contracts.ts";
6
6
  import type { AgentMode } from "./controller.ts";
7
+ import type { AcpSessionStartFailure } from "./client.ts";
7
8
  import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
8
9
  import type { Adapter } from "./adapters.ts";
9
10
  import type { ContextWindowStatus, ProviderCostSnapshot } from "./metering/context.ts";
@@ -35,6 +36,7 @@ export interface AgentSessionState {
35
36
  readonly operation: OperationActivity | null;
36
37
  readonly pendingHold: { readonly failedTurnId: string } | null;
37
38
  readonly providerConnection: "connected" | "disconnected" | "reconnecting";
39
+ readonly sessionStartFailure?: AcpSessionStartFailure;
38
40
  readonly phase: AgentSessionPhase;
39
41
  /** True only while an operation is executing; queued work is reported separately. */
40
42
  readonly isBusy: boolean;
@@ -1827,12 +1827,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1827
1827
  }
1828
1828
  /** Immutable current state. Late subscribers read this before listening for deltas. */
1829
1829
  get state(): AgentSessionState {
1830
+ const sessionStartFailure = this.controller.sessionStartFailure;
1830
1831
  return Object.freeze({
1831
1832
  pendingHold: this.steering.hold,
1832
1833
  operation: this.activeSupervisor?.activity ?? null,
1833
1834
  providerConnection: this.reconnecting
1834
1835
  ? "reconnecting"
1835
1836
  : this.controller.isConnected ? "connected" : "disconnected",
1837
+ ...(sessionStartFailure ? { sessionStartFailure } : {}),
1836
1838
  phase: this.phase,
1837
1839
  isBusy: this.isBusy,
1838
1840
  queuedOperationCount: this.queuedOperationCount,
@@ -4330,6 +4332,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
4330
4332
  const key = [
4331
4333
  state.pendingHold?.failedTurnId ?? "",
4332
4334
  state.providerConnection,
4335
+ state.sessionStartFailure?.rpcCode ?? "",
4336
+ state.sessionStartFailure?.message ?? "",
4333
4337
  state.operation?.stage ?? "",
4334
4338
  state.operation?.operationId ?? "",
4335
4339
  state.phase,
package/src/client.ts CHANGED
@@ -120,10 +120,18 @@ export interface ListSessionsOptions {
120
120
  cursor?: string;
121
121
  }
122
122
 
123
+ /** A recoverable ACP startup refusal on an initialized connection. */
124
+ export interface AcpSessionStartFailure {
125
+ /** The adapter's original JSON-RPC error code, when available. */
126
+ readonly rpcCode?: number;
127
+ readonly message: string;
128
+ }
129
+
123
130
  export interface ConnectResult {
124
131
  sessionId: string;
125
132
  /** true = resumed an existing session; false = started fresh (incl. resume fallback). */
126
133
  resumed: boolean;
134
+ sessionStartFailure?: AcpSessionStartFailure;
127
135
  }
128
136
 
129
137
  export interface SwitchSessionOptions {
@@ -1,4 +1,4 @@
1
- import { AcpClient, type ConnectResult } from "./client.ts";
1
+ import { AcpClient, type AcpSessionStartFailure, type ConnectResult } from "./client.ts";
2
2
  import type { AgentClient } from "./agent-client.ts";
3
3
  import type { ConnectionAttempt } from "./connection-attempt.ts";
4
4
  import type { AgentControllerConfig, AgentMode, ControllerStartEvent } from "./controller.ts";
@@ -89,8 +89,13 @@ export async function bringUp(
89
89
  await client.stop();
90
90
  throw err;
91
91
  }
92
- config.logger?.warn("session_start_failed", { error: String(err) });
93
- result = { sessionId: "", resumed: false };
92
+ const code = typeof err === "object" && err !== null && "code" in err ? err.code : undefined;
93
+ const sessionStartFailure: AcpSessionStartFailure = Object.freeze({
94
+ ...(typeof code === "number" && Number.isSafeInteger(code) ? { rpcCode: code } : {}),
95
+ message: "The ACP adapter refused to start a session.",
96
+ });
97
+ config.logger?.warn("session_start_failed", { ...sessionStartFailure });
98
+ result = { sessionId: "", resumed: false, sessionStartFailure };
94
99
  }
95
100
  attempt.throwIfCancelled();
96
101
  if (result.sessionId) {
package/src/controller.ts CHANGED
@@ -12,6 +12,7 @@ import type {
12
12
  import {
13
13
  type AcpClient,
14
14
  type AcpClientConfig,
15
+ type AcpSessionStartFailure,
15
16
  type ConnectResult,
16
17
  type SessionLoadFailure,
17
18
  type SwitchSessionOptions,
@@ -146,6 +147,7 @@ export class HarnessController implements AgentClient, ConversationController {
146
147
  private readonly connections = new ConnectionAttempts<ConnectResult, ControllerStartEvent>();
147
148
  private current: AgentClient | null = null;
148
149
  private acp: AcpClient | null = null;
150
+ private startupFailure: AcpSessionStartFailure | undefined;
149
151
  private mode: AgentMode;
150
152
  private readonly availableCommandListeners = new Set<
151
153
  (commands: readonly InternalSessionCommand[]) => void
@@ -223,6 +225,10 @@ export class HarnessController implements AgentClient, ConversationController {
223
225
  return this.acp?.currentSessionId ?? null;
224
226
  }
225
227
 
228
+ get sessionStartFailure(): AcpSessionStartFailure | undefined {
229
+ if (this.acp?.isConnected && !this.acp.hasSession) return this.startupFailure;
230
+ }
231
+
226
232
  get capabilities(): Capabilities {
227
233
  return this.requireAcp().capabilities;
228
234
  }
@@ -297,13 +303,19 @@ export class HarnessController implements AgentClient, ConversationController {
297
303
  }
298
304
 
299
305
  private existingConnection(): ConnectResult {
300
- return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
306
+ const sessionStartFailure = this.sessionStartFailure;
307
+ return {
308
+ sessionId: this.currentSessionId ?? "",
309
+ resumed: this.acp?.hasSession ?? false,
310
+ ...(sessionStartFailure ? { sessionStartFailure } : {}),
311
+ };
301
312
  }
302
313
 
303
314
  private installConnection(attempt: ConnectionAttempt<ControllerStartEvent>, brought: ReadyConnection, mode = this.mode): ConnectResult {
304
315
  attempt.throwIfCancelled();
305
316
  this.current = brought.client;
306
317
  this.acp = brought.acp;
318
+ this.startupFailure = brought.result.sessionStartFailure;
307
319
  this.mode = mode;
308
320
  this.attachAvailableCommandSource();
309
321
  return brought.result;
@@ -433,6 +445,7 @@ export class HarnessController implements AgentClient, ConversationController {
433
445
  const client = this.current;
434
446
  this.current = null;
435
447
  this.acp = null;
448
+ this.startupFailure = undefined;
436
449
  this.detachDisconnect?.();
437
450
  this.detachDisconnect = null;
438
451
  this.connectionChanged();
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import type { NativeTurnMetering } from "../metering/native/source.ts";
16
16
  import type { ClientPrompt } from "../agent-client.ts";
17
- import type { ConnectResult } from "../client.ts";
17
+ import type { AcpSessionStartFailure, ConnectResult } from "../client.ts";
18
18
  import type { AgentMode, ControllerStartEvent, HarnessController } from "../controller.ts";
19
19
  import type { ConfigOptions } from "../config-options.ts";
20
20
  import type { ConversationCapabilities } from "./capabilities.ts";
@@ -93,6 +93,7 @@ export interface ConversationController {
93
93
  startFresh(onProgress?: (event: ControllerStartEvent) => void): Promise<StartResult>;
94
94
  stop(): Promise<void>;
95
95
  readonly isConnected: boolean;
96
+ readonly sessionStartFailure?: AcpSessionStartFailure;
96
97
  subscribeConnection(listener: () => void): () => void;
97
98
  /** How long a cancelled turn gets before the supervisor escalates; undefined when the adapter sets none. */
98
99
  readonly cancelGraceMs: number | undefined;
package/src/index.ts CHANGED
@@ -11,6 +11,7 @@ export type { WorkerPersistence, WorkerRow } from "./persistence/workers.ts";
11
11
  export { AcpClient } from "./client.ts";
12
12
  export type {
13
13
  AcpClientConfig,
14
+ AcpSessionStartFailure,
14
15
  StartSessionOptions,
15
16
  ListSessionsOptions,
16
17
  SwitchSessionOptions,
@@ -15,6 +15,8 @@ import { closeSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, statSync
15
15
  import { tmpdir } from "node:os";
16
16
  import { join } from "node:path";
17
17
  import {
18
+ DEFAULT_INLINE_FUNCTION_RESULT_BYTES,
19
+ encodeInlineFunctionResult,
18
20
  FunctionError,
19
21
  type FunctionCall,
20
22
  type FunctionResult,
@@ -62,7 +64,7 @@ export interface NativeFunctionsConfig {
62
64
  readonly defaultDeadlineMs?: number;
63
65
  /** Where oversized results are kept. Default: a new private directory under the OS temp dir, removed on stop. */
64
66
  readonly resultDirectory?: string;
65
- /** Serialized output above this is stored and returned by reference. Default 16 384 bytes. */
67
+ /** UTF-8 bytes of the complete inline success result. Capped at 16 384 bytes. */
66
68
  readonly inlineBytes?: number;
67
69
  /** How long a stored result can be read. Default 86 400 000 ms (24 hours). */
68
70
  readonly resultTtlMs?: number;
@@ -71,7 +73,7 @@ export interface NativeFunctionsConfig {
71
73
  }
72
74
 
73
75
  /** Adjustable defaults (native harness BUSINESS_RULES.md, tools and host callbacks). */
74
- export const NATIVE_FUNCTION_DEFAULTS = { inlineBytes: 16_384, previewChars: 512, resultTtlMs: 86_400_000 } as const;
76
+ export const NATIVE_FUNCTION_DEFAULTS = { inlineBytes: DEFAULT_INLINE_FUNCTION_RESULT_BYTES, previewChars: 512, resultTtlMs: 86_400_000 } as const;
75
77
 
76
78
  const RESULT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
77
79
 
@@ -90,7 +92,7 @@ export interface NativeFunctionHost {
90
92
  }
91
93
 
92
94
  export function createNativeFunctionHost(config: NativeFunctionsConfig): NativeFunctionHost {
93
- const inlineBytes = config.inlineBytes ?? NATIVE_FUNCTION_DEFAULTS.inlineBytes;
95
+ const inlineBytes = Math.min(config.inlineBytes ?? NATIVE_FUNCTION_DEFAULTS.inlineBytes, NATIVE_FUNCTION_DEFAULTS.inlineBytes);
94
96
  const ttl = config.resultTtlMs ?? NATIVE_FUNCTION_DEFAULTS.resultTtlMs;
95
97
  const enabled = new Set(Object.entries(config.tools).filter(([, tool]) => tool.group === "runtime" && tool.enabled).map(([name]) => name));
96
98
  const active = new Set<string>();
@@ -116,8 +118,10 @@ export function createNativeFunctionHost(config: NativeFunctionsConfig): NativeF
116
118
  try {
117
119
  const output = await tool.handler(call.arguments, { invocationId: call.invocationId, channel: call.channel, turnId: call.turnId, tool: call.tool, policyNames: [...call.policyNames], signal, ...(takenSender ? { takenSender } : {}) });
118
120
  const text = JSON.stringify(output ?? null);
121
+ if (text === undefined) throw new TypeError("The function result must be a JSON value");
122
+ // Send the measured JSON value so wire serialization cannot invoke the handler's toJSON again.
123
+ if (encodeInlineFunctionResult(text).bytes <= inlineBytes) return { output: JSON.parse(text) };
119
124
  const bytes = Buffer.byteLength(text);
120
- if (bytes <= inlineBytes) return { output: output ?? null };
121
125
  // Too large to send inline: keep the bytes here and hand the harness a preview and an ID.
122
126
  const resultId = (config.newResultId ?? randomUUID)();
123
127
  if (!RESULT_ID.test(resultId)) throw new FunctionError("result_store_failed", "The result could not be stored");
@@ -688,7 +688,8 @@ await client.openSession({ sessionId, tools: { catalog: [
688
688
  repeated. `tool_call` events carry `invocationId`.
689
689
  - **Phase.** `session/status` reports `activeTurn.phase`: `model`, `approval`
690
690
  or `tool`, since when, and the model call, approval request or invocation ID.
691
- - **Large results.** Above 16384 bytes the handler stores the result itself
691
+ - **Large results.** The default inline limit is 16384 UTF-8 bytes, including
692
+ the success envelope. Above that limit the host stores the output JSON
692
693
  and returns a preview and a reference. The model reads parts with
693
694
  `read_tool_result`; the harness accepts only IDs recorded for the requesting
694
695
  channel and forwards the read to the host as `results/read`.
@@ -1,8 +1,9 @@
1
1
  import type { StorageSnapshot } from "../../../contracts/storage.ts";
2
2
  import type { FunctionCall, FunctionExecutor, ResultReference, ToolLimits, ToolOutcome, ToolRegistration } from "../../../contracts/tools.ts";
3
+ import { DEFAULT_INLINE_FUNCTION_RESULT_BYTES, encodeInlineFunctionResult } from "../../../contracts/tools.ts";
3
4
 
4
5
  /** Adjustable defaults (BUSINESS_RULES.md, tools and callbacks). */
5
- export const TOOL_LIMITS: Readonly<ToolLimits> = { inlineBytes: 16_384, previewBytes: 1_024, readBytes: 16_384 };
6
+ export const TOOL_LIMITS: Readonly<ToolLimits> = { inlineBytes: DEFAULT_INLINE_FUNCTION_RESULT_BYTES, previewBytes: 1_024, readBytes: 16_384 };
6
7
 
7
8
  /** The wait for a callback ended for a reason that says nothing about its
8
9
  * effect on the host: the connection is gone. The call stays dispatched with
@@ -70,10 +71,10 @@ export async function runFunction(options: {
70
71
  note: "The full result is stored. Read it in parts with read_tool_result and this result_id." }),
71
72
  outcome: { status: "succeeded", reference: structuredClone(answer.reference) } };
72
73
  }
73
- const content = JSON.stringify({ ok: true, output: (answer as { output?: unknown })?.output ?? null });
74
+ const { content, bytes: inlineBytes } = encodeInlineFunctionResult(JSON.stringify((answer as { output?: unknown })?.output ?? null) ?? "null");
74
75
  // A producer stores what does not fit and sends a reference. Bytes that
75
76
  // arrive inline anyway cannot be kept or shown in full.
76
- if (bytes(content) > limits.inlineBytes) return failure("failed", "result_too_large", `The tool's result exceeds ${limits.inlineBytes} bytes and was not stored by its producer.`);
77
+ if (inlineBytes > limits.inlineBytes) return failure("failed", "result_too_large", `The tool's result exceeds ${limits.inlineBytes} bytes and was not stored by its producer.`);
77
78
  return { content, outcome: { status: "succeeded" } };
78
79
  } catch (error) {
79
80
  if (signal.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("Turn interrupted");
@@ -1,6 +1,7 @@
1
1
  export { HarnessClient, HarnessClientError, FunctionError } from "./interfaces/client.ts";
2
2
  export type { FunctionHandler, ResultReader } from "./interfaces/client.ts";
3
3
  export type { ToolRegistration, ToolCatalogInput, ToolAvailability, ToolInvocation, ToolInvocationState, ToolOutcome, ResultReference, TurnPhase, FunctionCall, FunctionResult, ResultRead, ResultPage } from "./contracts/tools.ts";
4
+ export { DEFAULT_INLINE_FUNCTION_RESULT_BYTES, encodeInlineFunctionResult } from "./contracts/tools.ts";
4
5
  export { createInProcessTransport } from "./interfaces/protocol/in-process.ts";
5
6
  export { createStdioTransport } from "./interfaces/protocol/stdio-client.ts";
6
7
  export type { StdioConnection } from "./contracts/protocol.ts";
@@ -118,6 +118,15 @@ export type FunctionResult =
118
118
  | { output: unknown; preview?: never; reference?: never }
119
119
  | { output?: never; preview: string; reference: ResultReference };
120
120
 
121
+ /** Default UTF-8 byte limit for the complete inline success envelope. */
122
+ export const DEFAULT_INLINE_FUNCTION_RESULT_BYTES = 16_384;
123
+
124
+ /** Wrap an already serialized JSON output and measure the content the harness stores. */
125
+ export function encodeInlineFunctionResult(outputJson: string): { content: string; bytes: number } {
126
+ const content = `{"ok":true,"output":${outputJson}}`;
127
+ return { content, bytes: new TextEncoder().encode(content).length };
128
+ }
129
+
121
130
  /** `results/read` parameters and result. The harness has already checked that
122
131
  * `channel` produced `resultId`; the host serves bytes it holds. */
123
132
  export interface ResultRead { resultId: string; invocationId: string; channel: string; offset: number; length: number }