@qlairoslabs/acp-client 0.13.5-alpha.1 → 0.13.6-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/CONSUMER_GUIDE.md CHANGED
@@ -1247,6 +1247,25 @@ A failed turn reports `context_limit` and leaves the channel usable. The
1247
1247
  underlying `NativeTurnError.contextFailure` gives the applicable limit and,
1248
1248
  for local token and byte limits, the measured budget.
1249
1249
 
1250
+ When a native inference attempt fails, the prompt rejection and
1251
+ `turn_failed` event include the harness diagnostic. A metered conversation
1252
+ rejects with `AgentSessionOperationError` whose `cause` is a
1253
+ `NativeTurnError`. Both errors carry the same message, for example
1254
+ `native turn 1 failed: Chat Completions HTTP 429`. Use
1255
+ `NativeTurnError.outcome` for the turn classification. `"interrupted"`
1256
+ records an external interruption. A provider deadline leaves the turn
1257
+ `"failed"` and records `"timeout"` on the model call.
1258
+
1259
+ Provider diagnostics identify HTTP status where available, for example
1260
+ `Chat Completions HTTP 429` or `OpenRouter HTTP 500`. Other diagnostics
1261
+ identify a transport failure, refused redirect, invalid response,
1262
+ configuration error, or model request deadline. The harness uses fixed
1263
+ fallback wording when it has no validated provider detail. Remote
1264
+ response bodies, headers and URLs are excluded from these failure
1265
+ diagnostics. Reconciliation preserves the recorded reason, and the next
1266
+ prompt can run when the provider recovers.
1267
+
1268
+
1250
1269
  ```ts
1251
1270
  import { NativeInputStoppedError, type Agent, type ItemsReceipt } from "@qlairoslabs/acp-client";
1252
1271
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.5-alpha.1",
3
+ "version": "0.13.6-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",
@@ -504,8 +504,10 @@ export class NativeController implements ConversationController, ChannelPort {
504
504
  } else if (event.outcome === "interrupted" && turn.cancelRequested) {
505
505
  cancelled(true);
506
506
  } else {
507
- const reason = event.error ?? event.outcome;
508
- finish(() => reject(new NativeTurnError(event.outcome as "failed" | "interrupted", `native turn ${turn.harnessId} ${event.outcome}: ${reason}`,
507
+ const prefix = `${event.outcome}: `;
508
+ const reason = event.error?.startsWith(prefix) ? event.error.slice(prefix.length) : event.error;
509
+ const detail = reason && reason !== event.outcome ? `: ${reason}` : "";
510
+ finish(() => reject(new NativeTurnError(event.outcome as "failed" | "interrupted", `native turn ${turn.harnessId} ${event.outcome}${detail}`,
509
511
  event.uncertainCalls, event.contextFailure)), true);
510
512
  }
511
513
  return;
@@ -9,8 +9,8 @@ export function completeModelAttempt(model: Model): ModelAttempt {
9
9
  const answer = await model(request.messages, request.tools, signal);
10
10
  if (signal.aborted) return;
11
11
  yield { type: "response", response: { ...answer, stopReason: answer.calls.length ? "tool_calls" : "complete" } };
12
- } catch (error) {
13
- if (!signal.aborted) yield { type: "failure", kind: "provider", message: String(error) };
12
+ } catch {
13
+ if (!signal.aborted) yield { type: "failure", kind: "provider", message: "Model provider failed" };
14
14
  }
15
15
  };
16
16
  }
@@ -133,19 +133,20 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
133
133
  for (const url of imageUrls) { safe = safe.replaceAll(url, "[REDACTED_IMAGE]"); const encoded = url.slice(url.indexOf(",") + 1); if (encoded) safe = safe.replaceAll(encoded, "[REDACTED_IMAGE]"); }
134
134
  return safe;
135
135
  };
136
- const errorText = (error: unknown) => endpoint ? "Chat Completions transport failed" : redact(String(error));
136
+ const diagnosticProvider = endpoint ? "chat_completions" as const : "openrouter" as const;
137
+ const errorText = () => endpoint ? "Chat Completions transport failed" : "OpenRouter transport failed";
137
138
  onRequest?.(imageUrls.length ? redact(body) : body);
138
139
  let response: Response;
139
140
  try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: {
140
141
  ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json",
141
142
  ...(goSession ? { "User-Agent": "acp-client/native-harness", "x-opencode-session": goSession } : {}),
142
143
  }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
143
- catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; return; }
144
+ catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(), diagnostic: { provider: diagnosticProvider, category: "transport" } }; return; }
144
145
  if (!response.ok) {
145
146
  if (endpoint) {
146
147
  if (response.status >= 300 && response.status < 400) {
147
148
  void response.body?.cancel().catch(() => {});
148
- yield { type: "failure", kind: "provider", message: "redirect_refused",
149
+ yield { type: "failure", kind: "provider", message: "redirect_refused", diagnostic: { provider: diagnosticProvider, category: "redirect" },
149
150
  ...(goSession ? { providerFailure: `OpenCode Go HTTP ${response.status} (redirect_refused)` } : {}) }; return;
150
151
  }
151
152
  const upstream = await readErrorBody(response);
@@ -156,17 +157,11 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
156
157
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message, providerFailure: message };
157
158
  return;
158
159
  }
159
- yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}` }; return;
160
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}`, diagnostic: { provider: diagnosticProvider, category: "http", status: response.status } }; return;
160
161
  }
161
- if (profile) {
162
- if (isProviderContextError(await readErrorBody(response))) { yield providerContextFailure; return; }
163
- yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request",
164
- message: `OpenRouter HTTP ${response.status}` }; return;
165
- }
166
- const raw = await response.text();
167
- try { if (isProviderContextError(JSON.parse(raw))) { yield providerContextFailure; return; } } catch { /* Non-JSON error body. */ }
168
- const text = redact(raw);
169
- yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `OpenRouter HTTP ${response.status}: ${text}` }; return;
162
+ if (isProviderContextError(await readErrorBody(response))) { yield providerContextFailure; return; }
163
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request",
164
+ message: `OpenRouter HTTP ${response.status}`, diagnostic: { provider: diagnosticProvider, category: "http", status: response.status } }; return;
170
165
  }
171
166
  const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
172
167
  const requestId = safeRequestId(response.headers.get("x-request-id") ?? undefined);
@@ -209,14 +204,14 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
209
204
  const ordered = [...fragments.entries()].sort((a, b) => a[0] - b[0]);
210
205
  if (ordered.some(([n], i) => n !== i)) { yield { type: "failure", kind: "provider", message: "Non-contiguous tool fragments" }; return; }
211
206
  const stopReason = stop === "stop" ? "complete" : stop === "tool_calls" ? "tool_calls" : stop === "length" ? "output_limit" : undefined;
212
- if (!stopReason) { yield { type: "failure", kind: "provider", message: endpoint ? "Unsupported Chat Completions finish reason" : `Unsupported finish reason: ${stop}` }; return; }
207
+ if (!stopReason) { yield { type: "failure", kind: "provider", message: endpoint ? "Unsupported Chat Completions finish reason" : "Unsupported OpenRouter finish reason" }; return; }
213
208
  const calls = ordered.map(([, value]) => value);
214
209
  const message = { role: "assistant" as const, content: content || null, calls };
215
210
  const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, ...(endpoint ? {} : { providerState: { role: "assistant", content: message.content,
216
211
  ...(reasoning ? { reasoning } : {}), ...(reasoningDetails.length ? { reasoning_details: reasoningDetails } : {}),
217
212
  ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
218
213
  yield event;
219
- } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; }
214
+ } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(), diagnostic: { provider: diagnosticProvider, category: "transport" } }; }
220
215
  finally { if (endpoint || profile) void reader.cancel().catch(() => {}); reader.releaseLock(); }
221
216
  };
222
217
  }
@@ -1,14 +1,40 @@
1
+ import { parseContextLimitFailure } from "../../contracts/context.ts";
1
2
  import type { ModelAttempt, ModelAttemptEvent, ModelCallStore, ModelExecutionSettings, ModelRequest, ModelResponse, CallOutcome } from "../../contracts/model-execution.ts";
2
3
  import type { StorageResult, TimelineEntry } from "../../contracts/storage.ts";
3
4
 
4
5
  /** One deadline covers the first attempt, retry wait and retry. */
5
6
  export const MODEL_EXECUTION_DEFAULTS: Readonly<ModelExecutionSettings> = { timeoutMs: 120_000, retryDelayMs: 1_000, maxRetries: 1 };
6
7
  export class ModelCallError extends Error {
8
+ readonly turnFailureDetail?: string;
7
9
  constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string,
8
10
  readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
9
11
  readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
10
- readonly providerFailure?: string) { super(message); this.name = "ModelCallError"; }
12
+ readonly providerFailure?: string) {
13
+ super(message);
14
+ this.name = "ModelCallError";
15
+ const detail = Array.from(message.replace(/[\p{Cc}\p{Cf}]/gu, " ").trim().slice(0, 480)).slice(0, 240).join("");
16
+ if (!providerFailure && detail && detail !== outcome) this.turnFailureDetail = detail;
17
+ }
18
+ }
19
+ function safeDiagnostic(event: Extract<ModelAttemptEvent, { type: "failure" }>): string {
20
+ const diagnostic = event.diagnostic;
21
+ const provider = diagnostic?.provider === "openrouter" ? "OpenRouter"
22
+ : diagnostic?.provider === "chat_completions" ? "Chat Completions" : undefined;
23
+ if (provider && diagnostic) {
24
+ if (diagnostic.category === "http" && Number.isInteger(diagnostic.status) && diagnostic.status >= 400 && diagnostic.status <= 599)
25
+ return `${provider} HTTP ${diagnostic.status}`;
26
+ if (diagnostic.category === "transport") return `${provider} transport failed`;
27
+ if (diagnostic.category === "redirect") return `${provider} redirect refused`;
28
+ if (diagnostic.category === "protocol") return `${provider} returned an invalid response`;
29
+ }
30
+ switch (event.kind) {
31
+ case "transient": return "Temporary model provider failure";
32
+ case "invalid_request": return "Model provider rejected the request";
33
+ case "invalid_config": return "Model provider configuration failed";
34
+ default: return "Model provider failed";
35
+ }
11
36
  }
37
+
12
38
  class ModelStorageError extends Error {}
13
39
  function take<T>(result: StorageResult<T>): T {
14
40
  if (!result.ok) throw new ModelStorageError(`Model call storage ${result.error.code}: ${result.error.message}`);
@@ -81,7 +107,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
81
107
  if (event.type === "text_delta") { output = true; options.delta?.({ messageId: call.messageId, text: event.text }); }
82
108
  } else if (event.type === "usage") take(options.store.recordUsage(call.callId, attempt.attemptId, event.usage));
83
109
  }
84
- } catch (error) { if (error instanceof ModelStorageError) throw error; terminal = { type: "failure", kind: "provider", message: String(error) }; }
110
+ } catch (error) { if (error instanceof ModelStorageError) throw error; terminal = { type: "failure", kind: "provider", message: "Model attempt failed unexpectedly" }; }
85
111
  finally { clearTimeout(timer); options.signal?.removeEventListener("abort", abort); controller.abort(); }
86
112
  if (options.signal?.aborted || cancellation === "interrupted") {
87
113
  // The lifecycle transaction may already have ended this call. In that
@@ -91,11 +117,11 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
91
117
  take(ended); return finish("interrupted");
92
118
  }
93
119
  if (Date.now() >= deadline || cancellation === "timeout") {
94
- take(options.store.finishAttempt(call.callId, attempt.attemptId, "timeout")); return finish("timeout");
120
+ take(options.store.finishAttempt(call.callId, attempt.attemptId, "timeout")); return finish("timeout", "Model request deadline exceeded");
95
121
  }
96
122
  if (terminal?.type === "response") {
97
123
  if (terminal.providerRequestId) take(options.store.recordProviderRequestId(call.callId, attempt.attemptId, terminal.providerRequestId));
98
- if (!validResponse(terminal.response)) { take(options.store.finishAttempt(call.callId, attempt.attemptId, "invalid_request")); return finish("failed"); }
124
+ if (!validResponse(terminal.response)) { take(options.store.finishAttempt(call.callId, attempt.attemptId, "invalid_request")); return finish("failed", "Invalid model response"); }
99
125
  const result = options.store.confirm(call.callId, attempt.attemptId, "seen"); const items = take(result); if (result.ok && items.length) options.receipt?.("seen", items, result.revision);
100
126
  if (terminal.response.stopReason === "output_limit") { take(options.store.finishAttempt(call.callId, attempt.attemptId, "output_limit")); return finish("output_limit"); }
101
127
  const committed = options.store.commitResponse(call.callId, attempt.attemptId, terminal.response, terminal.providerRequestId);
@@ -108,20 +134,33 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
108
134
  const attemptOutcome = failure === "transient" ? "transient_failure" : failure === "provider" ? "provider_failure" : failure;
109
135
  take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
110
136
  if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
111
- if (terminal?.type === "failure" && terminal.code) return finish("failed", terminal.message, { code: terminal.code, attachmentIds: [...terminal.attachmentIds ?? []] });
112
- if (terminal?.type === "failure" && terminal.contextFailure) return finish("failed", terminal.message, undefined, terminal.contextFailure);
137
+ if (terminal?.type === "failure" && (terminal.code === "unsupported_image" || terminal.code === "attachment_unavailable" || terminal.code === "transfer_limit")) {
138
+ const ids = new Set(request.messages.flatMap(message => "parts" in message
139
+ ? (message.parts ?? []).flatMap(part => part.type === "attachment" ? [part.id] : []) : []));
140
+ return finish("failed", "Model attachment rejected", { code: terminal.code,
141
+ attachmentIds: [...new Set((terminal.attachmentIds ?? []).filter(id => ids.has(id)))] });
142
+ }
143
+ if (terminal?.type === "failure" && terminal.contextFailure) {
144
+ const context = parseContextLimitFailure(`context_limit:${JSON.stringify(terminal.contextFailure)}`);
145
+ if (context) return finish("failed", "Model context limit exceeded", undefined, context);
146
+ }
113
147
  if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) {
114
- const providerFailure = terminal?.type === "failure" ? terminal.providerFailure : undefined;
115
- return finish(failure === "incomplete" ? "incomplete" : "failed", providerFailure, undefined, undefined, providerFailure);
148
+ const candidate = terminal?.type === "failure" ? terminal.providerFailure : undefined;
149
+ const providerFailure = typeof candidate === "string" &&
150
+ /^OpenCode Go HTTP (?:[45][0-9]{2}(?: \((?:missing_session_id|invalid_api_key|access_denied|rate_limited)\))?|3[0-9]{2} \(redirect_refused\))$/.test(candidate)
151
+ ? candidate : undefined;
152
+ return finish(failure === "incomplete" ? "incomplete" : "failed",
153
+ providerFailure ?? (terminal?.type === "failure" ? safeDiagnostic(terminal) : "Model response ended before completion"),
154
+ undefined, undefined, providerFailure);
116
155
  }
117
- if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
156
+ if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout", "Model request deadline exceeded");
118
157
  const delay = await new Promise<"ready" | "interrupted">(resolve => {
119
158
  const done = (result: "ready" | "interrupted") => { clearTimeout(wait); options.signal?.removeEventListener("abort", interrupted); resolve(result); };
120
159
  const interrupted = () => done("interrupted"); const wait = setTimeout(() => done("ready"), settings.retryDelayMs);
121
160
  options.signal?.addEventListener("abort", interrupted, { once: true }); if (options.signal?.aborted) interrupted();
122
161
  });
123
162
  if (delay === "interrupted") return finish("interrupted");
124
- if (Date.now() >= deadline) return finish("timeout");
163
+ if (Date.now() >= deadline) return finish("timeout", "Model request deadline exceeded");
125
164
  }
126
165
  return finish("failed");
127
166
  }
@@ -34,9 +34,10 @@ export type ModelAttemptEvent =
34
34
  | { type: "failure"; kind: "transient" | "invalid_request" | "invalid_config" | "provider"; message: string; providerRequestId?: string;
35
35
  code?: "unsupported_image" | "attachment_unavailable" | "transfer_limit"; attachmentIds?: readonly string[];
36
36
  contextFailure?: import("./context.ts").ContextLimitFailure;
37
- /** Safe provider diagnosis for the turn outcome. Adapters must construct
38
- * this from fixed labels and status codes, never from the response body. */
39
- providerFailure?: string };
37
+ providerFailure?: string;
38
+ /** Only validated provider/category/status values may enter durable diagnostics. */
39
+ diagnostic?: { provider: "openrouter" | "chat_completions"; category: "http"; status: number }
40
+ | { provider: "openrouter" | "chat_completions"; category: "transport" | "redirect" | "protocol" } };
40
41
  /** One attempt emits exactly one terminal response or failure unless aborted;
41
42
  * EOF without a terminal is incomplete. A consumer ignores events after the
42
43
  * first terminal, timeout or abort. The adapter assembles and validates tools. */
@@ -188,7 +188,8 @@ export function createChannelScheduler(
188
188
  // Record the failure unless stop already ended the turn; either way the
189
189
  // channel stays usable.
190
190
  const attachmentFailure = error && typeof error === "object" && "attachmentFailure" in error ? error.attachmentFailure as import("../contracts/attachments.ts").AttachmentFailure | undefined : undefined;
191
- const outcome = attachmentFailure ? attachmentFailureReason(attachmentFailure) : error && typeof error === "object" && "outcome" in error && typeof error.outcome === "string" ? error.outcome : String(error);
191
+ const outcome = attachmentFailure ? attachmentFailureReason(attachmentFailure) : error && typeof error === "object" && "outcome" in error && typeof error.outcome === "string" ? ("turnFailureDetail" in error && typeof error.turnFailureDetail === "string" ? `${error.outcome}: ${error.turnFailureDetail}` : error.outcome)
192
+ : String(error);
192
193
  const failed = storage.finishTurn(turnId, { status: "failed", reason: outcome });
193
194
  release();
194
195
  if (failed.ok && failed.value.finished) { ended(failed.value.turn, failed.revision); settleChannel(channelId, failed.revision); }