acpx 0.19.4 → 0.19.5
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/dist/{cli-DCtHeMEi.js → cli-CQtZNbI4.js} +4 -4
- package/dist/{cli-DCtHeMEi.js.map → cli-CQtZNbI4.js.map} +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +9 -9
- package/dist/cli.js.map +1 -1
- package/dist/{client-DqCXdF0Q.d.ts → client-zT_kgYGW.d.ts} +2 -2
- package/dist/{client-DqCXdF0Q.d.ts.map → client-zT_kgYGW.d.ts.map} +1 -1
- package/dist/{flows--1zpaEh9.js → flows-Clk_mTYy.js} +4 -4
- package/dist/{flows--1zpaEh9.js.map → flows-Clk_mTYy.js.map} +1 -1
- package/dist/flows.d.ts +2 -2
- package/dist/flows.js +1 -1
- package/dist/{invocation-options-CvkenzCc.js → invocation-options-iM1Cc2A1.js} +4 -4
- package/dist/{invocation-options-CvkenzCc.js.map → invocation-options-iM1Cc2A1.js.map} +1 -1
- package/dist/{ipc-D7zT86b9.js → ipc-C96eDxkW.js} +95 -14
- package/dist/ipc-C96eDxkW.js.map +1 -0
- package/dist/{output-lylSoEBd.js → output-DnEPVCtT.js} +71 -11
- package/dist/output-DnEPVCtT.js.map +1 -0
- package/dist/{queue-owner-runtime-C0wIYowh.js → queue-owner-runtime-DoijBCvt.js} +64 -22
- package/dist/queue-owner-runtime-DoijBCvt.js.map +1 -0
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -3
- package/dist/runtime.js.map +1 -1
- package/dist/{session-options-X7LhX9BF.d.ts → session-options-CkcvthCv.d.ts} +2 -1
- package/dist/{session-options-X7LhX9BF.d.ts.map → session-options-CkcvthCv.d.ts.map} +1 -1
- package/dist/{session-watch-DPOwDRf8.js → session-watch-2CKSvPIS.js} +4 -4
- package/dist/{session-watch-DPOwDRf8.js.map → session-watch-2CKSvPIS.js.map} +1 -1
- package/dist/{watch-H7rNOJtv.js → watch-pnPd9LCw.js} +2 -2
- package/dist/{watch-H7rNOJtv.js.map → watch-pnPd9LCw.js.map} +1 -1
- package/package.json +4 -5
- package/skills/acpx/SKILL.md +2 -0
- package/dist/ipc-D7zT86b9.js.map +0 -1
- package/dist/output-lylSoEBd.js.map +0 -1
- package/dist/queue-owner-runtime-C0wIYowh.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as findSession, I as pruneSessions, N as listSessions, P as listSessionsForAgent, ct as
|
|
2
|
-
import { C as setSessionModeOnOwner, S as setSessionMode, T as setSessionModelOnOwner, _ as cancelSessionPrompt, a as runQueuedTask, at as normalizeQueueOwnerTtlMs, b as setSessionConfigOption, dt as TimeoutError, g as listAgentSessions, h as ensureSession, i as runOnce, it as DEFAULT_QUEUE_OWNER_TTL_MS, m as createSessionWithClient, n as runSessionQueueOwner, o as sendSessionDirect, p as createSession, r as sendSession, t as queueOwnerRuntimeTestInternals, ut as InterruptedError, v as closeSession, w as setSessionModel, x as setSessionConfigOptionOnOwner, y as sessionControlTestInternals } from "./queue-owner-runtime-
|
|
1
|
+
import { A as findSession, I as pruneSessions, N as listSessions, P as listSessionsForAgent, St as isProcessAlive, ct as parsePermissionNotice, j as findSessionByDirectoryWalk, k as findGitRepositoryRoot, lt as parsePromptStopReason, rt as extractSessionUpdateNotification, st as parseJsonRpcErrorMessage } from "./ipc-C96eDxkW.js";
|
|
2
|
+
import { C as setSessionModeOnOwner, S as setSessionMode, T as setSessionModelOnOwner, _ as cancelSessionPrompt, a as runQueuedTask, at as normalizeQueueOwnerTtlMs, b as setSessionConfigOption, dt as TimeoutError, g as listAgentSessions, h as ensureSession, i as runOnce, it as DEFAULT_QUEUE_OWNER_TTL_MS, m as createSessionWithClient, n as runSessionQueueOwner, o as sendSessionDirect, p as createSession, r as sendSession, t as queueOwnerRuntimeTestInternals, ut as InterruptedError, v as closeSession, w as setSessionModel, x as setSessionConfigOptionOnOwner, y as sessionControlTestInternals } from "./queue-owner-runtime-DoijBCvt.js";
|
|
3
3
|
//#region \0rolldown/runtime.js
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
5
5
|
var __exportAll = (all, no_symbols) => {
|
|
@@ -545,8 +545,47 @@ function summarizeToolInputJson(rawInput) {
|
|
|
545
545
|
const json = safeJson(rawInput, 0);
|
|
546
546
|
return json ? toInline(json) : void 0;
|
|
547
547
|
}
|
|
548
|
+
function malformedToolUpdateMessage(update) {
|
|
549
|
+
if (update.locations != null && !validToolLocations(update.locations)) return "Malformed tool call locations";
|
|
550
|
+
return malformedToolContentMessage(update.content);
|
|
551
|
+
}
|
|
552
|
+
function validToolLocations(locations) {
|
|
553
|
+
return Array.isArray(locations) && locations.every(validToolLocation);
|
|
554
|
+
}
|
|
555
|
+
function validToolLocation(location) {
|
|
556
|
+
const record = asRecord(location);
|
|
557
|
+
if (!record) return false;
|
|
558
|
+
if (record.path != null && typeof record.path !== "string") return false;
|
|
559
|
+
return record.line == null || typeof record.line === "number" && Number.isFinite(record.line);
|
|
560
|
+
}
|
|
561
|
+
function malformedToolContentMessage(content) {
|
|
562
|
+
if (content == null) return;
|
|
563
|
+
if (!Array.isArray(content)) return "Malformed tool call content";
|
|
564
|
+
for (const entry of content) {
|
|
565
|
+
const error = malformedToolContentEntry(entry);
|
|
566
|
+
if (error) return error;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
function malformedToolContentEntry(entry) {
|
|
570
|
+
const record = asRecord(entry);
|
|
571
|
+
if (!record) return "Malformed tool call content";
|
|
572
|
+
if (record.type === "diff") return malformedDiffMessage(record);
|
|
573
|
+
if (record.type === "content" && !validToolContentBlock(record.content)) return "Malformed tool call content";
|
|
574
|
+
if (record.type === "terminal" && typeof record.terminalId !== "string") return "Malformed tool call content";
|
|
575
|
+
}
|
|
576
|
+
function malformedDiffMessage(record) {
|
|
577
|
+
if (typeof record.path === "string" && typeof record.newText === "string" && (record.oldText == null || typeof record.oldText === "string")) return;
|
|
578
|
+
return "Malformed tool call diff";
|
|
579
|
+
}
|
|
580
|
+
function validToolContentBlock(content) {
|
|
581
|
+
const block = asRecord(content);
|
|
582
|
+
if (!block || typeof block.type !== "string") return false;
|
|
583
|
+
if (block.type === "text") return typeof block.text === "string";
|
|
584
|
+
if (block.type === "resource") return asRecord(block.resource) !== void 0;
|
|
585
|
+
return true;
|
|
586
|
+
}
|
|
548
587
|
function formatLocations(locations) {
|
|
549
|
-
if (!locations || locations.length === 0) return;
|
|
588
|
+
if (!Array.isArray(locations) || locations.length === 0) return;
|
|
550
589
|
const unique = /* @__PURE__ */ new Set();
|
|
551
590
|
for (const location of locations) {
|
|
552
591
|
const formatted = formatLocation(location);
|
|
@@ -560,7 +599,10 @@ function formatLocations(locations) {
|
|
|
560
599
|
return `${visible.join(", ")}, +${hidden} more`;
|
|
561
600
|
}
|
|
562
601
|
function formatLocation(location) {
|
|
563
|
-
|
|
602
|
+
if (!location || typeof location !== "object") return;
|
|
603
|
+
const rawPath = location.path;
|
|
604
|
+
if (typeof rawPath !== "string") return;
|
|
605
|
+
const path = rawPath.trim();
|
|
564
606
|
if (!path) return;
|
|
565
607
|
return `${path}${typeof location.line === "number" && Number.isFinite(location.line) ? `:${Math.max(1, Math.trunc(location.line))}` : ""}`;
|
|
566
608
|
}
|
|
@@ -581,13 +623,14 @@ function textFromContentBlock(content) {
|
|
|
581
623
|
}
|
|
582
624
|
}
|
|
583
625
|
function textFromResourceBlock(content) {
|
|
626
|
+
if (!content.resource || typeof content.resource !== "object") return "[resource]";
|
|
584
627
|
if ("text" in content.resource && typeof content.resource.text === "string") return content.resource.text;
|
|
585
628
|
const uri = content.resource.uri;
|
|
586
629
|
const mimeType = content.resource.mimeType;
|
|
587
630
|
return `[resource] ${uri}${mimeType ? ` (${mimeType})` : ""}`;
|
|
588
631
|
}
|
|
589
632
|
function summarizeToolContent(content) {
|
|
590
|
-
if (!content || content.length === 0) return;
|
|
633
|
+
if (!Array.isArray(content) || content.length === 0) return;
|
|
591
634
|
const fragments = [];
|
|
592
635
|
for (const entry of content) {
|
|
593
636
|
const fragment = summarizeToolContentEntry(entry);
|
|
@@ -598,13 +641,21 @@ function summarizeToolContent(content) {
|
|
|
598
641
|
return unique.join("\n\n");
|
|
599
642
|
}
|
|
600
643
|
function summarizeToolContentEntry(entry) {
|
|
601
|
-
if (entry
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
}
|
|
605
|
-
if (entry.type === "diff") return summarizeDiff(entry.path, entry.oldText, entry.newText);
|
|
644
|
+
if (!entry || typeof entry !== "object") return;
|
|
645
|
+
if (entry.type === "content") return summarizeContentEntry(entry);
|
|
646
|
+
if (entry.type === "diff") return summarizeDiffEntry(entry);
|
|
606
647
|
if (entry.type === "terminal") return `[terminal] ${entry.terminalId}`;
|
|
607
648
|
}
|
|
649
|
+
function summarizeContentEntry(entry) {
|
|
650
|
+
if (!entry.content || typeof entry.content !== "object") return;
|
|
651
|
+
const text = textFromContentBlock(entry.content);
|
|
652
|
+
return typeof text === "string" && text.trim() ? text.trimEnd() : void 0;
|
|
653
|
+
}
|
|
654
|
+
function summarizeDiffEntry(entry) {
|
|
655
|
+
if (typeof entry.path !== "string" || typeof entry.newText !== "string") return;
|
|
656
|
+
const oldText = typeof entry.oldText === "string" ? entry.oldText : void 0;
|
|
657
|
+
return summarizeDiff(entry.path, oldText, entry.newText);
|
|
658
|
+
}
|
|
608
659
|
function extractOutputText(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
|
|
609
660
|
if (value == null) return;
|
|
610
661
|
const scalar = extractScalarOutputText(value);
|
|
@@ -811,6 +862,15 @@ var TextOutputFormatter = class {
|
|
|
811
862
|
for (const line of restLines) this.writeLine(this.dim(` ${line}`));
|
|
812
863
|
}
|
|
813
864
|
renderToolUpdate(update) {
|
|
865
|
+
const shapeError = malformedToolUpdateMessage(update);
|
|
866
|
+
if (shapeError) {
|
|
867
|
+
this.onError({
|
|
868
|
+
code: "RUNTIME",
|
|
869
|
+
origin: "acp",
|
|
870
|
+
message: shapeError
|
|
871
|
+
});
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
814
874
|
const state = this.getOrCreateToolState(update.toolCallId);
|
|
815
875
|
this.mergeToolState(state, update);
|
|
816
876
|
const status = asStatus(state.status);
|
|
@@ -1009,4 +1069,4 @@ function createOutputFormatter(format, options = {}) {
|
|
|
1009
1069
|
//#endregion
|
|
1010
1070
|
export { MAX_TIMER_DELAY_MS as a, __exportAll as c, JsonMessageSanitizer as i, getTextErrorRemediationHints as n, toTimerMilliseconds as o, output_exports as r, session_exports as s, createOutputFormatter as t };
|
|
1011
1071
|
|
|
1012
|
-
//# sourceMappingURL=output-
|
|
1072
|
+
//# sourceMappingURL=output-DnEPVCtT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"output-DnEPVCtT.js","names":["asRecord"],"sources":["../src/session/session.ts","../src/cli/timer-duration.ts","../src/acp/jsonrpc-error.ts","../src/cli/output/read-suppression.ts","../src/cli/output/json-formatter.ts","../src/cli/output/output.ts"],"sourcesContent":["export * from \"./execution/contracts.js\";\nexport * from \"./execution/session-management.js\";\nexport * from \"./execution/queue-owner-runtime.js\";\nexport * from \"./execution/session-control.js\";\nexport * from \"./execution/runtime.js\";\nexport {\n DEFAULT_HISTORY_LIMIT,\n findGitRepositoryRoot,\n findSession,\n findSessionByDirectoryWalk,\n listSessions,\n listSessionsForAgent,\n pruneSessions,\n} from \"./persistence.js\";\nexport type { PruneOptions, PruneResult } from \"./persistence.js\";\nexport { isProcessAlive } from \"../process-liveness.js\";\n","export const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\nexport function toTimerMilliseconds(seconds: number, allowZero: boolean): number | undefined {\n if (allowZero && seconds === 0) {\n return 0;\n }\n const milliseconds = Math.max(1, Math.round(seconds * 1000));\n return milliseconds <= MAX_TIMER_DELAY_MS ? milliseconds : undefined;\n}\n","import type { OutputErrorAcpPayload, OutputErrorCode, OutputErrorOrigin } from \"../types.js\";\n\nexport const OUTPUT_ERROR_JSONRPC_CODES: Record<OutputErrorCode, number> = {\n NO_SESSION: -32002,\n TIMEOUT: -32070,\n PERMISSION_DENIED: -32071,\n PERMISSION_PROMPT_UNAVAILABLE: -32072,\n EXEC_DISABLED: -32603,\n RUNTIME: -32603,\n USAGE: -32602,\n};\n\ntype JsonRpcErrorObject = {\n code: number;\n message: string;\n data?: unknown;\n};\n\nexport type BuildJsonRpcErrorParams = {\n id?: string | number | null;\n outputCode: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n message: string;\n retryable?: boolean;\n timestamp?: string;\n sessionId?: string;\n acp?: OutputErrorAcpPayload;\n};\n\nfunction hasValidAcpError(\n acp: OutputErrorAcpPayload | undefined,\n): acp is { code: number; message: string; data?: unknown } {\n return Boolean(\n acp &&\n Number.isFinite(acp.code) &&\n typeof acp.message === \"string\" &&\n acp.message.trim().length > 0,\n );\n}\n\nfunction buildFallbackData(params: BuildJsonRpcErrorParams): Record<string, unknown> {\n const data: Record<string, unknown> = {\n acpxCode: params.outputCode,\n detailCode: params.detailCode,\n origin: params.origin,\n retryable: params.retryable,\n timestamp: params.timestamp,\n sessionId: params.sessionId,\n };\n\n for (const [key, value] of Object.entries(data)) {\n if (value === undefined) {\n delete data[key];\n }\n }\n\n return data;\n}\n\nfunction mergeAcpErrorData(acpData: unknown, fallbackData: Record<string, unknown>): unknown {\n if (Object.keys(fallbackData).length === 0) {\n return acpData;\n }\n if (acpData === undefined) {\n return fallbackData;\n }\n if (acpData && typeof acpData === \"object\" && !Array.isArray(acpData)) {\n return {\n ...fallbackData,\n ...acpData,\n };\n }\n return acpData;\n}\n\nfunction buildErrorObject(params: BuildJsonRpcErrorParams): JsonRpcErrorObject {\n const fallbackData = buildFallbackData(params);\n if (hasValidAcpError(params.acp)) {\n const data = mergeAcpErrorData(params.acp.data, fallbackData);\n return {\n code: params.acp.code,\n message: params.acp.message,\n ...(data !== undefined ? { data } : {}),\n };\n }\n\n const data = fallbackData;\n return {\n code: OUTPUT_ERROR_JSONRPC_CODES[params.outputCode] ?? -32603,\n message: params.message,\n ...(Object.keys(data).length > 0 ? { data } : {}),\n };\n}\n\nexport function buildJsonRpcErrorResponse(params: BuildJsonRpcErrorParams): {\n jsonrpc: \"2.0\";\n id: string | number | null;\n error: JsonRpcErrorObject;\n} {\n return {\n jsonrpc: \"2.0\",\n id: params.id ?? null,\n error: buildErrorObject(params),\n };\n}\n","export const SUPPRESSED_READ_OUTPUT = \"[read output suppressed]\";\n\nexport type ReadLikeToolDescriptor = {\n title?: string;\n kind?: string | null;\n};\n\nfunction inferToolKindFromTitle(title: string | undefined): string | undefined {\n const normalized = title?.trim().toLowerCase();\n if (!normalized) {\n return undefined;\n }\n\n const head = normalized.split(/[:\\s]/, 1)[0];\n if (!head) {\n return undefined;\n }\n\n if ([\"read\", \"cat\", \"open\", \"view\"].includes(head)) {\n return \"read\";\n }\n\n return undefined;\n}\n\nexport function isReadLikeTool(tool: ReadLikeToolDescriptor): boolean {\n return (\n tool.kind?.trim().toLowerCase() === \"read\" || inferToolKindFromTitle(tool.title) === \"read\"\n );\n}\n","import { buildJsonRpcErrorResponse } from \"../../acp/jsonrpc-error.js\";\nimport type {\n AcpMessageDirection,\n OutputErrorAcpPayload,\n OutputErrorCode,\n OutputErrorOrigin,\n OutputFormatter,\n OutputFormatterContext,\n} from \"../../types.js\";\nimport { isReadLikeTool, SUPPRESSED_READ_OUTPUT } from \"./read-suppression.js\";\n\ntype WritableLike = {\n write(chunk: string): void;\n};\n\ntype JsonRpcRequestMessage = {\n jsonrpc?: unknown;\n id?: unknown;\n method?: unknown;\n};\n\ntype JsonRpcResponseMessage = {\n jsonrpc?: unknown;\n id?: unknown;\n result?: unknown;\n error?: unknown;\n};\n\nconst DEFAULT_JSON_SESSION_ID = \"unknown\";\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n return value as Record<string, unknown>;\n}\n\nfunction jsonRpcIdKey(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n return `s:${value}`;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return `n:${value}`;\n }\n return undefined;\n}\n\nfunction requestCorrelationKey(\n id: unknown,\n direction: AcpMessageDirection | undefined,\n): string | undefined {\n const idKey = jsonRpcIdKey(id);\n return idKey === undefined ? undefined : `${direction ?? \"unknown\"}:${idKey}`;\n}\n\nfunction reverseDirection(\n direction: AcpMessageDirection | undefined,\n): AcpMessageDirection | undefined {\n if (direction === undefined) {\n return undefined;\n }\n return direction === \"inbound\" ? \"outbound\" : \"inbound\";\n}\n\nfunction sanitizeReadResult(result: unknown): unknown {\n const record = asRecord(result);\n if (!record || typeof record.content !== \"string\") {\n return result;\n }\n return {\n ...record,\n content: SUPPRESSED_READ_OUTPUT,\n };\n}\n\nfunction sanitizeToolContent(content: unknown): unknown {\n if (!Array.isArray(content)) {\n return content;\n }\n\n return [\n {\n type: \"content\",\n content: {\n type: \"text\",\n text: SUPPRESSED_READ_OUTPUT,\n },\n },\n ];\n}\n\nfunction sanitizeToolMessage(message: unknown): unknown {\n const root = asRecord(message);\n const params = asRecord(root?.params);\n const update = asRecord(params?.update);\n if (!root || !params || !update) {\n return message;\n }\n\n return {\n ...root,\n params: {\n ...params,\n update: sanitizeToolUpdate(update),\n },\n };\n}\n\nfunction sanitizeToolUpdate(update: Record<string, unknown>): Record<string, unknown> {\n return {\n ...update,\n rawOutput: sanitizedRawOutput(update),\n content: sanitizedContent(update),\n };\n}\n\nfunction sanitizedRawOutput(update: Record<string, unknown>): unknown {\n if (Object.prototype.hasOwnProperty.call(update, \"rawOutput\") && update.rawOutput !== undefined) {\n return { content: SUPPRESSED_READ_OUTPUT };\n }\n return update.rawOutput;\n}\n\nfunction sanitizedContent(update: Record<string, unknown>): unknown {\n if (Object.prototype.hasOwnProperty.call(update, \"content\") && update.content !== undefined) {\n return sanitizeToolContent(update.content);\n }\n return update.content;\n}\n\nexport class JsonMessageSanitizer {\n private readonly requestMethodById = new Map<string, string>();\n private readonly toolStateById = new Map<string, { title?: string; kind?: string | null }>();\n\n constructor(\n private readonly suppressReads: boolean,\n private readonly partialHistory = false,\n ) {}\n\n sanitize(message: unknown, direction?: AcpMessageDirection): unknown {\n if (!this.suppressReads) {\n return message;\n }\n\n const sanitizedResponse = this.sanitizeReadResponse(message, direction);\n if (sanitizedResponse !== message) {\n return sanitizedResponse;\n }\n\n const sanitizedToolMessage = this.sanitizeReadToolMessage(message);\n if (sanitizedToolMessage !== message) {\n return sanitizedToolMessage;\n }\n\n this.trackRequestMethod(message, direction);\n return message;\n }\n\n private trackRequestMethod(message: unknown, direction: AcpMessageDirection | undefined): void {\n const candidate = message as JsonRpcRequestMessage;\n if (typeof candidate.method !== \"string\") {\n return;\n }\n const idKey = requestCorrelationKey(candidate.id, direction);\n if (!idKey) {\n return;\n }\n this.requestMethodById.set(idKey, candidate.method);\n }\n\n private sanitizeReadResponse(\n message: unknown,\n direction: AcpMessageDirection | undefined,\n ): unknown {\n const candidate = message as JsonRpcResponseMessage;\n const idKey = requestCorrelationKey(candidate.id, reverseDirection(direction));\n if (!idKey) {\n return message;\n }\n\n const hasResult = Object.hasOwn(candidate, \"result\");\n const hasError = Object.hasOwn(candidate, \"error\");\n if (!hasResult && !hasError) {\n return message;\n }\n\n const method = this.requestMethodById.get(idKey);\n this.requestMethodById.delete(idKey);\n if (!hasResult || !this.suppressReadResponse(method)) {\n return message;\n }\n\n const root = asRecord(message);\n if (!root) {\n return message;\n }\n\n return {\n ...root,\n result: sanitizeReadResult(candidate.result),\n };\n }\n\n private suppressReadResponse(method: string | undefined): boolean {\n return method === \"fs/read_text_file\" || (this.partialHistory && method === undefined);\n }\n\n private sanitizeReadToolMessage(message: unknown): unknown {\n const update = this.readToolUpdate(message);\n if (!update) {\n return message;\n }\n\n const toolCallId = typeof update.toolCallId === \"string\" ? update.toolCallId : undefined;\n if (!toolCallId) {\n return message;\n }\n\n const current = this.mergeToolState(toolCallId, update);\n this.toolStateById.set(toolCallId, current);\n\n const unclassified = this.partialHistory && !current.kind && !current.title;\n return isReadLikeTool(current) || unclassified ? sanitizeToolMessage(message) : message;\n }\n\n private readToolUpdate(message: unknown): Record<string, unknown> | undefined {\n const root = asRecord(message);\n if (root?.method !== \"session/update\") {\n return undefined;\n }\n const params = asRecord(root.params);\n const update = asRecord(params?.update);\n if (!params || !update) {\n return undefined;\n }\n\n const sessionUpdate = update.sessionUpdate;\n if (sessionUpdate !== \"tool_call\" && sessionUpdate !== \"tool_call_update\") {\n return undefined;\n }\n return update;\n }\n\n private mergeToolState(\n toolCallId: string,\n update: Record<string, unknown>,\n ): { title?: string; kind?: string | null } {\n const previous = this.toolStateById.get(toolCallId) ?? {};\n return {\n title: typeof update.title === \"string\" ? update.title : previous.title,\n kind: typeof update.kind === \"string\" || update.kind === null ? update.kind : previous.kind,\n };\n }\n}\n\nclass JsonOutputFormatter implements OutputFormatter {\n private readonly stdout: WritableLike;\n private readonly sanitizer: JsonMessageSanitizer;\n private sessionId: string;\n\n constructor(stdout: WritableLike, suppressReads: boolean, context?: OutputFormatterContext) {\n this.stdout = stdout;\n this.sanitizer = new JsonMessageSanitizer(suppressReads);\n this.sessionId = context?.sessionId?.trim() || DEFAULT_JSON_SESSION_ID;\n }\n\n setContext(context: OutputFormatterContext): void {\n this.sessionId = context.sessionId?.trim() || this.sessionId || DEFAULT_JSON_SESSION_ID;\n }\n\n onAcpMessage(message: unknown, direction?: AcpMessageDirection): void {\n this.stdout.write(`${JSON.stringify(this.sanitizer.sanitize(message, direction))}\\n`);\n }\n\n onError(params: {\n code: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n message: string;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n timestamp?: string;\n }): void {\n this.stdout.write(\n `${JSON.stringify(\n buildJsonRpcErrorResponse({\n outputCode: params.code,\n detailCode: params.detailCode,\n origin: params.origin,\n message: params.message,\n retryable: params.retryable,\n timestamp: params.timestamp,\n sessionId: this.sessionId,\n acp: params.acp,\n }),\n )}\\n`,\n );\n }\n\n onPermissionEscalation(): void {\n // JSON mode is raw ACP NDJSON. Escalation details ride on the ACP\n // request_permission response _meta instead of a synthetic acpx event line.\n }\n\n flush(): void {\n // no-op for streaming output\n }\n}\n\nexport function createJsonOutputFormatter(\n stdout: WritableLike,\n suppressReads = false,\n context?: OutputFormatterContext,\n): OutputFormatter {\n return new JsonOutputFormatter(stdout, suppressReads, context);\n}\n","import type {\n AnyMessage,\n ContentBlock,\n SessionNotification,\n ToolCall,\n ToolCallContent,\n ToolCallLocation,\n ToolCallStatus,\n ToolCallUpdate,\n} from \"@agentclientprotocol/sdk\";\nimport {\n extractSessionUpdateNotification,\n parseJsonRpcErrorMessage,\n parsePromptStopReason,\n parsePermissionNotice,\n} from \"../../acp/jsonrpc.js\";\nimport type {\n AcpJsonRpcMessage,\n ClientOperation,\n OutputErrorAcpPayload,\n OutputErrorCode,\n OutputFormatterContext,\n OutputFormat,\n OutputFormatter,\n OutputErrorOrigin,\n PermissionEscalationEvent,\n} from \"../../types.js\";\nimport { createJsonOutputFormatter } from \"./json-formatter.js\";\nimport { isReadLikeTool, SUPPRESSED_READ_OUTPUT } from \"./read-suppression.js\";\n\ntype WritableLike = {\n write(chunk: string): void;\n isTTY?: boolean;\n};\n\ntype RenderableOutputError = {\n code: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n message: string;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n timestamp?: string;\n};\n\ntype OutputFormatterOptions = {\n stdout?: WritableLike;\n stderr?: WritableLike;\n jsonContext?: OutputFormatterContext;\n suppressReads?: boolean;\n};\n\ntype NormalizedToolStatus = ToolCallStatus | \"unknown\";\n\ntype ToolRenderState = {\n id: string;\n title?: string;\n status?: ToolCallStatus | null;\n kind?: string | null;\n locations?: Array<ToolCallLocation> | null;\n rawInput?: unknown;\n rawOutput?: unknown;\n content?: Array<ToolCallContent> | null;\n startedPrinted: boolean;\n finalSignature?: string;\n};\n\ntype ToolDisplay = {\n input?: string;\n files?: string;\n output?: string;\n};\n\nconst MAX_THOUGHT_CHARS = 900;\nconst MAX_INLINE_CHARS = 220;\nconst MAX_OUTPUT_CHARS = 2_000;\nconst MAX_OUTPUT_LINES = 28;\nconst MAX_LOCATION_ITEMS = 5;\nconst OUTPUT_PRIORITY_KEYS = [\n \"stdout\",\n \"stderr\",\n \"output\",\n \"content\",\n \"text\",\n \"message\",\n \"result\",\n \"response\",\n \"value\",\n] as const;\n\nfunction asStatus(status: ToolCallStatus | null | undefined): NormalizedToolStatus {\n return status ?? \"unknown\";\n}\n\nfunction isFinalStatus(status: NormalizedToolStatus): status is \"completed\" | \"failed\" {\n return status === \"completed\" || status === \"failed\";\n}\n\nfunction toStatusLabel(status: NormalizedToolStatus): string {\n return isFinalStatus(status) || status === \"pending\" ? status : \"running\";\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n return value as Record<string, unknown>;\n}\n\nfunction parseJsonRpcErrorSummary(message: AcpJsonRpcMessage): string | undefined {\n const fallback = parseJsonRpcErrorMessage(message);\n if (!fallback) {\n return undefined;\n }\n\n const error = asRecord((message as { error?: unknown }).error);\n const details = asRecord(error?.data)?.details;\n return typeof details === \"string\" && details.trim().length > 0 ? details.trim() : fallback;\n}\n\nfunction extractJsonRpcMethod(message: AnyMessage): string | undefined {\n return Object.hasOwn(message, \"method\")\n ? (message as { method?: unknown }).method?.toString()\n : undefined;\n}\n\nfunction collapseWhitespace(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nfunction normalizeLineEndings(value: string): string {\n return value.replace(/\\r\\n?/g, \"\\n\");\n}\n\nfunction truncate(value: string, maxChars: number): string {\n if (value.length <= maxChars) {\n return value;\n }\n if (maxChars <= 3) {\n return value.slice(0, maxChars);\n }\n return `${value.slice(0, maxChars - 3)}...`;\n}\n\nfunction toInline(value: string, maxChars = MAX_INLINE_CHARS): string {\n return truncate(collapseWhitespace(value), maxChars);\n}\n\nfunction indentBlock(value: string, prefix: string): string {\n return value\n .split(\"\\n\")\n .map((line) => `${prefix}${line}`)\n .join(\"\\n\");\n}\n\nfunction dedupeStrings(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction safeJson(value: unknown, spacing: number): string | undefined {\n const seen = new WeakSet();\n\n try {\n return JSON.stringify(\n value,\n (_key, entry: unknown) => {\n if (typeof entry === \"bigint\") {\n return `${entry}n`;\n }\n if (typeof entry === \"function\") {\n return `[Function ${entry.name || \"anonymous\"}]`;\n }\n if (typeof entry === \"symbol\") {\n return entry.toString();\n }\n if (entry && typeof entry === \"object\") {\n if (seen.has(entry)) {\n return \"[Circular]\";\n }\n seen.add(entry);\n }\n return entry;\n },\n spacing,\n );\n } catch {\n return undefined;\n }\n}\n\nfunction readFirstString(source: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = source[key];\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n }\n return undefined;\n}\n\nfunction readFirstFiniteNumber(\n source: Record<string, unknown>,\n keys: string[],\n): number | undefined {\n for (const key of keys) {\n const value = source[key];\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction formatMetadataNumber(value: number): string {\n return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(8)));\n}\n\nfunction readFirstStringArray(\n source: Record<string, unknown>,\n keys: string[],\n): string[] | undefined {\n for (const key of keys) {\n const value = source[key];\n if (!Array.isArray(value)) {\n continue;\n }\n const entries = value\n .map((entry) => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter((entry) => entry.length > 0);\n if (entries.length > 0) {\n return entries;\n }\n }\n return undefined;\n}\n\nfunction formatDisjunction(values: string[]): string {\n if (values.length <= 1) {\n return values[0] ?? \"\";\n }\n if (values.length === 2) {\n return `${values[0]} or ${values[1]}`;\n }\n return `${values.slice(0, -1).join(\", \")}, or ${values.at(-1)}`;\n}\n\nfunction parseAuthMethodIdsFromMessage(message: string): string[] {\n const methods: string[] = [];\n const methodListMatch = message.match(/auth methods \\[([^\\]]+)\\]/iu);\n if (methodListMatch) {\n methods.push(\n ...methodListMatch[1]\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0),\n );\n }\n\n const singleMethodMatch = message.match(/auth method ([\\w.-]+)/iu);\n if (singleMethodMatch) {\n methods.push(singleMethodMatch[1]);\n }\n\n return dedupeStrings(methods);\n}\n\nfunction parseAuthMethodIdsFromAcpData(data: unknown): string[] {\n const record = asRecord(data);\n if (!record) {\n return [];\n }\n\n const methodIds: string[] = [];\n if (typeof record.methodId === \"string\" && record.methodId.trim().length > 0) {\n methodIds.push(record.methodId.trim());\n }\n\n if (Array.isArray(record.methods)) {\n for (const entry of record.methods) {\n const id = parseAuthMethodIdEntry(entry);\n if (id) {\n methodIds.push(id);\n }\n }\n }\n\n return dedupeStrings(methodIds);\n}\n\nfunction parseAuthMethodIdEntry(entry: unknown): string | undefined {\n if (typeof entry === \"string\" && entry.trim().length > 0) {\n return entry.trim();\n }\n\n const id = asRecord(entry)?.id;\n return typeof id === \"string\" && id.trim().length > 0 ? id.trim() : undefined;\n}\n\nfunction renderAuthRequiredHint(params: RenderableOutputError): string {\n const methodIds = dedupeStrings([\n ...parseAuthMethodIdsFromAcpData(params.acp?.data),\n ...parseAuthMethodIdsFromMessage(params.message),\n ]);\n\n if (methodIds.length === 0) {\n return \"hint: run `acpx config show` to locate the active config, then add the required credential under `auth` and retry.\";\n }\n\n const configKeys = methodIds.map((methodId) => `\\`auth.${methodId}\\``);\n return `hint: run \\`acpx config show\\` to locate the active config, then add ${formatDisjunction(configKeys)} and retry.`;\n}\n\nexport function getTextErrorRemediationHints(params: RenderableOutputError): string[] {\n const lowerMessage = params.message.toLowerCase();\n\n if (params.detailCode === \"AUTH_REQUIRED\") {\n return [renderAuthRequiredHint(params)];\n }\n\n if (params.code === \"TIMEOUT\") {\n return [\n \"hint: increase `--timeout <seconds>` for long-running prompts, or check whether the agent/provider is stalled.\",\n ];\n }\n\n if (params.code === \"NO_SESSION\") {\n return noSessionHints(lowerMessage);\n }\n\n return matchingTextErrorRule(params, lowerMessage)?.hints ?? [];\n}\n\ntype TextErrorHintRule = {\n matches: (params: RenderableOutputError, lowerMessage: string) => boolean;\n hints: string[];\n};\n\nconst TEXT_ERROR_HINT_RULES: TextErrorHintRule[] = [\n {\n matches: (_params, lowerMessage) => isUnsupportedSessionLoadError(lowerMessage),\n hints: [\n \"hint: this adapter cannot resume saved ACP sessions; create a fresh one with `acpx <agent> sessions new` instead of reusing `--resume-session`.\",\n ],\n },\n {\n matches: (_params, lowerMessage) => isSessionLoadError(lowerMessage),\n hints: [\n \"hint: rerun with `--verbose` to capture the ACP load failure details.\",\n \"hint: if you do not need the old backend session, start a fresh one with `acpx <agent> sessions new` and retry.\",\n ],\n },\n {\n matches: (params, lowerMessage) => isRateLimitError(params.message, lowerMessage),\n hints: [\n \"hint: the provider appears rate-limited; retry later, switch model, or check provider quota/billing.\",\n ],\n },\n {\n matches: (_params, lowerMessage) => isModelLookupError(lowerMessage),\n hints: [\n \"hint: check the configured model name for this agent, then retry with `--model <model>` or `sessions set-model <model>`.\",\n ],\n },\n {\n matches: (_params, lowerMessage) => isSessionConfigMethodError(lowerMessage),\n hints: [\n \"hint: rerun with `--verbose` to capture the ACP method/error details before retrying.\",\n ],\n },\n {\n matches: isRuntimeAcpProtocolError,\n hints: [\"hint: rerun with `--verbose` to capture the underlying ACP error details.\"],\n },\n];\n\nfunction matchingTextErrorRule(\n params: RenderableOutputError,\n lowerMessage: string,\n): TextErrorHintRule | undefined {\n return TEXT_ERROR_HINT_RULES.find((rule) => rule.matches(params, lowerMessage));\n}\n\nfunction noSessionHints(lowerMessage: string): string[] {\n if (lowerMessage.includes(\"create one:\")) {\n return [];\n }\n return [\n \"hint: the saved ACP session is missing or stale; start a fresh session with `acpx <agent> sessions new`, then retry.\",\n ];\n}\n\nfunction isUnsupportedSessionLoadError(lowerMessage: string): boolean {\n return (\n lowerMessage.includes(\"does not support session/resume\") ||\n lowerMessage.includes(\"does not support session/load\")\n );\n}\n\nfunction isSessionLoadError(lowerMessage: string): boolean {\n return (\n lowerMessage.includes(\"failed to resume acp session\") ||\n lowerMessage.includes(\"session/resume\") ||\n lowerMessage.includes(\"session/load\")\n );\n}\n\nfunction isRateLimitError(message: string, lowerMessage: string): boolean {\n return (\n /\\b429\\b/u.test(message) ||\n [\"rate limit\", \"quota exceeded\"].some((text) => lowerMessage.includes(text))\n );\n}\n\nfunction isModelLookupError(lowerMessage: string): boolean {\n return [\"model not found\", \"unknown model\", \"invalid model\"].some((text) =>\n lowerMessage.includes(text),\n );\n}\n\nfunction isSessionConfigMethodError(lowerMessage: string): boolean {\n return [\"session/set_mode\", \"session/set_model\", \"session/set_config_option\"].some((text) =>\n lowerMessage.includes(text),\n );\n}\n\nfunction isRuntimeAcpProtocolError(params: RenderableOutputError, lowerMessage: string): boolean {\n return (\n params.origin === \"acp\" &&\n params.code === \"RUNTIME\" &&\n (params.acp?.code === -32602 ||\n params.acp?.code === -32603 ||\n lowerMessage.includes(\"internal error\"))\n );\n}\n\nfunction summarizeToolInput(rawInput: unknown): string | undefined {\n if (rawInput == null) {\n return undefined;\n }\n\n if (isScalarToolInput(rawInput)) {\n return toInline(String(rawInput));\n }\n\n const record = asRecord(rawInput);\n if (record) {\n return summarizeToolInputRecord(record) ?? summarizeToolInputJson(rawInput);\n }\n\n return summarizeToolInputJson(rawInput);\n}\n\nfunction isScalarToolInput(value: unknown): value is string | number | boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\nfunction summarizeToolInputRecord(record: Record<string, unknown>): string | undefined {\n const command = readFirstString(record, [\"command\", \"cmd\", \"program\"]);\n const args = readFirstStringArray(record, [\"args\", \"arguments\"]);\n if (command) {\n return toInline([command, ...(args ?? [])].join(\" \"));\n }\n\n const location = readFirstString(record, [\n \"path\",\n \"file\",\n \"filePath\",\n \"filepath\",\n \"target\",\n \"uri\",\n \"url\",\n ]);\n const query = readFirstString(record, [\"query\", \"pattern\", \"text\", \"search\"]);\n return location || query ? toInline(location ?? query ?? \"\") : undefined;\n}\n\nfunction summarizeToolInputJson(rawInput: unknown): string | undefined {\n const json = safeJson(rawInput, 0);\n return json ? toInline(json) : undefined;\n}\n\nfunction malformedToolUpdateMessage(update: {\n locations?: unknown;\n content?: unknown;\n}): string | undefined {\n if (update.locations != null && !validToolLocations(update.locations)) {\n return \"Malformed tool call locations\";\n }\n const contentError = malformedToolContentMessage(update.content);\n return contentError;\n}\n\nfunction validToolLocations(locations: unknown): boolean {\n return Array.isArray(locations) && locations.every(validToolLocation);\n}\n\nfunction validToolLocation(location: unknown): boolean {\n const record = asRecord(location);\n if (!record) {\n return false;\n }\n if (record.path != null && typeof record.path !== \"string\") {\n return false;\n }\n return record.line == null || (typeof record.line === \"number\" && Number.isFinite(record.line));\n}\n\nfunction malformedToolContentMessage(content: unknown): string | undefined {\n if (content == null) {\n return undefined;\n }\n if (!Array.isArray(content)) {\n return \"Malformed tool call content\";\n }\n for (const entry of content) {\n const error = malformedToolContentEntry(entry);\n if (error) {\n return error;\n }\n }\n return undefined;\n}\n\nfunction malformedToolContentEntry(entry: unknown): string | undefined {\n const record = asRecord(entry);\n if (!record) {\n return \"Malformed tool call content\";\n }\n if (record.type === \"diff\") {\n return malformedDiffMessage(record);\n }\n if (record.type === \"content\" && !validToolContentBlock(record.content)) {\n return \"Malformed tool call content\";\n }\n if (record.type === \"terminal\" && typeof record.terminalId !== \"string\") {\n return \"Malformed tool call content\";\n }\n return undefined;\n}\n\nfunction malformedDiffMessage(record: Record<string, unknown>): string | undefined {\n if (\n typeof record.path === \"string\" &&\n typeof record.newText === \"string\" &&\n (record.oldText == null || typeof record.oldText === \"string\")\n ) {\n return undefined;\n }\n return \"Malformed tool call diff\";\n}\n\nfunction validToolContentBlock(content: unknown): boolean {\n const block = asRecord(content);\n if (!block || typeof block.type !== \"string\") {\n return false;\n }\n if (block.type === \"text\") {\n return typeof block.text === \"string\";\n }\n if (block.type === \"resource\") {\n return asRecord(block.resource) !== undefined;\n }\n return true;\n}\n\nfunction formatLocations(\n locations: Array<ToolCallLocation> | null | undefined,\n): string | undefined {\n if (!Array.isArray(locations) || locations.length === 0) {\n return undefined;\n }\n\n const unique = new Set<string>();\n for (const location of locations) {\n const formatted = formatLocation(location);\n if (formatted) {\n unique.add(formatted);\n }\n }\n\n const items = [...unique];\n if (items.length === 0) {\n return undefined;\n }\n\n const visible = items.slice(0, MAX_LOCATION_ITEMS);\n const hidden = items.length - visible.length;\n if (hidden <= 0) {\n return visible.join(\", \");\n }\n\n return `${visible.join(\", \")}, +${hidden} more`;\n}\n\nfunction formatLocation(location: ToolCallLocation): string | undefined {\n if (!location || typeof location !== \"object\") {\n return undefined;\n }\n const rawPath = location.path;\n if (typeof rawPath !== \"string\") {\n return undefined;\n }\n const path = rawPath.trim();\n if (!path) {\n return undefined;\n }\n\n const line =\n typeof location.line === \"number\" && Number.isFinite(location.line)\n ? `:${Math.max(1, Math.trunc(location.line))}`\n : \"\";\n return `${path}${line}`;\n}\n\nfunction summarizeDiff(path: string, oldText: string | null | undefined, newText: string): string {\n const oldLines = oldText ? oldText.split(\"\\n\").length : 0;\n const newLines = newText.split(\"\\n\").length;\n const delta = newLines - oldLines;\n\n if (delta === 0) {\n return `diff ${path} (line count unchanged)`;\n }\n\n const signedDelta = `${delta > 0 ? \"+\" : \"\"}${delta}`;\n return `diff ${path} (${signedDelta} lines)`;\n}\n\nfunction textFromContentBlock(content: ContentBlock): string | undefined {\n switch (content.type) {\n case \"text\":\n return content.text;\n case \"resource_link\":\n return content.title ?? content.name ?? content.uri;\n case \"resource\": {\n return textFromResourceBlock(content);\n }\n case \"image\":\n return `[image] ${content.mimeType}`;\n case \"audio\":\n return `[audio] ${content.mimeType}`;\n default:\n return undefined;\n }\n}\n\nfunction textFromResourceBlock(content: Extract<ContentBlock, { type: \"resource\" }>): string {\n if (!content.resource || typeof content.resource !== \"object\") {\n return \"[resource]\";\n }\n if (\"text\" in content.resource && typeof content.resource.text === \"string\") {\n return content.resource.text;\n }\n const uri = content.resource.uri;\n const mimeType = content.resource.mimeType;\n return `[resource] ${uri}${mimeType ? ` (${mimeType})` : \"\"}`;\n}\n\nfunction summarizeToolContent(\n content: Array<ToolCallContent> | null | undefined,\n): string | undefined {\n if (!Array.isArray(content) || content.length === 0) {\n return undefined;\n }\n\n const fragments: string[] = [];\n\n for (const entry of content) {\n const fragment = summarizeToolContentEntry(entry);\n if (fragment) {\n fragments.push(fragment);\n }\n }\n\n const unique = dedupeStrings(\n fragments.map((fragment) => fragment.trim()).filter((fragment) => fragment.length > 0),\n );\n if (unique.length === 0) {\n return undefined;\n }\n\n return unique.join(\"\\n\\n\");\n}\n\nfunction summarizeToolContentEntry(entry: ToolCallContent): string | undefined {\n if (!entry || typeof entry !== \"object\") {\n return undefined;\n }\n if (entry.type === \"content\") {\n return summarizeContentEntry(entry);\n }\n if (entry.type === \"diff\") {\n return summarizeDiffEntry(entry);\n }\n if (entry.type === \"terminal\") {\n return `[terminal] ${entry.terminalId}`;\n }\n return undefined;\n}\n\nfunction summarizeContentEntry(\n entry: Extract<ToolCallContent, { type: \"content\" }>,\n): string | undefined {\n if (!entry.content || typeof entry.content !== \"object\") {\n return undefined;\n }\n const text = textFromContentBlock(entry.content);\n return typeof text === \"string\" && text.trim() ? text.trimEnd() : undefined;\n}\n\nfunction summarizeDiffEntry(entry: Extract<ToolCallContent, { type: \"diff\" }>): string | undefined {\n if (typeof entry.path !== \"string\" || typeof entry.newText !== \"string\") {\n return undefined;\n }\n const oldText = typeof entry.oldText === \"string\" ? entry.oldText : undefined;\n return summarizeDiff(entry.path, oldText, entry.newText);\n}\n\nfunction extractOutputText(\n value: unknown,\n depth = 0,\n seen = new Set<unknown>(),\n): string | undefined {\n if (value == null) {\n return undefined;\n }\n\n const scalar = extractScalarOutputText(value);\n if (scalar !== null) {\n return scalar;\n }\n\n if (depth >= 4) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n return extractOutputTextArray(value, depth, seen);\n }\n\n return extractOutputTextRecord(value, depth, seen);\n}\n\nfunction extractOutputTextRecord(\n value: unknown,\n depth: number,\n seen: Set<unknown>,\n): string | undefined {\n const record = asRecord(value);\n if (!record || seen.has(record)) {\n return undefined;\n }\n\n seen.add(record);\n\n return extractPreferredOutputText(record, depth, seen) ?? extractJsonOutputText(record);\n}\n\nfunction extractScalarOutputText(value: unknown): string | undefined | null {\n if (typeof value === \"string\") {\n const trimmed = value.trimEnd();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n\n return null;\n}\n\nfunction extractOutputTextArray(\n value: unknown[],\n depth: number,\n seen: Set<unknown>,\n): string | undefined {\n const parts = value\n .map((entry) => extractOutputText(entry, depth + 1, seen))\n .filter((entry): entry is string => Boolean(entry));\n return parts.length > 0 ? dedupeStrings(parts).join(\"\\n\") : undefined;\n}\n\nfunction extractPreferredOutputText(\n record: Record<string, unknown>,\n depth: number,\n seen: Set<unknown>,\n): string | undefined {\n const preferred = OUTPUT_PRIORITY_KEYS.flatMap((key) => {\n if (!(key in record)) {\n return [];\n }\n const extracted = extractOutputText(record[key], depth + 1, seen);\n return extracted ? [extracted] : [];\n });\n const uniquePreferred = dedupeStrings(preferred);\n return uniquePreferred.length > 0 ? uniquePreferred.join(\"\\n\") : undefined;\n}\n\nfunction extractJsonOutputText(record: Record<string, unknown>): string | undefined {\n const json = safeJson(record, 2);\n return !json || json === \"{}\" ? undefined : json;\n}\n\nfunction summarizeToolOutput(\n rawOutput: unknown,\n content: Array<ToolCallContent> | null | undefined,\n): string | undefined {\n const outputFromRaw = extractOutputText(rawOutput);\n const outputFromContent = summarizeToolContent(content);\n\n const fragments = dedupeStrings(\n [outputFromRaw, outputFromContent]\n .map((fragment) => fragment?.trim())\n .filter((fragment): fragment is string => Boolean(fragment)),\n );\n\n if (fragments.length === 0) {\n return undefined;\n }\n\n return fragments.join(\"\\n\\n\");\n}\n\nfunction renderToolOutput(state: ToolRenderState, suppressReads: boolean): string | undefined {\n if (suppressReads && isReadLikeTool(state)) {\n return SUPPRESSED_READ_OUTPUT;\n }\n\n return summarizeToolOutput(state.rawOutput, state.content);\n}\n\nfunction limitOutputBlock(value: string): string {\n const normalized = value.replace(/\\r\\n/g, \"\\n\").trim();\n if (!normalized) {\n return \"\";\n }\n\n const lines = normalized.split(\"\\n\");\n const visible = lines.slice(0, MAX_OUTPUT_LINES);\n let result = visible.join(\"\\n\");\n\n if (lines.length > visible.length) {\n const hidden = lines.length - visible.length;\n result += `\\n... (${hidden} more lines)`;\n }\n\n if (result.length > MAX_OUTPUT_CHARS) {\n result = `${result.slice(0, MAX_OUTPUT_CHARS - 3)}...`;\n }\n\n return result;\n}\n\nclass TextOutputFormatter implements OutputFormatter {\n private readonly stdout: WritableLike;\n private readonly useColor: boolean;\n private readonly suppressReads: boolean;\n private readonly toolStates = new Map<string, ToolRenderState>();\n private thoughtBuffer = \"\";\n private wroteAny = false;\n private atLineStart = true;\n\n constructor(stdout: WritableLike, suppressReads: boolean) {\n this.stdout = stdout;\n this.useColor = Boolean(stdout.isTTY);\n this.suppressReads = suppressReads;\n }\n\n setContext(_context: OutputFormatterContext): void {\n // no-op for text mode\n }\n\n onAcpMessage(message: AcpJsonRpcMessage): void {\n const notice = parsePermissionNotice(message);\n if (notice) {\n this.beginSection();\n this.writeLine(`${this.bold(\"[permission]\")} ${notice}`);\n return;\n }\n const notification = extractSessionUpdateNotification(message);\n if (notification) {\n this.renderSessionUpdate(notification);\n return;\n }\n\n const method = extractJsonRpcMethod(message);\n if (method && ![\"session/prompt\", \"session/cancel\", \"session/update\"].includes(method)) {\n this.onClientOperation({\n method: method as ClientOperation[\"method\"],\n status: \"running\",\n summary: method,\n timestamp: new Date().toISOString(),\n });\n return;\n }\n\n const stopReason = parsePromptStopReason(message);\n if (stopReason) {\n this.renderDone(stopReason);\n return;\n }\n\n const errorMessage = parseJsonRpcErrorSummary(message);\n if (errorMessage) {\n this.onError({\n code: \"RUNTIME\",\n origin: \"acp\",\n message: errorMessage,\n });\n }\n }\n\n private renderSessionUpdate(notification: SessionNotification): void {\n const update = notification.update;\n if (update.sessionUpdate !== \"agent_thought_chunk\") {\n this.flushThoughtBuffer();\n }\n this.renderSessionUpdateBody(update);\n }\n\n private renderSessionUpdateBody(update: SessionNotification[\"update\"]): void {\n switch (update.sessionUpdate) {\n case \"agent_message_chunk\": {\n if (update.content.type === \"text\") {\n this.write(update.content.text);\n }\n return;\n }\n case \"agent_thought_chunk\": {\n if (update.content.type === \"text\") {\n this.thoughtBuffer += update.content.text;\n }\n return;\n }\n case \"tool_call\": {\n this.renderToolUpdate(update);\n return;\n }\n case \"tool_call_update\": {\n this.renderToolUpdate(update);\n return;\n }\n case \"plan\": {\n this.renderPlanUpdate(update.entries);\n return;\n }\n default:\n return;\n }\n }\n\n private renderPlanUpdate(\n entries: Extract<SessionNotification[\"update\"], { sessionUpdate: \"plan\" }>[\"entries\"],\n ): void {\n this.beginSection();\n this.writeLine(this.bold(\"[plan]\"));\n for (const entry of entries) {\n this.writeLine(` - [${entry.status}] ${entry.content}`);\n }\n }\n\n private renderDone(stopReason: string): void {\n this.flushThoughtBuffer();\n this.beginSection();\n this.writeLine(this.dim(`[done] ${stopReason}`));\n }\n\n onError(params: RenderableOutputError): void {\n this.flushThoughtBuffer();\n this.beginSection();\n this.writeLine(this.formatAnsi(`[error] ${params.code}: ${params.message}`, \"31\"));\n for (const hint of getTextErrorRemediationHints(params)) {\n this.writeLine(this.dim(hint));\n }\n }\n\n onClientOperation(operation: ClientOperation): void {\n this.flushThoughtBuffer();\n this.beginSection();\n\n const normalizedStatus: NormalizedToolStatus =\n operation.status === \"completed\"\n ? \"completed\"\n : operation.status === \"failed\"\n ? \"failed\"\n : \"in_progress\";\n const statusText = this.colorStatus(operation.status, normalizedStatus);\n this.writeLine(`${this.bold(\"[client]\")} ${operation.summary} (${statusText})`);\n if (operation.details && operation.details.trim().length > 0) {\n this.writeLine(\" details:\");\n this.writeLine(indentBlock(operation.details, \" \"));\n }\n }\n\n onPermissionEscalation(event: PermissionEscalationEvent): void {\n this.flushThoughtBuffer();\n this.beginSection();\n this.writeLine(`${this.bold(\"[permission]\")} ${event.message}`);\n const details = [\n `sessionId: ${event.sessionId}`,\n `toolCallId: ${event.toolCallId}`,\n event.toolName ? `toolName: ${event.toolName}` : undefined,\n `toolTitle: ${event.toolTitle}`,\n event.toolInput !== undefined\n ? `toolInput: ${summarizeToolInput(event.toolInput) ?? \"(structured input)\"}`\n : undefined,\n event.toolKind ? `toolKind: ${event.toolKind}` : undefined,\n event.matchedRule ? `matchedRule: ${event.matchedRule}` : undefined,\n ].filter((line): line is string => Boolean(line));\n this.writeLine(indentBlock(details.join(\"\\n\"), \" \"));\n }\n\n flush(): void {\n this.flushThoughtBuffer();\n if (!this.atLineStart) {\n this.write(\"\\n\");\n }\n }\n\n private write(chunk: string): void {\n if (!chunk) {\n return;\n }\n this.stdout.write(chunk);\n this.wroteAny = true;\n this.atLineStart = chunk.endsWith(\"\\n\");\n }\n\n private writeLine(line: string): void {\n this.write(`${line}\\n`);\n }\n\n private beginSection(): void {\n if (!this.atLineStart) {\n this.write(\"\\n\");\n }\n if (this.wroteAny) {\n this.write(\"\\n\");\n }\n }\n\n private flushThoughtBuffer(): void {\n const thought = truncate(normalizeLineEndings(this.thoughtBuffer).trim(), MAX_THOUGHT_CHARS);\n this.thoughtBuffer = \"\";\n if (!thought) {\n return;\n }\n\n this.beginSection();\n const [firstLine, ...restLines] = thought.split(\"\\n\");\n this.writeLine(this.dim(`[thinking] ${firstLine}`));\n for (const line of restLines) {\n this.writeLine(this.dim(` ${line}`));\n }\n }\n\n private renderToolUpdate(update: ToolCall | ToolCallUpdate): void {\n const shapeError = malformedToolUpdateMessage(update);\n if (shapeError) {\n this.onError({\n code: \"RUNTIME\",\n origin: \"acp\",\n message: shapeError,\n });\n return;\n }\n const state = this.getOrCreateToolState(update.toolCallId);\n this.mergeToolState(state, update);\n\n const status = asStatus(state.status);\n const final = isFinalStatus(status);\n if (!final && state.startedPrinted) {\n return;\n }\n const display: ToolDisplay = {\n input: summarizeToolInput(state.rawInput),\n files: formatLocations(state.locations),\n output: final ? renderToolOutput(state, this.suppressReads) : undefined,\n };\n if (final) {\n const payload = { title: state.title, status: state.status, kind: state.kind, ...display };\n const signature = safeJson(payload, 0) ?? JSON.stringify(payload);\n if (signature === state.finalSignature) {\n return;\n }\n state.finalSignature = signature;\n } else {\n state.startedPrinted = true;\n }\n this.renderToolState(state, status, display);\n }\n\n private getOrCreateToolState(toolCallId: string): ToolRenderState {\n const existing = this.toolStates.get(toolCallId);\n if (existing) {\n return existing;\n }\n\n const created: ToolRenderState = {\n id: toolCallId,\n startedPrinted: false,\n };\n this.toolStates.set(toolCallId, created);\n return created;\n }\n\n private mergeToolState(state: ToolRenderState, update: ToolCall | ToolCallUpdate): void {\n this.mergeToolTitle(state, update.title);\n this.mergeToolPayloadState(state, update);\n }\n\n private mergeToolTitle(state: ToolRenderState, title: string | null | undefined): void {\n if (typeof title === \"string\" && title.trim().length > 0) {\n state.title = title;\n }\n }\n\n private mergeToolPayloadState(state: ToolRenderState, update: ToolCall | ToolCallUpdate): void {\n if (update.status !== undefined) {\n state.status = update.status;\n }\n if (update.kind !== undefined) {\n state.kind = update.kind;\n }\n if (update.locations !== undefined) {\n state.locations = update.locations;\n }\n if (update.rawInput !== undefined) {\n state.rawInput = update.rawInput;\n }\n if (update.rawOutput !== undefined) {\n state.rawOutput = update.rawOutput;\n }\n if (update.content !== undefined) {\n state.content = update.content;\n }\n }\n\n private renderToolState(\n state: ToolRenderState,\n status: NormalizedToolStatus,\n display: ToolDisplay,\n ): void {\n this.beginSection();\n const title = state.title ?? state.id;\n const statusText = this.colorStatus(toStatusLabel(status), status);\n this.writeLine(`${this.bold(\"[tool]\")} ${title} (${statusText})`);\n if (isFinalStatus(status) && state.kind) {\n this.writeLine(` kind: ${state.kind}`);\n }\n if (display.input) {\n this.writeLine(` input: ${display.input}`);\n }\n if (display.files) {\n this.writeLine(` files: ${display.files}`);\n }\n if (display.output) {\n this.writeLine(\" output:\");\n this.writeLine(indentBlock(limitOutputBlock(display.output), \" \"));\n }\n }\n\n private formatAnsi(text: string, code: string): string {\n if (!this.useColor) {\n return text;\n }\n return `\\u001b[${code}m${text}\\u001b[0m`;\n }\n\n private bold(text: string): string {\n return this.formatAnsi(text, \"1\");\n }\n\n private dim(text: string): string {\n return this.formatAnsi(text, \"2\");\n }\n\n private colorStatus(text: string, status: NormalizedToolStatus): string {\n if (!this.useColor) {\n return text;\n }\n\n switch (status) {\n case \"completed\":\n return this.formatAnsi(text, \"32\");\n case \"failed\":\n return this.formatAnsi(text, \"31\");\n case \"pending\":\n case \"in_progress\":\n case \"unknown\":\n default:\n return this.formatAnsi(text, \"33\");\n }\n }\n}\n\nclass QuietOutputFormatter implements OutputFormatter {\n private readonly stdout: WritableLike;\n private readonly stderr: WritableLike;\n private chunks: string[] = [];\n private finished = false;\n private outputWritten = false;\n private metadataFlushed = false;\n\n constructor(stdout: WritableLike, stderr: WritableLike) {\n this.stdout = stdout;\n this.stderr = stderr;\n }\n\n setContext(_context: OutputFormatterContext): void {\n // no-op for quiet mode\n }\n\n onAcpMessage(message: AcpJsonRpcMessage): void {\n const notice = parsePermissionNotice(message);\n if (notice) {\n this.stderr.write(`[acpx] permission: ${notice.replace(/\\r\\n?|\\n/g, \" \")}\\n`);\n return;\n }\n const update = extractSessionUpdateNotification(message);\n if (\n update?.update.sessionUpdate === \"agent_message_chunk\" &&\n update.update.content.type === \"text\"\n ) {\n if (!this.finished) {\n this.chunks.push(update.update.content.text);\n }\n return;\n }\n\n if (parsePromptStopReason(message)) {\n if (!this.finished) {\n this.finished = true;\n this.flushBufferedOutput(true);\n }\n this.flushMetadata(message);\n }\n }\n\n onError(params: {\n code: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n message: string;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n timestamp?: string;\n }): void {\n this.flush();\n const qualifier = params.detailCode ? `${params.code} ${params.detailCode}` : params.code;\n const message = preferredAcpErrorDetails(params.acp) ?? params.message;\n this.stderr.write(`[acpx] error: ${qualifier} ${message.replace(/\\r\\n?|\\n/g, \" \")}\\n`);\n }\n\n onPermissionEscalation(_event: PermissionEscalationEvent): void {\n // no-op in quiet mode\n }\n\n flush(): void {\n this.flushBufferedOutput();\n }\n\n private flushBufferedOutput(allowEmpty = false): void {\n const text = this.chunks.join(\"\");\n this.chunks = [];\n if (text.length === 0 && (!allowEmpty || this.outputWritten)) {\n return;\n }\n this.outputWritten = true;\n this.stdout.write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n }\n\n private flushMetadata(message: AcpJsonRpcMessage): void {\n if (this.metadataFlushed) {\n return;\n }\n\n this.metadataFlushed = true;\n const result = asRecord((message as { result?: unknown }).result);\n if (!result) {\n return;\n }\n\n const usageLine = this.formatUsageLine(asRecord(result.usage));\n if (usageLine) {\n this.stderr.write(`${usageLine}\\n`);\n }\n\n const costLine = this.formatCostLine(result.cost);\n if (costLine) {\n this.stderr.write(`${costLine}\\n`);\n }\n }\n\n private formatUsageLine(usage: Record<string, unknown> | undefined): string | undefined {\n if (!usage) {\n return undefined;\n }\n\n const parts: string[] = [];\n const fields: Array<[string, string[]]> = [\n [\"input\", [\"inputTokens\", \"input_tokens\"]],\n [\"output\", [\"outputTokens\", \"output_tokens\"]],\n [\"cache_read\", [\"cachedReadTokens\", \"cacheReadInputTokens\", \"cache_read_input_tokens\"]],\n [\n \"cache_write\",\n [\"cachedWriteTokens\", \"cacheCreationInputTokens\", \"cache_creation_input_tokens\"],\n ],\n [\"total\", [\"totalTokens\", \"total_tokens\"]],\n ];\n\n for (const [label, keys] of fields) {\n const value = readFirstFiniteNumber(usage, keys);\n if (value !== undefined) {\n parts.push(`${label}=${formatMetadataNumber(value)}`);\n }\n }\n\n return parts.length > 0 ? `[acpx] tokens: ${parts.join(\" \")}` : undefined;\n }\n\n private formatCostLine(cost: unknown): string | undefined {\n const scalar = this.formatScalarCostLine(cost);\n if (scalar) {\n return scalar;\n }\n const record = asRecord(cost);\n if (!record) {\n return undefined;\n }\n\n const amount = readFirstFiniteNumber(record, [\"amount\", \"value\", \"total\"]);\n if (amount === undefined) {\n return undefined;\n }\n\n const currency =\n typeof record.currency === \"string\" && record.currency.trim()\n ? ` ${record.currency.trim()}`\n : \"\";\n return `[acpx] cost: ${formatMetadataNumber(amount)}${currency}`;\n }\n\n private formatScalarCostLine(cost: unknown): string | undefined {\n if (typeof cost === \"number\" && Number.isFinite(cost)) {\n return `[acpx] cost: ${formatMetadataNumber(cost)}`;\n }\n\n if (typeof cost === \"string\" && cost.trim()) {\n return `[acpx] cost: ${cost.trim()}`;\n }\n\n return undefined;\n }\n}\n\nfunction preferredAcpErrorDetails(acp: OutputErrorAcpPayload | undefined): string | undefined {\n const details = asRecord(acp?.data)?.details;\n return typeof details === \"string\" && details.trim().length > 0 ? details.trim() : undefined;\n}\n\nexport function createOutputFormatter(\n format: OutputFormat,\n options: OutputFormatterOptions = {},\n): OutputFormatter {\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n const suppressReads = options.suppressReads === true;\n\n switch (format) {\n case \"text\":\n return new TextOutputFormatter(stdout, suppressReads);\n case \"json\":\n return createJsonOutputFormatter(stdout, suppressReads, options.jsonContext);\n case \"quiet\":\n return new QuietOutputFormatter(stdout, stderr);\n default: {\n const exhaustive: never = format;\n void exhaustive;\n throw new Error(\"Unsupported output format\");\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA,MAAa,qBAAqB;AAElC,SAAgB,oBAAoB,SAAiB,WAAwC;CAC3F,IAAI,aAAa,YAAY,GAC3B,OAAO;CAET,MAAM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AQ,KAAK,CAAC,CAAC,SAAS,IAAI,QAAQ,KAAK,IAAI,KAAA;AACrF;AAEA,SAAgB,sBACd,QACA,UAAkC,CAAC,GAClB;CACjB,MAAM,SAAS,QAAQ,UAAU,QAAQ;CACzC,MAAM,SAAS,QAAQ,UAAU,QAAQ;CACzC,MAAM,gBAAgB,QAAQ,kBAAkB;CAEhD,QAAQ,QAAR;EACE,KAAK,QACH,OAAO,IAAI,oBAAoB,QAAQ,aAAa;EACtD,KAAK,QACH,OAAO,0BAA0B,QAAQ,eAAe,QAAQ,WAAW;EAC7E,KAAK,SACH,OAAO,IAAI,qBAAqB,QAAQ,MAAM;EAChD,SAGE,MAAM,IAAI,MAAM,2BAA2B;CAE/C;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as measurePerf, $t as UnsupportedPromptContentError, Bt as AgentStartupError, C as textPrompt, Dt as normalizeOutputError, Et as isRetryablePromptError, F as normalizeName, G as normalizeAgentSessionId, Gt as PermissionDeniedError, H as canonicalAgentCommand, Ht as ClaudeAcpSessionCreateTimeoutError, Jt as SessionConfigOptionReplayError, K as SESSION_JOURNAL_SCHEMA, Kt as PermissionPromptUnavailableError, L as readSessionRecord, Lt as AcpxOperationalError, M as isoNow$1, O as absolutePath, Ot as extractAcpError, Q as incrementPerfCounter, Qt as SessionResumeRequiredError, R as resolveSessionRecord, Rt as AgentDisconnectedError, S as promptToDisplayText, St as isProcessAlive, T as lockOwnerPid, Tt as isAcpQueryClosedBeforeResponseError, Ut as CopilotAcpUnsupportedError, Vt as AuthPolicyError, W as extractAgentSessionId, Wt as GeminiAcpStartupTimeoutError, X as formatPerfMetric, Xt as SessionModelReplayError, Yt as SessionModeReplayError, Z as getPerfMetricsSnapshot, _ as ProcessDescendants, _t as sessionEventLockPath, a as trySetModelOnRunningOwner, at as isAcpMessageObject, d as releaseQueueOwnerLease, et as resetPerfMetrics, f as terminateProcess, ft as defaultSessionEventLog, g as QueueLeaseGuardSettlementError, gt as sessionEventActivePath, h as waitMs$1, ht as sessionBaseDir, i as trySetModeOnRunningOwner, it as isAcpJsonRpcMessage, j as findSessionByDirectoryWalk, k as findGitRepositoryRoot, kt as isAcpResourceNotFoundError, m as tryAcquireQueueOwnerLease, mt as retainedEventMaxSegments, n as tryCloseSessionOnRunningOwner, nt as startPerfTimer, o as trySubmitToRunningOwner, ot as isSessionUpdateNotification, p as terminateQueueOwnerForSession, pt as existingEventSegmentIndices, q as SessionJournalReader, qt as QueueConnectionError, r as trySetConfigOptionOnRunningOwner, s as SessionQueueOwner, t as tryCancelOnRunningOwner, tt as setPerfGauge, u as refreshQueueOwnerLease, vt as sessionEventSegmentPath, w as createLockOwner, wt as formatErrorMessage, y as getUnsupportedPromptContentMessage, z as writeSessionRecord, zt as AgentSpawnError } from "./ipc-C96eDxkW.js";
|
|
2
2
|
import { A as requireAgentStdio, C as PROCESS_HELPER_TIMEOUT_MS, D as isoNow$2, E as isChildProcessRunning, F as waitForChildExit, I as waitForSpawn, M as resolveAgentSessionCwd, N as runTimedExecFile, P as splitCommandLine, T as basenameToken, _ as buildSpawnCommandOptions, b as readWindowsEnvValue, f as resolveBuiltInAgentLaunch, g as buildAgentSpawnCommand, j as resolveAgentCommandParts, v as buildTerminalShellSpawnCommand, w as asAbsoluteCwd, x as resolveWindowsExecutablePath, y as buildTerminalSpawnCommand } from "./agent-registry-kHdpsK9F.js";
|
|
3
3
|
import fs, { readFileSync, realpathSync } from "node:fs";
|
|
4
4
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
@@ -112,8 +112,8 @@ async function pathExists(filePath) {
|
|
|
112
112
|
}
|
|
113
113
|
}
|
|
114
114
|
async function countExistingSegments(sessionId, maxSegments) {
|
|
115
|
-
|
|
116
|
-
|
|
115
|
+
const limit = retainedEventMaxSegments(maxSegments);
|
|
116
|
+
let count = (await existingEventSegmentIndices(sessionId)).filter((index) => index <= limit).length;
|
|
117
117
|
if (await pathExists(sessionEventActivePath(sessionId))) count += 1;
|
|
118
118
|
return count;
|
|
119
119
|
}
|
|
@@ -124,22 +124,36 @@ async function resolveInitialSegmentCount(record, maxSegments) {
|
|
|
124
124
|
async function resolveSessionMaxSegments(sessionId) {
|
|
125
125
|
try {
|
|
126
126
|
const configured = (await resolveSessionRecord(sessionId)).eventLog.max_segments;
|
|
127
|
-
|
|
127
|
+
const retained = retainedEventMaxSegments(configured);
|
|
128
|
+
if (retained > 0) return retained;
|
|
128
129
|
} catch {}
|
|
129
130
|
return 5;
|
|
130
131
|
}
|
|
131
132
|
async function rotateSegments(sessionId, maxSegments) {
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
await
|
|
133
|
+
const limit = retainedEventMaxSegments(maxSegments);
|
|
134
|
+
if (limit < 1) return;
|
|
135
|
+
await discardOverflowSegment(sessionId, limit);
|
|
136
|
+
await shiftRetainedSegments(sessionId, limit);
|
|
137
|
+
await promoteActiveSegment(sessionId);
|
|
138
|
+
}
|
|
139
|
+
async function discardOverflowSegment(sessionId, limit) {
|
|
140
|
+
if (!(await existingEventSegmentIndices(sessionId)).includes(limit)) return;
|
|
141
|
+
await fs$1.unlink(sessionEventSegmentPath(sessionId, limit)).catch((error) => {
|
|
135
142
|
if (error.code !== "ENOENT") throw error;
|
|
136
143
|
});
|
|
137
|
-
|
|
144
|
+
}
|
|
145
|
+
async function shiftRetainedSegments(sessionId, limit) {
|
|
146
|
+
const movable = (await existingEventSegmentIndices(sessionId)).filter((index) => index < limit).toSorted((left, right) => right - left);
|
|
147
|
+
for (const segment of movable) {
|
|
138
148
|
const from = sessionEventSegmentPath(sessionId, segment);
|
|
139
|
-
const to = sessionEventSegmentPath(sessionId, segment + 1);
|
|
140
149
|
if (!await pathExists(from)) continue;
|
|
141
|
-
|
|
150
|
+
const next = segment + 1;
|
|
151
|
+
if (!Number.isSafeInteger(next)) throw new Error("Session journal segment index exceeds its supported range");
|
|
152
|
+
await fs$1.rename(from, sessionEventSegmentPath(sessionId, next));
|
|
142
153
|
}
|
|
154
|
+
}
|
|
155
|
+
async function promoteActiveSegment(sessionId) {
|
|
156
|
+
const active = sessionEventActivePath(sessionId);
|
|
143
157
|
if (await pathExists(active)) await fs$1.rename(active, sessionEventSegmentPath(sessionId, 1));
|
|
144
158
|
}
|
|
145
159
|
var SessionEventWriter = class SessionEventWriter {
|
|
@@ -174,7 +188,7 @@ var SessionEventWriter = class SessionEventWriter {
|
|
|
174
188
|
}
|
|
175
189
|
static async open(record, options = {}) {
|
|
176
190
|
const maxSegmentBytes = options.maxSegmentBytes ?? record.eventLog.max_segment_bytes ?? 67108864;
|
|
177
|
-
const maxSegments = options.maxSegments ?? record.eventLog.max_segments ?? 5;
|
|
191
|
+
const maxSegments = retainedEventMaxSegments(options.maxSegments ?? record.eventLog.max_segments ?? 5);
|
|
178
192
|
const activePath = sessionEventActivePath(record.acpxRecordId);
|
|
179
193
|
const tail = await new SessionJournalReader({
|
|
180
194
|
...record,
|
|
@@ -339,7 +353,7 @@ var SessionEventWriter = class SessionEventWriter {
|
|
|
339
353
|
}
|
|
340
354
|
};
|
|
341
355
|
async function listSessionEvents(sessionId, maxSegments) {
|
|
342
|
-
maxSegments
|
|
356
|
+
maxSegments = retainedEventMaxSegments(maxSegments ?? await resolveSessionMaxSegments(sessionId));
|
|
343
357
|
return await new SessionJournalReader({
|
|
344
358
|
acpxRecordId: sessionId,
|
|
345
359
|
eventLog: { max_segments: maxSegments }
|
|
@@ -558,7 +572,7 @@ async function acquireSessionTurn(recordId, signal) {
|
|
|
558
572
|
}
|
|
559
573
|
async function acquireSessionScope(scope, signal) {
|
|
560
574
|
return await acquireSessionTurn(`ensure:${createHash("sha256").update(JSON.stringify([
|
|
561
|
-
scope.agentCommand,
|
|
575
|
+
canonicalAgentCommand(scope.agentCommand),
|
|
562
576
|
scope.cwd,
|
|
563
577
|
scope.name
|
|
564
578
|
])).digest("hex")}`, signal);
|
|
@@ -4299,6 +4313,7 @@ function cloneUsageCost(cost) {
|
|
|
4299
4313
|
function cloneSessionAcpxState(state) {
|
|
4300
4314
|
if (!state) return;
|
|
4301
4315
|
return {
|
|
4316
|
+
...state.session_origin ? { session_origin: state.session_origin } : {},
|
|
4302
4317
|
current_mode_id: state.current_mode_id,
|
|
4303
4318
|
desired_mode_id: state.desired_mode_id,
|
|
4304
4319
|
desired_config_options: state.desired_config_options ? { ...state.desired_config_options } : void 0,
|
|
@@ -4520,7 +4535,7 @@ function createInitialSessionRecord(params) {
|
|
|
4520
4535
|
closed: false,
|
|
4521
4536
|
closedAt: void 0,
|
|
4522
4537
|
...createSessionConversation(now),
|
|
4523
|
-
acpx: {}
|
|
4538
|
+
acpx: params.sessionOrigin ? { session_origin: params.sessionOrigin } : {}
|
|
4524
4539
|
};
|
|
4525
4540
|
}
|
|
4526
4541
|
function applyLifecycleSnapshotToRecord(record, snapshot) {
|
|
@@ -4547,6 +4562,17 @@ function reconcileAgentSessionId(record, agentSessionId) {
|
|
|
4547
4562
|
function sessionHasAgentMessages(recordOrConversation) {
|
|
4548
4563
|
return recordOrConversation.messages.some((message) => typeof message === "object" && message !== null && "Agent" in message);
|
|
4549
4564
|
}
|
|
4565
|
+
function sessionHasAtMostOneUserMessage(recordOrConversation) {
|
|
4566
|
+
let userMessageCount = 0;
|
|
4567
|
+
for (const message of recordOrConversation.messages) if (typeof message === "object" && message !== null && "User" in message) {
|
|
4568
|
+
userMessageCount += 1;
|
|
4569
|
+
if (userMessageCount > 1) return false;
|
|
4570
|
+
}
|
|
4571
|
+
return true;
|
|
4572
|
+
}
|
|
4573
|
+
function sessionHasUserMessages(recordOrConversation) {
|
|
4574
|
+
return recordOrConversation.messages.some((message) => typeof message === "object" && message !== null && "User" in message);
|
|
4575
|
+
}
|
|
4550
4576
|
function applyConversation(record, conversation) {
|
|
4551
4577
|
record.title = conversation.title;
|
|
4552
4578
|
record.updated_at = conversation.updated_at;
|
|
@@ -4985,7 +5011,8 @@ async function connectAndLoadSession(options) {
|
|
|
4985
5011
|
reusingLoadedSession,
|
|
4986
5012
|
sameSessionOnly,
|
|
4987
5013
|
timeoutMs: options.timeoutMs,
|
|
4988
|
-
authority: options.authority
|
|
5014
|
+
authority: options.authority,
|
|
5015
|
+
promptRecorded: options.promptRecorded
|
|
4989
5016
|
});
|
|
4990
5017
|
const { resumed, loadError, sessionId, createdFreshSession, pendingAgentSessionId, sessionModels } = loadState;
|
|
4991
5018
|
applyReconnectedModelState(record, sessionModels, loadState.configOptionsPresent, loadState.legacyModelMetadataPresent, createdFreshSession);
|
|
@@ -5184,19 +5211,32 @@ function rethrowCancelledLoad(error, authority) {
|
|
|
5184
5211
|
}
|
|
5185
5212
|
async function recoverRuntimeSessionLoadFailure(params, error) {
|
|
5186
5213
|
const loadError = formatErrorMessage(error);
|
|
5187
|
-
if (params
|
|
5188
|
-
|
|
5189
|
-
|
|
5190
|
-
|
|
5191
|
-
|
|
5192
|
-
|
|
5214
|
+
if (!canRecoverLoadWithFreshSession(params, error)) {
|
|
5215
|
+
if (params.sameSessionOnly) throw makeSessionResumeRequiredError({
|
|
5216
|
+
record: params.record,
|
|
5217
|
+
reason: loadError,
|
|
5218
|
+
cause: error
|
|
5219
|
+
});
|
|
5220
|
+
throw error;
|
|
5221
|
+
}
|
|
5193
5222
|
return {
|
|
5194
5223
|
...await createFreshRuntimeSession(params.client, params.record, params.timeoutMs, params.authority),
|
|
5195
5224
|
loadError
|
|
5196
5225
|
};
|
|
5197
5226
|
}
|
|
5227
|
+
function canRecoverLoadWithFreshSession(params, error) {
|
|
5228
|
+
if (!params.sameSessionOnly) return shouldFallbackToNewSession(error, params.record);
|
|
5229
|
+
return isUnpromptedNewSession(params.record, params.promptRecorded) && extractAcpError(error)?.code === -32603;
|
|
5230
|
+
}
|
|
5231
|
+
function isUnpromptedNewSession(record, promptRecorded = false) {
|
|
5232
|
+
return record.acpx?.session_origin === "new" && !record.importedFrom && !sessionHasAgentMessages(record) && !record.messages.includes("Resume") && (promptRecorded ? sessionHasAtMostOneUserMessage(record) : !sessionHasUserMessages(record));
|
|
5233
|
+
}
|
|
5198
5234
|
async function createFreshRuntimeSession(client, record, timeoutMs, authority) {
|
|
5199
5235
|
const createdSession = await withTimeout(client.createSession(record.cwd, authority), timeoutMs);
|
|
5236
|
+
record.acpx = {
|
|
5237
|
+
...record.acpx,
|
|
5238
|
+
session_origin: "new"
|
|
5239
|
+
};
|
|
5200
5240
|
applyConfigOptionsToRecord(record, createdSession);
|
|
5201
5241
|
return {
|
|
5202
5242
|
sessionId: createdSession.sessionId,
|
|
@@ -5735,6 +5775,7 @@ async function createSessionRecordWithClient(client, options, resumedRecordId) {
|
|
|
5735
5775
|
recordId: resumedRecordId ?? randomUUID(),
|
|
5736
5776
|
sessionId,
|
|
5737
5777
|
agentSessionId,
|
|
5778
|
+
sessionOrigin: options.resumeSessionId ? "resume" : "new",
|
|
5738
5779
|
agentCommand: options.agentCommand,
|
|
5739
5780
|
agentArgv: options.agentArgv,
|
|
5740
5781
|
cwd,
|
|
@@ -7284,6 +7325,7 @@ async function runOwnedSessionPrompt(options) {
|
|
|
7284
7325
|
timeoutMs: options.timeoutMs,
|
|
7285
7326
|
verbose: options.verbose,
|
|
7286
7327
|
suppressWarnings: options.suppressSdkConsoleErrors,
|
|
7328
|
+
promptRecorded: true,
|
|
7287
7329
|
activeController,
|
|
7288
7330
|
authority: { signal: options.ownedSignal },
|
|
7289
7331
|
onClientAvailable: (controller) => {
|
|
@@ -8079,4 +8121,4 @@ const queueOwnerRuntimeTestInternals = { queueOwnerExitIsFatal };
|
|
|
8079
8121
|
//#endregion
|
|
8080
8122
|
export { isRequestedModelUnsupportedError as $, applyInitialModelSelection as A, reconcileAgentSessionId as B, setSessionModeOnOwner as C, connectAndLoadSession as D, withConnectedSession as E, persistSessionOptions as F, recordSessionUpdate as G, createSessionConversation as H, sessionOptionsFromRecord as I, advertisedModelState as J, trimConversationForRuntime as K, applyConversation as L, applyRequestedModelIfAdvertised as M, setDesiredModeId as N, applyConfigOptionSelection as O, normalizeSessionOptionShape as P, RequestedModelUnsupportedError as Q, applyLifecycleSnapshotToRecord as R, setSessionMode as S, setSessionModelOnOwner as T, recordClientOperation as U, cloneSessionConversation as V, recordPromptSubmission as W, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as X, AcpClient as Y, REQUESTED_MODEL_UNSUPPORTED_REASONS as Z, cancelSessionPrompt as _, runQueuedTask as a, normalizeQueueOwnerTtlMs as at, setSessionConfigOption as b, LiveSessionCheckpoint as c, listSessionEvents as ct, flushPerfMetricsCapture as d, TimeoutError as dt, resolveRequestedConfigOption as et, installPerfMetricsCapture as f, assertControlAuthority as ft, listAgentSessions as g, ensureSession as h, runOnce as i, DEFAULT_QUEUE_OWNER_TTL_MS as it, applyModelSelection as j, applyConfigOptionsToRecord as k, runPromptTurn as l, isLegacyZedCodexAcpInvocation as lt, createSessionWithClient as m, withTimeout as mt, runSessionQueueOwner as n, getAcpxVersion as nt, sendSessionDirect as o, acquireSessionImport as ot, createSession as p, withInterrupt as pt, cloneSessionAcpxState as q, sendSession as r, permissionModeSatisfies as rt, DISCARD_OUTPUT_FORMATTER as s, acquireSessionScope as st, queueOwnerRuntimeTestInternals as t, resolveRequestedModelId as tt, buildQueueOwnerArgOverride as u, InterruptedError as ut, closeSession as v, setSessionModel as w, setSessionConfigOptionOnOwner as x, sessionControlTestInternals as y, createInitialSessionRecord as z };
|
|
8081
8123
|
|
|
8082
|
-
//# sourceMappingURL=queue-owner-runtime-
|
|
8124
|
+
//# sourceMappingURL=queue-owner-runtime-DoijBCvt.js.map
|