@qlairoslabs/acp-client 0.13.11-e-alpha.1 → 0.13.12-e-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONSUMER_GUIDE.md CHANGED
@@ -2087,6 +2087,21 @@ results may be absent until the harness opens. Delivery states are `pending`
2087
2087
  retries only the newest policy-blocked delivery. A retired or missing
2088
2088
  destination remains a failed delivery.
2089
2089
 
2090
+ For native giving conversations, `orchestrator.workerApprovals` defaults
2091
+ to `"consumer"`. Set it to `"model"` to let the native model answer eligible
2092
+ asks, or `"both"` to keep the host responder available as well. Grant
2093
+ `worker_answer` in the applicable harness policy and use
2094
+ `orchestrator.toolNames.answer` to rename it.
2095
+
2096
+ Each contributing orchestrator policy must explicitly grant the action
2097
+ in `modelApproval.rules`. The initial model path supports structured
2098
+ workspace-relative read requests. List the paths safe to include in
2099
+ shared history in each contributing policy's `modelApproval.shareReadPaths`.
2100
+ For example, use
2101
+ `modelApproval: { rules: { "kind:read": "allow" }, shareReadPaths: ["README.md"] }`.
2102
+ The model can select a one-time answer. An ask stays with the conversation
2103
+ that received it. After redirect, new asks follow the new giving conversation.
2104
+
2090
2105
  From the source checkout, run the offline smoke test with
2091
2106
  `bun smoke-tests/orchestrator/run.ts`. Live mode requires explicit approval
2092
2107
  for spend, `ACP_ORCH_LIVE=1`, `OPENROUTER_API_KEY`, local Codex binaries
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.11e-alpha.1",
3
+ "version": "0.13.12e-alpha.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
package/src/agent.ts CHANGED
@@ -163,9 +163,9 @@ export class Agent {
163
163
  this.adapters = adapters;
164
164
  const orchestration = config.orchestrator;
165
165
  if (orchestration) {
166
- const toolNames = resolveDelegationToolNames(orchestration.toolNames);
166
+ const toolNames = resolveDelegationToolNames(orchestration.toolNames, orchestration.workerApprovals);
167
167
  this.wrapNativeFunctions = functions => withDelegationTools(functions, orchestration,
168
- () => this.orchestrator!, () => this.conversations, toolNames);
168
+ () => this.orchestrator!, () => this.conversations, toolNames, id => this.manager.liveConversation(id));
169
169
  }
170
170
  const channels = config.harness ? protectedChannels(persistence) : undefined;
171
171
  this.nativeHarness = config.harness
@@ -259,7 +259,10 @@ export class Agent {
259
259
  () => this.nativeHarness?.flushWorkerDelivery());
260
260
  this.orchestrator = new Orchestrator(persistence.workers!, this.conversations, { ...workerOptions, adapterId,
261
261
  defaultPermissions: config.orchestrator.defaults?.workerPermissions }, logger,
262
- event => this.eventBus.publishWorker(event), assignments, id => this.manager.liveConversation(id));
262
+ event => this.eventBus.publishWorker(event), assignments, id => this.manager.liveConversation(id),
263
+ this.nativeHarness && config.orchestrator.workerApprovals && config.orchestrator.workerApprovals !== "consumer" ? {
264
+ config: config.orchestrator, send: this.nativeHarness.sendWorkerApprovalNotice.bind(this.nativeHarness),
265
+ } : undefined);
263
266
  this.workers = workerConsumerApi(this.orchestrator);
264
267
  }
265
268
  if (checkpointing?.enabled) {
@@ -204,24 +204,56 @@ export class NativeHarnessHost {
204
204
  this.#log, config.onChannelChangeBlocked);
205
205
  if (workerDelivery) this.#workerDelivery = new NativeWorkerDelivery(
206
206
  workerDelivery, () => this.#state === "running",
207
- ({ id, destination, source, text, policyNames }) => this.#changes.enqueue(destination.id, async () => {
208
- if (this.#state !== "running" || await this.#changes.pendingChange(destination.id)) return false;
209
- const client = this.#client();
210
- const params = { channel: destination.id, notice: { id, source, text, policyNames: [...policyNames] } };
211
- try {
212
- await client.notify(params);
213
- } catch (error) {
214
- if (codeOf(error) !== "timeout" || client !== this.#connection?.client) throw error;
215
- await client.notify(params);
216
- }
217
- return true;
218
- }),
207
+ ({ id, destination, source, text, policyNames }) =>
208
+ this.#sendWorkerNotice(destination.id, { id, source, text, policyNames: [...policyNames] }),
219
209
  );
220
210
  if (channels && fileHasPendingChannelChanges(records)) {
221
211
  this.#log.warn("native_file_channel_changes_ignored", { sessionId: this.sessionId });
222
212
  }
223
213
  }
224
214
 
215
+ #sendWorkerNotice(channel: string, notice: Parameters<HarnessClient["notify"]>[0]["notice"], signal?: AbortSignal) {
216
+ return this.#changes.enqueue(channel, async () => {
217
+ if (this.#state !== "running" || await this.#changes.pendingChange(channel) || signal?.aborted) return false;
218
+ const client = this.#client();
219
+ try {
220
+ await client.notify({ channel, notice });
221
+ } catch (error) {
222
+ if (codeOf(error) !== "timeout" || client !== this.#connection?.client || signal?.aborted) throw error;
223
+ await client.notify({ channel, notice });
224
+ }
225
+ return true;
226
+ });
227
+ }
228
+
229
+ /** Approval delivery may wait for an existing reconnect, without starting a process. */
230
+ async sendWorkerApprovalNotice(channel: string, notice: Parameters<HarnessClient["notify"]>[0]["notice"],
231
+ signal: AbortSignal): Promise<boolean> {
232
+ const original = this.#connection;
233
+ if (this.#state !== "running" || !original || signal.aborted) return false;
234
+ try {
235
+ return await this.#sendWorkerNotice(channel, notice, signal);
236
+ } catch (error) {
237
+ if (!ambiguous(error) || signal.aborted) return false;
238
+ const ready = await new Promise<boolean>(resolve => {
239
+ const finish = (available: boolean) => {
240
+ unsubscribe();
241
+ signal.removeEventListener("abort", check);
242
+ resolve(available);
243
+ };
244
+ const check = () => {
245
+ if (signal.aborted || this.#stopped || this.#state === "failed") finish(false);
246
+ else if (this.#state === "running" && this.#connection !== original) finish(true);
247
+ };
248
+ const unsubscribe = this.subscribeState(check);
249
+ signal.addEventListener("abort", check, { once: true });
250
+ check();
251
+ });
252
+ if (!ready) return false;
253
+ return this.#sendWorkerNotice(channel, notice, signal).catch(() => false);
254
+ }
255
+ }
256
+
225
257
  get state(): NativeHostState { return this.#state; }
226
258
  /** Why the host is `failed`. */
227
259
  get failure(): Error | null { return this.#failure ?? this.#wakeFailure; }
@@ -5,14 +5,21 @@ import type { PersistenceBackend, RecordCaptureLevel } from "../persistence/back
5
5
 
6
6
  const defaultDelegationToolNames = { delegate: "delegate", check: "check", list: "list", stop: "stop" } as const;
7
7
  type DelegationToolNames = Readonly<Record<keyof typeof defaultDelegationToolNames, string>>;
8
+ export type WorkerApprovalMode = "consumer" | "model" | "both";
8
9
 
9
10
  export interface OrchestratorConfig {
10
11
  /** Model-facing names for ACP-client's native worker tools. Unspecified names keep their defaults. */
11
- readonly toolNames?: Partial<DelegationToolNames>;
12
+ readonly toolNames?: Partial<DelegationToolNames & { answer: string }>;
13
+ readonly workerApprovals?: WorkerApprovalMode;
12
14
  /** Each entry corresponds to a configured native harness policy name. */
13
15
  readonly policies?: Readonly<Record<string, {
14
16
  readonly delegation: DelegationPolicy;
15
17
  readonly workerPermissions?: PermissionSettings;
18
+ /** Scope of model answers and the read paths safe to include in shared notices. */
19
+ readonly modelApproval?: {
20
+ readonly rules: NonNullable<PermissionSettings["rules"]>;
21
+ readonly shareReadPaths?: readonly string[];
22
+ };
16
23
  }>>;
17
24
  /** Forwarded requests retain owner options only when every contributing name is listed here. */
18
25
  readonly ownerPolicies?: readonly string[];
@@ -30,20 +37,21 @@ export interface OrchestratorConfig {
30
37
  };
31
38
  }
32
39
 
33
- export function resolveDelegationToolNames(input: OrchestratorConfig["toolNames"]): DelegationToolNames {
34
- if (input === undefined) return defaultDelegationToolNames;
40
+ export function resolveDelegationToolNames(input: OrchestratorConfig["toolNames"], mode: WorkerApprovalMode = "consumer"): DelegationToolNames & { answer?: string } {
41
+ if (input === undefined) return mode === "consumer" ? defaultDelegationToolNames : { ...defaultDelegationToolNames, answer: "worker_answer" };
35
42
  if (input === null || typeof input !== "object" || Array.isArray(input)) {
36
43
  throw new TypeError("orchestrator.toolNames must be a map of worker operations to tool names");
37
44
  }
38
- const names: Record<keyof DelegationToolNames, string> = { ...defaultDelegationToolNames };
45
+ const names: Record<keyof DelegationToolNames, string> & { answer?: string } = { ...defaultDelegationToolNames };
46
+ if (mode !== "consumer") names.answer = "worker_answer";
39
47
  for (const [operation, name] of Object.entries(input)) {
40
- if (!Object.hasOwn(defaultDelegationToolNames, operation)) {
48
+ if (operation !== "answer" && !Object.hasOwn(defaultDelegationToolNames, operation)) {
41
49
  throw new Error(`unknown orchestrator tool operation: ${operation}`);
42
50
  }
43
51
  if (typeof name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(name)) {
44
52
  throw new Error(`invalid orchestrator tool name for ${operation}`);
45
53
  }
46
- names[operation as keyof DelegationToolNames] = name;
54
+ if (operation !== "answer" || mode !== "consumer") names[operation as keyof DelegationToolNames | "answer"] = name;
47
55
  }
48
56
  const resolved = Object.values(names);
49
57
  if (new Set(resolved).size !== resolved.length) throw new Error("orchestrator tool names must be distinct");
@@ -53,6 +61,9 @@ export function resolveDelegationToolNames(input: OrchestratorConfig["toolNames"
53
61
  export function validateOrchestrator(
54
62
  config: OrchestratorConfig, persistence: PersistenceBackend, messageCapture: RecordCaptureLevel,
55
63
  ): void {
64
+ if (config.workerApprovals !== undefined && !["consumer", "model", "both"].includes(config.workerApprovals)) {
65
+ throw new Error("invalid orchestrator.workerApprovals mode");
66
+ }
56
67
  if (!persistence.capabilities.workers || !persistence.workers) throw new PersistenceCapabilityError("workers");
57
68
  if (!persistence.capabilities.workerDelivery || !persistence.workerDelivery) throw new PersistenceCapabilityError("workerDelivery");
58
69
  if (messageCapture !== "content") throw new Error('orchestrator requires message capture "content"');
@@ -0,0 +1,17 @@
1
+ import { matchPermissionLevel } from "../permissions/matcher.ts";
2
+ import type { PermissionRequest } from "../types.ts";
3
+ import type { OrchestratorConfig } from "./config.ts";
4
+
5
+ /** Paths included in a notice are explicitly designated shareable by the host. */
6
+ export function describeModelApproval(config: OrchestratorConfig, policies: readonly string[], request: PermissionRequest): string | undefined {
7
+ if (!policies.length || request.tool?.kind !== "read") return;
8
+ const input = request.tool.rawInput;
9
+ if (!input || typeof input !== "object" || Array.isArray(input) || !("path" in input)) return;
10
+ const { path } = input;
11
+ if (Object.keys(input).length !== 1 || typeof path !== "string" || path.length > 200 ||
12
+ !/^[a-zA-Z0-9_.\/-]+$/.test(path) || path.split("/").some(part => !part || part === "." || part === "..")) return;
13
+ if (policies.every(name => {
14
+ const grant = Object.hasOwn(config.policies ?? {}, name) ? config.policies?.[name]?.modelApproval : undefined;
15
+ return Array.isArray(grant?.shareReadPaths) && grant.shareReadPaths.includes(path) && matchPermissionLevel(request, { default: "deny", rules: grant.rules }) === "allow";
16
+ })) return `Read workspace file ${path}`;
17
+ }
@@ -1,3 +1,5 @@
1
+ import { answerForwardedWorkerPermission } from "../permissions/conversation.ts";
2
+ import type { FindGivingConversation } from "./permissions.ts";
1
3
  import { isAgentConversationId } from "../agent-ids.ts";
2
4
  import type { AgentConversationManager } from "../agent/config.ts";
3
5
  import { WorkerPolicyError } from "../errors.ts";
@@ -19,7 +21,8 @@ export function withDelegationTools(
19
21
  config: OrchestratorConfig,
20
22
  orchestrator: () => Orchestrator,
21
23
  conversations: () => Pick<AgentConversationManager, "get">,
22
- names = resolveDelegationToolNames(config.toolNames),
24
+ names = resolveDelegationToolNames(config.toolNames, config.workerApprovals),
25
+ findGivingConversation?: FindGivingConversation,
23
26
  ): NativeFunctionsConfig {
24
27
  for (const name of Object.values(names)) {
25
28
  if (functions && Object.hasOwn(functions.tools, name)) throw new Error(`native delegation tool name is already registered: ${name}`);
@@ -79,6 +82,16 @@ export function withDelegationTools(
79
82
  ...functions,
80
83
  tools: {
81
84
  ...functions?.tools,
85
+ ...(names.answer ? { [names.answer]: tool(
86
+ "Answer a pending worker approval for this conversation. Use the request and one-time choice from its notice.",
87
+ { type: "object", properties: { request: string, option: { type: "string", enum: ["allow_once", "reject_once"] } },
88
+ required: ["request", "option"], additionalProperties: false },
89
+ async (args, caller) => ({
90
+ status: caller.kind === "conversation" && await answerForwardedWorkerPermission(
91
+ findGivingConversation?.(caller.conversationId), args.request as string, args.option as string, caller.policyNames,
92
+ ) ? "answered" : "request_unavailable",
93
+ }),
94
+ ) } : {}),
82
95
  [names.delegate]: tool(`Omit worker to open a worker. ${WORKER_SEND_DESCRIPTION}`, {
83
96
  type: "object",
84
97
  properties: { worker: string, text: string, about: string, redirect: { type: "boolean" },
@@ -1,6 +1,6 @@
1
1
  import { ownPermissions } from "../permissions/policy.ts";
2
2
  import type { PermissionSettings } from "../permissions/matcher.ts";
3
- import { workerPermissionHandler, type FindGivingConversation } from "./permissions.ts";
3
+ import { workerPermissionHandler, type FindGivingConversation, type WorkerApprovalRouting } from "./permissions.ts";
4
4
  import { WorkerPolicyError } from "../errors.ts";
5
5
  import { canSeeWorker, checkWorkerOpenLimit, requireWorkerRedirect, requireWorkerUse } from "./policy.ts";
6
6
  import type { AssignmentPlan, WorkerAssignmentPort } from "./assignments.ts";
@@ -29,6 +29,7 @@ export class Orchestrator {
29
29
  private readonly emit: (event: WorkerEvent) => void,
30
30
  private readonly assignments?: WorkerAssignmentPort,
31
31
  private readonly findGivingConversation?: FindGivingConversation,
32
+ private readonly approvals?: WorkerApprovalRouting,
32
33
  ) {
33
34
  this.pool = new WorkerPool(options.limit, options.idleStopMs ?? 600_000);
34
35
  const defaults = ownPermissions(options.defaultPermissions);
@@ -267,7 +268,7 @@ export class Orchestrator {
267
268
  const input = {
268
269
  text,
269
270
  handlers: {
270
- onPermissionRequest: workerPermissionHandler(actor, row, this.findGivingConversation, this.defaultWorkerPermissions),
271
+ onPermissionRequest: workerPermissionHandler(actor, row, this.findGivingConversation, this.defaultWorkerPermissions, this.approvals),
271
272
  ...(accepted ? { onUpdate: confirmDispatch } : {}),
272
273
  },
273
274
  delivery: plan.kind === "start" ? "queue" as const : "steer" as const,
@@ -1,3 +1,6 @@
1
+ import type { OrchestratorConfig } from "./config.ts";
2
+ import type { NativeHarnessHost } from "../native/host.ts";
3
+ import { describeModelApproval } from "./model-approval.ts";
1
4
  import type { PermissionSettings } from "../permissions/matcher.ts";
2
5
  import type { AgentConversationId } from "../agent-ids.ts";
3
6
  import { forwardPermission } from "../permissions/conversation.ts";
@@ -7,10 +10,15 @@ import type { PromptHandlers } from "../types.ts";
7
10
  import type { WorkerActor } from "./contracts.ts";
8
11
  import { matchWorkerPermissionLevel } from "./policy.ts";
9
12
 
13
+ export interface WorkerApprovalRouting {
14
+ readonly config: OrchestratorConfig;
15
+ readonly send: NativeHarnessHost["sendWorkerApprovalNotice"];
16
+ }
17
+
10
18
  export type FindGivingConversation = (id: AgentConversationId) => object | undefined;
11
19
 
12
20
  export function workerPermissionHandler(
13
- actor: WorkerActor, worker: WorkerRow, findGivingConversation?: FindGivingConversation, defaults: readonly PermissionSettings[] = [],
21
+ actor: WorkerActor, worker: WorkerRow, findGivingConversation?: FindGivingConversation, defaults: readonly PermissionSettings[] = [], approvals?: WorkerApprovalRouting,
14
22
  ): NonNullable<PromptHandlers["onPermissionRequest"]> {
15
23
  return (request, signal) => {
16
24
  const policies = actor.kind === "consumer" ? defaults : actor.workerPermissions;
@@ -18,8 +26,21 @@ export function workerPermissionHandler(
18
26
  if (level !== "ask") return selectPermissionOutcome(level, request.options)!;
19
27
  const unanswered = policies.some(policy => policy.unanswered === "cancel") ? "cancel" : "reject";
20
28
  if (actor.kind === "consumer") return unansweredPermissionOutcome(request.options, unanswered);
29
+ const mode = approvals?.config.workerApprovals;
30
+ const description = approvals && (mode === "model" || mode === "both") && actor.destinationKind === "native" &&
31
+ request.options.some(option => option.kind === "allow_once" || option.kind === "reject_once")
32
+ ? describeModelApproval(approvals.config, actor.policyNames, request) : undefined;
21
33
  return forwardPermission(findGivingConversation?.(actor.conversationId), request, {
22
34
  source: { kind: "worker", handle: worker.handle, conversationId: worker.conversationId },
35
+ ...(approvals && description && (mode === "model" || mode === "both") ? { model: {
36
+ mode,
37
+ authorize: policies => describeModelApproval(approvals.config, policies, request) === description,
38
+ deliver: (id, choices, expiresAt, liveSignal) => approvals.send(actor.conversationId, {
39
+ id: `worker-approval:${id}`, source: worker.handle, policyNames: [...actor.policyNames],
40
+ text: JSON.stringify({ kind: "worker_approval", worker: worker.handle, action: description,
41
+ request: id, choices, expiresAt }),
42
+ }, liveSignal),
43
+ } } : {}),
23
44
  includeAllowAlways: actor.isOwner === true,
24
45
  unanswered,
25
46
  signal,
@@ -8,7 +8,7 @@ import type { PermissionSettings } from "./matcher.ts";
8
8
  import { selectPermissionOutcome, unansweredPermissionOutcome } from "./outcome.ts";
9
9
  import { permissionLevel, recordingPermissionHandlers, type ConversationPermissionConfig } from "./policy.ts";
10
10
 
11
- export type PermissionResolutionSource = "handler" | "consumer" | "default" | "timeout" | "turn_ended";
11
+ export type PermissionResolutionSource = "handler" | "consumer" | "delegator" | "default" | "timeout" | "turn_ended";
12
12
  export type PermissionResolution = {
13
13
  readonly outcome: PermissionOutcome;
14
14
  readonly by: PermissionResolutionSource;
@@ -73,6 +73,7 @@ interface PermissionEntry {
73
73
  close(resolution: PermissionResolution): void;
74
74
  closeLocally(stopping?: boolean): void;
75
75
  answer?(optionId: string): Promise<boolean>;
76
+ answerAsModel?(option: string, policyNames: readonly string[]): Promise<boolean>;
76
77
  }
77
78
 
78
79
  const forwarding = new WeakMap<object, {
@@ -80,9 +81,22 @@ const forwarding = new WeakMap<object, {
80
81
  readonly policy: () => ConversationPermissionConfig;
81
82
  }>();
82
83
 
84
+ export interface ModelWorkerApproval {
85
+ readonly mode: "model" | "both";
86
+ readonly authorize: (policies: readonly string[]) => boolean;
87
+ deliver(id: string, choices: readonly string[], expiresAt: number, signal: AbortSignal): Promise<boolean>;
88
+ }
89
+
90
+ export async function answerForwardedWorkerPermission(conversation: object | undefined, id: string, option: string,
91
+ policies: readonly string[]): Promise<boolean> {
92
+ const destination = conversation && forwarding.get(conversation);
93
+ return destination ? destination.coordinator.answerAsModel(id, option, policies) : false;
94
+ }
95
+
83
96
  export interface ForwardPermissionOptions {
84
97
  readonly source: WorkerPermissionSource;
85
98
  readonly includeAllowAlways: boolean;
99
+ readonly model?: ModelWorkerApproval;
86
100
  readonly unanswered?: PermissionSettings["unanswered"];
87
101
  readonly signal?: AbortSignal;
88
102
  }
@@ -99,7 +113,7 @@ export async function forwardPermission(
99
113
  };
100
114
  const time = acpPermissionArrivals.get(request);
101
115
  if (time && offered !== request) acpPermissionArrivals.set(offered, time);
102
- return (await destination.coordinator.request(undefined, offered, destination.policy(), undefined, signal, undefined, source)).outcome;
116
+ return (await destination.coordinator.request(undefined, offered, destination.policy(), undefined, signal, undefined, source, options.model)).outcome;
103
117
  }
104
118
 
105
119
  export class ConversationPermissions {
@@ -128,6 +142,10 @@ export class ConversationPermissions {
128
142
  return { accepted: await this.pending.get(id)?.answer?.(optionId) ?? false };
129
143
  }
130
144
 
145
+ async answerAsModel(id: string, option: string, policies: readonly string[]): Promise<boolean> {
146
+ return await this.pending.get(id)?.answerAsModel?.(option, policies) ?? false;
147
+ }
148
+
131
149
  internalHandler(turnId: string, policy: ConversationPermissionConfig): PromptHandlers {
132
150
  const onPermissionRequest: NonNullable<PromptHandlers["onPermissionRequest"]> = async (request, signal) =>
133
151
  (await this.request(turnId, request, policy, undefined, signal)).outcome;
@@ -143,6 +161,7 @@ export class ConversationPermissions {
143
161
  signal?: AbortSignal,
144
162
  recordRequested?: () => Promise<void>,
145
163
  source?: WorkerPermissionSource,
164
+ model?: ModelWorkerApproval,
146
165
  ): Promise<PermissionResolution> {
147
166
  const native = nativePermissionRequests.get(request);
148
167
  if (this.stopped || signal?.aborted) {
@@ -168,7 +187,7 @@ export class ConversationPermissions {
168
187
  }
169
188
  }
170
189
 
171
- const waitForConsumer = level === "ask" && !handler && policy.answersPermissions === true;
190
+ const waitForConsumer = level === "ask" && !handler && model?.mode !== "model" && policy.answersPermissions === true;
172
191
  const offered = Object.freeze(request.options.map(option => Object.freeze({ ...option })));
173
192
  const arrival = native?.arrival ?? acpPermissionArrivals.get(request) ?? permissionArrival();
174
193
  const budget = policy.permissionTimeoutMs ?? DEFAULT_PERMISSION_TIMEOUT_MS;
@@ -223,34 +242,60 @@ export class ConversationPermissions {
223
242
  return send(decision);
224
243
  };
225
244
 
226
- if (waitForConsumer) {
245
+ if (waitForConsumer || model) {
227
246
  const claim = () => {
228
- if (!entry.answer) return false;
247
+ if (!entry.answer && !entry.answerAsModel) return false;
229
248
  entry.answer = undefined;
249
+ entry.answerAsModel = undefined;
230
250
  clearTimeout(timer);
231
251
  return true;
232
252
  };
233
253
  const expire = () => {
234
254
  if (claim()) void send(refuse("timeout")).catch(failed);
235
255
  };
236
- entry.answer = async optionId => {
256
+ const answer = async (optionId: string, by: "consumer" | "delegator") => {
237
257
  if (remaining() <= 0) expire();
238
258
  if (!offered.some(option => option.optionId === optionId) || !claim()) return false;
239
- const accepted = await sendAfterRecord({ outcome: { outcome: "selected", optionId }, by: "consumer" }).catch(failed);
240
- return accepted && (await result).by === "consumer";
259
+ const accepted = await sendAfterRecord({ outcome: { outcome: "selected", optionId }, by }).catch(failed);
260
+ return accepted && (await result).by === by;
241
261
  };
262
+ if (waitForConsumer) entry.answer = optionId => answer(optionId, "consumer");
263
+ if (model) {
264
+ const choices = new Map<string, string>();
265
+ for (const option of offered) {
266
+ if ((option.kind === "allow_once" || option.kind === "reject_once") && !choices.has(option.kind))
267
+ choices.set(option.kind, option.optionId);
268
+ }
269
+ entry.answerAsModel = async (option, policies) => {
270
+ const optionId = choices.get(option);
271
+ return optionId !== undefined && model.authorize(policies) && answer(optionId, "delegator");
272
+ };
273
+ const unavailable = () => {
274
+ if (!entry.answerAsModel || !this.pending.has(id)) return;
275
+ if (!entry.answer && claim()) {
276
+ void sendAfterRecord({
277
+ outcome: unansweredPermissionOutcome(request.options, policy.permissions?.unanswered),
278
+ by: "default", refused: true,
279
+ }).catch(failed);
280
+ } else entry.answerAsModel = undefined;
281
+ };
282
+ void Promise.resolve().then(async () => {
283
+ if (!entry.answerAsModel || handlerAbort.signal.aborted) return;
284
+ if (!await model.deliver(id, [...choices.keys()], arrival.wallTime + budget, handlerAbort.signal)) unavailable();
285
+ }).catch(unavailable);
286
+ }
242
287
  timer = setTimeout(expire, Math.max(0, Math.ceil(remaining())));
243
288
  // A failed requested record cannot leave an otherwise unclaimed request open.
244
289
  void record.catch(() => { if (claim()) void sendAfterRecord(refuse("default")).catch(failed); });
245
290
  }
246
291
 
247
- this.emit({
292
+ if (!model || waitForConsumer) this.emit({
248
293
  kind: "permission_requested", id, ...(source ? { source: Object.freeze({ ...source }) } : { turnId: turnId! }),
249
294
  tool: request.tool && Object.freeze(structuredClone(request.tool)),
250
- title: request.title, options: offered, ...(waitForConsumer ? { expiresAt: arrival.wallTime + budget } : {}),
295
+ title: request.title, options: offered, ...(waitForConsumer || model ? { expiresAt: arrival.wallTime + budget } : {}),
251
296
  });
252
297
 
253
- if (native?.hostHandled || native?.settled || waitForConsumer) return result;
298
+ if (native?.hostHandled || native?.settled || waitForConsumer || model) return result;
254
299
  if (level !== "ask" || !handler) {
255
300
  const unanswered = level === "ask" && !handler;
256
301
  const cancelTurn = unanswered && policy.permissions?.unanswered === "cancel";