Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Preserve agent cancellation, tool accounting and replay

wytc0cc0317b2fd
diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.ts
index 22edea11..fb4dd6c3 100644
--- a/src/core-agent/src/agent/runner.ts
+++ b/src/core-agent/src/agent/runner.ts
@@ -439,11 +439,17 @@ function estimateRequestInputTokens(
toolDefs: unknown[],
turnEphemeral?: string,
): number {
- return session.estimateModelTokens()
- + estimateFixedOverheadTokens(systemPrompt, toolDefs, turnEphemeral);
+ return estimateCompletionRequestInputTokens({
+ model: "",
+ messages: session.getMessagesForModel(turnEphemeral ? { turnContext: turnEphemeral } : undefined),
+ systemPrompt,
+ tools: toolDefs as CompletionParams["tools"],
+ });
}
-/** Price the actual request view at candidate admission, including scoped
+const requestThinkingTokenCache = new WeakMap<object, { text: string; tokens: number }>();
+
+/** Price the actual request view at preparation and candidate admission, including scoped
* controls already in messages. Reuse Session's block cache and tool schema
* cache; never serialize binary media or read/mutate session state. Plaintext
* thinking is conservatively included even if a foreign adapter omits it. */
@@ -451,7 +457,13 @@ export function estimateCompletionRequestInputTokens(params: CompletionParams):
let tokens = sumMessageTokens(params.messages)
+ estimateFixedOverheadTokens(params.systemPrompt || "", params.tools || []);
for (const message of params.messages) for (const block of message.content) {
- if (block.type === "thinking") tokens += estimateTextTokens(block.thinking);
+ if (block.type !== "thinking") continue;
+ let cached = requestThinkingTokenCache.get(block);
+ if (!cached || cached.text !== block.thinking) {
+ cached = { text: block.thinking, tokens: estimateTextTokens(block.thinking) };
+ requestThinkingTokenCache.set(block, cached);
+ }
+ tokens += cached.tokens;
}
return tokens;
}
@@ -1772,8 +1784,9 @@ export class AgentRunner {
// Injected by reference into each round's `toolState` under the
// `readFileState` key — a host/tool contract (like `sandboxEnv`): file
// tools stamp it on read and check/refresh it on edit. The runner itself
- // never reads it.
- const readFileState = new Map<string, unknown>();
+ // never reads it. A host may seed stamps for files whose complete bytes it
+ // injected into this turn; the copy keeps the seed from outliving the run.
+ const readFileState = new Map<string, unknown>(params.initialReadFileState ?? []);
// Generic run-scoped counters/ledgers used by tools whose safety budgets
// must survive the per-model-round ToolContext reconstruction.
const runScopedLedger = new Map<string, unknown>();
@@ -1840,6 +1853,30 @@ export class AgentRunner {
const budgetEphemeral = [params.turnEphemeral, continuationBudgetTail]
.filter(Boolean)
.join("\n\n");
+ // Preparation and dispatch must price the same view. This is read-only:
+ // controls are still acknowledged only after a completed provider call.
+ const requestControlsNow = (): string[] => {
+ const repeat = guards.pendingCompletedRepeatNudge();
+ return [
+ ...pendingRequestControls,
+ ...(repeat ? [repeat] : []),
+ ...(outputRecoveryControl ? [outputRecoveryControl] : []),
+ ...(toolBoundarySynthesisPending ? [toolBoundarySynthesisControl] : []),
+ ];
+ };
+ const requestMessagesNow = (controls = requestControlsNow()): Message[] => {
+ const persisted = this.session.getMessagesForModel(
+ params.turnEphemeral ? { turnContext: params.turnEphemeral } : undefined,
+ );
+ const messages: Message[] = outputContinuationDraft?.content.length
+ ? [...persisted, ...(outputContinuationDraft.replayContents ?? [outputContinuationDraft.content])
+ .map((content): Message => ({ role: "assistant", content }))]
+ : persisted;
+ return withRequestScopedControls(messages, controls);
+ };
+ const estimatePreparedRequest = (): number => estimateCompletionRequestInputTokens({
+ model: modelId, messages: requestMessagesNow(), systemPrompt, tools: toolDefs,
+ });
const reconciledWorkspace = this.session.reconcileWorkspaceObservations();
if (reconciledWorkspace) {
@@ -1870,7 +1907,6 @@ export class AgentRunner {
);
const callUsableInputTokens = this.resolveUsableInputTokens(modelId, servedModelId);
// In-memory scalar evidence only; the provider emits it on failure.
- // Reuse compaction's existing estimates rather than rescan healthy requests.
const contextBudgetDiagnostics: Record<string, number | string> = {
version: 1,
budget_context_window: historyModel?.contextWindow ?? 200_000,
@@ -1882,7 +1918,7 @@ export class AgentRunner {
const resultCapacityExhausted = exhaustedResultCallCount > 0 && calculateToolResultInlineBudget({
requestTokensBeforeResults: anchoredRequestTokens(
requestTokenAnchor,
- estimateRequestInputTokens(this.session, systemPrompt, toolDefs, budgetEphemeral || undefined),
+ estimatePreparedRequest(),
this.session.contentEpoch(),
this.session.getEstimatorCalibration(),
).tokens,
@@ -1927,6 +1963,7 @@ export class AgentRunner {
requestTokenAnchor,
contextBudgetDiagnostics,
exhaustedResultCallCount,
+ estimatePreparedRequest,
);
exhaustedResultCallCount = 0;
} finally {
@@ -1953,34 +1990,16 @@ export class AgentRunner {
// `CompletionResult`-shaped object at the end for the tool loop.
const pendingControlCount = pendingRequestControls.length;
const completedRepeatNudge = guards.pendingCompletedRepeatNudge();
- const requestControls = [
- ...pendingRequestControls,
- ...(completedRepeatNudge ? [completedRepeatNudge] : []),
- ...(outputRecoveryControl ? [outputRecoveryControl] : []),
- ...(toolBoundarySynthesisPending ? [toolBoundarySynthesisControl] : []),
- ];
- const persistedMessages = this.session.getMessagesForModel(
- params.turnEphemeral ? { turnContext: params.turnEphemeral } : undefined,
- );
- const requestMessages: Message[] = outputContinuationDraft?.content.length
- ? [
- ...persistedMessages,
- ...(outputContinuationDraft!.replayContents ?? [outputContinuationDraft!.content])
- .map((content): Message => ({ role: "assistant", content })),
- ]
- : persistedMessages;
+ const requestMessages = requestMessagesNow();
await this.session.flushPending(params.signal);
activeProviderStartedAt = Date.now();
providerOutput = { terminalSeen: false, textChars: 0, thinkingChars: 0, toolCalls: 0 };
- const streamIter = provider.stream({
+ const completionParams: CompletionParams = {
model: modelId,
// Only the real provider turn injects per-turn ephemeral context;
// summary / reflection callers of getMessagesForModel do not, so the
// block never leaks into those views (or into persistence).
- messages: withRequestScopedControls(
- requestMessages,
- requestControls,
- ),
+ messages: requestMessages,
systemPrompt,
tools: toolDefs.length > 0 ? toolDefs : undefined,
// Main-turn output cap. Do NOT hard-code: a fixed cap (was 4096)
@@ -2002,7 +2021,28 @@ export class AgentRunner {
// provider or upstream model apply its default; explicit `'off'`
// opts out of a provider-configured default.
...(params.thinkingLevel !== undefined ? { reasoning: params.thinkingLevel } : {}),
+ };
+ const preparedTokens = anchoredRequestTokens(
+ requestTokenAnchor,
+ estimateCompletionRequestInputTokens(completionParams),
+ this.session.contentEpoch(),
+ this.session.getEstimatorCalibration(),
+ );
+ const measuredModel = servedModelId || modelId;
+ Object.assign(contextBudgetDiagnostics, {
+ estimated_input_tokens: preparedTokens.tokens, estimate_source: preparedTokens.source,
});
+ // Reuse the calibrated/anchored result in either direction, rather
+ // than taking max(raw, measured). Identity guards keep it request-local;
+ // a different model, image projection, prompt or tool set cannot borrow it.
+ completionParams.requestTokenEstimate = {
+ model: measuredModel,
+ messages: requestMessages,
+ systemPrompt,
+ tools: completionParams.tools,
+ ...preparedTokens,
+ };
+ const streamIter = provider.stream(completionParams);
let streamText = "";
let streamContent: import("../shared/types.js").MessageContent[] | undefined;
@@ -2324,12 +2364,10 @@ export class AgentRunner {
// prompt accounting clears the anchor instead of keeping a stale one.
const anchorFootprint = usageRequestFootprintTokens(result.usage);
if (anchorFootprint > 0) {
- const estimatedAtAnchor = estimateRequestInputTokens(
- this.session,
- systemPrompt,
- toolDefs,
- budgetEphemeral || undefined,
- );
+ const estimatedAtAnchor = estimateCompletionRequestInputTokens({
+ ...completionParams,
+ messages: [...requestMessages, { role: "assistant", content: responseContent }],
+ });
requestTokenAnchor = {
realTokens: anchorFootprint,
estimatedTokens: estimatedAtAnchor,
@@ -3577,6 +3615,7 @@ export class AgentRunner {
anchor: RequestTokenAnchor | null = null,
diagnostics?: Record<string, number | string>,
exhaustedResultCallCount = 0,
+ estimatePreparedRequest?: () => number,
): AsyncIterable<AgentRunEvent> {
// Anchored to the previous call's real usage when the anchor is still
// valid; a fold earlier in this prepare phase bumps the content epoch, so
@@ -3584,7 +3623,8 @@ export class AgentRunner {
// `after` reading below by construction.
const requestTokens = () => anchoredRequestTokens(
anchor,
- estimateRequestInputTokens(this.session, systemPrompt, toolDefs, turnEphemeral),
+ estimatePreparedRequest?.()
+ ?? estimateRequestInputTokens(this.session, systemPrompt, toolDefs, turnEphemeral),
this.session.contentEpoch(),
this.session.getEstimatorCalibration(),
);
diff --git a/src/core-agent/src/agent/types.ts b/src/core-agent/src/agent/types.ts
index 836afd0e..bd928c76 100644
--- a/src/core-agent/src/agent/types.ts
+++ b/src/core-agent/src/agent/types.ts
@@ -78,6 +78,15 @@ export type AgentRunParams = {
* helpers inheriting `ELECTRON_RUN_AS_NODE=1` crash at boot).
*/
sandboxEnv?: Record<string, string>;
+ /**
+ * Read evidence the host already holds for this run, keyed by absolute
+ * path, copied into the run-scoped `ToolContext.state.readFileState` map
+ * before the first round. A host that injected a file's complete contents
+ * into the turn may seed its stamp so the first edit of that file is not
+ * refused as unread. Entries are opaque to the runtime; the file tools own
+ * their shape and still enforce path scope and staleness on every edit.
+ */
+ initialReadFileState?: ReadonlyMap<string, unknown>;
/** Prompt-cache TTL policy forwarded to pi-ai. Default (undefined) lets
* pi-ai pick `"short"`; set `"long"` for extended retention (Anthropic 1h
* / OpenAI 24h), `"none"` to opt out. Provider-specific; providers without
diff --git a/src/core-agent/src/shared/errors.ts b/src/core-agent/src/shared/errors.ts
index 7d01b57c..efe054ba 100644
--- a/src/core-agent/src/shared/errors.ts
+++ b/src/core-agent/src/shared/errors.ts
@@ -342,6 +342,17 @@ export function providerHttpStatusOf(err: unknown): number | undefined {
return undefined;
}
+/** A structured HTTP 451 rejection is terminal, independently of retry policy.
+ * A transient wrapper must not reopen retries or route around that rejection. */
+export function isProviderLegalRestrictionError(err: unknown): boolean {
+ let current: unknown = err;
+ for (let depth = 0; current && depth < 8; depth++) {
+ if (errorStatusOf(current) === 451) return true;
+ current = errorCauseOf(current);
+ }
+ return false;
+}
+
const PROVIDER_SAFETY_CODE_RE =
/^(?:PROVIDER_EMPTY_SAFETY|CONTENT[_\s-]?(?:FILTER|POLICY(?:[_\s-]?VIOLATION)?)|SAFETY(?:[_\s-]?VIOLATION)?|RESPONSIBLE[_\s-]?AI[_\s-]?POLICY[_\s-]?VIOLATION|RESPONSIBLEAIPOLICYVIOLATION|PROHIBITED[_\s-]?CONTENT|PROMPT[_\s-]?(?:FILTER|BLOCKED)|MODERATION[_\s-]?(?:BLOCKED|REJECTED)|BLOCKED[_\s-]?BY[_\s-]?POLICY|BLOCKLIST|IMAGE[_\s-]?SAFETY)$/i;
@@ -418,7 +429,7 @@ const TERMINAL_RECOVERY_CODE_RE = /^(?:CONTEXT_OVERFLOW|context_length_exceeded|
/** Hard runtime barriers also apply when an adapter proves a remote rejection.
* Authentication itself is recovered by the credential owner, before Runner. */
export function isTerminalRecoveryError(err: unknown): boolean {
- return isProviderSafetyError(err) || isStorageFullError(err, false)
+ return isProviderLegalRestrictionError(err) || isProviderSafetyError(err) || isStorageFullError(err, false)
|| providerErrorFacts(err, false).codes.some(code => TERMINAL_RECOVERY_CODE_RE.test(code));
}
@@ -481,7 +492,7 @@ export function classifyRetryableErrorWithPolicy(
config?: Partial<RetryErrorPolicyConfig> | null,
): RetryableErrorKind | null {
const policy = config ? compileRetryErrorPolicy(config) : activeRetryErrorPolicy;
- if (err == null || isProviderRateLimitError(err)) return null;
+ if (err == null || isProviderLegalRestrictionError(err) || isProviderRateLimitError(err)) return null;
if (err instanceof AuthError || err instanceof ContextOverflowError || err instanceof OutputLimitError || err instanceof StorageFullError) return null;
// Retry budget already spent below us (for example after provider rotation).
diff --git a/src/core-agent/test/agent-runner.test.ts b/src/core-agent/test/agent-runner.test.ts
index 78ca2b0a..4b31d71b 100644
--- a/src/core-agent/test/agent-runner.test.ts
+++ b/src/core-agent/test/agent-runner.test.ts
@@ -4225,7 +4225,8 @@ describe("AgentRunner", () => {
// recovery folds deterministically and retries the same request exactly
// once. Before this path existed, a tracked session's overflow was a
// terminal error — the one hole every peer product had covered.
- it("recovers from a provider context overflow by folding and retrying once", async () => {
+ it.each(['context_length_exceeded', 'exceed_context_size_error'])(
+ 'recovers from a provider context overflow by folding and retrying once (%s)', async type => {
let streamCalls = 0;
let summaryCalls = 0;
const capturedRequests: Message[][] = [];
@@ -4258,8 +4259,8 @@ describe("AgentRunner", () => {
if (call === 2) {
// Exercise the structured provider boundary as well as recovery.
throw wrapErrorForTest(new ProviderError(
- '400: {"code":"context_length_exceeded","message":"Request rejected"}',
- "mock", 400, Object.assign(new Error('opaque'), { code: 'context_length_exceeded' }),
+ 'Request rejected',
+ "mock", 400, Object.assign(new Error('opaque'), { code: 400, type }),
), "mock");
}
yield { type: "text_delta" as const, text: "done" };
@@ -4278,11 +4279,14 @@ describe("AgentRunner", () => {
// Modest by the estimator's measure — under every layered trigger — yet
// the provider still refuses: exactly the blind-spot shape (image bytes,
// a first call with no anchor) this recovery exists for.
+ const execute = vi.fn(async (input: Record<string, unknown>) => ({
+ content: `bulk\n${(input.round === 0 ? "z" : "y").repeat(20_000)}`,
+ }));
const bulk = defineTool({
name: "bulk",
description: "emits a large observation",
inputSchema: { type: "object", properties: { round: { type: "number" } } },
- async execute(input) { return { content: `bulk\n${(input.round === 0 ? "z" : "y").repeat(20_000)}` }; },
+ execute,
});
const config = createConfig({
agent: { defaultProvider: "mock", defaultModel: "mock-model", maxToolLoops: 10 },
@@ -4319,6 +4323,7 @@ describe("AgentRunner", () => {
expect(retried).not.toContain("z".repeat(1_000));
expect(retried).toContain("y".repeat(20_000));
expect(streamCalls).toBe(4);
+ expect(execute.mock.calls.map(([input]) => input.round)).toEqual([0, 1]);
// The user's message is committed exactly once as message text — the
// second textual occurrence in a request is the plan anchor's
// deterministically derived objective, which is projection, not a
@@ -4327,7 +4332,10 @@ describe("AgentRunner", () => {
expect(runner.getSession().hasTurnTracking()).toBe(true);
});
- it.each([100, 100_000])("preserves the only unread parallel round on overflow (result chars: %i)", async (chars) => {
+ it.each([
+ [100, 'context_length_exceeded'], [100_000, 'context_length_exceeded'],
+ [100, 'exceed_context_size_error'], [100_000, 'exceed_context_size_error'],
+ ] as const)('preserves the only unread parallel round on overflow (result chars: %i / %s)', async (chars, type) => {
// Asserted: done.meta.error.kind === 'context_overflow' with one request.
expectTestLog({ level: 'error', source: 'console', message: /^\[agent-runner\] context overflow with nothing to recover \{/ });
const session = new Session();
@@ -4344,7 +4352,8 @@ describe("AgentRunner", () => {
async *stream(params) {
requests.push(params);
yield { type: "message_start" as const };
- throw new ContextOverflowError("request exceeds context window");
+ throw wrapErrorForTest(new ProviderError('Request rejected', 'mock', 400,
+ Object.assign(new Error('opaque'), { code: 400, type })), 'mock');
},
async validateAuth() { return true; },
};
@@ -4368,7 +4377,8 @@ describe("AgentRunner", () => {
expect(events.filter(e => e.type === "compaction")).toHaveLength(0);
});
- it("declines a consecutive overflow after recovery with no completed call between", async () => {
+ it.each(['context_length_exceeded', 'exceed_context_size_error'])(
+ 'declines a consecutive overflow after recovery with no completed call between (%s)', async type => {
// Asserted: error kind context_overflow whose message names the recovery.
expectTestLog({ level: 'error', source: 'console', message: /^\[agent-runner\] context overflow after recovery \{/ });
let streamCalls = 0;
@@ -4395,7 +4405,8 @@ describe("AgentRunner", () => {
};
return;
}
- throw new ContextOverflowError("request exceeds context window");
+ throw wrapErrorForTest(new ProviderError('Request rejected', 'mock', 400,
+ Object.assign(new Error('opaque'), { code: 400, type })), 'mock');
},
async validateAuth() { return true; },
};
@@ -9115,6 +9126,50 @@ describe("AgentRunner", () => {
expect(seen[1].runScopedLedger).toBe(seen[0].runScopedLedger);
});
+ it("copies host-seeded read stamps into the run-scoped map without sharing the host's map", async () => {
+ // A host that showed a file whole in the turn seeds its read stamp so the
+ // first edit is not refused as unread. The runtime copies the entries:
+ // reads during the run must not leak back into the host's object, and a
+ // later run starts from the host's seed again, not from this run's reads.
+ const mockProvider = createMockProvider([
+ {
+ content: [{ type: "tool_use", id: "c1", name: "capture_state", input: {} }],
+ stopReason: "tool_use",
+ usage: { inputTokens: 5, outputTokens: 5, totalTokens: 10 },
+ model: "mock-model",
+ },
+ {
+ content: [{ type: "text", text: "done" }],
+ stopReason: "end_turn",
+ usage: { inputTokens: 5, outputTokens: 2, totalTokens: 7 },
+ model: "mock-model",
+ },
+ ]);
+ const registry = new ProviderRegistry();
+ registry.registerFactory("mock", () => mockProvider);
+ const seen: Map<string, unknown>[] = [];
+ const captureTool = defineTool({
+ name: "capture_state",
+ description: "capture readFileState for assertion",
+ inputSchema: { type: "object", properties: {} },
+ async execute(_input, ctx) {
+ const state = ctx.state.readFileState as Map<string, unknown>;
+ seen.push(state);
+ state.set("/tmp/read-during-run.md", { mtimeMs: 2, size: 2 });
+ return { content: "ok" };
+ },
+ });
+ const config = createConfig({ agent: { defaultProvider: "mock", defaultModel: "mock-model" } });
+ const runner = new AgentRunner({ config, providers: registry, tools: [captureTool] });
+ const seed = new Map<string, unknown>([["/tmp/handoff/note.md", { mtimeMs: 1, size: 10, hash: "sha256:abc" }]]);
+ await runner.run({ message: "edit the note", initialReadFileState: seed });
+
+ expect(seen[0].get("/tmp/handoff/note.md")).toEqual({ mtimeMs: 1, size: 10, hash: "sha256:abc" });
+ expect(seen[0]).not.toBe(seed);
+ expect(seed.has("/tmp/read-during-run.md")).toBe(false);
+ expect(seed.size).toBe(1);
+ });
+
it("omits sandboxEnv from state when not provided", async () => {
// Preserves the pre-change default: sandboxEnv is absent from state when the
// caller didn't opt in (the run-scoped readFileState map is always present).
@@ -9381,6 +9436,45 @@ describe("continuation-aware loop protection", () => {
});
describe("runner persistence barriers", () => {
+ it("stops on HTTP 451 after a completed tool and preserves its receipt across reload", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "runner-451-"));
+ const file = path.join(dir, "session.jsonl");
+ const session = new PersistentSession({ sessionFile: file });
+ let calls = 0, writes = 0;
+ const first = createMockProvider([{
+ content: [{ type: "tool_use", id: "write-once", name: "write_fixture", input: {} }],
+ stopReason: "tool_use", model: "mock-model", usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
+ }]);
+ const provider: LLMProvider = {
+ id: "mock", name: "Mock",
+ async complete() { throw new Error("must not summarize a rejected request"); },
+ async *stream(params) {
+ if (++calls === 1) yield* first.stream(params);
+ else throw new ProviderError("opaque rejection", "mock", 451);
+ },
+ async validateAuth() { return true; },
+ };
+ const providers = new ProviderRegistry();
+ providers.registerFactory("mock", () => provider);
+ const runner = new AgentRunner({ session, providers, config: createConfig({ agent: {
+ defaultProvider: "mock", defaultModel: "mock-model", maxRetries: 1,
+ } }), tools: [defineTool({ name: "write_fixture", description: "Commit one operation", inputSchema: { type: "object", properties: {} },
+ execute: async () => { writes++; return { content: "committed-operation-receipt" }; },
+ })] });
+ try {
+ const events = await collectRunEvents(runner, "Perform the operation and report its outcome");
+ expect(calls).toBe(2);
+ expect(writes).toBe(1);
+ expect(events.some(event => event.type === "retry")).toBe(false);
+ const terminal = events.filter(event => event.type === "done");
+ expect(terminal).toHaveLength(1);
+ expect(terminal[0].result.meta.error?.statusCode).toBe(451);
+ const reloaded = new PersistentSession({ sessionFile: file });
+ expect(JSON.stringify(reloaded.getMessages())).toContain("committed-operation-receipt");
+ expect(reloaded.getCompletedWorkLedger()).toContainEqual(expect.objectContaining({ tool: "write_fixture", status: "succeeded" }));
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+ });
+
it.each(["first request", "completion"])("does not hide save failure at %s", async (phase) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "runner-save-boundary-"));
const file = path.join(dir, "session.jsonl");
diff --git a/src/core-agent/test/codex-turn-state.test.ts b/src/core-agent/test/codex-turn-state.test.ts
index 4d8c79a3..79df8168 100644
--- a/src/core-agent/test/codex-turn-state.test.ts
+++ b/src/core-agent/test/codex-turn-state.test.ts
@@ -10,9 +10,11 @@ const params = (providerTurnContext?: object): CompletionParams => ({
model: "gpt-5.5", sessionId: "fixture-session", providerTurnContext,
messages: [{ role: "user", content: [{ type: "text", text: "Process the next batch" }] }],
});
-const provider = (account = "account-a", onPayload?: (value: unknown) => void) => createPiProvider({
- provider: "openai-codex", model: "gpt-5.5", apiKey: token(account), onPayload,
-});
+const provider = (account = "account-a", onPayload?: (value: unknown) => void) => {
+ const config = { provider: "openai-codex", model: "gpt-5.5", apiKey: token(account), onPayload,
+ userCacheKey: 'opaque-user-a' };
+ return createPiProvider(config);
+};
function response(state?: string, status = 200): Response {
const headers: Record<string, string> = { "content-type": "text/event-stream" };
if (state !== undefined) headers[routingHeader] = state;
@@ -30,6 +32,19 @@ async function stream(p: ReturnType<typeof provider>, request: CompletionParams)
afterEach(() => vi.unstubAllGlobals());
describe("Codex user-turn routing continuity", () => {
+ it('never replays routing state to another user sharing credentials and a turn handle', async () => {
+ const requests: Headers[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url, init) => {
+ requests.push(new Headers(init.headers)); return response(`state-${requests.length}`);
+ }));
+ const request = params({});
+ for (const userCacheKey of ['user-a', 'user-a', 'user-b', 'user-b']) {
+ const config = { provider: 'openai-codex', model: 'gpt-5.5', apiKey: token('shared'), userCacheKey };
+ await stream(createPiProvider(config), request);
+ }
+ expect(requests.map(h => h.get(routingHeader))).toEqual([null, 'state-1', null, 'state-3']);
+ });
+
it.each([undefined, "low"] as const)("replays the first state across rebuilt providers and complete/stream (reasoning=%s)", async (reasoning) => {
const requests: Headers[] = [];
const bodies: string[] = [];
@@ -46,7 +61,9 @@ describe("Codex user-turn routing continuity", () => {
expect(requests.map(h => h.get(routingHeader))).toEqual([null, "private-routing-first", "private-routing-first"]);
expect(bodies.join(" ")).not.toContain("private-routing");
expect(JSON.stringify(request)).not.toContain("private-routing");
- expect(requests.map(h => h.get("session-id"))).toEqual(Array(3).fill("fixture-session"));
+ expect(requests[0].get("session-id")).not.toBe("fixture-session");
+ expect(requests.map(h => h.get("session-id"))).toEqual(Array(3).fill(requests[0].get("session-id")));
+ expect(requests.map(h => h.get("x-client-request-id"))).toEqual(Array(3).fill("fixture-session"));
});
it("isolates interleaved tasks and starts a new user turn without the previous state", async () => {
@@ -75,7 +92,7 @@ describe("Codex user-turn routing continuity", () => {
expect(requests.map(h => h.get(routingHeader))).toEqual([null, "state-1", null, null, "state-4"]);
});
- it("does not let a delayed response from an old owner overwrite the new owner's state", async () => {
+ it.each(['credential', 'user'] as const)("does not let a delayed response overwrite the new %s owner's state", async boundary => {
let release!: (value: Response) => void;
const requests: Headers[] = [];
vi.stubGlobal("fetch", vi.fn(async (_url, init) => {
@@ -84,12 +101,14 @@ describe("Codex user-turn routing continuity", () => {
return response("new-owner-state");
}));
const request = params({});
- const old = stream(provider("old"), request);
+ const build = (owner: string) => boundary === 'credential' ? provider(owner)
+ : createPiProvider({ provider: 'openai-codex', model: 'gpt-5.5', apiKey: token('shared'), userCacheKey: owner });
+ const old = stream(build("old"), request);
await vi.waitFor(() => expect(release).toBeTypeOf("function"));
- await stream(provider("new"), request);
+ await stream(build("new"), request);
release(response("old-owner-state"));
await old;
- await stream(provider("new"), request);
+ await stream(build("new"), request);
expect(requests[2].get(routingHeader)).toBe("new-owner-state");
});
diff --git a/src/core-agent/test/output-limit-replay.test.ts b/src/core-agent/test/output-limit-replay.test.ts
index 8a4a583d..565d8f5b 100644
--- a/src/core-agent/test/output-limit-replay.test.ts
+++ b/src/core-agent/test/output-limit-replay.test.ts
@@ -136,23 +136,31 @@ it('keeps each original reasoning item through repeated truncation, later execut
} finally { fs.rmSync(root, { recursive: true, force: true }); }
});
-it('replays original Chat reasoning after a truncated tool proposal without a placeholder', async () => {
+it.each([
+ { label: 'text control', text: 'Ready.', proposal: true, field: 'reasoning_content' },
+ { label: 'reasoning only', text: '', proposal: false, field: 'reasoning_content' },
+ { label: 'whitespace body', text: ' \n ', proposal: false, field: 'reasoning_content' },
+ { label: 'discarded tool without text', text: '', proposal: true, field: 'reasoning_content' },
+ { label: 'portable reasoning field', text: '', proposal: false, field: 'reasoning' },
+ { label: 'portable reasoning_text field', text: '', proposal: false, field: 'reasoning_text' },
+])('replays original Chat reasoning without a placeholder: $label', async scenario => {
const bodies: any[] = [];
let executed = 0;
vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
bodies.push(JSON.parse(init.body));
expect(bodies.length).toBeLessThanOrEqual(2);
const first = bodies.length === 1;
- const delta = first ? { role: 'assistant', content: 'Ready.', reasoning_content: originalReason,
- tool_calls: [{ index: 0, id: 'discard', type: 'function', function: { name: 'write_file', arguments: '{}' } }] }
+ const delta = first ? { role: 'assistant', content: scenario.text, [scenario.field]: originalReason,
+ ...(scenario.proposal ? { tool_calls: [{ index: 0, id: 'discard', type: 'function', function: { name: 'write_file', arguments: '{}' } }] } : {}) }
: { role: 'assistant', content: 'Finished.' };
return new Response(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: first ? 'length' : 'stop' }] })}\n\ndata: [DONE]\n\n`,
{ headers: { 'content-type': 'text/event-stream' } });
}));
const registry = new ProviderRegistry();
- registry.registerFactory('deepseek', () => createPiProvider({ provider: 'deepseek', apiKey: 'synthetic',
- customModel: { ...model, api: 'openai-completions', provider: 'deepseek' } }));
- const runner = new AgentRunner({ config: createConfig({ agent: { defaultProvider: 'deepseek', defaultModel: 'fixture' } }),
+ const providerId = scenario.label === 'text control' ? 'deepseek' : 'custom';
+ registry.registerFactory(providerId, () => createPiProvider({ provider: providerId, apiKey: 'synthetic',
+ customModel: { ...model, api: 'openai-completions', provider: providerId } }));
+ const runner = new AgentRunner({ config: createConfig({ agent: { defaultProvider: providerId, defaultModel: 'fixture' } }),
providers: registry, session: new Session(), evolution: { enabled: false }, tools: [defineTool({ name: 'write_file',
description: 'Synthetic write counter.', inputSchema: { type: 'object' },
execute: async () => { executed++; return { content: 'Unexpected.' }; } })] });
@@ -160,6 +168,8 @@ it('replays original Chat reasoning after a truncated tool proposal without a pl
expect(executed).toBe(0);
expect(bodies).toHaveLength(2);
const assistant = bodies[1].messages.find((m: any) => m.role === 'assistant');
- expect(assistant.reasoning_content).toBe(originalReason);
+ expect(assistant?.[scenario.field]).toBe(originalReason);
expect(assistant).not.toHaveProperty('tool_calls');
+ expect(assistant.content || '').toBe(scenario.text.trim() ? scenario.text : '');
+ expect(JSON.stringify(bodies)).not.toContain('orkas-chat-replay:');
});
diff --git a/src/core-agent/test/process-session.test.ts b/src/core-agent/test/process-session.test.ts
index f9358ce7..8613ba5c 100644
--- a/src/core-agent/test/process-session.test.ts
+++ b/src/core-agent/test/process-session.test.ts
@@ -2,6 +2,8 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
+import { createServer as createTcpServer } from "node:net";
+import { get as httpGet } from "node:http";
import { SandboxExecutor } from "../src/sandbox/executor.js";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
@@ -97,6 +99,44 @@ afterEach(async () => {
});
describe("persistent process sessions", () => {
+ it.each(["legacy", "managed"])("keeps a local server alive through startup, readiness checks and explicit shutdown: %s", async mode => {
+ const reservation = createTcpServer();
+ await new Promise<void>(resolve => reservation.listen(0, "127.0.0.1", resolve));
+ const port = (reservation.address() as { port: number }).port;
+ await new Promise<void>(resolve => reservation.close(() => resolve()));
+ const fixture = path.join(workingDir, "startup-server.cjs");
+ await fs.writeFile(fixture, `console.log('BOOTING');
+process.stdin.once('data', () => {
+ require('node:http').createServer((_req,res) => res.end('local-service-ready'))
+ .listen(${port}, '127.0.0.1', () => console.log('LISTENING'));
+});
+process.stdin.resume();`);
+ const owner = `local-server-${mode}`;
+ const ctx = { ...context(owner), state: { processSessionOwner: owner, commandSessionEnabled: mode === "managed" } };
+ const command = shellInvoke(TEST_NODE, [fixture]);
+ const started = mode === "managed"
+ ? await bashTool.execute({ command, yield_time_ms: 0 }, ctx)
+ : await tool("process_session").execute({ action: "start", command }, ctx);
+ const sessionId = json(started.content).session_id;
+ const read = await waitForProcessRead(owner, sessionId, 0, value => value.output.includes("BOOTING"));
+ expect(read.payload.status).toBe("running");
+ const request = () => new Promise<Record<string, unknown>>(resolve => {
+ const req = httpGet({ hostname: "127.0.0.1", port, path: "/", timeout: 1000 }, res => {
+ let body = "";
+ res.setEncoding("utf8"); res.on("data", data => { body += data; });
+ res.on("end", () => resolve({ status: res.statusCode, body }));
+ });
+ req.on("timeout", () => req.destroy(Object.assign(new Error("timeout"), { code: "ETIMEDOUT" })));
+ req.on("error", error => resolve({ error: (error as NodeJS.ErrnoException).code }));
+ });
+ expect(await request()).toEqual({ error: "ECONNREFUSED" });
+ await tool("process_session").execute({ action: "write", session_id: sessionId, chars: "listen\n" }, ctx);
+ await waitForProcessRead(owner, sessionId, 0, value => value.output.includes("LISTENING"));
+ expect(await request()).toEqual({ status: 200, body: "local-service-ready" });
+ await tool("process_session").execute({ action: "stop", session_id: sessionId }, ctx);
+ expect(await request()).toEqual({ error: "ECONNREFUSED" });
+ });
+
it.each(["legacy", "foreground", "managed", "detached"])("honors the configured Windows shell at actual startup: %s", async mode => {
const descriptor = Object.getOwnPropertyDescriptor(process, "platform")!;
vi.stubEnv("ORKAS_WINDOWS_SHELL", "cmd.exe");
diff --git a/src/core-agent/test/replay-compatibility.test.ts b/src/core-agent/test/replay-compatibility.test.ts
index 6c537d35..95dc1db9 100644
--- a/src/core-agent/test/replay-compatibility.test.ts
+++ b/src/core-agent/test/replay-compatibility.test.ts
@@ -38,6 +38,48 @@ async function invoke(provider: LLMProvider, method: 'complete' | 'stream', para
}
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
+// The history consumer must receive original plaintext even before any public
+// answer exists. Exercise both SDK entry points, observer hooks and disk reload.
+it.each(['complete', 'stream'] as const)('preserves plaintext-only Chat history on %s after reload', async method => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-chat-reasoning-'));
+ const file = path.join(directory, 'session.jsonl');
+ const chat = { ...model, api: 'openai-completions' as const, provider: 'custom' };
+ const session = new PersistentSession({ sessionFile: file });
+ session.beginUserTurn([{ type: 'text', text: 'Continue the calculation.' }]);
+ const fields = ['reasoning_content', 'reasoning', 'reasoning_text'];
+ for (const field of fields) {
+ session.addAssistantMessage([{ type: 'thinking', thinking: `Original ${field}.`,
+ thinkingSignature: field, replayOrigin: replayOrigin(chat, 'fixture') }]);
+ }
+ const messages = new PersistentSession({ sessionFile: file }).getMessagesForModel();
+ messages.push({ role: 'developer', content: [{ type: 'text', text: 'Use the preserved calculation.' }] });
+ const before = JSON.stringify(messages);
+ const wires: any[] = [], observed: any[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
+ wires.push(JSON.parse(init.body));
+ return new Response('data: {"choices":[{"index":0,"delta":{"content":"Seven."},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',
+ { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ try {
+ const provider = createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: chat,
+ onPayload: async payload => { observed.push(structuredClone(payload)); } });
+ await invoke(provider, method, { messages, maxTokens: 73 });
+ expect(wires).toHaveLength(1);
+ expect(observed[0].messages).toEqual(wires[0].messages);
+ expect(wires[0].max_completion_tokens ?? wires[0].max_tokens).toBe(73);
+ expect(JSON.stringify(wires)).not.toContain('orkas-chat-replay:');
+ const assistants = wires[0].messages.filter((m: any) => m.role === 'assistant');
+ expect(assistants).toHaveLength(3);
+ fields.forEach((field, index) => {
+ expect(assistants[index][field]).toBe(`Original ${field}.`);
+ expect(assistants[index].content || '').toBe('');
+ expect(assistants[index]).not.toHaveProperty('tool_calls');
+ });
+ expect(JSON.stringify(messages)).toBe(before);
+ expect(fs.readFileSync(file, 'utf8')).not.toContain('orkas-chat-replay:');
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
+});
+
it.each(['complete', 'stream'] as const)('keeps managed replay provenance off direct %s requests', async method => {
const marked = { ...reasoning, _orkas_replay: 'v1:synthetic-managed-source' };
const messages: CompletionParams['messages'] = [
diff --git a/src/core-agent/test/shared.test.ts b/src/core-agent/test/shared.test.ts
index 711caab8..aef62b7f 100644
--- a/src/core-agent/test/shared.test.ts
+++ b/src/core-agent/test/shared.test.ts
@@ -16,6 +16,7 @@ import {
getRetryErrorPolicy,
isRetryableError,
isStorageFullError,
+ isTerminalRecoveryError,
isTransientNetworkError,
errorCodeForLog,
formatError,
@@ -201,6 +202,24 @@ describe("Errors", () => {
expect(isRetryableError(wrappedAuth)).toBe(false);
});
+ it("keeps HTTP 451 terminal through wrappers even when runtime policy clears every blacklist", () => {
+ const policy = { permanent_statuses: [], permanent_message_patterns: [], permanent_code_patterns: [] };
+ for (const error of [
+ new ProviderError("opaque", "test", 451),
+ { status: 451 }, { httpStatus: 451 }, { http_status: 451 },
+ { statusCode: 503, cause: { status: 451, code: "rate_limit_error" } },
+ { cause: { error: { status: 451, code: "insufficient_quota" } } },
+ ]) {
+ expect(classifyRetryableError(error)).toBeNull();
+ expect(classifyRetryableErrorWithPolicy(error, policy)).toBeNull();
+ expect(isTerminalRecoveryError(error)).toBe(true);
+ }
+ // A number in diagnostic prose is not an authoritative HTTP rejection.
+ const lookalike = Object.assign(new Error("451 status code (no body)"), { status: 503 });
+ expect(classifyRetryableError(lookalike)).toBe("service_unavailable");
+ expect(isTerminalRecoveryError(lookalike)).toBe(false);
+ });
+
it("never retries structured provider safety errors even when runtime policy removes every blacklist", () => {
const policy = {
permanent_statuses: [],
diff --git a/src/core-agent/test/tool-input-diagnostics.test.ts b/src/core-agent/test/tool-input-diagnostics.test.ts
index 053f28ce..0f7e724e 100644
--- a/src/core-agent/test/tool-input-diagnostics.test.ts
+++ b/src/core-agent/test/tool-input-diagnostics.test.ts
@@ -20,7 +20,7 @@ function completions(argumentsText?: string): Response {
return new Response(chunks.map(chunk => `data: ${JSON.stringify({ id: 'fixture', model: 'fixture', ...chunk })}\n\n`).join('') + 'data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } });
}
-it.each([false, true])('keeps strict/partial input evidence through the real SDK and runner (partial=%s)', async partial => {
+it.each([false, true])('executes only strict final input through the real SDK and runner (partial=%s)', async partial => {
const input = { paths: [{ path: '@skill/skill-creator},{' }] };
const json = JSON.stringify(input);
const wire = partial ? json.slice(0, -1) : json;
@@ -37,20 +37,30 @@ it.each([false, true])('keeps strict/partial input evidence through the real SDK
const execute = vi.fn(async (received: Record<string, unknown>) => {
expect(received).toEqual(input);
expect(toolInputDiagnostic(received)).toMatchObject({
- stream_json: partial ? 'non_strict' : 'strict', tolerant_parse: partial ? 'used' : 'not_used',
+ stream_json: 'strict', tolerant_parse: 'not_used',
});
return { content: 'E_SKILL_REF_INVALID: Use the advertised reference.', isError: true,
observations: { fileFailure: { code: 'E_SKILL_REF_INVALID' as const, reason: 'skill_ref_format' as const, skill_ref_valid: false } } };
});
const session = new Session();
- const runner = new AgentRunner({ session, config: createConfig({ agent: { defaultProvider: 'fixture', defaultModel: 'fixture' } }), providers: registry,
+ const runner = new AgentRunner({ session, config: createConfig({ agent: { defaultProvider: 'fixture', defaultModel: 'fixture', maxRetries: 0 } }), providers: registry,
tools: [defineTool({ name: 'read_files', description: 'Read files.', inputSchema: { type: 'object' }, execute })] });
- await runner.run({ message: 'Inspect the protocol.' });
+ const result = await runner.run({ message: 'Inspect the protocol.' });
+ if (partial) {
+ // SDK partial parsing is suitable for streaming previews. An incomplete
+ // final argument document must never reach the real tool executor.
+ expect(execute).not.toHaveBeenCalled();
+ expect(requests).toBe(1);
+ expect(result.meta.error).toMatchObject({ kind: 'provider_error' });
+ expect(result.meta.error?.message).toContain('Invalid tool call arguments');
+ expect(warning.mock.calls.filter(call => call[1] === 'Tool returned error')).toHaveLength(0);
+ return;
+ }
expect(execute).toHaveBeenCalledOnce();
expect(requests).toBe(2);
const errors = warning.mock.calls.filter(call => call[1] === 'Tool returned error');
expect(errors).toHaveLength(1);
- expect(errors[0][2]).toMatchObject({ input_parse: { stream_json: partial ? 'non_strict' : 'strict', tolerant_parse: partial ? 'used' : 'not_used' }, file_failure: { code: 'E_SKILL_REF_INVALID', skill_ref_valid: false } });
+ expect(errors[0][2]).toMatchObject({ input_parse: { stream_json: 'strict', tolerant_parse: 'not_used' }, file_failure: { code: 'E_SKILL_REF_INVALID', skill_ref_valid: false } });
expect(JSON.stringify(warning.mock.calls)).not.toContain('skill-creator');
expect(JSON.stringify(session.getMessagesForModel())).not.toContain('tolerant_parse');
});
diff --git a/src/core-agent/test/tools.test.ts b/src/core-agent/test/tools.test.ts
index be033632..089fae8c 100644
--- a/src/core-agent/test/tools.test.ts
+++ b/src/core-agent/test/tools.test.ts
@@ -1188,7 +1188,7 @@ describe("Tools", () => {
}
});
- it("returns a structured GitHub repository snapshot and caches its URL aliases", async () => {
+ it("returns a structured GitHub repository snapshot and caches its default API aliases", async () => {
const metadata = {
full_name: "example/project",
description: "Example local-first project",
@@ -1239,7 +1239,7 @@ describe("Tools", () => {
ctx,
);
const readmeAlias = await webFetch.execute(
- { url: "https://raw.githubusercontent.com/example/project/main/README.md" },
+ { url: "https://api.github.com/repos/example/project/readme" },
ctx,
);
const metadataAlias = await webFetch.execute(
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 81284400..3f24c848 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -1588,6 +1588,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
conversationTitleUpdatedAt,
turnId,
historyBoundaryMessageId,
+ outputDelivery,
projectId,
onFileWritten,
onOutputsPublished,
@@ -1886,8 +1887,10 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
...(conversationTitleUpdatedAt ? { conversationTitleUpdatedAt } : {}),
...(turnId ? { turnId } : {}),
...(historyBoundaryMessageId ? { historyBoundaryMessageId } : {}),
+ ...(outputDelivery ? { outputDelivery } : {}),
...(message ? { userMessage: message } : {}),
...(attachmentMetadata ? { attachmentMetadata } : {}),
+ ...(opts.requireImageInput ? { requireImageInput: true } : {}),
...(projectId ? { projectId } : {}),
...(skillList !== undefined ? { skillList } : {}),
...(systemSkillList !== undefined ? { systemSkillList: [...systemSkillList] } : {}),
@@ -1950,6 +1953,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
toolSurfaceMode,
resolvedSystemPrompt,
turnEphemeral,
+ initialReadFileState,
profileId,
entryId,
toolDefs,
@@ -2055,6 +2059,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
sandboxEnv,
...(workingDir ? { workingDir } : {}),
...(turnEphemeral ? { turnEphemeral } : {}),
+ ...(initialReadFileState?.size ? { initialReadFileState } : {}),
...(images && images.length ? { images } : {}),
...(historyResources && historyResources.length ? { historyResources } : {}),
...(Object.keys(requestMetadata).length ? { requestMetadata } : {}),
diff --git a/src/main/model/core-agent/event-mapper.ts b/src/main/model/core-agent/event-mapper.ts
index 0e43f5f4..6731725e 100644
--- a/src/main/model/core-agent/event-mapper.ts
+++ b/src/main/model/core-agent/event-mapper.ts
@@ -28,8 +28,8 @@
* context_status → {type:'event', event:{stream:'context', data:{phase,...}}}
* — semantic only; renderer localizes the phase
* compaction → {type:'progress', text: 'compacted <before>→<after> tokens'}
- * done (ok) → {type:'final', text} then {type:'done'}
- * done (err) → {type:'error', text: meta.error.message} then {type:'done'}
+ * done (ok) → {type:'final', text}; the host owns stream completion
+ * done (err) → {type:'error', text: localized error}; same completion owner
*
* The returned generator is ready to be `yield*`'d straight out of
* `streamChatWithModel`.
@@ -198,6 +198,9 @@ function modelFailureDetails(
if (error.code === 'SESSION_PERSISTENCE_FAILED') {
return { failureKind: 'model', failureCode: 'session_persistence_failed', retryExhausted: true };
}
+ if (error.code === 'CONTEXT_CAPACITY_INSUFFICIENT') {
+ return { failureKind: 'model', failureCode: 'context_capacity_insufficient', failurePhase: 'preflight' };
+ }
const rawCode = String(error.code || '').trim();
const code = rawCode.toUpperCase();
// These terminal codes are emitted after the owning retry policy finishes.
diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.ts
index 53890b6b..c7b1a5c9 100644
--- a/src/main/model/core-agent/local-tools.ts
+++ b/src/main/model/core-agent/local-tools.ts
@@ -126,6 +126,7 @@ import { enabledPackageSkillRoots } from '../../features/packages';
import { getGlobalSkillRootsEnabledForUser } from '../../features/config';
import { chatAttachmentDirForConversation } from '../../util/project-layout';
import * as chatArtifacts from '../../features/chat_artifacts';
+import { getActiveUserId } from '../../features/users';
import { finalizeProducedArtifact, producedDocumentFooterText } from '../../features/produced_output_hooks';
import { readDisabledSets } from '../../features/component_enabled';
import {
@@ -172,6 +173,7 @@ import {
const log = createLogger('local-tools');
export interface ArtifactInteractionSmokeResult {
+ sdkByViewport?: Array<{ viewport: string; calls: Array<{ method: string; code: string }> }>;
ok: boolean;
blockers: string[];
/** Non-blocking embed findings worth telling the author about, e.g. content
@@ -255,7 +257,7 @@ export interface LocalToolsOpts {
/** Fires after a successful `create_artifact` call. The caller (group_chat
* bus) collects these per turn and attaches `message.artifacts` to the
* assistant record so the renderer embeds each one in the bubble. */
- onArtifactCreated?: (a: { id: string; title: string }) => void;
+ onArtifactCreated?: (a: { id: string; title: string; revision?: number }) => void;
/** Internal override for deterministic tests. Production uses the packaged
* isolated-browser interaction smoke before exposing an artifact card. */
artifactInteractionSmoke?: (entryPath: string) => Promise<ArtifactInteractionSmokeResult>;
@@ -5433,6 +5435,8 @@ function createHostApplyPatchTool(opts: LocalToolsOpts): AgentTool {
});
return {
...coreTool,
+ description:
+ 'Apply multiple known edits in one transactional patch to one or more existing or new text files. Existing targets require an unchanged baseline from this run: read_files and successful file-tool writes establish it; bash reads/writes do not. Validation or conflicts leave every target unchanged. Use edit_file for one small replacement.',
async execute(input, ctx) {
const result = await coreTool.execute(input, ctx);
if (result.isError) return result;
@@ -5473,7 +5477,7 @@ function createEditFileTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'edit_file',
description:
- 'Replace one text pattern in an existing UTF-8 file. Requires an unchanged read/write baseline from this run or a matching expected_hash; earlier turns alone do not establish a baseline. Use write_file to create files and apply_patch for multiple known edits in one or more files.',
+ 'Replace one text pattern in an existing UTF-8 file. Requires an unchanged baseline from this run or a matching expected_hash. read_files and successful file-tool writes establish a baseline; bash reads/writes and earlier turns alone do not. Use write_file to create files and apply_patch for multiple known edits in one or more files.',
inputSchema: {
type: 'object',
properties: {
@@ -6010,13 +6014,17 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'html_preview',
description:
- 'Audit a local HTML entry in an isolated, network-blocked browser and return runtime, resource, overflow, layout, focus, and interaction findings.',
+ 'Audit local HTML or a current-conversation app in an isolated browser and return runtime, resource, overflow, layout, focus, and interaction findings.',
inputSchema: {
type: 'object',
properties: {
path: {
type: 'string',
- description: 'Existing local .html/.htm entry path, absolute or relative to $working_dir.',
+ description: 'Existing local .html/.htm entry path, absolute or relative to $working_dir. Supply exactly one of path or artifact_id.',
+ },
+ artifact_id: {
+ type: 'string',
+ description: 'App ID returned by create_artifact in the current conversation. Previews its index.html. Supply exactly one of artifact_id or path.',
},
target: {
type: 'string',
@@ -6051,21 +6059,41 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
},
},
},
- required: ['path'],
+ required: [],
},
async execute(input, ctx) {
- const rawPath = String(input.path ?? '').trim();
- if (!rawPath) {
- return { content: errText('E_BAD_INPUT', '`path` is required'), isError: true };
+ const artifactMode = input.artifact_id !== undefined;
+ if (artifactMode === (input.path !== undefined)) {
+ return { content: errText('E_BAD_INPUT', 'supply exactly one of `path` or `artifact_id`'), isError: true };
+ }
+ let abs: string;
+ let artifactId: string | undefined;
+ if (artifactMode) {
+ if (typeof input.artifact_id !== 'string' || !input.artifact_id.trim()) {
+ return { content: errText('E_BAD_INPUT', '`artifact_id` must be a non-empty app ID'), isError: true };
+ }
+ artifactId = input.artifact_id.trim();
+ if (!opts.userId || !opts.cid || getActiveUserId() !== opts.userId) {
+ return { content: errText('E_NO_CONVERSATION', 'artifact preview requires the current account and conversation'), isError: true };
+ }
+ const resolved = chatArtifacts.resolveArtifactFilePath(opts.userId, opts.cid, artifactId, 'index.html');
+ if (!resolved.ok) {
+ return { content: errText('E_HTML_PREVIEW_NOT_FOUND', 'app is unavailable in the current conversation'), isError: true };
+ }
+ abs = resolved.absPath;
+ } else {
+ const rawPath = String(input.path ?? '').trim();
+ if (!rawPath) return { content: errText('E_BAD_INPUT', '`path` is required'), isError: true };
+ abs = resolveAbs(ctx, rawPath);
}
- const abs = resolveAbs(ctx, rawPath);
if (!/\.html?$/i.test(abs)) {
return {
content: errText('E_BAD_INPUT', '`path` must point to an .html or .htm file'),
isError: true,
};
}
- const scopeError = guardHtmlPreviewPath(opts, abs);
+ // Artifact access is confined by its owning resolver, independently of workspace access.
+ const scopeError = artifactMode ? null : guardHtmlPreviewPath(opts, abs);
if (scopeError) return { content: scopeError, isError: true };
const sensitiveError = await gateSensitiveLocalPath(
opts,
@@ -6081,7 +6109,7 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
stat = fs.lstatSync(abs);
} catch (error) {
return {
- content: errText('E_HTML_PREVIEW_NOT_FOUND', (error as Error).message),
+ content: errText('E_HTML_PREVIEW_NOT_FOUND', artifactMode ? 'app entry is unavailable' : (error as Error).message),
isError: true,
};
}
@@ -6138,14 +6166,17 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
}
try {
- // Deliverable pages open in the chat file viewer; check them under its sandbox.
- const rendered = input.interactions === false
- ? await renderResponsiveHtmlPreview(abs, viewports, {}, { interactions: false, fileViewer: true })
- : await renderResponsiveHtmlPreview(abs, viewports, {}, { fileViewer: true });
+ const options = artifactMode ? { bridgeJavaScript: chatArtifacts.BRIDGE_JS } : { fileViewer: true };
+ const rendered = await renderResponsiveHtmlPreview(abs, viewports, {}, {
+ ...options,
+ ...(input.interactions === false ? { interactions: false } : {}),
+ });
+ const { entryPath: _entryPath, ...artifactEvidence } = rendered.evidence;
+ const evidence = artifactMode ? { ...artifactEvidence, artifact_id: artifactId } : rendered.evidence;
if (!rendered.evidence.ok) {
return {
content: JSON.stringify({
- ...rendered.evidence,
+ ...evidence,
visual_evidence: {
attached: false,
reason: 'deterministic_checks_failed',
@@ -6158,7 +6189,7 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
if (input.screenshots !== true) {
return {
content: JSON.stringify({
- ...rendered.evidence,
+ ...evidence,
visual_evidence: {
attached: false,
reason: 'not_requested',
@@ -6172,7 +6203,7 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
);
return {
content: JSON.stringify({
- ...rendered.evidence,
+ ...evidence,
visual_evidence: {
attached: true,
viewports: rendered.evidence.viewports.map((viewport) => viewport.name),
@@ -6192,7 +6223,7 @@ function createHtmlPreviewTool(opts: LocalToolsOpts): AgentTool {
return {
content: errText(
code,
- detail,
+ artifactMode ? 'app preview could not complete; retry after checking the app' : detail,
),
isError: true,
};
@@ -6215,8 +6246,9 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
inputSchema: {
type: 'object',
properties: {
- title: { type: 'string', description: 'Short title shown above the embedded app. Optional; defaults to "Interactive app".' },
- appType: {type:'string',enum:opts.lockedAppType?[opts.lockedAppType]:['local','web'],description:'Omit to inherit the selected creation task or editing source; otherwise defaults to local. Web apps use browser and common data interfaces only; read web-app-sdk for the matching contract.'},
+ artifact_id: { type: 'string', description: 'For a correction, an app ID returned to this creator in the current conversation. Replaces that app with the complete files array, retaining its identity; omit only to create a separate app.' },
+ title: { type: 'string', description: 'Short title above the embedded app. Omit to retain a revised app title; new apps default to "Interactive app".' },
+ appType: {type:'string',enum:opts.lockedAppType?[opts.lockedAppType]:['local','web'],description:'Omit to retain the revised app type or inherit the selected task/editing source; otherwise defaults to local. Web apps use browser and common data interfaces only; read web-app-sdk for the matching contract.'},
files: {
type: 'array',
description: 'Relative app files with a top-level index.html. Local apps may load __orkas/bridge.js for send and resize.',
@@ -6239,15 +6271,18 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
if (!uid || !cid) {
return { content: errText('E_NO_CONVERSATION', 'create_artifact is only available inside a conversation.'), isError: true };
}
+ let finalizationFailed = false;
const r = await chatArtifacts.createArtifact(uid, cid, opts.agentId || '', {
+ artifactId: (input as { artifact_id?: unknown }).artifact_id,
title: (input as { title?: unknown }).title,
appType: (input as {appType?:unknown}).appType,
files: (input as { files?: unknown }).files,
+ }, async (stagedDir, artifactId) => {
+ try {
+ await finalizeProducedArtifact(stagedDir, { userId: uid, cid, artifactId, source: 'create_artifact' });
+ } catch (err) { finalizationFailed = true; throw err; }
});
if (!r.ok) {
- if ((await import('../../features/web_apps/commercial-entry')).isCommercialWebAppFailure(r)) {
- return { content: JSON.stringify(r), isError: true };
- }
// Cast in the error branch — `strictNullChecks: false` keeps the
// whole `Result<>` union here (codebase-wide workaround).
const errMsg = (r as { error?: string }).error || 'invalid artifact';
@@ -6257,30 +6292,12 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
agent_id: maskId(opts.agentId),
error: logErrorRef(new Error(errMsg)),
});
- return { content: errText('E_BAD_ARTIFACT', errMsg), isError: true };
+ return { content: errText(finalizationFailed ? 'E_ARTIFACT_FINALIZE_FAILED' : 'E_BAD_ARTIFACT', errMsg), isError: true };
}
const resolved = chatArtifacts.resolveArtifactDir(uid, cid, r.artifactId);
if (!resolved.ok) {
return { content: errText('E_ARTIFACT_FINALIZE_FAILED', 'artifact directory could not be resolved after creation'), isError: true };
}
- try {
- await finalizeProducedArtifact(resolved.dirPath, {
- userId: uid,
- cid,
- artifactId: r.artifactId,
- source: 'create_artifact',
- });
- } catch (err) {
- const discarded = chatArtifacts.discardArtifact(uid, cid, r.artifactId);
- log.warn('create_artifact finalizer failed', {
- user_id: maskId(uid),
- cid: maskId(cid),
- artifact_id: maskId(r.artifactId),
- discarded: discarded.ok,
- error: logErrorRef(err),
- });
- return { content: errText('E_ARTIFACT_FINALIZE_FAILED', (err as Error).message || 'artifact post-processing failed'), isError: true };
- }
let smoke: ArtifactInteractionSmokeResult;
try {
const runSmoke = opts.artifactInteractionSmoke ?? (async (entryPath: string) => {
@@ -6290,6 +6307,7 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
const interactions = rendered.evidence.interactions;
return {
ok: rendered.evidence.ok,
+ sdkByViewport: rendered.evidence.sdkByViewport,
blockers: rendered.evidence.blockers,
warnings: rendered.evidence.warnings,
controlsExercised: interactions.controlsExercised,
@@ -6305,7 +6323,7 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
smoke = { ok: false, blockers: ['Preview unavailable; verify the application in its window.'] };
}
if (opts.onArtifactCreated) {
- try { opts.onArtifactCreated({ id: r.artifactId, title: r.title }); }
+ try { opts.onArtifactCreated({ id: r.artifactId, title: r.title, revision: r.revision }); }
catch (err) { log.warn('onArtifactCreated callback failed', { artifact_id: maskId(r.artifactId), error: logErrorRef(err) }); }
}
log.info('create_artifact created', {
@@ -6320,13 +6338,19 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
// artifact that does not know the box it lands in writes a full-screen
// shell and ships it clipped.
const smokeWarnings = [...smoke.blockers, ...(smoke.warnings ?? [])];
+ // Preserve bounded facts even when the app handles an SDK error itself.
+ // Neither denial nor unavailable preview capabilities block delivery.
+ const sdkObservations = [...new Set((smoke.sdkByViewport ?? []).flatMap(view =>
+ view.calls.filter(call => call.code !== 'OK').map(call => `${view.viewport} ${call.method}: ${call.code}`)))];
const web=chatArtifacts.readArtifactMeta(uid,cid,r.artifactId)?.appType==='web';
return {
content:
- `Artifact "${r.title}" created (id ${r.artifactId}); preview ${smoke.ok ? 'checks passed' : 'reported issues'} ` +
+ `Artifact "${r.title}" ${(input as { artifact_id?: unknown }).artifact_id !== undefined ? 'updated' : 'created'} (id ${r.artifactId}); revision ${r.revision}; preview ${smoke.ok ? 'completed' : 'reported issues'} ` +
`(${smoke.controlsExercised ?? 0} control(s), ${smoke.observableEffects ?? 0} observable effect(s)) ` +
- `at desktop, chat-embed, and mobile viewports. ` +
+ `at desktop, chat-embed, and mobile viewports. This bounded preview is not a full functional verification. ` +
+ (sdkObservations.length ? `SDK observations (temporary preview data): ${sdkObservations.slice(0, 12).join(' | ')}${sdkObservations.length > 12 ? ` | ${sdkObservations.length - 12} more observation(s)` : ''}. ` : '') +
`It is now shown to the user inside this reply, so do NOT paste its HTML in your message. ` +
+ `For corrections, call create_artifact with artifact_id "${r.artifactId}" and the complete files array to update this same app. ` +
`Frame: the card opens ${chatArtifacts.ARTIFACT_FRAME.defaultHeight}px tall and grows to at most ` +
`${chatArtifacts.ARTIFACT_FRAME.maxHeight}px, at roughly ${chatArtifacts.ARTIFACT_FRAME.smokeWidth}px wide. ` +
(web ? `Web app: use browser and common data interfaces. Keep content within the embedded frame; taller content scrolls. ` :
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index d262e653..79afab4f 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -274,11 +274,15 @@ export interface BuildRunnerParams {
/** Stable inbound message id used as the exclusive upper bound for
* current-conversation history tools. */
historyBoundaryMessageId?: string;
+ /** Host-owned final delivery versus intermediate work for Commander. */
+ outputDelivery?: 'final' | 'process';
/** Host-side post-success hook for a user-confirmed custom Connector. */
onCustomConnectorAdded?: (connectorId: string) => void;
/** Current real user text, used by tools that must bind an approval action
* to explicit user intent rather than merely to the existence of a turn. */
userMessage?: string;
+ /** Image-understanding calls must never fall back to a text-only request. */
+ requireImageInput?: boolean;
/** Current-turn attachment kinds. Tool exposure uses this metadata without
* inspecting attachment contents or eagerly running extraction. */
attachmentMetadata?: { hasAttachments?: boolean; attachmentTypes?: readonly string[] };
@@ -375,7 +379,7 @@ export interface BuildRunnerParams {
hasProducedPath?: (absPath: string) => boolean;
/** Fires after each successful `create_artifact` call. See `model/client.ts`
* `ChatOptions.onArtifactCreated`. */
- onArtifactCreated?: (a: { id: string; title: string }) => void;
+ onArtifactCreated?: (a: { id: string; title: string; revision?: number }) => void;
/** Fires once per skill id rendered into the system-prompt skills index,
* with its source system. Called at runner build time (before the LLM
* sees the prompt). Bus collects per turn for `skill_advertised`. */
@@ -463,6 +467,10 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
* forwards this as `runStream({ turnEphemeral })` so it rides this turn's
* user message instead. Empty for runs with no volatile blocks. */
turnEphemeral: string;
+ /** Read stamps for files whose complete text `turnEphemeral` carries; the
+ * caller forwards this as `runStream({ initialReadFileState })` so the
+ * run's file tools treat them as read. Absent when nothing was shown whole. */
+ initialReadFileState?: ReadonlyMap<string, unknown>;
entryId?: string;
profileId?: string;
providerId: string;
@@ -492,7 +500,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// resolve authentication method".
const group = await pickChatEntryGroup();
const primary: ChatEntryChoice | undefined = group[0];
- if (!primary && !process.env.ANTHROPIC_API_KEY) {
+ if (!primary && (params.requireImageInput || !process.env.ANTHROPIC_API_KEY)) {
const oauthExpiredMessage = getConfiguredModelOAuthExpiredMessage();
if (oauthExpiredMessage) throw new Error(oauthExpiredMessage);
const cooldown = getConfiguredModelCooldown();
@@ -669,7 +677,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
}
};
const onArtifactCreatedForHistory = params.onArtifactCreated
- ? (a: { id: string; title: string }) => {
+ ? (a: { id: string; title: string; revision?: number }) => {
try {
params.onArtifactCreated!(a);
} finally {
@@ -734,63 +742,20 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
}));
}
- // Project sessions keep their bound backlog. A non-project Commander may
- // dynamically load the same tool with an account-scoped project selector;
- // other actors never receive that selector. Owner is a display NAME; the store only
- // VALIDATES an already-resolved id (project_tasks.ts: "name→id resolution
- // lives with the caller"), so this handler resolves name → bound agent id
- // before persisting — unknown owners fail closed with the valid set.
+ // Backlogs follow the conversation scope. An unbound Commander uses the
+ // same global-only executor as an unbound named Agent; project selectors
+ // cannot widen either direct or programmatic calls.
if (uid && memoryAgentScope && (params.projectId || isCommander || isGroupAgent)) {
- const cid = params.cid || '';
- const { createProjectTasksHandler: createBoundHandler } = await import('../../features/project_tasks_tool_handler');
- const createProjectTasksHandler = (pid: string) => createBoundHandler(uid, pid, cid, agentDisplayNameById,
- { actorId: isCommander ? 'commander' : memoryAgentScope }, { sourceProjectId: params.projectId || '' },
- params.onTodoTaskSaved, params.onTodoTaskDeleted);
+ const { createProjectTasksHandler } = await import('../../features/project_tasks_tool_handler');
const { createProjectTasksTool } = await import('../../../core-agent/src/tools/project-tasks-tool');
- if (params.projectId || isGroupAgent) {
- injectedTools.push(createProjectTasksTool(createProjectTasksHandler(params.projectId || ''), {
- globalScope: !params.projectId,
- readOnly: !isCommander && !isGroupAgent,
- }));
- } else {
- const { listProjectNameRows } = await import('../../features/projects');
- // No project scan or schema data in the initial prompt. Resolve locally
- // on demand, using this runner's uid even if the active account changes.
- // `__global__` is a stable tool-only selector for account-global todos.
- // Its backing store still uses the canonical empty project scope; the
- // synthetic id merely lets an unbound Commander address it explicitly.
- const globalTasks = { project_id: '__global__', name: 'Global' };
- const listProjects = async () => [
- globalTasks,
- ...(await listProjectNameRows(uid))
- .sort((a, b) => a.name.localeCompare(b.name) || a.project_id.localeCompare(b.project_id)),
- ];
- injectedTools.push(createProjectTasksTool({
- listProjects,
- async resolveProject(reference) {
- const rows = await listProjects();
- const exactId = rows.find((row) => row.project_id === reference);
- const candidates = exactId ? [exactId] : rows.filter((row) => (
- row.name.toLocaleLowerCase() === reference.toLocaleLowerCase()
- ));
- if (candidates.length !== 1) {
- return {
- ok: false,
- error: candidates.length
- ? 'project_ambiguous: multiple projects match this name'
- : 'project_not_found: no matching project in this account',
- ...(candidates.length ? { candidates } : {}),
- };
- }
- const project = candidates[0];
- return {
- ok: true,
- project,
- handler: createProjectTasksHandler(project.project_id === globalTasks.project_id ? '' : project.project_id),
- };
- },
- }));
- }
+ injectedTools.push(createProjectTasksTool(createProjectTasksHandler(
+ uid, params.projectId || '', params.cid || '', agentDisplayNameById,
+ { actorId: isCommander ? 'commander' : memoryAgentScope }, { sourceProjectId: params.projectId || '' },
+ params.onTodoTaskSaved, params.onTodoTaskDeleted,
+ ), {
+ globalScope: !params.projectId,
+ readOnly: !isCommander && !isGroupAgent,
+ }));
}
if (uid && memoryAgentScope && params.projectId) {
@@ -1287,8 +1252,10 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
? ['workspace.read', 'connectors']
: [];
// Resolve trusted entry context once for both initial tools and turn guidance.
- const conversationAssistance = (uid && params.cid && isCommander)
- ? await (await import('../../features/conversation_assistance_context')).resolveConversationAssistanceForTurn(uid, params.cid)
+ const conversationAssistance = (uid && params.cid && (isCommander || (isGroupAgent && agentId)))
+ ? await (await import('../../features/conversation_assistance_context')).resolveConversationAssistanceForTurn(uid, params.cid, {
+ ...(isGroupAgent ? { agentId } : {}), outputDelivery: params.outputDelivery,
+ })
: { kind: undefined, guidance: '' };
const toolSurface = createToolSurfaceController({
availableToolNames: surfaceAvailableToolNames,
@@ -1318,8 +1285,8 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// until the user clicks the staged card. App diagnosis stays behind
// its focused Management child group.
...(isCommander && availableToolNames.includes('open_app_view') ? ['open_app_view'] : []),
- // Preserve the existing project-bound backlog surface. Only the
- // non-project Commander selector is deferred under Management.
+ // Preserve the existing project-bound backlog surface. The
+ // non-project global-only executor is deferred under Management.
...(params.projectId ? ['todo_tasks', ...((isCommander || isGroupAgent) ? ['auto_tasks'] : [])] : []),
...(params.onOutputsPublished ? ['publish_outputs'] : []),
],
@@ -1491,6 +1458,12 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
: '';
// Entry guidance stays on the current turn, outside the stable system prefix.
const conversationAssistanceBlock = conversationAssistance.guidance;
+ // A file the guidance showed whole is already read for this run: the file
+ // tools accept its first edit without an E_NOT_READ round, and still reject
+ // it as stale if the bytes change before then.
+ const initialReadFileState = conversationAssistance.readSeeds?.length
+ ? new Map<string, unknown>(conversationAssistance.readSeeds.map((seed) => [seed.path, seed.stamp]))
+ : undefined;
const turnEphemeral = [
orchestrationBlock,
volatileTail,
@@ -1602,6 +1575,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
turnId: params.turnId,
},
params.cid,
+ params.requireImageInput,
);
// Inject the rotating provider into BOTH the factory slot AND the
// pre-built instance cache. ProviderRegistry.get() short-circuits on
@@ -1706,6 +1680,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
failureTrackingScope: session,
resolvedSystemPrompt,
turnEphemeral,
+ ...(initialReadFileState ? { initialReadFileState } : {}),
entryId: primary?.entryId,
profileId: primary?.profileId,
providerId,
@@ -1837,6 +1812,7 @@ async function buildRotatingProvider(
retryLimits?: { networkRetryAttempts: number; normalEmptyRetryAttempts: number },
usageContext?: OrkasApiUsageContext,
cid?: string,
+ requireImageInput = false,
): Promise<LLMProvider> {
const candidates: RotatingCandidate[] = group.map((choice) => {
const candProviderId = choice.provider;
@@ -1883,7 +1859,7 @@ async function buildRotatingProvider(
provider: candProviderId,
...(resolvedModel?.needsCustomModel ? { customModel: resolvedModel.model } : { model: candModelId }),
apiKey: currentApiKey,
- onPayload: omitReservedOutputLimitForProvider(
+ onPayload: omitReservedOutputLimitForProvider(
candProviderId,
buildNativeSearchOnPayload(candProviderId, candModelId, onNativeSearchInjected),
),
@@ -1896,6 +1872,7 @@ async function buildRotatingProvider(
return createRotatingProvider({
providerId,
candidates,
+ requireImageInput,
...retryLimits,
...(process.env.ORKAS_MODEL_EVAL_PINNED_ROUTE === '1'
&& providerId === 'custom'
diff --git a/src/main/model/core-agent/tool-catalog-revision.ts b/src/main/model/core-agent/tool-catalog-revision.ts
index e0655887..5879d208 100644
--- a/src/main/model/core-agent/tool-catalog-revision.ts
+++ b/src/main/model/core-agent/tool-catalog-revision.ts
@@ -5,4 +5,4 @@
* it as their current-state oracle without pulling the Electron runtime or the
* tool catalog's logger/path dependency chain into model-eval processes.
*/
-export const TOOL_CATALOG_REVISION = '69';
+export const TOOL_CATALOG_REVISION = '81';
diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.ts
index 059247de..d4c92ea3 100644
--- a/src/main/model/core-agent/tool-catalog.ts
+++ b/src/main/model/core-agent/tool-catalog.ts
@@ -114,7 +114,7 @@ export const TOOL_GROUPS: readonly ToolGroupEntry[] = [
{ id: 'orchestration', title: 'Orchestration', summary: 'Commander delegation, handoff, and anonymous worker controls.', activation: 'host-managed', agentDependency: false },
{ id: 'management', title: 'Management', summary: 'App support, Skill, marketplace, and automation management controls.', activation: 'loadable', agentDependency: false },
{ id: 'management.app', title: 'App support', summary: 'Navigate supported Orkas screens and inspect sanitized app health.', parent: 'management', activation: 'loadable', agentDependency: false },
- { id: 'management.projects', title: 'Project tasks', summary: 'Find an existing project and read or update its task backlog.', parent: 'management', activation: 'loadable', agentDependency: true },
+ { id: 'management.projects', title: 'To-dos', summary: "Read or update global to-dos outside a project, or the current project's backlog.", parent: 'management', activation: 'loadable', agentDependency: true },
{ id: 'management.skills', title: 'Skill management', summary: 'Search available shared Skills or import a user-requested Skill package.', parent: 'management', activation: 'loadable', agentDependency: false },
{ id: 'management.marketplace', title: 'Marketplace management', summary: 'Search the Marketplace and request a confirmed installation.', parent: 'management', activation: 'loadable', agentDependency: false },
{ id: 'management.automation', title: 'Automation management', summary: 'Manage scheduled automations.', parent: 'management', activation: 'loadable', agentDependency: true },
@@ -171,7 +171,7 @@ export const TOOL_CATALOG: readonly ToolCatalogEntry[] = [
{ name: 'process_session', loadGroups: ['workspace.execute.command', 'workspace.execute.session'], permission: 'localExec', summary: 'Manage a persistent process session.' },
{ name: 'interactive_cli', loadGroups: ['workspace.execute.session'], permission: 'localExec', summary: 'Manage a live user-input CLI session.' },
{ name: 'create_artifact', loadGroups: ['workspace.artifact'], permission: 'localExec', summary: 'Build an interactive HTML/CSS/JS artifact.' },
- { name: 'html_preview', loadGroups: ['workspace.artifact'], permission: 'localExec', summary: 'Audit local HTML at desktop or mobile targets.' },
+ { name: 'html_preview', loadGroups: ['workspace.artifact'], permission: 'localExec', summary: 'Audit local HTML or a current-conversation app at desktop or mobile targets.' },
{ name: 'create_pdf', loadGroups: ['office.pdf'], permission: 'localExec', summary: 'Create a PDF from Markdown or HTML.' },
{ name: 'edit_pdf', loadGroups: ['office.pdf'], permission: 'localExec', summary: 'Edit PDF pages, overlays, watermarks, and forms.' },
@@ -205,10 +205,10 @@ export const TOOL_CATALOG: readonly ToolCatalogEntry[] = [
{ name: 'cross_session_memory', loadGroups: ['context'], summary: 'Read or update cross-session memory.' },
{ name: 'metacognition', loadGroups: ['context'], summary: 'Read or update agent competence and strategies.' },
{ name: 'project_instructions', loadGroups: ['context'], summary: 'Update project standing instructions.' },
- { name: 'todo_tasks', loadGroups: ['management.projects'], programmatic: { mode: 'allow' }, summary: 'Manage a selected project backlog.' },
+ { name: 'todo_tasks', loadGroups: ['management.projects'], programmatic: { mode: 'allow' }, summary: "Manage the global to-do list outside a project; project to-dos require a conversation in that project." },
// Commander-only: it relocates this conversation, which is an orchestration
// decision, and `run_program` gets no access to that side effect.
- { name: 'project_setup', loadGroups: ['management.projects'], agentAssignable: false, summary: "Create a project for this conversation's work, or undo that." },
+ { name: 'project_setup', loadGroups: ['management.projects'], agentAssignable: false, summary: "Create or rename this conversation's project, or undo its filing." },
{ name: 'dispatch_to', loadGroups: ['orchestration'], summary: 'Delegate visible work and continue the commander turn.' },
{ name: 'hand_off_to', loadGroups: ['orchestration'], summary: 'Transfer terminal ownership to another Agent.' },
diff --git a/test/main/model/core-agent/client-stall.test.ts b/test/main/model/core-agent/client-stall.test.ts
index a8fbf69d..8704f169 100644
--- a/test/main/model/core-agent/client-stall.test.ts
+++ b/test/main/model/core-agent/client-stall.test.ts
@@ -149,6 +149,43 @@ async function drain(opts: Record<string, unknown>): Promise<{ events: DrainedEv
}
describe('streamChatWithModel — phase-aware idle watchdog (Phase 1)', () => {
+ it.each(['wall', 'idle', 'cancel'] as const)('aborts a pending transport once on %s termination and settles the stream', async (termination) => {
+ await import('../../../../src/main/model/core-agent/client');
+ const transportAborted = vi.fn();
+ vi.useFakeTimers();
+ let started!: () => void;
+ const ready = new Promise<void>(resolve => { started = resolve; });
+ h.makeStream = async function* () {
+ const signal = h.lastRunStreamParams?.signal as AbortSignal;
+ started();
+ await new Promise<void>(resolve => signal.addEventListener('abort', () => {
+ transportAborted(); resolve();
+ }, {once:true}));
+ expect(signal.aborted).toBe(true);
+ throw new Error('Controlled transport abort');
+ };
+ const controller = new AbortController();
+ try {
+ const result = drain({ idleTimeout: termination === 'idle' ? 0.1 : 10,
+ abortSignal: controller.signal,
+ ...(termination === 'wall' ? { executionDeadlineAt: Date.now() + 200 } : {}) });
+ await ready;
+ if (termination === 'cancel') controller.abort();
+ await vi.advanceTimersByTimeAsync(200);
+ const { events } = await result;
+ expect(events.filter(event => event.type === 'error')).toEqual([
+ expect.objectContaining(termination === 'cancel' ? { aborted: true }
+ : { failureCode: termination === 'wall' ? 'execution_wall_timeout' : 'idle_timeout' }),
+ ]);
+ expect(transportAborted).toHaveBeenCalledTimes(1);
+ expect((h.lastRunStreamParams?.signal as AbortSignal).aborted).toBe(true);
+ expect(h.runStreamCalls).toBe(1);
+ expect(events.at(-1)?.type).toBe('done');
+ } finally {
+ controller.abort();
+ }
+ });
+
it('does not charge the provider usage again when the enclosing run finishes', async () => {
const meter = await import('../../../../src/main/util/conversation-cost-meter');
@@ -165,6 +202,12 @@ describe('streamChatWithModel — phase-aware idle watchdog (Phase 1)', () => {
} finally { meter.resetTaskTokens(cid); }
});
+ it.each(['final', 'process'] as const)('preserves host delivery ownership through the client adapter: %s', async (outputDelivery) => {
+ h.makeStream = async function* () { yield completedEvent('done'); };
+ await drain({ outputDelivery });
+ expect(h.lastBuildRunnerParams?.outputDelivery).toBe(outputDelivery);
+ });
+
it('localizes a directly thrown task backstop without suggesting a model retry', async () => {
h.makeStream = async function* () { throw Object.assign(new Error('Task token limit reached'), { code: 'TASK_TOKEN_LIMIT_REACHED' }); };
const { t } = await import('../../../../src/main/i18n');
diff --git a/test/main/model/core-agent/local-tools.test.ts b/test/main/model/core-agent/local-tools.test.ts
index ba5a2984..2f7314d9 100644
--- a/test/main/model/core-agent/local-tools.test.ts
+++ b/test/main/model/core-agent/local-tools.test.ts
@@ -14,12 +14,17 @@ const TEST_NODE = process.env.ORKAS_TEST_NODE || process.execPath;
const UID = 'u-localtools-001';
const CID = 'conv-edit';
-it('advertises edit freshness before the model attempts a cross-turn revision', async () => {
+it.each(['apply_patch', 'edit_file'])('advertises the accepted read/write baseline before a %s call', async name => {
const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');
- const edit = createLocalTools({}).find(tool => tool.name === 'edit_file')!;
- expect(edit.description).toContain('unchanged read/write baseline from this run');
- expect(edit.description).toContain('or a matching expected_hash');
- expect(edit.description).toContain('earlier turns alone do not establish a baseline');
+ const tool = createLocalTools({}).find(tool => tool.name === name)!;
+ expect(tool.description).toContain('unchanged baseline from this run');
+ expect(tool.description).toContain('read_files and successful file-tool writes establish');
+ expect(tool.description).toContain('bash reads/writes');
+ expect(tool.description).toContain('do not');
+ if (name === 'edit_file') {
+ expect(tool.description).toContain('or a matching expected_hash');
+ expect(tool.description).toContain('earlier turns alone do not');
+ }
});
let tmpDir: string;
@@ -703,13 +708,11 @@ async function buildBashTool() {
}
describe('local-tools › interactive CLI action contract', () => {
- it('advertises a portable action schema and rejects cross-action fields before session lookup', async () => {
+ it('uses a portable schema and ignores send fields during close', async () => {
const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');
const interactive = createLocalTools({ userId: UID, cid: CID })
.find((tool) => tool.name === 'interactive_cli')!;
const schema = interactive.inputSchema as any;
- expect(schema.required).toEqual(['action']);
- expect(schema).not.toHaveProperty('oneOf');
const rejected = await interactive.execute({
action: 'close',
@@ -2399,43 +2402,34 @@ describe('local-tools › apply_patch › transactional text changes', () => {
it('keeps read and stale-write guards when context-only hunks locate an edit', async () => {
await allFilesAuto();
- const { applyPatch, wsDir } = await buildPatchTool();
+ const written: string[] = [];
+ const { applyPatch, wsDir } = await buildPatchTool({ onFileWritten: (p) => written.push(p) });
const source = path.join(wsDir, 'source.ts');
- fs.writeFileSync(source, 'const value = 1;\nconst label = "before";\n');
+ fs.writeFileSync(source, '// target\nconst value = 1;\n');
const ctx = { workingDir: wsDir, state: { readFileState: new Map() } } as any;
+ const patch = [
+ '*** Begin Patch', `*** Update File: ${source}`,
+ '@@', ' // target', '@@', '-const value = 2;', '+const value = 3;',
+ '*** End Patch',
+ ].join('\n');
- const blocked = await applyPatch.execute({
- patch: [
- '*** Begin Patch',
- `*** Update File: ${source}`,
- '@@',
- '-const label = "before";',
- '+const label = "after";',
- '*** End Patch',
- ].join('\n'),
- }, ctx);
-
- expect(blocked.isError).toBe(true);
- expect(blocked.content).toContain('E_NOT_READ');
- expect(blocked.content).toContain('<patch-recovery file_hash=');
- expect(blocked.content).toContain('rebuild the patch against these bytes');
- expect(blocked.content).not.toContain('expected_hash');
- expect(fs.readFileSync(source, 'utf8')).toBe('const value = 1;\nconst label = "before";\n');
+ const unread = await applyPatch.execute({ patch }, ctx);
+ expect(unread.content).toContain('E_NOT_READ');
+ expect(fs.readFileSync(source, 'utf8')).toBe('// target\nconst value = 1;\n');
+ const tracker = await import('../../../../src/main/model/core-agent/read-tracker');
+ tracker.recordRead(ctx, source, undefined, hash('// target\nconst value = 1;\n'));
+ fs.writeFileSync(source, '// target\nconst value = 2;\n');
- const retried = await applyPatch.execute({
- patch: [
- '*** Begin Patch',
- `*** Update File: ${source}`,
- '@@',
- ' const value = 1;',
- '-const label = "before";',
- '+const label = "after";',
- '*** End Patch',
- ].join('\n'),
- }, ctx);
+ const stale = await applyPatch.execute({ patch }, ctx);
+ expect(stale.content).toContain('E_STALE');
+ expect(fs.readFileSync(source, 'utf8')).toBe('// target\nconst value = 2;\n');
+ expect(written).toEqual([]);
- expect(retried.isError).toBeFalsy();
- expect(fs.readFileSync(source, 'utf8')).toBe('const value = 1;\nconst label = "after";\n');
+ // The existing stale response supplies current bytes and refreshes the baseline.
+ const recovered = await applyPatch.execute({ patch }, ctx);
+ expect(recovered.isError).toBeFalsy();
+ expect(fs.readFileSync(source, 'utf8')).toBe('// target\nconst value = 3;\n');
+ expect(written).toEqual([source]);
});
it('moves an updated file while preserving its mode and reporting the destination', async () => {
@@ -2915,6 +2909,7 @@ async function buildCreateArtifactTool(opts: {
warnings?: string[];
controlsExercised?: number;
observableEffects?: number;
+ sdkByViewport?: Array<{ viewport: string; calls: Array<{ method: string; code: string }> }>;
}>;
} = {}) {
const localTools = await import('../../../../src/main/model/core-agent/local-tools');
@@ -2935,6 +2930,29 @@ async function buildCreateArtifactTool(opts: {
const MIN_FILES = [{ path: 'index.html', content: '<!doctype html><h1>hi</h1>' }];
+it('repairs a preview issue through the same application identity and exposes the committed revision', async () => {
+ const events: Array<{ id: string; title: string; revision?: number }> = [];
+ const tool = await buildCreateArtifactTool({ agentId: 'builder', onArtifactCreated: a => events.push(a),
+ artifactInteractionSmoke: async () => ({ ok: events.length > 0, blockers: events.length ? [] : ['runtime fault'] }) });
+ const first = await run(tool, { title: 'Chat', files: MIN_FILES });
+ expect(first.content).toContain('preview reported issues');
+ expect(first.content).toContain('artifact_id');
+ const second = await run(tool, { artifact_id: events[0].id, files: [{ path: 'index.html', content: '<!doctype html><button>Corrected</button>' }] });
+ expect(second.isError).toBeFalsy();
+ expect(events).toEqual([{ id: events[0].id, title: 'Chat', revision: 1 }, { id: events[0].id, title: 'Chat', revision: 2 }]);
+ expect(second.content).toContain('updated');
+ expect(fs.readdirSync(path.join(tmpDir, UID, 'cloud/chat_artifacts', CID))).toEqual([events[0].id]);
+});
+
+it('reports a failed correction without publishing another app or deleting the previous version', async () => {
+ const events: Array<{ id: string }> = [];
+ const tool = await buildCreateArtifactTool({ agentId: 'builder', onArtifactCreated: a => events.push(a) });
+ await run(tool, { files: MIN_FILES });
+ const result = await run(tool, { artifact_id: events[0].id, files: [{ path: 'style.css', content: 'body{}' }] });
+ expect(result.isError).toBe(true); expect(events).toHaveLength(1);
+ expect(fs.readFileSync(path.join(tmpDir, UID, 'cloud/chat_artifacts', CID, events[0].id, 'index.html'), 'utf8')).toContain('<h1>hi</h1>');
+});
+
describe('local-tools › create_artifact › availability', () => {
it('is offered only when both cid and onArtifactCreated are present', async () => {
expect(await buildCreateArtifactTool({ cid: CID, onArtifactCreated: () => {} })).toBeTruthy();
@@ -2953,7 +2971,8 @@ describe('local-tools › create_artifact › permission mode', () => {
const r = await run(tool, { title: 'X', files: MIN_FILES });
expect(r.isError).toBeFalsy();
expect(r.content).toMatch(/do NOT paste/i);
- expect(r.content).toMatch(/preview checks passed/i);
+ expect(r.content).toContain('preview completed');
+ expect(r.content).toContain('not a full functional verification');
});
it('publishes a valid bundle with honest diagnostics even when preview checks find issues', async () => {
@@ -2987,6 +3006,20 @@ describe('local-tools › create_artifact › permission mode', () => {
expect(fs.existsSync(candidateDir)).toBe(true);
});
+ it.each(['E_PERMISSION', 'E_UNAVAILABLE', 'E_CANCELLED'])('delivers an app with factual %s SDK observations without requiring repair', async code => {
+ const created: Array<{ id: string }> = [];
+ const tool = await buildCreateArtifactTool({ onArtifactCreated: a => created.push(a),
+ artifactInteractionSmoke: async () => ({ ok: true, blockers: [], controlsExercised: 1, observableEffects: 1,
+ sdkByViewport: [{ viewport: 'mobile', calls: [{ method: 'data.query', code }, { method: 'data.query', code }] }] }) });
+ const result = await run(tool, { title: 'Editable app', files: MIN_FILES });
+ expect(result.isError).toBeFalsy();
+ expect(created).toHaveLength(1);
+ expect(result.content).toContain(`mobile data.query: ${code}`);
+ expect(result.content.match(new RegExp(code, 'g'))).toHaveLength(1);
+ expect(result.content).not.toContain('checks passed');
+ expect(fs.existsSync(path.join(tmpDir, UID, 'cloud/chat_artifacts', CID, created[0].id, 'index.html'))).toBe(true);
+ });
+
it('retains unavailable remote resource diagnostics without forcing an offline rewrite', async () => {
await allFilesAuto();
const tool = await buildCreateArtifactTool({
@@ -3010,17 +3043,17 @@ describe('local-tools › create_artifact › permission mode', () => {
});
describe('local-tools › create_artifact › success + callback', () => {
- it.each(['web', 'cloud'])('refuses an explicit %s artifact without output or callback', async appType => {
+ it('declares and persists an explicit cloud type without granting desktop interfaces', async () => {
await allFilesAuto();
- const created: Array<{ id: string }> = [];
- const smoke = vi.fn();
- const tool = await buildCreateArtifactTool({ onArtifactCreated: a => created.push(a), artifactInteractionSmoke: smoke });
- expect(tool.inputSchema.properties.appType.enum).toEqual(['local', 'web']);
- const result = await run(tool, { appType, files: MIN_FILES });
- expect(result.isError).toBe(true);
- expect(JSON.parse(String(result.content))).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
- expect(created).toEqual([]); expect(smoke).not.toHaveBeenCalled();
- expect(fs.existsSync(path.join(tmpDir, UID, 'cloud/chat_artifacts', CID))).toBe(false);
+ const created: Array<{id:string}>=[];
+ const tool=await buildCreateArtifactTool({onArtifactCreated:a=>created.push(a)});
+ expect(tool.inputSchema.properties.appType.enum).toEqual(['local','web']);
+ const result=await run(tool,{appType:'web',files:MIN_FILES});
+ expect(result.isError).toBeFalsy();
+ const meta=JSON.parse(fs.readFileSync(path.join(tmpDir,UID,'cloud/chat_artifacts',CID,created[0].id,'__orkas-meta.json'),'utf8'));
+ expect(meta.appType).toBe('web');
+ expect(result.content).not.toContain('orkasArtifact.send');
+ expect(result.content).not.toContain('bridge.js');
});
it('preserves the application and reports unavailable preview without claiming verification', async () => {
const created: unknown[]=[];
@@ -3260,32 +3293,3 @@ describe('local-tools › markdown_to_pdf › locked probe+render wiring', () =>
}
});
});
-
-describe('PDF output publication', () => {
- it.each(['markdown', 'html'])('keeps a successfully rendered %s PDF successful when the publication callback fails', async (sourceType) => {
- vi.resetModules();
- const render = vi.fn(async (_content: string, outPath: string) => { fs.writeFileSync(outPath, '%PDF-fixture'); });
- vi.doMock('../../../../src/main/util/md-to-pdf', () => ({ markdownToPdf: render, htmlToPdf: render }));
- try {
- const users = await import('../../../../src/main/features/users');
- users.activateUser(UID);
- await allFilesAuto();
- const ws = await import('../../../../src/main/features/user_workspace');
- const wsDir = path.join(tmpDir, 'ws');
- fs.mkdirSync(wsDir, { recursive: true });
- expect(ws.setWorkspacePath(UID, wsDir).ok).toBe(true);
- const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');
- const onFileWritten = vi.fn(async () => { throw new Error('publication fixture failed'); });
- const tool = createLocalTools({ userId: UID, cid: CID, onFileWritten }).find((item) => item.name === 'create_pdf')!;
- const target = path.join(wsDir, 'report.pdf');
- const result = await tool.execute({ source_type: sourceType, path: target, content: '<h1>Report</h1>' }, { workingDir: wsDir, state: {} } as any);
- expect(result.isError).toBeFalsy();
- expect(String(result.content)).toContain('PDF written:');
- expect(fs.readFileSync(target, 'utf8')).toBe('%PDF-fixture');
- expect(onFileWritten).toHaveBeenCalledWith(target);
- } finally {
- vi.doUnmock('../../../../src/main/util/md-to-pdf');
- vi.resetModules();
- }
- });
-});
diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.ts
index 8c876a81..57ef03fc 100644
--- a/test/main/model/core-agent/tool-catalog.test.ts
+++ b/test/main/model/core-agent/tool-catalog.test.ts
@@ -13,6 +13,7 @@ import {
canonicalizeAgentToolGroups,
canonicalizeToolGroups,
expandToolGroups,
+ getLoadableToolGroupsSystemPromptBlock,
invalidAgentToolGroupRefs,
invalidToolGroupRefs,
isToolVisibleToAgent,
@@ -324,6 +325,28 @@ describe('tool-catalog', () => {
]);
});
+ it('tells an unbound Commander that the to-do group also holds the global list', () => {
+ // Outside a project todo_tasks is dormant and the open-work block only
+ // appears once to-dos exist, so the directory line is the first place a
+ // Commander learns where "save this as a to-do" goes.
+ const directory = getLoadableToolGroupsSystemPromptBlock({
+ availableToolNames: ['todo_tasks', 'project_setup', 'tool_load'],
+ purpose: 'runtime',
+ });
+ const todoLine = directory.split('\n').find((line) => line.includes('`todo_tasks`')) || '';
+ expect(todoLine).toMatch(/global to-do list/);
+ expect(todoLine).toMatch(/project/);
+ expect(directory).toContain('`management.projects` — To-dos.');
+ // Inside a project the tool is resident, so the directory stops describing it.
+ const resident = getLoadableToolGroupsSystemPromptBlock({
+ availableToolNames: ['todo_tasks', 'project_setup', 'tool_load'],
+ initialActiveToolNames: ['todo_tasks'],
+ purpose: 'runtime',
+ });
+ expect(resident).not.toContain('`todo_tasks`');
+ expect(resident).toContain('`project_setup`');
+ });
+
it('scopes Office leaves while preserving the parent and pdf alias', () => {
expect(TOOL_GROUPS.filter((group) => group.parent === 'office').map((group) => group.id))
.toEqual(['office.word', 'office.spreadsheet', 'office.presentation', 'office.pdf']);
@@ -500,9 +523,49 @@ describe('tool-catalog', () => {
const schemas = enumerateAllInjectedTools()
.map((tool) => ({ name: tool.name, inputSchema: withoutDescriptions(tool.inputSchema) }))
.sort((left, right) => left.name.localeCompare(right.name));
+ // The approved Zod 4 migration changes JSON key order and adds the implicit
+ // safe-integer ceiling. Compare the browser with the bounded legacy schema
+ // oracle, then retain the original whole-corpus fingerprints below.
+ // Legacy Zod is used only to describe this static test fixture, never input.
+ const browser = schemas.find(tool => tool.name === 'inner_browser')!;
+ const browserSchema = structuredClone(browser.inputSchema) as any;
+ expect(browserSchema.properties.option_offset.maximum).toBe(Number.MAX_SAFE_INTEGER);
+ delete browserSchema.properties.option_offset.maximum;
+ const { z: legacyZod } = require('zod/v3');
+ const { zodToJsonSchema } = require('zod-to-json-schema');
+ const { $schema, ...legacyBrowserSchema } = zodToJsonSchema(legacyZod.object(
+ require('../../../../bin/browser-tool-contract.cjs').shape(legacyZod),
+ ).strict());
+ expect(browserSchema).toEqual(withoutDescriptions(legacyBrowserSchema));
+ browser.inputSchema = withoutDescriptions(legacyBrowserSchema);
+ // 2026-10-23: list_files advertises its existing runtime rejection of an
+ // empty path. Undo only that bound to retain the preceding corpus oracle.
+ const listFiles = schemas.find(tool => tool.name === 'list_files')!.inputSchema as any;
+ expect(listFiles.properties.path).toEqual({ type: 'string', minLength: 1 });
+ delete listFiles.properties.path.minLength;
+ // 2026-10-21, requester-confirmed: corrections retain the app identity.
+ const artifact = schemas.find(tool => tool.name === 'create_artifact')!.inputSchema as any;
+ expect(artifact.properties.artifact_id).toEqual({ type: 'string' });
+ delete artifact.properties.artifact_id;
+ // 2026-10-20, requester-confirmed: preview accepts path XOR artifact_id.
+ // Undo only that exact delta to keep the preceding corpus pinned.
+ const preview = schemas.find(tool => tool.name === 'html_preview')!.inputSchema as any;
+ expect(preview.properties.artifact_id).toEqual({ type: 'string' });
+ expect(preview.required).toEqual([]);
+ delete preview.properties.artifact_id;
+ preview.required = ['path'];
const fingerprint = createHash('sha256')
.update(JSON.stringify(schemas))
.digest('hex');
+ // 2026-10-19, requester-confirmed: the sole structural addition is an
+ // optional history segment index. Removing it must reproduce the prior
+ // corpus exactly; unrelated names, defaults and permissions cannot drift.
+ const previousSchemas = structuredClone(schemas);
+ const history = previousSchemas.find(tool => tool.name === 'chat_history')!;
+ expect((history.inputSchema as any).properties.process_index).toEqual({ type: 'integer', minimum: 0 });
+ delete (history.inputSchema as any).properties.process_index;
+ expect(createHash('sha256').update(JSON.stringify(previousSchemas)).digest('hex'))
+ .toBe('74dd4963f96a37267a8bbb1080994ccba845619bb062ff77fe7f70f298bea84a');
// Requester-confirmed portable root objects replace the nine first-party
// action unions; executors retain conditional requirements and scope checks.
// 2026-09-18: inner_browser gained an optional `scope` on observe. It only
@@ -544,7 +607,7 @@ describe('tool-catalog', () => {
expect(
fingerprint,
'A model-visible field, enum, bound, default, or required rule changed; review it as a schema change, not description cleanup.',
- ).toBe('74dd4963f96a37267a8bbb1080994ccba845619bb062ff77fe7f70f298bea84a');
+ ).toBe('9eef8d03356d5a886f545d8e88f1e3f97645f152e01cd2d71990ad096045aee6');
});
it('keeps the reviewed stable tool corpus within the description budgets', () => {
@@ -690,7 +753,7 @@ describe('tool-catalog', () => {
edit_file: ['old_string', 'new_string', 'unique', 'optimistic concurrency'],
publish_outputs: ['complete', 'final', 'paths', 'current turn'],
create_artifact: ['interactive', 'files', 'path', 'content', 'index.html'],
- html_preview: ['local', 'desktop', 'mobile', 'screenshot', 'overflow', 'network'],
+ html_preview: ['local', 'desktop', 'mobile', 'screenshot', 'overflow', 'isolated', 'artifact_id', 'current conversation', 'exactly one'],
delete_file: ['confirmation', 'confirmation_token', 'path'],
process_session: ['bash', 'session_id', 'read', 'write', 'stop', 'yield_time_ms'],
interactive_cli: ['live user input', 'command', 'purpose', 'read', 'send', 'close'],