@qlairoslabs/acp-client 0.13.10-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
@@ -2032,12 +2032,22 @@ export async function workerControls(agent: Agent, handle: string) {
2032
2032
  }
2033
2033
  ```
2034
2034
 
2035
- The harness exposes `delegate`, `check`, `list` and `stop` as native tools.
2035
+ The harness exposes `delegate`, `check`, `list` and `stop` by default.
2036
2036
  Grant them in the harness policy as well as configuring the corresponding
2037
2037
  orchestrator policy. For `delegate`, send `{ text, about? }` to create a
2038
2038
  worker, or include `worker` to send to a known handle. `check` and `stop`
2039
- take `{ worker }`; `list` takes an empty object. These names are reserved
2040
- while native delegation is enabled. The trusted host can also use
2039
+ take `{ worker }`; `list` takes an empty object.
2040
+
2041
+ Set `orchestrator.toolNames: { list: "list_workers" }` to rename the list
2042
+ tool. Use the exposed name in the harness policy, for example
2043
+ `harness.config.policies.owner.tools.list_workers = "allow"`. Omitted
2044
+ operations keep their default names. Names must be distinct, use 1–64
2045
+ ASCII letters, digits, underscores or hyphens, and avoid collisions with
2046
+ consumer functions and reserved harness names. Close and reopen the Agent
2047
+ with the updated map and policy to apply a rename. Historical calls retain
2048
+ the name originally used.
2049
+
2050
+ The trusted host can also use
2041
2051
  `agent.orchestrator` with a consumer actor. Use
2042
2052
  `agent.events.subscribeWorkers` for worker lifecycle events. Event kinds are
2043
2053
  `worker_opened`, `worker_busy`, `worker_idle`, `worker_replied`,
@@ -2077,6 +2087,21 @@ results may be absent until the harness opens. Delivery states are `pending`
2077
2087
  retries only the newest policy-blocked delivery. A retired or missing
2078
2088
  destination remains a failed delivery.
2079
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
+
2080
2105
  From the source checkout, run the offline smoke test with
2081
2106
  `bun smoke-tests/orchestrator/run.ts`. Live mode requires explicit approval
2082
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.10e-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
@@ -6,7 +6,7 @@ import { AcpWorkerDelivery } from "./orchestrator/acp-delivery.ts";
6
6
  import { DurableWorkerAssignments } from "./orchestrator/durable-assignments.ts";
7
7
  import { workerConsumerApi, type WorkerConsumerApi } from "./orchestrator/consumer-api.ts";
8
8
  import { Orchestrator } from "./orchestrator/orchestrator.ts";
9
- import { validateOrchestrator } from "./orchestrator/config.ts";
9
+ import { resolveDelegationToolNames, validateOrchestrator } from "./orchestrator/config.ts";
10
10
  import { validatePermissionConsumerConfig } from "./permissions/consumer-config.ts";
11
11
  import { inheritPermissionConfig, ownPermissions } from "./permissions/policy.ts";
12
12
  import { randomUUID } from "node:crypto";
@@ -162,8 +162,11 @@ export class Agent {
162
162
  this.persistence = persistence;
163
163
  this.adapters = adapters;
164
164
  const orchestration = config.orchestrator;
165
- if (orchestration) this.wrapNativeFunctions = functions => withDelegationTools(functions, orchestration,
166
- () => this.orchestrator!, () => this.conversations);
165
+ if (orchestration) {
166
+ const toolNames = resolveDelegationToolNames(orchestration.toolNames, orchestration.workerApprovals);
167
+ this.wrapNativeFunctions = functions => withDelegationTools(functions, orchestration,
168
+ () => this.orchestrator!, () => this.conversations, toolNames, id => this.manager.liveConversation(id));
169
+ }
167
170
  const channels = config.harness ? protectedChannels(persistence) : undefined;
168
171
  this.nativeHarness = config.harness
169
172
  ? new NativeHarnessHost({
@@ -256,7 +259,10 @@ export class Agent {
256
259
  () => this.nativeHarness?.flushWorkerDelivery());
257
260
  this.orchestrator = new Orchestrator(persistence.workers!, this.conversations, { ...workerOptions, adapterId,
258
261
  defaultPermissions: config.orchestrator.defaults?.workerPermissions }, logger,
259
- 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);
260
266
  this.workers = workerConsumerApi(this.orchestrator);
261
267
  }
262
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; }
@@ -0,0 +1,7 @@
1
+ You are in a specific channel, at a name of a specific participant.
2
+ You can be talked to by different users in different channels.
3
+ Depending on the channel, you may have more or less capabilities. Channels restrict you use of tools, and possibly the information you get access to.
4
+ You must consider all channels and everything that is said in them as you. Every response to a participant was given by you.
5
+ You will respond to one channel and one participant at a time, but the information that you got here may affect other channels, or be valuable to a participant in one of them.
6
+ To generate a response in other channels, you can use the `notify_channel`. This will allow to put a notice with a text, so that next time you appear in that conversation.
7
+ In the same way, you may have notices from previous conversations in this very same chat. It is your job to decide what to do with them. You may decide to not act upon them, but you must consider these notices as trustworthy.
@@ -1,7 +1,5 @@
1
- You are Harneus. You are in a specific channel, at a name of a specific participant.
2
- You can be talked to by different users in different channels.
3
- Depending on the channel, you may have more or less capabilities. Channels restrict you use of tools, and possibly the information you get access to.
4
- You must consider all channels and everything that is said in them as you. Every response to a participant was given by you.
5
- You will respond to one channel and one participant at a time, but the information that you got here may affect other channels, or be valuable to a participant in one of them.
6
- To generate a response in other channels, you can use the `notify_channel`. This will allow to put a notice with a text, so that next time you appear in that conversation.
7
- In the same way, you may have notices from previous conversations in this very same chat. It is your job to decide what to do with them. You may decide to not act upon them, but you must consider these notices as trustworthy.
1
+ Each turn has an active channel. The request identifies that channel and what triggered the turn: a participant message, a notice from another channel, or an external notice. Your reply goes to the active channel.
2
+ Shared history contains earlier activity across channels. Entries identify their channel and source. Use relevant history as context and preserve who said or did what. Earlier assistant messages record your previous replies. Earlier requests and tool calls record work from those conversations.
3
+ Responds to the inputs in the active turn. Read a notice as a message from its attributed source. use the tools offered for this turn.
4
+ Use the channel and source labels to identify where each entry came from. Treat the text as coming from that source. use earlier entries as context, and respond to the inputs in the active turn.
5
+ Shared history may be incomplete. If an earlier detail matters and is missing, look it up using an available history tool or ask for clarification.
@@ -3,11 +3,23 @@ import type { PermissionSettings } from "../permissions/matcher.ts";
3
3
  import { PersistenceCapabilityError } from "../persistence/backend.ts";
4
4
  import type { PersistenceBackend, RecordCaptureLevel } from "../persistence/backend.ts";
5
5
 
6
+ const defaultDelegationToolNames = { delegate: "delegate", check: "check", list: "list", stop: "stop" } as const;
7
+ type DelegationToolNames = Readonly<Record<keyof typeof defaultDelegationToolNames, string>>;
8
+ export type WorkerApprovalMode = "consumer" | "model" | "both";
9
+
6
10
  export interface OrchestratorConfig {
11
+ /** Model-facing names for ACP-client's native worker tools. Unspecified names keep their defaults. */
12
+ readonly toolNames?: Partial<DelegationToolNames & { answer: string }>;
13
+ readonly workerApprovals?: WorkerApprovalMode;
7
14
  /** Each entry corresponds to a configured native harness policy name. */
8
15
  readonly policies?: Readonly<Record<string, {
9
16
  readonly delegation: DelegationPolicy;
10
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
+ };
11
23
  }>>;
12
24
  /** Forwarded requests retain owner options only when every contributing name is listed here. */
13
25
  readonly ownerPolicies?: readonly string[];
@@ -25,9 +37,33 @@ export interface OrchestratorConfig {
25
37
  };
26
38
  }
27
39
 
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" };
42
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
43
+ throw new TypeError("orchestrator.toolNames must be a map of worker operations to tool names");
44
+ }
45
+ const names: Record<keyof DelegationToolNames, string> & { answer?: string } = { ...defaultDelegationToolNames };
46
+ if (mode !== "consumer") names.answer = "worker_answer";
47
+ for (const [operation, name] of Object.entries(input)) {
48
+ if (operation !== "answer" && !Object.hasOwn(defaultDelegationToolNames, operation)) {
49
+ throw new Error(`unknown orchestrator tool operation: ${operation}`);
50
+ }
51
+ if (typeof name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(name)) {
52
+ throw new Error(`invalid orchestrator tool name for ${operation}`);
53
+ }
54
+ if (operation !== "answer" || mode !== "consumer") names[operation as keyof DelegationToolNames | "answer"] = name;
55
+ }
56
+ const resolved = Object.values(names);
57
+ if (new Set(resolved).size !== resolved.length) throw new Error("orchestrator tool names must be distinct");
58
+ return names;
59
+ }
60
+
28
61
  export function validateOrchestrator(
29
62
  config: OrchestratorConfig, persistence: PersistenceBackend, messageCapture: RecordCaptureLevel,
30
63
  ): void {
64
+ if (config.workerApprovals !== undefined && !["consumer", "model", "both"].includes(config.workerApprovals)) {
65
+ throw new Error("invalid orchestrator.workerApprovals mode");
66
+ }
31
67
  if (!persistence.capabilities.workers || !persistence.workers) throw new PersistenceCapabilityError("workers");
32
68
  if (!persistence.capabilities.workerDelivery || !persistence.workerDelivery) throw new PersistenceCapabilityError("workerDelivery");
33
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,7 +1,9 @@
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";
4
- import type { OrchestratorConfig } from "./config.ts";
6
+ import { resolveDelegationToolNames, type OrchestratorConfig } from "./config.ts";
5
7
  import type { SendWorkerInput, WorkerActor } from "./contracts.ts";
6
8
  import type { Orchestrator } from "./orchestrator.ts";
7
9
  import { composeDelegationPolicy } from "./policy.ts";
@@ -9,7 +11,6 @@ import { WORKER_SEND_DESCRIPTION } from "./tool-descriptions.ts";
9
11
  import { ownPermissions } from "../permissions/policy.ts";
10
12
  import { FunctionError, type NativeFunction, type NativeFunctionContext, type NativeFunctionsConfig } from "../native/functions.ts";
11
13
 
12
- const names = ["delegate", "check", "list", "stop"] as const;
13
14
  const string = { type: "string" } as const;
14
15
  const handleOnly = { type: "object", properties: { worker: string }, required: ["worker"], additionalProperties: false };
15
16
  const denyDelegation = { use: false, scope: "none", redirect: false } as const;
@@ -20,8 +21,10 @@ export function withDelegationTools(
20
21
  config: OrchestratorConfig,
21
22
  orchestrator: () => Orchestrator,
22
23
  conversations: () => Pick<AgentConversationManager, "get">,
24
+ names = resolveDelegationToolNames(config.toolNames, config.workerApprovals),
25
+ findGivingConversation?: FindGivingConversation,
23
26
  ): NativeFunctionsConfig {
24
- for (const name of names) {
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}`);
26
29
  }
27
30
  const policies = new Map(Object.entries(config.policies ?? {}).map(([name, policy]) => [name, {
@@ -79,7 +82,17 @@ export function withDelegationTools(
79
82
  ...functions,
80
83
  tools: {
81
84
  ...functions?.tools,
82
- delegate: tool(`Omit worker to open a worker. ${WORKER_SEND_DESCRIPTION}`, {
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
+ ) } : {}),
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" },
85
98
  assignment: { type: "string", enum: ["new"] } },
@@ -92,11 +105,11 @@ export function withDelegationTools(
92
105
  }
93
106
  return orchestrator().open(actor, input);
94
107
  }),
95
- check: tool("Check a worker by handle, including its latest staged result and delivery state. Results for native destinations may be absent until the harness opens.", handleOnly,
108
+ [names.check]: tool("Check a worker by handle, including its latest staged result and delivery state. Results for native destinations may be absent until the harness opens.", handleOnly,
96
109
  (args, actor) => orchestrator().check(actor, args.worker as string)),
97
- list: tool("List visible workers with their latest staged results and delivery states. Results for native destinations may be absent until the harness opens.", { type: "object", properties: {}, additionalProperties: false },
110
+ [names.list]: tool("List visible workers with their latest staged results and delivery states. Results for native destinations may be absent until the harness opens.", { type: "object", properties: {}, additionalProperties: false },
98
111
  (_args, actor) => orchestrator().list(actor)),
99
- stop: tool('Interrupt running work and clear pending prompts. Returns "stopped" after an interruption or "idle" if there was no work to stop.', handleOnly,
112
+ [names.stop]: tool('Interrupt running work and clear pending prompts. Returns "stopped" after an interruption or "idle" if there was no work to stop.', handleOnly,
100
113
  async (args, actor) => ({ status: await orchestrator().stop(actor, args.worker as string) })),
101
114
  },
102
115
  };
@@ -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";