Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): enforce subagent authorization on resume and new turns
Jackf8d4feb6f3b0
diff --git a/docs/adr/0279-resumable-subagent-delegations.md b/docs/adr/0279-resumable-subagent-delegations.mdindex 0a063a9ac..1a7a46aaf 100644--- a/docs/adr/0279-resumable-subagent-delegations.md+++ b/docs/adr/0279-resumable-subagent-delegations.md@@ -100,7 +100,10 @@ same unknown-id error, because the model's only correct action is identical.A resume keeps the chain's own model binding. The `providerId/modelId` key thechain recorded is preferred; a chain rebuilt from the transcript only knows the-model id, which is matched against what the session has configured. Changing the+model id, which is matched only against the current definition's pin/fallbacks,+the session binding, and currently authorized overrides. A remembered key whose+turn grant expired is reauthorized before use; a denied key cannot select another+account by model id. Other definitions' private pins are never candidates (#841). Changing theparent's own session model therefore does not strand a chain, and a delegate neverswaps models by accident. If nothing resolves the recorded binding any more, therun continues on the binding the definition resolves to now and records thediff --git a/docs/adr/subagent-model-opt-in.md b/docs/adr/subagent-model-opt-in.mdindex 397065dc3..9980336e7 100644--- a/docs/adr/subagent-model-opt-in.md+++ b/docs/adr/subagent-model-opt-in.md@@ -32,7 +32,13 @@ reuse matching and must not overwrite a definition pin with a differentprovider id. On-demand provider matching uses the same unique id / vendor /name rule as pin resolution; ambiguous vendor aliases fail closed unless thecaller uses the exact provider id. A changed launch list retires an idle-runtime on the next prompt, including after opt-in is revoked.+runtime on the next prompt, including after opt-in is revoked. On-demand grants+expire at every new parent prompt or approved plan/goal execution, even when the+launch list is unchanged. Late responses from an expired turn are discarded.+Resume uses the same authorization boundary: only the current definition's+pin/fallbacks, session inheritance, and current override grants may be selected;+a remembered key is reauthorized when necessary. Other definitions' pins do not+authorize a model-id match (#841).The opt-in belongs to the decision, not to the Task tool: it governs everyentry point through which the AI picks a model for work it delegates.diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 12f7e73bd..2b1799870 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,9 @@# Unreleased changes+- Resuming a subagent no longer selects another definition's private model+ binding. On-demand delegation permissions are checked again on the next parent+ turn, so revoking automatic delegation takes effect without restarting the runtime.+- A stored hosted web-search record that cannot be replayed no longer fails everylater request in that conversation: the message continues without search replay,so histories written before the contract change stay usable.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 95dda728a..10e56e5c7 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -772,7 +772,9 @@ core set rather than the on-demand catalog of §7.1:include definition-only pins, while only the former authorizes cachedoverrides and the model summary. Missing keys default to an empty list;successful on-demand resolution is cached separately from launch opt-in and- does not rewrite definition pins or runtime reuse matching. On-demand+ does not rewrite definition pins or runtime reuse matching. Grants expire at+ each new parent prompt or approved plan/goal execution; late responses from+ an older turn cannot repopulate the cache. On-demandprovider matching uses the same unique id/vendor/name rule as pin resolution.A changed opt-in list retires the idle runtime on the next launch. Pins remain usableby their own definitions when `model` is omitted or when `Task.model` repeats@@ -911,8 +913,12 @@ Resume is strictly same-session and never queues: resuming a runningdelegation is a tool error telling the parent to converge with `TaskWait`first, and a chain has at most one live record at a time. `model` and `resume`together are rejected, and a resumed run keeps the chain's recorded binding:-the `providerId/modelId` key it resolved is preferred, a chain rebuilt from the-transcript is matched by model id, and when nothing resolves it the run+the `providerId/modelId` key it resolved is preferred and reauthorized on demand+when its turn grant has expired. A chain rebuilt from the transcript is matched+by model id only among the current definition pin/fallbacks, the session binding,+and currently authorized overrides. Other definitions' private pins are excluded.+A known key never falls through to another account just because its model id+matches. When nothing authorized resolves it the runcontinues on the definition's current binding and records the previous model idas `modelChangedFrom` in its lifecycle details. Changing models on purpose meansstarting a new delegation. An unknown id, an id belonging to another definition,diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 6c6930488..9c6a832a0 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -10761,6 +10761,14 @@ are withdrawn with ADR 0165.UI/persistence journey and live external provider execution remain manual;this fixture does not claim a complete native UI journey.+- **Authorization regression coverage (#841)**: `pnpm test:e2e:subagent-models`+ grants a model on demand, reuses the runtime, then revokes it without changing+ the launch catalog. The next prompt must reauthorize and issue no child request.+ A transcript-restored resume with a colliding model id must use the session+ binding rather than another definition's private account. Runtime tests also+ cover own pins/fallbacks, opted-in bindings, visible fallback metadata, live-key+ reauthorization, and late RPC responses crossing parent turns.+#### E2E-170: Shell titlebars use borderless chrome- **Preconditions**: PI-Desktop is open in chat, at least one destination page,diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 026d712c1..65955fbca 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -690,6 +690,13 @@ Stop / 运行时销毁。主 Agent 用 `TaskStop` 判断要不要取消;运行不可恢复的状态、超出读预算的链,以及行已经不在的链,各自返回一个说明原因的工具错误;对未知 id,还会一并列出当前可复用的 id。+On-demand grants expire at each new parent prompt or approved plan/goal execution;+late responses cannot restore expired grants. Resume reauthorizes a remembered key+when necessary. Model-id matching is limited to the current definition's pin and+fallbacks, session inheritance, and current override grants; other definitions'+private pins are excluded. A denied known key never selects another account by+model id (#841).+父级通过系统提示发现可复用的链:那里列出每条链最新的 `delegationId`、它的目标,以及它读过的文件最多 `MAX_RESUMABLE_LISTED_FILES`(8)个(超出部分带 `(+N more)` 后缀)。清单会在委托结算时围绕既有的提示段落重新组装。对 `MAX_SUBAGENT_CONCURRENCY`、diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex e25fb7794..6a850c45a 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -6629,6 +6629,14 @@ eleven-tool-round desktop paths are verified by验证独立许可、撤销和多账号别名冲突,连接测试检查按需唯一匹配。设置复选框 UI/持久化旅程及外部真实提供商执行仍需手动验证;此夹具不代表完整原生 UI 旅程已通过。+- **Authorization regression coverage (#841)**: `pnpm test:e2e:subagent-models`+ grants a model on demand, reuses the runtime, then revokes it without changing+ the launch catalog. The next prompt must reauthorize and issue no child request.+ A transcript-restored resume with a colliding model id must use the session+ binding rather than another definition's private account. Runtime tests also+ cover own pins/fallbacks, opted-in bindings, visible fallback metadata, live-key+ reauthorization, and late RPC responses crossing parent turns.+#### E2E-167:原生边缘调整大小保持流畅并保存稳定边界- **前置条件**:PI-Desktop 在 macOS、Windows 或 Linux 上以普通、未最大化diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex c7ff7917a..59be9d557 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -6532,6 +6532,50 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});+ it("rechecks an on-demand grant after revocation on the next prompt (#841)", async () => {+ const selected = { ...provider, modelId: "new-model", modelConfig: undefined };+ const host = { call: vi.fn().mockResolvedValue(selected) };+ const runtime = createRuntime({ subagents: [explorer], host });+ const agent = (runtime as unknown as { agent: Agent }).agent;+ vi.spyOn(agent, "prompt").mockResolvedValue();+ vi.spyOn(agent, "waitForIdle").mockResolvedValue();+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ try {+ await taskTool(runtime).execute("granted", { agent: "explorer", task: "Search.", model: "new/new-model" });+ expect(subagentRuns.calls).toHaveLength(1);+ host.call.mockRejectedValue(new Error("model is not enabled for delegation"));+ expect(runtimeMatches(runtime)).toBe(true);+ await runtime.prompt("Search again.");+ const denied = await taskTool(runtime).execute("revoked", { agent: "explorer", task: "Search.", model: "new/new-model" });+ expect(denied.details.error).toContain("not available for delegation");+ expect(subagentRuns.calls).toHaveLength(1);+ expect(host.call).toHaveBeenLastCalledWith("provider.resolveSubagentModel", { key: "new/new-model" });+ } finally { await runtime.dispose(); }+ });++ it("discards an on-demand grant returned after its prompt ended (#841)", async () => {+ let resolveGrant: (value: RuntimeProviderConfig) => void = () => {};+ const host = { call: vi.fn().mockImplementation(() => new Promise<RuntimeProviderConfig>((resolve) => { resolveGrant = resolve; })) };+ const runtime = createRuntime({ subagents: [explorer], host });+ const agent = (runtime as unknown as { agent: Agent }).agent;+ vi.spyOn(agent, "prompt").mockResolvedValue();+ vi.spyOn(agent, "waitForIdle").mockResolvedValue();+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ try {+ const pending = taskTool(runtime).execute("pending", { agent: "explorer", task: "Search.", model: "new/new-model" });+ await runtime.prompt("A new turn.");+ resolveGrant({ ...provider, modelId: "new-model", modelConfig: undefined });+ const expired = await pending;+ expect(expired.details.error).toContain("not available for delegation");+ host.call.mockRejectedValue(new Error("model is not enabled for delegation"));+ const denied = await taskTool(runtime).execute("revoked", { agent: "explorer", task: "Search.", model: "new/new-model" });+ expect(denied.details.error).toContain("not available for delegation");+ expect(subagentRuns.calls).toHaveLength(0);+ } finally { await runtime.dispose(); }+ });+it("is the only tool allowed to run in parallel", async () => {const runtime = createRuntime({ subagents: [explorer] });const catalog = (runtime as any).toolCatalog as Map<string, any>;@@ -7932,6 +7976,91 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});+ it.each(["session", "opt-in", "definition", "fallback", "missing"])("resumes only an authorized %s binding with a colliding private pin (#841)", async (source) => {+ const privatePin = { ...provider, id: "other-account", modelId: "recorded-model", modelConfig: undefined };+ const authorized = { ...privatePin, id: "authorized-account" };+ const own = { providerId: authorized.id, modelId: authorized.modelId };+ const target = {+ ...explorer,+ ...(source === "definition" ? { model: own } : {}),+ ...(source === "fallback" ? { fallbackModels: [own] } : {}),+ };+ const runtime = createRuntime({+ provider: source === "session" ? authorized : provider,+ subagents: [target],+ subagentProviders: {+ "other/recorded-model": privatePin,+ ...(source !== "missing" ? { "authorized-account/recorded-model": authorized } : {}),+ },+ subagentModelKeys: source === "opt-in" ? ["authorized-account/recorded-model"] : [],+ history: [restartedTaskRow("task-1", "del-1", { status: "completed", modelId: "recorded-model" }), delegateRow("child-1", "task-1")],+ });+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ try {+ const result = await startTask(runtime, "task-2", { agent: "explorer", task: "Continue.", resume: "del-1" });+ expect(result.details.error).toBeUndefined();+ expect(subagentRuns.calls[0].provider).toBe(source === "missing" ? provider : authorized);+ const records = (runtime as unknown as { delegations: Map<string, { modelChangedFrom?: string }> }).delegations;+ expect(records.get(result.details.delegationId)?.modelChangedFrom).toBe(source === "missing" ? "recorded-model" : undefined);+ } finally { await runtime.dispose(); }+ });++ it.each([true, false])("reauthorizes a live resume key after its turn grant expires: allowed=%s (#841)", async (allowed) => {+ const selected = { ...provider, id: "dynamic", modelId: "dynamic-model", modelConfig: undefined };+ const host = { call: allowed ? vi.fn().mockResolvedValue(selected) : vi.fn().mockRejectedValue(new Error("revoked")) };+ const runtime = createRuntime({+ subagents: [explorer], host,+ history: [restartedTaskRow("task-1", "del-1", { status: "completed", modelId: selected.modelId }), delegateRow("child-1", "task-1")],+ });+ const registry = (runtime as unknown as { delegationChains: { lookup(id: string): { latestModelKey?: string } | undefined } }).delegationChains;+ const chain = registry.lookup("del-1");+ if (!chain) throw new Error("fixture chain missing");+ chain.latestModelKey = "dynamic/dynamic-model";+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ try {+ await startTask(runtime, "task-2", { agent: "explorer", task: "Continue.", resume: "del-1" });+ expect(host.call).toHaveBeenCalledWith("provider.resolveSubagentModel", { key: "dynamic/dynamic-model" });+ expect(subagentRuns.calls[0].provider).toBe(allowed ? selected : provider);+ } finally { await runtime.dispose(); }+ });++ it("does not start a resumed delegate after Stop during authorization (#841)", async () => {+ let resolveGrant: (value: RuntimeProviderConfig) => void = () => {};+ const host = { call: vi.fn().mockImplementation(() => new Promise<RuntimeProviderConfig>((resolve) => { resolveGrant = resolve; })) };+ const runtime = createRuntime({ subagents: [explorer], host,+ history: [restartedTaskRow("task-1", "del-1", { status: "completed", modelId: provider.modelId }), delegateRow("child-1", "task-1")],+ });+ const registry = (runtime as unknown as { delegationChains: { lookup(id: string): { latestModelKey?: string } | undefined } }).delegationChains;+ const chain = registry.lookup("del-1");+ if (!chain) throw new Error("fixture chain missing");+ chain.latestModelKey = "dynamic/local-model";+ subagentRuns.calls.length = 0;+ try {+ const pending = startTask(runtime, "task-2", { agent: "explorer", task: "Continue.", resume: "del-1" });+ await runtime.abort();+ resolveGrant(provider);+ expect((await pending).details.error).toContain("parent turn ended");+ expect(subagentRuns.calls).toHaveLength(0);+ } finally { await runtime.dispose(); }+ });++ it("allows only one parallel resume while model authorization yields (#841)", async () => {+ const runtime = createRuntime({+ subagents: [explorer],+ history: [restartedTaskRow("task-1", "del-1", { status: "completed", modelId: provider.modelId }), delegateRow("child-1", "task-1")],+ });+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = true;+ try {+ const results = await Promise.all(["task-2", "task-3"].map((id) => startTask(runtime, id, { agent: "explorer", task: "Continue.", resume: "del-1" })));+ expect(results.filter((result) => !result.details.error)).toHaveLength(1);+ expect(results.find((result) => result.details.error)?.details.error).toContain("still running");+ expect(subagentRuns.calls).toHaveLength(1);+ } finally { subagentRuns.deferred = false; await runtime.dispose(); }+ });+it("keeps a resumed chain on its recorded model after the session model moved", async () => {const remote = {...provider,diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex d9a19eb80..347879878 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -3711,18 +3711,22 @@ Delegation rules:* On-demand model resolution for Task-time model overrides. Asks Electron* main to authorize and resolve a `providerId/modelId` key outside the* opted-in launch catalog. Grants live in a separate cache so they cannot- * rewrite definition pins or change launch-time reuse matching.+ * rewrite definition pins or change launch-time reuse matching. Each new+ * parent turn replaces the cache so revoked grants must be authorized again.*/private async resolveSubagentModel(key: string,): Promise<RuntimeProviderConfig | undefined> {- const cached = this.subagentOverrideProviders[key];+ const grants = this.subagentOverrideProviders;+ const cached = grants[key];if (cached) return cached;try {const result = await (this.host as any).call("provider.resolveSubagentModel",{ key },);+ // A late response cannot authorize work in a newer turn or after disposal.+ if (this.disposed || grants !== this.subagentOverrideProviders) return undefined;if (result && typeof result === "object" && "modelId" in result) {const provider = result as RuntimeProviderConfig;const pinned = this.subagentProviders[key];@@ -3741,7 +3745,7 @@ Delegation rules:providerId: provider.id,});}- this.subagentOverrideProviders[key] = provider;+ grants[key] = provider;return provider;}} catch {@@ -3934,29 +3938,35 @@ Delegation rules:/*** The binding a resumed run keeps (ADR 0279 §4). A live chain records the* `providerId/modelId` key it resolved, which is preferred here; a chain- * rebuilt from the transcript only knows the model id, matched against what- * is configured in this session. `undefined` means the binding is gone.+ * rebuilt from the transcript only knows the model id. Both paths are limited+ * to this definition's pins, session inheritance, and current override grants.*/- private resumedChainProvider(+ private async resumedChainProvider(chain: DelegationChain,- ): RuntimeProviderConfig | undefined {+ definition: SubagentDefinition,+ ): Promise<RuntimeProviderConfig | undefined> {const modelId = chain.latestModelId?.trim().toLowerCase();if (!modelId) return undefined;- const candidates: RuntimeProviderConfig[] = [];+ const keys = new Set(this.availableSubagentModelKeys());+ if (definition.model) keys.add(subagentModelKey(definition.model));+ for (const pin of definition.fallbackModels ?? []) keys.add(subagentModelKey(pin));+ const binding = (key: string) => keys.has(key)+ ? this.subagentProviders[key] ?? this.subagentOverrideProviders[key]+ : undefined;+ const matches = (candidate: RuntimeProviderConfig | undefined) =>+ candidate?.modelId.trim().toLowerCase() === modelId;if (chain.latestModelKey) {- const keyed =- this.subagentProviders[chain.latestModelKey] ??- this.subagentOverrideProviders[chain.latestModelKey];- if (keyed) candidates.push(keyed);+ const keyed = binding(chain.latestModelKey) ??+ await this.resolveSubagentModel(chain.latestModelKey);+ // A known binding must not silently become a different account with the+ // same model id after its grant disappears.+ return matches(keyed) ? keyed : undefined;}- candidates.push(- ...Object.values(this.subagentProviders),- ...Object.values(this.subagentOverrideProviders),+ return [+ this.subagentProvider(definition),this.provider,- );- return candidates.find(- (candidate) => candidate.modelId.trim().toLowerCase() === modelId,- );+ ...[...keys].map(binding),+ ].find(matches);}/** The delegation-model key a resolved binding is registered under, if any. */@@ -4162,13 +4172,6 @@ Delegation rules:);}const startedAt = Date.now();- const running = this.runningDelegations().length;- if (running >= MAX_SUBAGENT_CONCURRENCY) {- return this.subagentToolError(- toolCallId,- `${MAX_SUBAGENT_CONCURRENCY} subagents are already running for this session. Wait for some with TaskWait or stop them with TaskStop before delegating more.`,- );- }// The delegate runs in the background (ADR 0089): `Task` returns// immediately with a delegation id, and TaskWait converges later.const resumeLookup = resume@@ -4183,9 +4186,24 @@ Delegation rules:// never swap models by accident. When the recorded binding is gone the// run continues on the definition's current one and says so in its// lifecycle details, because refusing would strand the chain forever.+ const resumeEpoch = this.turnEpoch;const resumedProvider = resumedChain- ? this.resumedChainProvider(resumedChain)+ ? await this.resumedChainProvider(resumedChain, definition): undefined;+ if (this.disposed || this.runCancelled || this.turnHadError || resumeEpoch !== this.turnEpoch) {+ return this.subagentToolError(toolCallId, "The parent turn ended before delegation could resume.");+ }+ // Authorization may yield while a parallel Task starts this chain.+ if (resume) {+ const current = this.resolveResumeChain(resume, definition.name);+ if (!current.ok) return this.subagentToolError(toolCallId, current.message);+ }+ if (this.runningDelegations().length >= MAX_SUBAGENT_CONCURRENCY) {+ return this.subagentToolError(+ toolCallId,+ `${MAX_SUBAGENT_CONCURRENCY} subagents are already running for this session. Wait for some with TaskWait or stop them with TaskStop before delegating more.`,+ );+ }if (resumedProvider) provider = resumedProvider;const modelChangedFrom =resumedChain?.latestModelId && !resumedProvider@@ -7476,7 +7494,9 @@ Delegation rules:// Keep every new user turn small. A capability loaded for the preceding// turn can be searched again when the new task actually needs it.+ this.subagentOverrideProviders = {};this.resetDeferredToolsForPrompt();+ this.refreshResumablePrompt();// Claims are message-scoped: a later prompt must observe edited or newly// created instruction files instead of reusing a previous chain.this.pathInstructionClaims.clear();@@ -7563,7 +7583,9 @@ Delegation rules:this.runCancelled = false;this.turnSubagentUsage = undefined;// Capabilities and path-scoped instruction claims belong to one prompt.+ this.subagentOverrideProviders = {};this.resetDeferredToolsForPrompt();+ this.refreshResumablePrompt();this.pathInstructionClaims.clear();this.pendingUserMessageId = userMessageId;this.resetRunRecoveryState();diff --git a/scripts/e2e-subagent-models.mjs b/scripts/e2e-subagent-models.mjsindex 339c392c8..6bb00954c 100644--- a/scripts/e2e-subagent-models.mjs+++ b/scripts/e2e-subagent-models.mjs@@ -11,6 +11,8 @@ const resolutions = [];const scenarios = new Map();const events = [];const pending = new Map();+const histories = new Map();+let dynamicEnabled = true;let sequence = 0;const server = createServer(async (req, res) => {try {@@ -18,6 +20,7 @@ const server = createServer(async (req, res) => {for await (const chunk of req) body += chunk;const payload = JSON.parse(body);requests.push(payload);+ payload.fixtureAccount = req.headers["x-fixture-account"];const user = payload.messages.findLast((m) => m.role === "user");const userText = typeof user?.content === "string" ? user.content : JSON.stringify(user?.content);const scenario = [...scenarios.values()].find((s) => userText.includes(s.marker));@@ -110,11 +113,11 @@ const lines = readNdjsonLines(child.stdout, (line) => {const { method, params } = message.params;if (method === "provider.resolveSubagentModel") {resolutions.push(params.key);- send(params.key === "fixture/dynamic"+ send(params.key === "fixture/dynamic" && dynamicEnabled? { id: message.id, result: model("dynamic") }: { id: message.id, error: { code: -32000, message: "model is not enabled for delegation" } });} else {- send({ id: message.id, result: method === "session.get" ? { session: { messages: [] } } : {} });+ send({ id: message.id, result: method === "session.get" ? { session: { messages: histories.get(params.id) ?? [] } } : {} });}} else if (message.id != null) {const entry = pending.get(message.id);@@ -152,6 +155,7 @@ async function run(id, args, expectedModel, keys = ["fixture/allowed"], sessionI...(inheritCatalog ? [definition("worker", undefined, { inheritTools: true, tools: [] })] : []),];const marker = `scenario-${id}`;+ if (options.history) histories.set(sessionId, options.history);const before = requests.length;scenarios.set(id, { marker, args: { ...args, task: `Complete fixture ${id}.` } });await rpc("agent.prompt", {@@ -170,6 +174,7 @@ async function run(id, args, expectedModel, keys = ["fixture/allowed"], sessionIassert.ok(!system.includes("`fixture/private`"), "private pin must not enter override catalog");assert.ok(parent.tools.find((t) => t.function?.name === "Task").function.description.includes(`Default model: fixture/${primaryModel}`));const delegates = captured.filter((p) => !p.tools?.some((t) => t.function?.name === "Task"));+ assert.ok(delegates.every((p) => p.fixtureAccount !== "private-account"), "resume must not send a request using another definition's private binding");if (expectedModel) assert.deepEqual(delegates.map((p) => p.model), options.expectedAttempts ?? [expectedModel]);else {assert.equal(delegates.length, 0, "forbidden override must not issue a provider request");@@ -262,6 +267,22 @@ try {const demand = await run("on-demand-opt-in", { agent: "explorer", model: "fixture/dynamic" }, "dynamic", ["fixture/allowed"], "demand");const demandAgain = await run("on-demand-reuse", { agent: "explorer", model: "fixture/dynamic" }, "dynamic", ["fixture/allowed"], "demand");assert.equal(demand.runtimeId, demandAgain.runtimeId, "on-demand grants must not retire an idle runtime");+ assert.equal(resolutions.filter((key) => key === "fixture/dynamic").length, 2, "each new prompt reauthorizes an on-demand grant");+ dynamicEnabled = false;+ const revoked = await run("on-demand-revoked", { agent: "explorer", model: "fixture/dynamic" }, undefined, ["fixture/allowed"], "demand");+ assert.equal(revoked.runtimeId, demand.runtimeId, "revocation must work even when the launch catalog is unchanged");+ dynamicEnabled = true;+ const restartedHistory = [+ { id: "old-task", role: "tool", content: "", createdAt: "2026-09-21T00:00:00.000Z", toolName: "Task", toolCallId: "old-task",+ toolArgs: { agent: "explorer", task: "Inspect the fixture." }, toolStatus: "success",+ toolResult: { details: { delegationId: "old-delegation", status: "completed", modelId: "parent" } } },+ { id: "old-child", role: "assistant", content: "Fixture inspected.", status: "complete", createdAt: "2026-09-21T00:00:01.000Z",+ parentToolCallId: "old-task", agentName: "explorer", providerId: "fixture", modelId: "parent" },+ ];+ await run("resume-private-collision", { agent: "explorer", resume: "old-delegation" }, "parent", [], "resume-restarted", {+ history: restartedHistory,+ bindings: { "fixture/private": { ...model("parent"), id: "private-account", headers: { "x-fixture-account": "private-account" } } },+ });await run("session-inheritance", { agent: "explorer", model: "fixture/parent" }, "parent", []);const first = await run("before-revocation", { agent: "explorer", model: "fixture/allowed" }, "allowed", ["fixture/allowed"], "reload");const second = await run("after-revocation", { agent: "explorer", model: "fixture/allowed" }, undefined, [], "reload");