mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-06 10:48:12 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent adapters select a provider, a model, and a runtime. > - Runner conversion rejected existing Claude agents. The model list mixed providers. > - The native Claude runner rejected custom models and could not launch on macOS. > - This pull request fixes conversion, model selection, and verified macOS execution. > - It also groups configuration fields consistently across adapters and opens artifact images in the task gallery. > - Operators can change an agent configuration and run the selected model on their Mac. ## Linked Issues or Issue Description **What happened?** Converting an existing Claude agent to Paperclip Runner failed with a Codex-only restriction. ACPX Claude showed unrelated models and required `claude-sonnet-5`. Its native runtime rejected macOS. Configuration mixed common model settings with process controls. Artifact cards labeled “Open gallery” navigated to attachment URLs instead of opening the task gallery. **Expected behavior** Conversion keeps agent identity and compatible settings. ACPX Claude uses the normal Claude catalog and accepts typed model IDs. Codex uses the native runner. The verified Claude runtime can launch on macOS ARM64 and x64. Common configuration sections place the same fields together across adapters. Artifact images open in the shared task gallery with navigation and downloads. **Steps to reproduce** 1. Open the configuration of an existing Claude agent. 2. Convert it to Paperclip Runner. 3. Select ACPX Claude and a different catalog model or a typed model ID. 4. Save the agent and run a disposable task on macOS. 5. Inspect configuration and advanced run-policy controls across adapters. **Paperclip version or commit** The bugs were reproduced on `165ca56a22adb60e5fda56045442d9c8498116a8`. This branch was rebased onto `7ed122911`. **Deployment mode** Built from source. Local test-drive instance on macOS ARM64 with an isolated database. Related work: #11798 addresses unsupported ACP session options in the existing adapter path. #13048 addresses working-folder preservation. This change fixes native runner configuration and launch behavior. ## What Changed - Remove the Codex-only conversion restriction. Preserve agent identity, instructions, directories, credentials, and compatible model settings. Reset incompatible sessions while retaining history. - Show ACPX Claude and native Codex as distinct provider choices. Remove ACPX Codex from advertised configuration. Normalize legacy configurations before fresh runs without rewriting historical run descriptors. - Select model catalogs and cache entries by provider. Support refresh and typed model IDs. Pass exact Claude IDs through session creation, model changes, and recovery. - Add verified macOS ARM64 and x64 Claude SDK snapshots. Bound executable allocation and total snapshot size. Preserve package checks, dependency isolation, process ownership, cancellation, and Linux descriptor loading. - Probe local runtime readiness. Report remote platform checks as incomplete until the remote runner verifies its runtime. - Surface actual model rejection and allow correction and retry. - Repair missing ACPX goal-capability helpers exposed by the post-rebase live test. Persist and restore the optional capability without breaking session startup. - Put Agent identity first and intentionally remove the Capabilities editor, as requested. This is removal of UI editing, not relocation: preserve existing capability metadata and API compatibility without adding another editor. Use the themed select for configurable permission modes, with normal text instead of monospace. - Put model and provider under Adapter. Give environment variables their own section. Fold command and arguments under Configuration. Fold lifecycle, timeout, and interrupt grace under Advanced Run Policy. Hide single-option permission controls. - Open image and video artifact cards in the existing task gallery, including cards in the artifacts panel. Chat attachment images use the same gallery. Preserve standalone media previews and download links. ## Verification - Rebased focused UI/API/database suites: 293 tests passed. - Rebased native runtime and ACPX suites: 242 passed, 7 skipped. - Repository typecheck, build, and token gates passed for the runner changes. Gallery follow-up UI typecheck, build, and token gates also passed. - Follow-up UI suites passed (86 tests), packaging checks passed (14 tests), and the final focused runtime suites passed (126 passed, 7 skipped). - Linux container isolation and lifecycle fixtures passed before rebase (57 passed, 2 skipped). Rust ACPX provider-session tests passed after rebase (8 tests). - Browser tests completed actual Claude and native Codex tasks on macOS ARM64. They covered conversion, catalog refresh, a non-default catalog model, a typed `haiku` ID, save/reload, cancel, follow-up session continuity, invalid-model errors, and recovery. - Final-revision live tests completed a typed Claude task, a follow-up with the same provider session, and a native Codex task on macOS ARM64. - Browser tests confirmed the moved interrupt-grace field saves and survives reload. Cross-adapter tests cover Claude, Codex, Gemini, process, gateway, and schema forms. - Full local run: 7,080 passed, 30 skipped, and two timeouts. Both timeout suites passed on isolated rerun (84 tests); the failures were the plugin login-worker exit diagnostic and the runner real-server vertical slice. - Final follow-up checks: 50 registry tests and 45 snapshot/installation tests passed (6 platform-specific skips). Oversized executable rejection is covered before allocation or reading; unsupported-platform tests invoke the real installation probe. - Runner head `ddb5101c483a297f74875ab96b3c66035b002d50`: all CI gates green, including full runner verification, repository build, typecheck, general/serialized server suites, browser tests, and canary dry run. [CI run](https://github.com/paperclipai/paperclip/actions/runs/34286178670). - Greptile: 5/5 on that runner head. All four review threads resolved. Superagent, Socket, and Snyk checks green. - After snapshot hardening, another real Claude task completed on this Mac using the rebuilt runtime. - Gallery follow-up: 148 focused tests passed, covering artifact selection, shared attachment collections, deduplication, image/video cards, standalone previews, downloads, and closing. Live browser verification completed on the settings follow-up: artifact selection, 6-image pagination with wrapping, download action, and closing all stayed on the same task URL. All checks passed on gallery head `96136da58ff195bf6ca00b281eb3022ad12d7bd8`: [CI run](https://github.com/paperclipai/paperclip/actions/runs/34287987536). Greptile returned 5/5 on that exact head with no unresolved threads. - Final settings polish: 96 focused tests, UI typecheck/build, and token gates passed. A real browser walkthrough verified readable permission options, identity placement, Capabilities removal, and permission save/reload. Original test-agent permission mode restored. All 31 checks passed on final head `e46540d6bf32bfb0566dca16b2f4a75ba437618c`: [CI run](https://github.com/paperclipai/paperclip/actions/runs/34292797886). Greptile returned 5/5 with no unresolved threads. ## Risks - Capabilities intentionally has no editable UI field after this change. Existing values remain readable and API-compatible; removing the field does not erase stored metadata. - macOS launch now copies verified package files into private snapshots. The implementation must retain isolation and clean up snapshots on exit. - Runtime provider or model changes reset the current session. Historical runs remain available. - The macOS x64 SDK executable digest was verified, but a live Intel Mac run was not available. Linux verification used container fixtures, not a real Claude task. - Remote environment tests report a warning when only the platform has been checked. They do not claim package readiness from the server host. ## Model Used OpenAI Codex, based on GPT-6. The exact served model identifier and context-window limit are not exposed in this session. Used reasoning, repository inspection, code execution, Rust and TypeScript tests, and browser automation. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (focused suites and both timeout suites on rerun; full-run counts above) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
459 lines
24 KiB
Diff
459 lines
24 KiB
Diff
diff --git a/dist/client-CxNllqui.d.ts b/dist/client-CxNllqui.d.ts
|
|
index 5e2113a..b7b5151 100644
|
|
--- a/dist/client-CxNllqui.d.ts
|
|
+++ b/dist/client-CxNllqui.d.ts
|
|
@@ -135,6 +135,7 @@ declare class AcpClient {
|
|
private throwPromptPermissionFailureIfPresent;
|
|
setSessionMode(sessionId: string, modeId: string): Promise<void>;
|
|
setSessionConfigOption(sessionId: string, configId: string, value: string): Promise<SetSessionConfigOptionResponse>;
|
|
+ requestExtension(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
setSessionModel(sessionId: string, modelId: string, controlOverride?: ModelControlOverride): Promise<SetSessionConfigOptionResponse | undefined>;
|
|
private setSessionModelThroughConfig;
|
|
private setSessionModelThroughLegacyMethod;
|
|
diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
|
|
index d454fd7c5bf742b469be75eb8c3988b694a0ffaa..f5775e731d6a4808c7bd59b4228da766f46ce3db 100644
|
|
--- a/dist/live-checkpoint-BSIrfgVo.js
|
|
+++ b/dist/live-checkpoint-BSIrfgVo.js
|
|
@@ -1068,6 +1068,7 @@ function serializeSessionRecordForDisk(record) {
|
|
last_agent_disconnect_reason: canonical.lastAgentDisconnectReason,
|
|
protocol_version: canonical.protocolVersion,
|
|
agent_capabilities: canonical.agentCapabilities,
|
|
+ agent_goal_capability: canonical.agentGoalCapability,
|
|
title: canonical.title,
|
|
messages: canonical.messages,
|
|
updated_at: canonical.updated_at,
|
|
@@ -1541,6 +1542,7 @@ function parseSessionRecord(raw) {
|
|
lastAgentDisconnectReason: optionals.lastAgentDisconnectReason,
|
|
protocolVersion: typeof record.protocol_version === "number" ? record.protocol_version : void 0,
|
|
agentCapabilities: asRecord$4(record.agent_capabilities),
|
|
+ agentGoalCapability: asRecord$4(record.agent_goal_capability),
|
|
title: conversation.title,
|
|
messages: conversation.messages,
|
|
updated_at: conversation.updated_at,
|
|
@@ -1661,7 +1663,7 @@ const ZED_TAG_KEYS = /* @__PURE__ */ new Set([
|
|
"RedactedThinking",
|
|
"ToolUse"
|
|
]);
|
|
-const MAP_OBJECT_PATHS = /* @__PURE__ */ new Set(["request_token_usage", "messages.Agent.tool_results"]);
|
|
+const MAP_OBJECT_PATHS = /* @__PURE__ */ new Set(["request_token_usage", "messages.Agent.tool_results", "acpx.session_options.env"]);
|
|
const OPAQUE_VALUE_PATHS = /* @__PURE__ */ new Set([
|
|
"agent_capabilities",
|
|
"messages.Agent.content.ToolUse.input",
|
|
@@ -3135,8 +3135,18 @@ function promotePrefixedAuthEnvironment(env) {
|
|
}
|
|
return protectedKeys;
|
|
}
|
|
-function buildAgentEnvironment(authCredentials, sessionEnv) {
|
|
- const env = { ...process.env };
|
|
+function isPlainStringEnvironment(value) {
|
|
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
+ const prototype = Object.getPrototypeOf(value);
|
|
+ return (prototype === Object.prototype || prototype === null) && Object.values(value).every((entry) => typeof entry === "string");
|
|
+}
|
|
+function buildAgentEnvironment(authCredentials, sessionEnv, spawnEnvironment) {
|
|
+ let sourceEnvironment = process.env;
|
|
+ if (spawnEnvironment !== void 0) {
|
|
+ sourceEnvironment = spawnEnvironment();
|
|
+ if (!isPlainStringEnvironment(sourceEnvironment)) throw new TypeError("ACPX spawn environment must be a plain record of string values");
|
|
+ }
|
|
+ const env = { ...sourceEnvironment };
|
|
const protectedAuthEnvKeys = promotePrefixedAuthEnvironment(env);
|
|
if (authCredentials) for (const [methodId, credential] of Object.entries(authCredentials)) {
|
|
addAuthCredentialEnvKeys(protectedAuthEnvKeys, methodId, credential);
|
|
@@ -3178,10 +3188,10 @@ function resolveConfiguredAuthCredential(methodId, authCredentials) {
|
|
const configCredentials = authCredentials ?? {};
|
|
return configCredentials[methodId] ?? configCredentials[toEnvToken(methodId)];
|
|
}
|
|
-function buildAgentSpawnOptions(cwd, authCredentials, sessionEnv) {
|
|
+function buildAgentSpawnOptions(cwd, authCredentials, sessionEnv, spawnEnvironment) {
|
|
return {
|
|
cwd,
|
|
- env: buildAgentEnvironment(authCredentials, sessionEnv),
|
|
+ env: buildAgentEnvironment(authCredentials, sessionEnv, spawnEnvironment),
|
|
stdio: [
|
|
"pipe",
|
|
"pipe",
|
|
@@ -4216,9 +4226,21 @@ var AcpClient = class {
|
|
this.lastAgentExit = void 0;
|
|
this.lastKnownPid = child.pid ?? void 0;
|
|
this.attachAgentLifecycleObservers(child);
|
|
+ if (this.options.onAgentSpawn) {
|
|
+ try {
|
|
+ if (!child.pid) throw new Error("ACPX agent spawn did not expose a valid process id.");
|
|
+ await this.options.onAgentSpawn({ pid: child.pid, startedAt: this.agentStartedAt });
|
|
+ } catch (error) {
|
|
+ try {
|
|
+ child.kill("SIGKILL");
|
|
+ } catch {}
|
|
+ throw error;
|
|
+ }
|
|
+ }
|
|
const startupStderr = [];
|
|
child.stderr.on("data", (chunk) => {
|
|
this.captureStartupStderr(startupStderr, chunk);
|
|
+ this.options.onAgentStderr?.(String(chunk));
|
|
if (!this.options.verbose) return;
|
|
process.stderr.write(chunk);
|
|
});
|
|
@@ -4253,7 +4275,12 @@ var AcpClient = class {
|
|
geminiAcp: isGeminiAcpCommand(spawnCommand, args),
|
|
copilotAcp: isCopilotAcpCommand(spawnCommand, args),
|
|
claudeAcp: isClaudeAcpCommand(spawnCommand, args),
|
|
- spawnOptions: buildAgentSpawnOptions(this.options.cwd, this.options.authCredentials, this.options.sessionOptions?.env)
|
|
+ spawnOptions: buildAgentSpawnOptions(
|
|
+ this.options.spawnCwd ?? this.options.cwd,
|
|
+ this.options.authCredentials,
|
|
+ this.options.sessionOptions?.env,
|
|
+ this.options.spawnEnvironment
|
|
+ )
|
|
};
|
|
}
|
|
logAgentLaunch(plan) {
|
|
@@ -4279,10 +4306,17 @@ var AcpClient = class {
|
|
}
|
|
async spawnAgentProcess(plan) {
|
|
const spawnCommand = buildAgentSpawnCommand(plan.spawnCommand, plan.args, process.platform, plan.spawnOptions.env);
|
|
- const spawnedChild = spawn(spawnCommand.command, spawnCommand.args, {
|
|
+ const options = {
|
|
...plan.spawnOptions,
|
|
windowsVerbatimArguments: spawnCommand.windowsVerbatimArguments
|
|
- });
|
|
+ };
|
|
+ const spawnedChild = this.options.spawnAgent
|
|
+ ? this.options.spawnAgent({
|
|
+ command: spawnCommand.command,
|
|
+ args: spawnCommand.args,
|
|
+ options
|
|
+ })
|
|
+ : spawn(spawnCommand.command, spawnCommand.args, options);
|
|
try {
|
|
await waitForSpawn$1(spawnedChild);
|
|
} catch (error) {
|
|
@@ -5028,6 +5062,12 @@ var AcpClient = class {
|
|
attachAgentLifecycleObservers(child) {
|
|
child.once("exit", (exitCode, signal) => {
|
|
this.recordAgentExit("process_exit", exitCode, signal);
|
|
+ this.options.onAgentExit?.({
|
|
+ pid: child.pid ?? this.lastKnownPid,
|
|
+ exitCode,
|
|
+ signal,
|
|
+ exitedAt: isoNow$1()
|
|
+ });
|
|
});
|
|
child.once("close", (exitCode, signal) => {
|
|
this.recordAgentExit("process_close", exitCode, signal);
|
|
@@ -6518,4 +6547,4 @@ var LiveSessionCheckpoint = class {
|
|
//#endregion
|
|
export { writeSessionRecord as $, PERMISSION_POLICY_ACTIONS as $t, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as A, TimeoutError as At, getAcpxVersion as B, formatErrorMessage as Bt, mergeSessionOptions as C, PromptInputValidationError as Ct, applyLifecycleSnapshotToRecord as D, promptToDisplayText as Dt, applyConversation as E, parsePromptSource as Et, modelStateFromConfigOptions as F, normalizeAgentName$1 as Ft, findSession as G, toAcpErrorPayload as Gt, DEFAULT_HISTORY_LIMIT as H, normalizeOutputError as Ht, normalizeAgentCommandInput as I, resolveAgentArgv as It, listSessions as J, NON_INTERACTIVE_PERMISSION_POLICIES as Jt, findSessionByDirectoryWalk as K, AUTH_POLICIES as Kt, renderArgvIdentity as L, resolveAgentCommand as Lt, RequestedModelUnsupportedError as M, withTimeout as Mt, assertRequestedModelSupported as N, DEFAULT_AGENT_NAME as Nt, reconcileAgentSessionId as O, textPrompt as Ot, isRequestedModelUnsupportedError as P, listBuiltInAgents as Pt, resolveSessionRecord as Q, PERMISSION_MODES as Qt, runTimedExecFile as R, resolveCanonicalAgentName as Rt, advertisedModelState as S, parsePromptStopReason as St, sessionOptionsFromRecord as T, mergePromptSourceWithText as Tt, absolutePath as U, extractAcpError as Ut, permissionModeSatisfies as V, isRetryablePromptError as Vt, findGitRepositoryRoot as W, isAcpResourceNotFoundError as Wt, normalizeName as X, OUTPUT_ERROR_ORIGINS as Xt, listSessionsForAgent as Y, OUTPUT_ERROR_CODES as Yt, pruneSessions as Z, OUTPUT_FORMATS as Zt, createSessionConversation as _, sessionEventLockPath as _t, applyRequestedModelIfAdvertised as a, measurePerf as at, recordSessionUpdate as b, isAcpJsonRpcMessage as bt, setCurrentModelId as c, setPerfGauge as ct, setDesiredModelId as d, serializeSessionRecordForDisk as dt, SESSION_RECORD_SCHEMA as en, createAtomicWriteTempPath as et, syncAdvertisedModelState as f, normalizeRuntimeSessionId as ft, cloneSessionConversation as g, sessionEventActivePath as gt, cloneSessionAcpxState as h, sessionBaseDir$1 as ht, connectAndLoadSession as i, QueueProtocolError as in, incrementPerfCounter as it, REQUESTED_MODEL_UNSUPPORTED_REASONS as j, withInterrupt as jt, AcpClient as k, InterruptedError as kt, setDesiredConfigOption as l, startPerfTimer as lt, applyConfigOptionsToState as m, defaultSessionEventLog as mt, runPromptTurn as n, AgentSpawnError as nn, formatPerfMetric as nt, currentModelIdFromSetModelResponse as o, recordPerfDuration as ot, applyConfigOptionsToRecord as p, DEFAULT_EVENT_SEGMENT_MAX_BYTES as pt, isoNow$2 as q, EXIT_CODES as qt, withConnectedSession as r, QueueConnectionError as rn, getPerfMetricsSnapshot as rt, clearDesiredConfigOption as s, resetPerfMetrics as st, LiveSessionCheckpoint as t, AcpxOperationalError as tn, assertPersistedKeyPolicy as tt, setDesiredModeId as u, parseSessionRecord as ut, recordClientOperation as v, sessionEventSegmentPath as vt, persistSessionOptions as w, isPromptInput as wt, trimConversationForRuntime as x, parseJsonRpcErrorMessage as xt, recordPromptSubmission as y, extractSessionUpdateNotification as yt, splitCommandLine as z, exitCodeForOutputErrorCode as zt };
|
|
|
|
-//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map
|
|
\ No newline at end of file
|
|
+//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map
|
|
diff --git a/dist/runtime.d.ts b/dist/runtime.d.ts
|
|
index e8102acb03c4c38830ad5ec22f356125eb0423b7..fcb1a1906f587b33ad818389c035f90362b0617e 100644
|
|
--- a/dist/runtime.d.ts
|
|
+++ b/dist/runtime.d.ts
|
|
@@ -1,7 +1,8 @@
|
|
import { _ as SessionRecord, a as AcpElicitationHandler, c as AcpElicitationResponse, f as McpServer$1, h as PermissionPolicy, i as AcpElicitationContext, l as AcpPermissionDecision, m as PermissionMode, n as SystemPromptOption, o as AcpElicitationMode, p as NonInteractivePermissionPolicy, s as AcpElicitationRequest, t as SessionAgentOptions, u as AcpPermissionRequest } from "./session-options-DwRDODlr.js";
|
|
import { a as RequestedModelUnsupportedErrorCode, i as RequestedModelUnsupportedError, n as REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, o as RequestedModelUnsupportedReason, r as REQUESTED_MODEL_UNSUPPORTED_REASONS, s as isRequestedModelUnsupportedError, t as AcpClient } from "./client-CxNllqui.js";
|
|
+import { ChildProcess, SpawnOptionsWithoutStdio } from "node:child_process";
|
|
import fs from "node:fs";
|
|
-import { ToolCallContent, ToolCallLocation, ToolKind } from "@agentclientprotocol/sdk";
|
|
+import { SessionNotification, ToolCallContent, ToolCallLocation, ToolKind } from "@agentclientprotocol/sdk";
|
|
//#region src/agent-registry.d.ts
|
|
declare const DEFAULT_AGENT_NAME = "codex";
|
|
//#endregion
|
|
@@ -141,6 +142,11 @@ type AcpTextDeltaOriginMeta = {
|
|
kind?: string;
|
|
source?: string;
|
|
};
|
|
+type AcpRuntimePlanEntry = {
|
|
+ content: string;
|
|
+ priority?: string;
|
|
+ status: "pending" | "in_progress" | "completed";
|
|
+};
|
|
type AcpRuntimeEvent = {
|
|
type: "text_delta";
|
|
text: string;
|
|
@@ -186,6 +192,10 @@ type AcpRuntimeEvent = {
|
|
* non-null `input` schema.
|
|
*/
|
|
availableCommands?: AcpRuntimeAvailableCommand[];
|
|
+} | {
|
|
+ type: "plan";
|
|
+ tag: "plan";
|
|
+ entries: AcpRuntimePlanEntry[];
|
|
} | {
|
|
type: "tool_call";
|
|
text: string;
|
|
@@ -313,6 +323,35 @@ type AcpRuntimeOptions = {
|
|
onPermissionRequest?: (req: AcpPermissionRequest, ctx: {
|
|
signal: AbortSignal;
|
|
}) => Promise<AcpPermissionDecision | undefined>;
|
|
+ /** Ephemeral allowlisted environment evaluated immediately before child spawn. */
|
|
+ spawnEnvironment?: () => Record<string, string>;
|
|
+ /** Host-only spawn cwd; does not change the cwd advertised in session/new. */
|
|
+ spawnCwd?: string;
|
|
+ /** Host-owned verified executable launch. */
|
|
+ spawnAgent?: (input: {
|
|
+ command: string;
|
|
+ args: readonly string[];
|
|
+ options: SpawnOptionsWithoutStdio;
|
|
+ }) => ChildProcess;
|
|
+ onAgentSpawn?: (meta: { pid: number; startedAt: string }) => Promise<void> | void;
|
|
+ onAgentStderr?: (chunk: string) => void;
|
|
+ onAgentExit?: (meta: {
|
|
+ pid?: number;
|
|
+ exitCode: number | null;
|
|
+ signal: NodeJS.Signals | null;
|
|
+ exitedAt: string;
|
|
+ }) => void;
|
|
+ onAcpMessage?: (direction: "inbound" | "outbound", message: unknown) => void;
|
|
+ /** Ephemeral full ACP notification callback; never written to session records. */
|
|
+ onSessionNotification?: (notification: SessionNotification) => void;
|
|
+ /** Ephemeral normalized ACP client filesystem/terminal operation callback. */
|
|
+ onClientOperation?: (operation: {
|
|
+ method: string;
|
|
+ status: string;
|
|
+ summary: string;
|
|
+ details?: string;
|
|
+ timestamp: string;
|
|
+ }) => void;
|
|
};
|
|
type AcpFileSessionStoreOptions = {
|
|
stateDir: string;
|
|
diff --git a/dist/runtime.js b/dist/runtime.js
|
|
index a1f4a70a003792c6eacf68b6b038f37bfec1db53..50029e881c07a7228ddd978bb03d040629cf776b 100644
|
|
--- a/dist/runtime.js
|
|
+++ b/dist/runtime.js
|
|
@@ -371,7 +371,7 @@ const PROMPT_EVENT_PARSERS = {
|
|
current_mode_update: (payload) => statusUpdateEvent("current_mode_update", payload),
|
|
config_option_update: (payload) => statusUpdateEvent("config_option_update", payload),
|
|
session_info_update: (payload) => statusUpdateEvent("session_info_update", payload),
|
|
- plan: (payload) => statusUpdateEvent("plan", payload),
|
|
+ plan: planUpdateEvent,
|
|
client_operation: clientOperationEvent,
|
|
update: updateStatusEvent,
|
|
done: () => null,
|
|
@@ -424,6 +424,34 @@ function availableCommandsUpdateEvent(payload) {
|
|
availableCommands
|
|
};
|
|
}
|
|
+function persistedGoalCapability(goal) {
|
|
+ if (!isRecord(goal) || goal.version !== 1 || goal.controlMethod !== "_session/goal" || !Array.isArray(goal.actions)) return;
|
|
+ const actions = goal.actions.filter((action) => ["set", "pause", "resume", "clear"].includes(action));
|
|
+ if (!actions.includes("set") || !actions.includes("clear")) return;
|
|
+ return { version: 1, control_method: goal.controlMethod, actions };
|
|
+}
|
|
+function restoredGoalCapability(goal) {
|
|
+ if (!isRecord(goal)) return;
|
|
+ const canonical = persistedGoalCapability({ ...goal, controlMethod: goal.control_method ?? goal.controlMethod });
|
|
+ if (!canonical) return;
|
|
+ return { version: canonical.version, controlMethod: canonical.control_method, actions: canonical.actions };
|
|
+}
|
|
+
|
|
+
|
|
+function planUpdateEvent(payload) {
|
|
+ const raw = Array.isArray(payload.entries) ? payload.entries : [];
|
|
+ const entries = [];
|
|
+ for (const entry of raw) {
|
|
+ if (!isRecord(entry)) continue;
|
|
+ const content = asTrimmedString(entry.content);
|
|
+ if (!content) continue;
|
|
+ const status = asTrimmedString(entry.status);
|
|
+ if (status !== "pending" && status !== "in_progress" && status !== "completed") continue;
|
|
+ const priority = asTrimmedString(entry.priority);
|
|
+ entries.push({ content, status, ...priority ? { priority } : {} });
|
|
+ }
|
|
+ return { type: "plan", tag: "plan", entries };
|
|
+}
|
|
function normalizeUsageCost(value) {
|
|
if (!isRecord(value)) return;
|
|
const amount = asOptionalFiniteNumber(value.amount);
|
|
@@ -812,7 +826,17 @@ var AcpRuntimeManager = class {
|
|
this.deps = deps;
|
|
}
|
|
createClient(options) {
|
|
- return this.deps.clientFactory?.(options) ?? new AcpClient(options);
|
|
+ const patchedOptions = {
|
|
+ ...options,
|
|
+ spawnCwd: this.options.spawnCwd,
|
|
+ spawnEnvironment: this.options.spawnEnvironment,
|
|
+ spawnAgent: this.options.spawnAgent,
|
|
+ onAgentSpawn: this.options.onAgentSpawn,
|
|
+ onAgentStderr: this.options.onAgentStderr,
|
|
+ onAgentExit: this.options.onAgentExit,
|
|
+ onAcpMessage: this.options.onAcpMessage
|
|
+ };
|
|
+ return this.deps.clientFactory?.(patchedOptions) ?? new AcpClient(patchedOptions);
|
|
}
|
|
createSessionOwner(input) {
|
|
const owner = {
|
|
@@ -821,12 +845,16 @@ var AcpRuntimeManager = class {
|
|
pendingSessionUpdates: []
|
|
};
|
|
input.client.setEventHandlers({
|
|
+ onAcpMessage: this.options.onAcpMessage,
|
|
onSessionUpdate: (notification) => this.routeOwnedSessionUpdate(owner, notification),
|
|
onClientOperation: (operation) => this.routeOwnedClientOperation(owner, operation)
|
|
});
|
|
return owner;
|
|
}
|
|
routeOwnedSessionUpdate(owner, notification) {
|
|
+ try {
|
|
+ this.options.onSessionNotification?.(notification);
|
|
+ } catch {}
|
|
const active = owner.activeTurn;
|
|
if (active) {
|
|
const { task, turn } = active;
|
|
@@ -863,6 +891,9 @@ var AcpRuntimeManager = class {
|
|
projection.checkpoint.request();
|
|
}
|
|
routeOwnedClientOperation(owner, operation) {
|
|
+ try {
|
|
+ this.options.onClientOperation?.(operation);
|
|
+ } catch {}
|
|
const active = owner.activeTurn;
|
|
if (!active) return;
|
|
const { task, turn } = active;
|
|
@@ -1008,6 +1062,8 @@ var AcpRuntimeManager = class {
|
|
record.closedAt = void 0;
|
|
record.protocolVersion = owner.client.initializeResult?.protocolVersion;
|
|
record.agentCapabilities = owner.client.initializeResult?.agentCapabilities;
|
|
+ record.agentGoalCapability = persistedGoalCapability(owner.client.initializeResult?._meta?.goal);
|
|
+ this.options.onAgentInitialize?.(owner.client.initializeResult);
|
|
applyLifecycleSnapshotToRecord(record, owner.client.getAgentLifecycleSnapshot());
|
|
}
|
|
async finishBufferedOwnerControl(owner, record) {
|
|
@@ -1086,6 +1142,11 @@ var AcpRuntimeManager = class {
|
|
record.closed = false;
|
|
record.closedAt = void 0;
|
|
this.closingActiveRecords.delete(record.acpxRecordId);
|
|
+ this.options.onAgentInitialize?.({
|
|
+ protocolVersion: record.protocolVersion,
|
|
+ agentCapabilities: record.agentCapabilities,
|
|
+ _meta: record.agentGoalCapability ? { goal: restoredGoalCapability(record.agentGoalCapability) } : void 0
|
|
+ });
|
|
await this.options.sessionStore.save(record);
|
|
return record;
|
|
}
|
|
@@ -1149,6 +1210,8 @@ var AcpRuntimeManager = class {
|
|
this.closingActiveRecords.delete(record.acpxRecordId);
|
|
record.protocolVersion = client.initializeResult?.protocolVersion;
|
|
record.agentCapabilities = client.initializeResult?.agentCapabilities;
|
|
+ record.agentGoalCapability = persistedGoalCapability(client.initializeResult?._meta?.goal);
|
|
+ this.options.onAgentInitialize?.(client.initializeResult);
|
|
applyConfigOptionsToRecord(record, session.sessionResult);
|
|
const modelApplication = await applyRequestedModelIfAdvertised({
|
|
client,
|
|
@@ -1469,6 +1532,10 @@ var AcpRuntimeManager = class {
|
|
setSessionConfigOption: async (configId, value) => {
|
|
return (await task.state.activeController.setResolvedSessionConfigOption(configId, value)).response;
|
|
},
|
|
+ requestExtension: async (method, params) => {
|
|
+ await this.waitForRuntimeControlSession(task, turn);
|
|
+ return await turn.client.requestExtension(method, params);
|
|
+ },
|
|
setResolvedSessionConfigOption: async (configId, value) => await this.setRuntimeResolvedSessionConfigOption(task, turn, configId, value)
|
|
};
|
|
}
|
|
@@ -1575,6 +1642,8 @@ var AcpRuntimeManager = class {
|
|
reconcileAgentSessionId(turn.record, turn.record.agentSessionId);
|
|
turn.record.protocolVersion = turn.client.initializeResult?.protocolVersion;
|
|
turn.record.agentCapabilities = turn.client.initializeResult?.agentCapabilities;
|
|
+ turn.record.agentGoalCapability = persistedGoalCapability(turn.client.initializeResult?._meta?.goal);
|
|
+ this.options.onAgentInitialize?.(turn.client.initializeResult);
|
|
turn.record.acpx = turn.acpxState;
|
|
applyConversation(turn.record, turn.conversation);
|
|
applyLifecycleSnapshotToRecord(turn.record, turn.client.getAgentLifecycleSnapshot());
|
|
@@ -1707,6 +1776,17 @@ var AcpRuntimeManager = class {
|
|
});
|
|
await this.options.sessionStore.save(result.record);
|
|
}
|
|
+ async requestExtension(input) {
|
|
+ const recordId = input.handle.acpxRecordId ?? input.handle.sessionKey;
|
|
+ return await this.withManagerLock(this.runtimeOperationLocks, recordId, async () => {
|
|
+ const record = await this.requireRecord(recordId);
|
|
+ const controller = this.activeControllers.get(record.acpxRecordId);
|
|
+ if (controller) return await controller.requestExtension(input.method, input.params);
|
|
+ return (await this.withRuntimeControlSession(record, input.sessionMode ?? "persistent", async ({ client }) => {
|
|
+ return await client.requestExtension(input.method, input.params);
|
|
+ })).value;
|
|
+ });
|
|
+ }
|
|
async cancel(handle) {
|
|
await this.activeControllers.get(handle.acpxRecordId ?? handle.sessionKey)?.requestCancelActivePrompt();
|
|
}
|
|
@@ -2119,6 +2199,14 @@ var AcpxRuntime = class {
|
|
const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
await (await this.getManager()).setConfigOption(handle, input.key, input.value, state.mode);
|
|
}
|
|
+ async requestExtension(input) {
|
|
+ const { handle, state } = this.resolveManagerHandle(input.handle);
|
|
+ return await (await this.getManager()).requestExtension({
|
|
+ ...input,
|
|
+ handle,
|
|
+ sessionMode: input.sessionMode ?? state.mode
|
|
+ });
|
|
+ }
|
|
async cancel(input) {
|
|
const { handle } = this.resolveManagerHandle(input.handle);
|
|
await (await this.getManager()).cancel(handle);
|
|
@@ -2178,4 +2266,4 @@ function createRuntimeStore(options) {
|
|
//#endregion
|
|
export { ACPX_BACKEND_ID, AcpRuntimeError, AcpxRuntime, DEFAULT_AGENT_NAME, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, REQUESTED_MODEL_UNSUPPORTED_REASONS, RequestedModelUnsupportedError, createAcpRuntime, createAgentRegistry, createFileSessionStore, createRuntimeStore, decodeAcpxRuntimeHandleState, encodeAcpxRuntimeHandleState, isAcpRuntimeError, isRequestedModelUnsupportedError };
|
|
|
|
-//# sourceMappingURL=runtime.js.map
|
|
\ No newline at end of file
|
|
+//# sourceMappingURL=runtime.js.map
|
|
diff --git a/dist/session-options-DwRDODlr.d.ts b/dist/session-options-DwRDODlr.d.ts
|
|
index c3da1645235bbea22de3f8484149051cd7dca56b..ad1f2f6c6a7f477e83dc0061e4168c00c23382da 100644
|
|
--- a/dist/session-options-DwRDODlr.d.ts
|
|
+++ b/dist/session-options-DwRDODlr.d.ts
|
|
@@ -1,4 +1,5 @@
|
|
import { AgentCapabilities, AnyMessage, ContentBlock, CreateElicitationRequest, ElicitationContentValue, JsonRpcId, McpServer, McpServer as McpServer$1, RequestPermissionRequest, SessionConfigOption, SessionNotification, SetSessionConfigOptionResponse, ToolKind } from "@agentclientprotocol/sdk";
|
|
+import { ChildProcess, SpawnOptionsWithoutStdio } from "node:child_process";
|
|
//#region src/prompt-content.d.ts
|
|
type PromptInput = ContentBlock[];
|
|
//#endregion
|
|
@@ -116,6 +117,24 @@ type AcpClientOptions = {
|
|
};
|
|
env?: Record<string, string>;
|
|
};
|
|
+ /** Ephemeral child environment factory; its return value is never persisted. */
|
|
+ spawnEnvironment?: () => Record<string, string>;
|
|
+ /** Host-only child cwd, separate from the cwd advertised to ACP. */
|
|
+ spawnCwd?: string;
|
|
+ /** Host-owned verified executable launch. */
|
|
+ spawnAgent?: (input: {
|
|
+ command: string;
|
|
+ args: readonly string[];
|
|
+ options: SpawnOptionsWithoutStdio;
|
|
+ }) => ChildProcess;
|
|
+ onAgentSpawn?: (meta: { pid: number; startedAt: string }) => Promise<void> | void;
|
|
+ onAgentStderr?: (chunk: string) => void;
|
|
+ onAgentExit?: (meta: {
|
|
+ pid?: number;
|
|
+ exitCode: number | null;
|
|
+ signal: NodeJS.Signals | null;
|
|
+ exitedAt: string;
|
|
+ }) => void;
|
|
onAcpMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;
|
|
onAcpOutputMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;
|
|
onSessionUpdate?: (notification: SessionNotification) => void;
|
|
@@ -263,6 +275,7 @@ type SessionRecord = {
|
|
lastAgentDisconnectReason?: string;
|
|
protocolVersion?: number;
|
|
agentCapabilities?: AgentCapabilities;
|
|
+ agentGoalCapability?: Record<string, unknown>;
|
|
title?: string | null;
|
|
messages: SessionMessage[];
|
|
updated_at: string;
|
|
@@ -295,4 +308,4 @@ type SessionAgentOptions = {
|
|
};
|
|
//#endregion
|
|
export { SessionRecord as _, AcpElicitationHandler as a, AcpElicitationResponse as c, AuthPolicy as d, McpServer$1 as f, PermissionStats as g, PermissionPolicy as h, AcpElicitationContext as i, AcpPermissionDecision as l, PermissionMode as m, SystemPromptOption as n, AcpElicitationMode as o, NonInteractivePermissionPolicy as p, AcpClientOptions as r, AcpElicitationRequest as s, SessionAgentOptions as t, AcpPermissionRequest as u, PromptInput as v };
|
|
-//# sourceMappingURL=session-options-DwRDODlr.d.ts.map
|
|
\ No newline at end of file
|
|
+//# sourceMappingURL=session-options-DwRDODlr.d.ts.map
|