@qlairoslabs/acp-client 0.12.1 → 0.13.1-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/CHANGELOG-consumer-fixes.md +17 -10
- package/CHANGELOG-controller-interface.md +258 -0
- package/CHANGELOG-metering.md +29 -0
- package/CHANGELOG-operation-lifecycle.md +15 -1
- package/CONSUMER_GUIDE.md +984 -6
- package/MIGRATION-0.10-to-0.12.md +4 -1
- package/MIGRATION-0.12-to-0.13.md +288 -0
- package/README.md +17 -16
- package/package.json +11 -2
- package/src/acp-client-handlers.ts +48 -0
- package/src/activity.ts +3 -0
- package/src/adapters.ts +25 -0
- package/src/agent/adoption/provider-attachment.ts +33 -0
- package/src/agent/adoption/provider-session-delete.ts +1 -1
- package/src/agent/adoption/provider-sessions.ts +3 -2
- package/src/agent/append-assistant-message.ts +91 -0
- package/src/agent/config.ts +54 -6
- package/src/agent/conversation-manager.ts +95 -158
- package/src/agent/manager-settings.ts +1 -0
- package/src/agent/native-channel-lifecycle.ts +111 -0
- package/src/agent/native-operations.ts +39 -0
- package/src/agent/persisted-lifecycle.ts +44 -4
- package/src/agent/persistence-policy/context.ts +13 -0
- package/src/agent/persistence-policy/resolver.ts +7 -0
- package/src/agent/persistence-policy/types.ts +1 -0
- package/src/agent/record-capture.ts +1 -0
- package/src/agent-adapter-registry.ts +33 -7
- package/src/agent-conversation-contracts.ts +14 -1
- package/src/agent-conversation-errors.ts +8 -0
- package/src/agent-conversation-owner.ts +9 -4
- package/src/agent-session-config.ts +137 -0
- package/src/agent-session.ts +440 -934
- package/src/agent.ts +168 -0
- package/src/capabilities.ts +2 -0
- package/src/checkpointing/recovery.ts +3 -0
- package/src/cli/index.ts +3 -3
- package/src/cli/managed.ts +2 -2
- package/src/client.ts +56 -96
- package/src/connection-attempt.ts +95 -0
- package/src/controller-connection.ts +115 -0
- package/src/controller.ts +158 -148
- package/src/conversation-controller/capabilities.ts +88 -0
- package/src/conversation-controller/contracts.ts +208 -0
- package/src/conversation-controller/factory.ts +39 -0
- package/src/conversation-controller/guards.ts +98 -0
- package/src/conversation-controller/index.ts +20 -0
- package/src/conversation-startup.ts +35 -0
- package/src/conversation-turns/backend-turns.ts +373 -0
- package/src/conversation-turns/clear-operations.ts +37 -0
- package/src/conversation-turns/context.ts +135 -0
- package/src/conversation-turns/index.ts +4 -0
- package/src/conversation-turns/record-helpers.ts +75 -0
- package/src/conversation-turns/recording.ts +235 -0
- package/src/conversation-turns/run-turn.ts +367 -0
- package/src/conversation-turns/turn-run.ts +57 -0
- package/src/errors.ts +41 -0
- package/src/handoff-options.ts +81 -0
- package/src/identity/checkpoint-backed.ts +1 -1
- package/src/index.ts +59 -3
- package/src/internal-inference/coordination/manager.ts +11 -0
- package/src/internal-inference/runtime/harness-runtime.ts +4 -4
- package/src/launcher.ts +37 -2
- package/src/media/parts.ts +5 -0
- package/src/message-status.ts +83 -0
- package/src/metering/engine.ts +39 -64
- package/src/metering/measurement-provenance.ts +36 -0
- package/src/metering/native/durability.ts +115 -0
- package/src/metering/native/ledger.ts +104 -0
- package/src/metering/native/operation.ts +85 -0
- package/src/metering/native/projection.ts +114 -0
- package/src/metering/native/proof.ts +51 -0
- package/src/metering/native/requirements.ts +10 -0
- package/src/metering/native/retirement.ts +92 -0
- package/src/metering/native/source.ts +90 -0
- package/src/metering/record.ts +38 -1
- package/src/metering/state.ts +13 -3
- package/src/native/approvals.ts +186 -0
- package/src/native/capabilities.ts +17 -0
- package/src/native/channel-changes.ts +211 -0
- package/src/native/connection.ts +56 -0
- package/src/native/controller.ts +592 -0
- package/src/native/delegation-sender.ts +26 -0
- package/src/native/errors.ts +35 -0
- package/src/native/functions.ts +156 -0
- package/src/native/host-config.ts +59 -0
- package/src/native/host.ts +978 -0
- package/src/native/item-receipts.ts +15 -0
- package/src/native/metering.ts +12 -0
- package/src/native/records.ts +166 -0
- package/src/native/recovery.ts +186 -0
- package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
- package/src/native/reminders/idle.ts +70 -0
- package/src/native/reminders/limits.ts +19 -0
- package/src/native/reminders/notifications.ts +29 -0
- package/src/native/reminders/routine-guard.ts +66 -0
- package/src/native/reminders/routine-schedule.ts +25 -0
- package/src/native/reminders/routine-wire.ts +21 -0
- package/src/native/reminders/schedule.ts +97 -0
- package/src/native/reminders/service.ts +280 -0
- package/src/native/reminders/supervisor.ts +91 -0
- package/src/native/reminders/sync.ts +301 -0
- package/src/native/reminders/wire.ts +197 -0
- package/src/native/submission-withdrawal.ts +65 -0
- package/src/native/usage.ts +15 -0
- package/src/native/worker-delivery.ts +61 -0
- package/src/native-harness/README.md +726 -0
- package/src/native-harness/package.json +24 -0
- package/src/native-harness/scripts/build-routine-zones.py +47 -0
- package/src/native-harness/src/capabilities/context/build.ts +59 -0
- package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
- package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
- package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
- package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
- package/src/native-harness/src/capabilities/context/session.ts +93 -0
- package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
- package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
- package/src/native-harness/src/capabilities/model/runner.ts +116 -0
- package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
- package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
- package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
- package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
- package/src/native-harness/src/capabilities/model/usage.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
- package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
- package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
- package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
- package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
- package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
- package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
- package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
- package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
- package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
- package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
- package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
- package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
- package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
- package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
- package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
- package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
- package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
- package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
- package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
- package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
- package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
- package/src/native-harness/src/client.ts +18 -0
- package/src/native-harness/src/contracts/agent.ts +105 -0
- package/src/native-harness/src/contracts/config-permissions.ts +49 -0
- package/src/native-harness/src/contracts/context.ts +112 -0
- package/src/native-harness/src/contracts/events.ts +47 -0
- package/src/native-harness/src/contracts/input-limits.ts +7 -0
- package/src/native-harness/src/contracts/inspection.ts +22 -0
- package/src/native-harness/src/contracts/loop.ts +31 -0
- package/src/native-harness/src/contracts/model-execution.ts +83 -0
- package/src/native-harness/src/contracts/operator-controls.ts +106 -0
- package/src/native-harness/src/contracts/output.ts +13 -0
- package/src/native-harness/src/contracts/protocol.ts +320 -0
- package/src/native-harness/src/contracts/reminders.ts +134 -0
- package/src/native-harness/src/contracts/routines.ts +20 -0
- package/src/native-harness/src/contracts/scenario.ts +42 -0
- package/src/native-harness/src/contracts/session-file.ts +20 -0
- package/src/native-harness/src/contracts/session.ts +184 -0
- package/src/native-harness/src/contracts/storage.ts +597 -0
- package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
- package/src/native-harness/src/contracts/tools.ts +133 -0
- package/src/native-harness/src/governance/permissions/gate.ts +129 -0
- package/src/native-harness/src/governance/policy/resolve.ts +32 -0
- package/src/native-harness/src/index.ts +322 -0
- package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
- package/src/native-harness/src/interfaces/cli/development.ts +145 -0
- package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
- package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
- package/src/native-harness/src/interfaces/cli/main.ts +47 -0
- package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
- package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
- package/src/native-harness/src/interfaces/cli/start.ts +106 -0
- package/src/native-harness/src/interfaces/client.ts +225 -0
- package/src/native-harness/src/interfaces/inspector/index.html +283 -0
- package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
- package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
- package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
- package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
- package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
- package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
- package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
- package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
- package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
- package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
- package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
- package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
- package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
- package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
- package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
- package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
- package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
- package/src/native-harness/src/kernel/channels.ts +409 -0
- package/src/native-harness/src/kernel/loop.ts +45 -0
- package/src/native-harness/src/runtime/config/development.ts +23 -0
- package/src/native-harness/src/runtime/config/managed.ts +2 -0
- package/src/native-harness/src/runtime/config/paths.ts +33 -0
- package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
- package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
- package/src/native-harness/src/runtime/reminders.ts +66 -0
- package/src/native-harness/src/state/storage/archive.ts +257 -0
- package/src/native-harness/src/state/storage/engine.ts +1204 -0
- package/src/native-harness/src/state/storage/inference.ts +124 -0
- package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
- package/src/native-harness/src/state/storage/memory.ts +354 -0
- package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
- package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
- package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
- package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
- package/src/native-harness/src/state/storage/retrieval.ts +122 -0
- package/src/native-harness/src/state/storage/routine-row.ts +25 -0
- package/src/native-harness/src/state/storage/script-identity.ts +7 -0
- package/src/native-harness/src/state/storage/session-file.ts +85 -0
- package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
- package/src/native-harness/src/state/storage/sqlite.ts +632 -0
- package/src/native-harness/src/testing.ts +190 -0
- package/src/native-harness/src/util/config.ts +66 -0
- package/src/native-harness/src/util/intake.ts +7 -0
- package/src/native-harness/src/util/json.ts +41 -0
- package/src/native-harness/src/util/message-position.ts +3 -0
- package/src/native-harness/src/util/reminder-schedule.ts +44 -0
- package/src/native-harness/src/util/schema.ts +40 -0
- package/src/native-harness/src/util/timeline-text.ts +72 -0
- package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
- package/src/native-harness/tsconfig.json +20 -0
- package/src/observation/agent-event-bus.ts +44 -18
- package/src/observation/index.ts +1 -0
- package/src/operations/contracts.ts +11 -3
- package/src/operations/errors.ts +5 -0
- package/src/operations/stale-policy.ts +1 -1
- package/src/operations/supervisor.ts +34 -10
- package/src/orchestrator/acp-delivery.ts +68 -0
- package/src/orchestrator/assignments.ts +27 -0
- package/src/orchestrator/busy.ts +15 -0
- package/src/orchestrator/config.ts +41 -0
- package/src/orchestrator/consumer-api.ts +24 -0
- package/src/orchestrator/contracts.ts +71 -0
- package/src/orchestrator/durable-assignments.ts +111 -0
- package/src/orchestrator/native-delegation.ts +103 -0
- package/src/orchestrator/orchestrator.ts +318 -0
- package/src/orchestrator/permissions.ts +28 -0
- package/src/orchestrator/policy.ts +44 -0
- package/src/orchestrator/pool.ts +123 -0
- package/src/orchestrator/tool-descriptions.ts +11 -0
- package/src/permissions/acp.ts +18 -0
- package/src/permissions/arrival.ts +13 -0
- package/src/permissions/consumer-config.ts +19 -0
- package/src/permissions/conversation.ts +288 -0
- package/src/permissions/matcher.ts +87 -0
- package/src/permissions/outcome.ts +26 -0
- package/src/permissions/policy.ts +86 -0
- package/src/permissions/request.ts +26 -0
- package/src/persistence/activity-projection.ts +1 -0
- package/src/persistence/backend.ts +34 -1
- package/src/persistence/channels.ts +23 -0
- package/src/persistence/index.ts +4 -0
- package/src/persistence/protocol-method.ts +5 -0
- package/src/persistence/reminder-wake.ts +49 -0
- package/src/persistence/reminders.ts +385 -0
- package/src/persistence/sqlite-backend.ts +84 -6
- package/src/persistence/sqlite-channels.ts +65 -0
- package/src/persistence/sqlite-reminders.ts +85 -0
- package/src/persistence/sqlite-schema.ts +108 -3
- package/src/persistence/sqlite-worker-delivery.ts +374 -0
- package/src/persistence/sqlite-workers.ts +59 -0
- package/src/persistence/worker-delivery-contract.ts +104 -0
- package/src/persistence/worker-terminal-reason.ts +29 -0
- package/src/persistence/workers.ts +19 -0
- package/src/provider-notices.ts +137 -0
- package/src/repl/commands.ts +2 -2
- package/src/steering/combine.ts +3 -1
- package/src/steering/contracts.ts +11 -2
- package/src/steering/controller.ts +3 -2
- package/src/terminals.ts +9 -6
- package/src/transport/acp-transport.ts +24 -14
- package/src/types.ts +15 -12
- package/src/updates.ts +14 -2
- package/src/wire-log.ts +1 -1
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
2
|
+
import type { AgentSessionEvent } from "../agent-conversation-contracts.ts";
|
|
3
|
+
import type { Logger } from "../logger.ts";
|
|
4
|
+
import type { PermissionOutcome, PermissionRequest, PromptHandlers } from "../types.ts";
|
|
5
|
+
import { acpPermissionArrivals, permissionArrival, type PermissionArrival } from "./arrival.ts";
|
|
6
|
+
import { DEFAULT_PERMISSION_TIMEOUT_MS } from "./consumer-config.ts";
|
|
7
|
+
import type { PermissionSettings } from "./matcher.ts";
|
|
8
|
+
import { selectPermissionOutcome, unansweredPermissionOutcome } from "./outcome.ts";
|
|
9
|
+
import { permissionLevel, recordingPermissionHandlers, type ConversationPermissionConfig } from "./policy.ts";
|
|
10
|
+
|
|
11
|
+
export type PermissionResolutionSource = "handler" | "consumer" | "default" | "timeout" | "turn_ended";
|
|
12
|
+
export type PermissionResolution = {
|
|
13
|
+
readonly outcome: PermissionOutcome;
|
|
14
|
+
readonly by: PermissionResolutionSource;
|
|
15
|
+
/** ACP can only cancel on the wire if no reject option is offered. */
|
|
16
|
+
readonly refused?: boolean;
|
|
17
|
+
};
|
|
18
|
+
export interface WorkerPermissionSource {
|
|
19
|
+
readonly kind: "worker";
|
|
20
|
+
readonly handle: string;
|
|
21
|
+
readonly conversationId: AgentConversationId;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface PermissionRequestEventFields {
|
|
25
|
+
readonly kind: "permission_requested";
|
|
26
|
+
readonly id: string;
|
|
27
|
+
readonly tool: PermissionRequest["tool"];
|
|
28
|
+
readonly title: string | undefined;
|
|
29
|
+
readonly options: readonly Readonly<PermissionRequest["options"][number]>[];
|
|
30
|
+
readonly expiresAt?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ConversationPermissionEvent =
|
|
34
|
+
| (PermissionRequestEventFields & ({ readonly turnId: string; readonly source?: never }
|
|
35
|
+
| { readonly turnId?: string; readonly source: WorkerPermissionSource }))
|
|
36
|
+
| { kind: "permission_resolved"; id: string; outcome: "approved" | "denied" | "cancelled"; by: PermissionResolutionSource };
|
|
37
|
+
|
|
38
|
+
export const cancelledPermission: PermissionResolution = { outcome: { outcome: "cancelled" }, by: "turn_ended" };
|
|
39
|
+
|
|
40
|
+
export function permissionOutcome(request: PermissionRequest, resolution: PermissionResolution) {
|
|
41
|
+
if (resolution.refused) return "denied" as const;
|
|
42
|
+
if (resolution.outcome.outcome === "cancelled") return "cancelled" as const;
|
|
43
|
+
const { optionId } = resolution.outcome;
|
|
44
|
+
const kind = request.options.find(option => option.optionId === optionId)?.kind;
|
|
45
|
+
return kind === "allow_once" || kind === "allow_always" ? "approved" as const : "denied" as const;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A native approval already has a request identity and a wire-level settlement. */
|
|
49
|
+
export interface NativePermission {
|
|
50
|
+
readonly arrival: PermissionArrival;
|
|
51
|
+
readonly hostHandled: boolean;
|
|
52
|
+
readonly settled: boolean;
|
|
53
|
+
readonly signal: AbortSignal;
|
|
54
|
+
readonly hasWireOutcome: boolean;
|
|
55
|
+
readonly resolution: Promise<PermissionResolution>;
|
|
56
|
+
answer(resolution: PermissionResolution): Promise<boolean>;
|
|
57
|
+
onCancelTurn?(listener: () => void): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const nativeProviderTurnEnded = Symbol("native provider turn ended");
|
|
61
|
+
export const nativeConversationStopping = Symbol("native conversation stopping");
|
|
62
|
+
|
|
63
|
+
export function refuseNativeOnClose(native: NativePermission | undefined, stopping: boolean, log: () => Logger): void {
|
|
64
|
+
if (!native || native.hasWireOutcome || (native.hostHandled && !stopping)) return;
|
|
65
|
+
void native.answer(cancelledPermission).catch(error =>
|
|
66
|
+
log().warn("native_approval_local_refusal_failed", { error: String(error) }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const nativePermissionRequests = new WeakMap<PermissionRequest, NativePermission>();
|
|
70
|
+
|
|
71
|
+
interface PermissionEntry {
|
|
72
|
+
readonly turnId?: string;
|
|
73
|
+
close(resolution: PermissionResolution): void;
|
|
74
|
+
closeLocally(stopping?: boolean): void;
|
|
75
|
+
answer?(optionId: string): Promise<boolean>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const forwarding = new WeakMap<object, {
|
|
79
|
+
readonly coordinator: ConversationPermissions;
|
|
80
|
+
readonly policy: () => ConversationPermissionConfig;
|
|
81
|
+
}>();
|
|
82
|
+
|
|
83
|
+
export interface ForwardPermissionOptions {
|
|
84
|
+
readonly source: WorkerPermissionSource;
|
|
85
|
+
readonly includeAllowAlways: boolean;
|
|
86
|
+
readonly unanswered?: PermissionSettings["unanswered"];
|
|
87
|
+
readonly signal?: AbortSignal;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function forwardPermission(
|
|
91
|
+
conversation: object | undefined, request: PermissionRequest, options: ForwardPermissionOptions,
|
|
92
|
+
): Promise<PermissionOutcome> {
|
|
93
|
+
const destination = conversation && forwarding.get(conversation);
|
|
94
|
+
if (!destination) return unansweredPermissionOutcome(request.options, options.unanswered);
|
|
95
|
+
const { source, signal, includeAllowAlways } = options;
|
|
96
|
+
// A forwarded UI request must not answer the worker's native ticket directly.
|
|
97
|
+
const offered = {
|
|
98
|
+
...request, options: includeAllowAlways ? request.options : request.options.filter(option => option.kind !== "allow_always"),
|
|
99
|
+
};
|
|
100
|
+
const time = acpPermissionArrivals.get(request);
|
|
101
|
+
if (time && offered !== request) acpPermissionArrivals.set(offered, time);
|
|
102
|
+
return (await destination.coordinator.request(undefined, offered, destination.policy(), undefined, signal, undefined, source)).outcome;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export class ConversationPermissions {
|
|
106
|
+
private readonly pending = new Map<string, PermissionEntry>();
|
|
107
|
+
private stopped = false;
|
|
108
|
+
|
|
109
|
+
constructor(
|
|
110
|
+
private readonly emit: (event: AgentSessionEvent) => void,
|
|
111
|
+
private readonly log: () => Logger,
|
|
112
|
+
conversation?: object,
|
|
113
|
+
policy?: () => ConversationPermissionConfig,
|
|
114
|
+
) {
|
|
115
|
+
if (conversation && policy) forwarding.set(conversation, { coordinator: this, policy });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
end(turnId: string): void {
|
|
119
|
+
for (const entry of this.pending.values()) if (entry.turnId === turnId) entry.closeLocally();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
stop(): void {
|
|
123
|
+
this.stopped = true;
|
|
124
|
+
for (const entry of this.pending.values()) entry.closeLocally(true);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async answer(id: string, optionId: string): Promise<{ accepted: boolean }> {
|
|
128
|
+
return { accepted: await this.pending.get(id)?.answer?.(optionId) ?? false };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
internalHandler(turnId: string, policy: ConversationPermissionConfig): PromptHandlers {
|
|
132
|
+
const onPermissionRequest: NonNullable<PromptHandlers["onPermissionRequest"]> = async (request, signal) =>
|
|
133
|
+
(await this.request(turnId, request, policy, undefined, signal)).outcome;
|
|
134
|
+
recordingPermissionHandlers.add(onPermissionRequest);
|
|
135
|
+
return { onPermissionRequest };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
request(
|
|
139
|
+
turnId: string | undefined,
|
|
140
|
+
request: PermissionRequest,
|
|
141
|
+
policy: ConversationPermissionConfig,
|
|
142
|
+
consumer: PromptHandlers | undefined,
|
|
143
|
+
signal?: AbortSignal,
|
|
144
|
+
recordRequested?: () => Promise<void>,
|
|
145
|
+
source?: WorkerPermissionSource,
|
|
146
|
+
): Promise<PermissionResolution> {
|
|
147
|
+
const native = nativePermissionRequests.get(request);
|
|
148
|
+
if (this.stopped || signal?.aborted) {
|
|
149
|
+
refuseNativeOnClose(native, this.stopped || signal?.reason === nativeConversationStopping, this.log);
|
|
150
|
+
return Promise.resolve(cancelledPermission);
|
|
151
|
+
}
|
|
152
|
+
const id = crypto.randomUUID();
|
|
153
|
+
const handlerAbort = new AbortController();
|
|
154
|
+
const abort = () => {
|
|
155
|
+
if (signal?.reason === nativeProviderTurnEnded && native?.hasWireOutcome) return;
|
|
156
|
+
entry.closeLocally(signal?.reason === nativeConversationStopping);
|
|
157
|
+
};
|
|
158
|
+
const handler = consumer?.onPermissionRequest;
|
|
159
|
+
const refuse = (by: PermissionResolutionSource): PermissionResolution =>
|
|
160
|
+
({ outcome: selectPermissionOutcome("deny", request.options)!, by, refused: true });
|
|
161
|
+
let level: ReturnType<typeof permissionLevel> | undefined;
|
|
162
|
+
if (source) level = "ask";
|
|
163
|
+
else if (!native?.hostHandled && !native?.settled) {
|
|
164
|
+
try {
|
|
165
|
+
level = permissionLevel(request, policy, Boolean(native));
|
|
166
|
+
} catch (error) {
|
|
167
|
+
this.log().warn("conversation_permission_rule_failed", { turnId, id, error: String(error) });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const waitForConsumer = level === "ask" && !handler && policy.answersPermissions === true;
|
|
172
|
+
const offered = Object.freeze(request.options.map(option => Object.freeze({ ...option })));
|
|
173
|
+
const arrival = native?.arrival ?? acpPermissionArrivals.get(request) ?? permissionArrival();
|
|
174
|
+
const budget = policy.permissionTimeoutMs ?? DEFAULT_PERMISSION_TIMEOUT_MS;
|
|
175
|
+
const remaining = () => budget - (performance.now() - arrival.monotonicTime);
|
|
176
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
177
|
+
let resolve!: (resolution: PermissionResolution) => void;
|
|
178
|
+
const result = new Promise<PermissionResolution>(accept => { resolve = accept; });
|
|
179
|
+
const entry: PermissionEntry = {
|
|
180
|
+
turnId,
|
|
181
|
+
closeLocally: (stopping = false) => {
|
|
182
|
+
if (!this.pending.has(id)) return;
|
|
183
|
+
entry.close(cancelledPermission);
|
|
184
|
+
refuseNativeOnClose(native, stopping, this.log);
|
|
185
|
+
},
|
|
186
|
+
close: resolution => {
|
|
187
|
+
if (!this.pending.delete(id)) return;
|
|
188
|
+
signal?.removeEventListener("abort", abort);
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
handlerAbort.abort();
|
|
191
|
+
const outcome = permissionOutcome(request, resolution);
|
|
192
|
+
// Finish notifying all request listeners before any reentrant stop publishes its resolution.
|
|
193
|
+
queueMicrotask(() => this.emit({ kind: "permission_resolved", id, outcome, by: resolution.by }));
|
|
194
|
+
resolve(resolution);
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
this.pending.set(id, entry);
|
|
198
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
199
|
+
if (native) void native.resolution.then(entry.close);
|
|
200
|
+
if (this.stopped || signal?.aborted) abort();
|
|
201
|
+
|
|
202
|
+
const send = async (decision: PermissionResolution) => {
|
|
203
|
+
if (!this.pending.has(id)) return false;
|
|
204
|
+
if (native) return native.answer(decision);
|
|
205
|
+
entry.close(decision);
|
|
206
|
+
return true;
|
|
207
|
+
};
|
|
208
|
+
const failed = (error: unknown) => {
|
|
209
|
+
this.log().warn("conversation_permission_response_failed", { turnId, id, error: String(error) });
|
|
210
|
+
entry.close(cancelledPermission);
|
|
211
|
+
return false;
|
|
212
|
+
};
|
|
213
|
+
const record = Promise.resolve().then(recordRequested);
|
|
214
|
+
const recordReady = () => Promise.race([record.then(() => true), result.then(() => false)]);
|
|
215
|
+
const sendAfterRecord = async (decision: PermissionResolution) => {
|
|
216
|
+
try {
|
|
217
|
+
if (!await recordReady()) return false;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
this.log().warn("conversation_permission_record_failed", { turnId, id, error: String(error) });
|
|
220
|
+
await send(refuse("default"));
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
return send(decision);
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
if (waitForConsumer) {
|
|
227
|
+
const claim = () => {
|
|
228
|
+
if (!entry.answer) return false;
|
|
229
|
+
entry.answer = undefined;
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
return true;
|
|
232
|
+
};
|
|
233
|
+
const expire = () => {
|
|
234
|
+
if (claim()) void send(refuse("timeout")).catch(failed);
|
|
235
|
+
};
|
|
236
|
+
entry.answer = async optionId => {
|
|
237
|
+
if (remaining() <= 0) expire();
|
|
238
|
+
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";
|
|
241
|
+
};
|
|
242
|
+
timer = setTimeout(expire, Math.max(0, Math.ceil(remaining())));
|
|
243
|
+
// A failed requested record cannot leave an otherwise unclaimed request open.
|
|
244
|
+
void record.catch(() => { if (claim()) void sendAfterRecord(refuse("default")).catch(failed); });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
this.emit({
|
|
248
|
+
kind: "permission_requested", id, ...(source ? { source: Object.freeze({ ...source }) } : { turnId: turnId! }),
|
|
249
|
+
tool: request.tool && Object.freeze(structuredClone(request.tool)),
|
|
250
|
+
title: request.title, options: offered, ...(waitForConsumer ? { expiresAt: arrival.wallTime + budget } : {}),
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
if (native?.hostHandled || native?.settled || waitForConsumer) return result;
|
|
254
|
+
if (level !== "ask" || !handler) {
|
|
255
|
+
const unanswered = level === "ask" && !handler;
|
|
256
|
+
const cancelTurn = unanswered && policy.permissions?.unanswered === "cancel";
|
|
257
|
+
const decision = cancelTurn
|
|
258
|
+
? { outcome: unansweredPermissionOutcome(request.options, "cancel"), by: "default" as const }
|
|
259
|
+
: level === "ask" || level === undefined ? refuse("default")
|
|
260
|
+
: { outcome: selectPermissionOutcome(level, request.options)!, by: "default" as const };
|
|
261
|
+
void sendAfterRecord(decision).catch(failed);
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const runHandler = async () => {
|
|
266
|
+
try {
|
|
267
|
+
if (!await recordReady()) return;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
this.log().warn("conversation_permission_record_failed", { turnId, id, error: String(error) });
|
|
270
|
+
await send(refuse("default"));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (!this.pending.has(id)) return;
|
|
274
|
+
try {
|
|
275
|
+
const outcome = await Promise.race([
|
|
276
|
+
Promise.resolve(handler.call(consumer, request, handlerAbort.signal)),
|
|
277
|
+
result.then(resolution => resolution.outcome),
|
|
278
|
+
]);
|
|
279
|
+
await send({ outcome, by: "handler" });
|
|
280
|
+
} catch (error) {
|
|
281
|
+
this.log().warn("conversation_permission_handler_failed", { turnId, id, error: String(error) });
|
|
282
|
+
await send(refuse("handler"));
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
void runHandler().catch(failed);
|
|
286
|
+
return result;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { NeutralPermissionRequest } from "./request.ts";
|
|
2
|
+
|
|
3
|
+
export type PermissionLevel = "deny" | "ask" | "allow";
|
|
4
|
+
|
|
5
|
+
export interface PermissionSettings {
|
|
6
|
+
readonly default: PermissionLevel;
|
|
7
|
+
readonly rules?: Readonly<Record<string, PermissionLevel>>;
|
|
8
|
+
/** How to answer an ask with no handler or answering consumer. Defaults to reject. */
|
|
9
|
+
readonly unanswered?: "reject" | "cancel";
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const weight: Record<PermissionLevel, number> = { deny: 0, ask: 1, allow: 2 };
|
|
13
|
+
|
|
14
|
+
export function mostRestrictivePermissionLevel(left: PermissionLevel, right: PermissionLevel): PermissionLevel {
|
|
15
|
+
return weight[left] <= weight[right] ? left : right;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Match explicit ACP kind and exact command keys. No match uses the configured default. */
|
|
19
|
+
export function matchPermissionLevel(
|
|
20
|
+
request: Partial<Pick<NeutralPermissionRequest, "tool">>,
|
|
21
|
+
settings: PermissionSettings,
|
|
22
|
+
): PermissionLevel {
|
|
23
|
+
const { rules } = settings;
|
|
24
|
+
const kind = request.tool?.kind;
|
|
25
|
+
if (!rules || !kind) return settings.default;
|
|
26
|
+
const command = kind === "execute" ? normalizeCommand(request.tool?.rawInput) : undefined;
|
|
27
|
+
const byKind = lookup(rules, `kind:${kind}`);
|
|
28
|
+
const byCommand = command === undefined ? undefined : lookup(rules, `command:${command}`);
|
|
29
|
+
if (byKind === undefined) return byCommand ?? settings.default;
|
|
30
|
+
if (byCommand === undefined) return byKind;
|
|
31
|
+
return mostRestrictivePermissionLevel(byKind, byCommand);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function lookup(rules: NonNullable<PermissionSettings["rules"]>, key: string): PermissionLevel | undefined {
|
|
35
|
+
return Object.hasOwn(rules, key) ? rules[key] : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function normalizeCommand(input: unknown): string | undefined {
|
|
39
|
+
if (typeof input === "string") return normalizeShellLine(input);
|
|
40
|
+
if (Array.isArray(input)) return normalizeArgv(input);
|
|
41
|
+
if (typeof input !== "object" || input === null) return undefined;
|
|
42
|
+
|
|
43
|
+
const fields = input as Record<string, unknown>;
|
|
44
|
+
const hasArgs = Object.hasOwn(fields, "args");
|
|
45
|
+
if (Object.hasOwn(fields, "argv")) {
|
|
46
|
+
if (Object.hasOwn(fields, "command") || hasArgs) return undefined;
|
|
47
|
+
return Array.isArray(fields.argv) ? normalizeArgv(fields.argv) : undefined;
|
|
48
|
+
}
|
|
49
|
+
if (!Object.hasOwn(fields, "command")) return undefined;
|
|
50
|
+
if (hasArgs) {
|
|
51
|
+
return typeof fields.command === "string" && Array.isArray(fields.args)
|
|
52
|
+
? normalizeArgv([fields.command, ...fields.args])
|
|
53
|
+
: undefined;
|
|
54
|
+
}
|
|
55
|
+
if (typeof fields.command === "string") return normalizeShellLine(fields.command);
|
|
56
|
+
return Array.isArray(fields.command) ? normalizeArgv(fields.command) : undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeShellLine(command: string): string | undefined {
|
|
60
|
+
if (!isSingleLine(command)) return undefined;
|
|
61
|
+
// The only string wrappers accepted are exactly bash -lc '…' and bash -lc "…".
|
|
62
|
+
// Double quotes admit outer-shell expansion, so reject expansion or escape characters there.
|
|
63
|
+
const wrapped = /^bash -lc '(?<single>[^']*)'$|^bash -lc "(?<double>[^"`$\\]*)"$/.exec(command);
|
|
64
|
+
if (wrapped) {
|
|
65
|
+
const inner = wrapped.groups?.single ?? wrapped.groups?.double;
|
|
66
|
+
return inner !== undefined && isSingleLine(inner) ? inner : undefined;
|
|
67
|
+
}
|
|
68
|
+
// A malformed or compound bash -lc expression is ambiguous, even if it starts with a known wrapper.
|
|
69
|
+
if (/^\s*bash[ \t]+-lc(?:\s|$)/.test(command)) return undefined;
|
|
70
|
+
return command;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function normalizeArgv(argv: readonly unknown[]): string | undefined {
|
|
74
|
+
const [executable, flag, body] = argv;
|
|
75
|
+
// The only argv wrapper accepted is exactly ["bash", "-lc", command].
|
|
76
|
+
if (executable === "bash" && flag === "-lc") {
|
|
77
|
+
return argv.length === 3 && typeof body === "string" && isSingleLine(body) ? body : undefined;
|
|
78
|
+
}
|
|
79
|
+
if (typeof executable !== "string" || executable.includes("=")) return undefined;
|
|
80
|
+
// Joining an empty, quoted or compound token would lose the original argument boundaries.
|
|
81
|
+
if (!argv.every((arg) => typeof arg === "string" && /^[A-Za-z0-9_./:@%+=,-]+$/.test(arg))) return undefined;
|
|
82
|
+
return argv.join(" ");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function isSingleLine(command: string): boolean {
|
|
86
|
+
return command.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(command);
|
|
87
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { PermissionOutcome } from "../types.ts";
|
|
2
|
+
import type { PermissionLevel, PermissionSettings } from "./matcher.ts";
|
|
3
|
+
import type { PermissionOption } from "./request.ts";
|
|
4
|
+
|
|
5
|
+
/** Translate an automatic level to an ACP reply. Ask is left for the caller to route. */
|
|
6
|
+
export function selectPermissionOutcome(
|
|
7
|
+
level: PermissionLevel,
|
|
8
|
+
options: readonly PermissionOption[],
|
|
9
|
+
): PermissionOutcome | undefined {
|
|
10
|
+
if (level === "ask") return undefined;
|
|
11
|
+
const option = level === "allow"
|
|
12
|
+
? options.find(({ kind }) => kind === "allow_once") ?? options.find(({ kind }) => kind === "allow_always")
|
|
13
|
+
: options.find(({ kind }) => kind === "reject_once");
|
|
14
|
+
return option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Preserve the intent across internal prompt handlers that return only a PermissionOutcome.
|
|
18
|
+
export const unansweredCancellation = Object.freeze({ outcome: "cancelled" } as const);
|
|
19
|
+
|
|
20
|
+
/** An unattended ask can refuse only the tool, or cancel instead. */
|
|
21
|
+
export function unansweredPermissionOutcome(
|
|
22
|
+
options: readonly PermissionOption[],
|
|
23
|
+
mode: PermissionSettings["unanswered"],
|
|
24
|
+
): PermissionOutcome {
|
|
25
|
+
return mode === "cancel" ? unansweredCancellation : selectPermissionOutcome("deny", options)!;
|
|
26
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { validatePermissionConsumerConfig, type PermissionConsumerConfig } from "./consumer-config.ts";
|
|
2
|
+
import type { PermissionRequest, PromptHandlers } from "../types.ts";
|
|
3
|
+
import { matchPermissionLevel, type PermissionLevel, type PermissionSettings } from "./matcher.ts";
|
|
4
|
+
import { selectPermissionOutcome, unansweredPermissionOutcome } from "./outcome.ts";
|
|
5
|
+
|
|
6
|
+
export interface PermissionPolicyConfig {
|
|
7
|
+
/** The whole setting replaces any inherited setting. Defaults to ask. */
|
|
8
|
+
readonly permissions?: PermissionSettings;
|
|
9
|
+
/** ACP and native requests. Native supplies tool.name and the original arguments as string tool.rawInput. */
|
|
10
|
+
readonly permissionRule?: (request: PermissionRequest) => PermissionLevel | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ConversationPermissionConfig extends PermissionPolicyConfig, PermissionConsumerConfig {}
|
|
14
|
+
|
|
15
|
+
export function validateConversationPermissionConfig(config: ConversationPermissionConfig | undefined): void {
|
|
16
|
+
ownPermissions(config?.permissions);
|
|
17
|
+
validatePermissionConsumerConfig(config);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Apply policy settings from broadest to most specific without merging the rule maps. */
|
|
21
|
+
export function inheritPermissionConfig(
|
|
22
|
+
...configs: readonly (ConversationPermissionConfig | undefined)[]
|
|
23
|
+
): ConversationPermissionConfig {
|
|
24
|
+
let permissions: PermissionSettings | undefined;
|
|
25
|
+
let permissionRule: PermissionPolicyConfig["permissionRule"];
|
|
26
|
+
let answersPermissions: boolean | undefined;
|
|
27
|
+
let permissionTimeoutMs: number | undefined;
|
|
28
|
+
for (const config of configs) {
|
|
29
|
+
permissions = config?.permissions ?? permissions;
|
|
30
|
+
permissionRule = config?.permissionRule ?? permissionRule;
|
|
31
|
+
answersPermissions = config?.answersPermissions ?? answersPermissions;
|
|
32
|
+
permissionTimeoutMs = config?.permissionTimeoutMs ?? permissionTimeoutMs;
|
|
33
|
+
}
|
|
34
|
+
return { permissions, permissionRule, answersPermissions, permissionTimeoutMs };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const DEFAULT_PERMISSIONS: PermissionSettings = Object.freeze({ default: "ask" });
|
|
38
|
+
const kinds = new Set(["read", "edit", "delete", "move", "search", "execute", "think", "fetch", "switch_mode", "other"]);
|
|
39
|
+
|
|
40
|
+
function isLevel(value: unknown): value is PermissionLevel {
|
|
41
|
+
return value === "deny" || value === "ask" || value === "allow";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Validate and own the configuration before it can be used for a request. */
|
|
45
|
+
export function ownPermissions(settings: PermissionSettings | undefined): PermissionSettings | undefined {
|
|
46
|
+
if (settings === undefined) return undefined;
|
|
47
|
+
if (settings === null || typeof settings !== "object" || !isLevel(settings.default)) {
|
|
48
|
+
throw new Error("permissions.default must be deny, ask, or allow");
|
|
49
|
+
}
|
|
50
|
+
const { rules, unanswered } = settings;
|
|
51
|
+
if (unanswered !== undefined && unanswered !== "reject" && unanswered !== "cancel") {
|
|
52
|
+
throw new Error("permissions.unanswered must be reject or cancel");
|
|
53
|
+
}
|
|
54
|
+
const base = { default: settings.default, ...(unanswered === undefined ? {} : { unanswered }) };
|
|
55
|
+
if (rules === undefined) return Object.freeze(base);
|
|
56
|
+
if (rules === null || typeof rules !== "object" || Array.isArray(rules)) throw new Error("permissions.rules must be an object");
|
|
57
|
+
for (const [key, level] of Object.entries(rules)) {
|
|
58
|
+
const command = key.startsWith("command:") ? key.slice(8) : "";
|
|
59
|
+
const valid = key.startsWith("kind:") && kinds.has(key.slice(5))
|
|
60
|
+
|| command.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(command);
|
|
61
|
+
if (!valid) throw new Error(`invalid permission rule key: ${key}`);
|
|
62
|
+
if (!isLevel(level)) throw new Error(`invalid permission level for ${key}: ${String(level)}`);
|
|
63
|
+
}
|
|
64
|
+
return Object.freeze({ ...base, rules: Object.freeze({ ...rules }) });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function permissionLevel(request: PermissionRequest, config: PermissionPolicyConfig, native = false): PermissionLevel {
|
|
68
|
+
const override = config.permissionRule?.(request);
|
|
69
|
+
if (override !== undefined && !isLevel(override)) throw new Error("permissionRule must return deny, ask, allow, or undefined");
|
|
70
|
+
const settings = config.permissions ?? DEFAULT_PERMISSIONS;
|
|
71
|
+
return override ?? (native ? settings.default : matchPermissionLevel(request, settings));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Resolve an ACP request outside a conversation permission coordinator. */
|
|
75
|
+
export function answerPermissionLevel(
|
|
76
|
+
level: PermissionLevel,
|
|
77
|
+
request: PermissionRequest,
|
|
78
|
+
handler: (() => ReturnType<NonNullable<PromptHandlers["onPermissionRequest"]>>) | undefined,
|
|
79
|
+
unanswered: PermissionSettings["unanswered"],
|
|
80
|
+
) {
|
|
81
|
+
if (level === "ask") return handler ? handler() : unansweredPermissionOutcome(request.options, unanswered);
|
|
82
|
+
return selectPermissionOutcome(level, request.options)!;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A turn's recording handler already applies policy and must see every request for persistence. */
|
|
86
|
+
export const recordingPermissionHandlers = new WeakSet<NonNullable<PromptHandlers["onPermissionRequest"]>>();
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type PermissionOptionKind =
|
|
2
|
+
| "allow_once"
|
|
3
|
+
| "allow_always"
|
|
4
|
+
| "reject_once"
|
|
5
|
+
| "reject_always"
|
|
6
|
+
| (string & {});
|
|
7
|
+
|
|
8
|
+
export interface PermissionOption {
|
|
9
|
+
optionId: string;
|
|
10
|
+
name: string;
|
|
11
|
+
kind: PermissionOptionKind;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The tool fields a producer can reliably identify. */
|
|
15
|
+
export interface PermissionTool {
|
|
16
|
+
readonly name?: string;
|
|
17
|
+
readonly kind?: string;
|
|
18
|
+
readonly rawInput?: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A permission request without transport-specific identity or response routing. */
|
|
22
|
+
export interface NeutralPermissionRequest {
|
|
23
|
+
readonly tool: PermissionTool;
|
|
24
|
+
readonly title?: string;
|
|
25
|
+
readonly options: readonly PermissionOption[];
|
|
26
|
+
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import type { ReminderPersistence } from "./reminders.ts";
|
|
2
|
+
import type { WorkerPersistence } from "./workers.ts";
|
|
3
|
+
import type { WorkerDeliveryRepository } from "./worker-delivery-contract.ts";
|
|
1
4
|
import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
|
|
2
5
|
import type { CancelOutcome, CancelReason } from "../operations/contracts.ts";
|
|
3
|
-
import type { OperationMeteringRecord } from "../metering/record.ts";
|
|
6
|
+
import type { NativeEarlierCallEvidence, NativeEarlierCallSummary, OperationMeteringRecord } from "../metering/record.ts";
|
|
4
7
|
import type { AgentSessionMeteringState } from "../metering/state.ts";
|
|
5
8
|
import type { InternalInferenceRepository } from "../internal-inference/persistence/repository.ts";
|
|
6
9
|
import type { ConversationRecoveryCheckpointRepository } from "../checkpointing/contracts.ts";
|
|
@@ -9,6 +12,7 @@ import type { SharedFilesPersistence } from "../media/files.ts";
|
|
|
9
12
|
import type { MediaCaptureLevel } from "../media/capture.ts";
|
|
10
13
|
import type { MediaStore } from "../media/store.ts";
|
|
11
14
|
import type { MediaKind } from "../media/parts.ts";
|
|
15
|
+
import type { ChannelPersistence } from "./channels.ts";
|
|
12
16
|
import { contentText } from "../media/content.ts";
|
|
13
17
|
|
|
14
18
|
export type PersistenceJsonPrimitive = string | number | boolean | null;
|
|
@@ -311,6 +315,9 @@ export interface AgentPersistenceIdentity {
|
|
|
311
315
|
}
|
|
312
316
|
|
|
313
317
|
export interface AgentConversationSummary {
|
|
318
|
+
readonly role?: "worker";
|
|
319
|
+
/** Absent on rows written before controller kinds were recorded. */
|
|
320
|
+
readonly controllerKind?: "acp" | "native";
|
|
314
321
|
readonly agentConversationId: AgentConversationId;
|
|
315
322
|
readonly agentSessionId: AgentSessionId;
|
|
316
323
|
readonly title?: string;
|
|
@@ -327,6 +334,8 @@ export interface AgentConversationSummary {
|
|
|
327
334
|
}
|
|
328
335
|
|
|
329
336
|
export interface CreateAgentConversationInput {
|
|
337
|
+
readonly role?: AgentConversationSummary["role"];
|
|
338
|
+
readonly controllerKind?: AgentConversationSummary["controllerKind"];
|
|
330
339
|
readonly agentConversationId: AgentConversationId;
|
|
331
340
|
readonly agentSessionId: AgentSessionId;
|
|
332
341
|
readonly participants?: readonly ParticipantRef[];
|
|
@@ -687,7 +696,23 @@ export interface MeteringRecordPage {
|
|
|
687
696
|
readonly nextCursor?: string;
|
|
688
697
|
}
|
|
689
698
|
|
|
699
|
+
/** The durable deduplication row survives removal of an operation's detailed record. */
|
|
700
|
+
export interface MeteringOperationIdentity {
|
|
701
|
+
readonly outcome: OperationMeteringRecord["outcome"];
|
|
702
|
+
readonly adapterId: string;
|
|
703
|
+
readonly completedAt: number;
|
|
704
|
+
/** Attested measured attempt IDs, retained even when operation detail is pruned. */
|
|
705
|
+
readonly nativeAccountedAttemptIds?: readonly string[];
|
|
706
|
+
readonly nativeAccountedAttemptCount?: number;
|
|
707
|
+
readonly nativeAccountedAttemptsTruncated?: true;
|
|
708
|
+
/** Earlier calls reported outside the operation's totals, retained with its cursor proof. */
|
|
709
|
+
readonly unaccountedEarlierCalls?: readonly NativeEarlierCallEvidence[];
|
|
710
|
+
readonly unaccountedEarlierSummary?: NativeEarlierCallSummary;
|
|
711
|
+
}
|
|
712
|
+
|
|
690
713
|
export interface MeteringPersistence {
|
|
714
|
+
/** Implementations retain native proof independently of detailed record retention. */
|
|
715
|
+
operationIdentity?(agentConversationId: AgentConversationId, operationId: string): Promise<MeteringOperationIdentity | null>;
|
|
691
716
|
/** Atomically deduplicate the operation and advance its bounded restoration state. */
|
|
692
717
|
commit(input: MeteringCommitInput): Promise<PersistedConversationMeteringState>;
|
|
693
718
|
saveState(
|
|
@@ -765,6 +790,10 @@ export interface PersistenceCapabilities {
|
|
|
765
790
|
readonly transactions: true;
|
|
766
791
|
readonly fullTextSearch: boolean;
|
|
767
792
|
readonly identity: boolean;
|
|
793
|
+
readonly channels: boolean;
|
|
794
|
+
readonly reminders?: boolean;
|
|
795
|
+
readonly workerDelivery?: boolean;
|
|
796
|
+
readonly workers?: boolean;
|
|
768
797
|
readonly auditOutbox: boolean;
|
|
769
798
|
readonly extensions: boolean;
|
|
770
799
|
readonly vectorSearch: boolean;
|
|
@@ -789,6 +818,10 @@ export interface PersistenceScope {
|
|
|
789
818
|
readonly internalInferences?: InternalInferenceRepository;
|
|
790
819
|
readonly recoveryCheckpoints?: ConversationRecoveryCheckpointRepository;
|
|
791
820
|
readonly identity?: IdentityPersistence;
|
|
821
|
+
readonly channels?: ChannelPersistence;
|
|
822
|
+
readonly reminders?: ReminderPersistence;
|
|
823
|
+
readonly workerDelivery?: WorkerDeliveryRepository;
|
|
824
|
+
readonly workers?: WorkerPersistence;
|
|
792
825
|
readonly identityDelivery?: IdentityDeliveryPersistence;
|
|
793
826
|
readonly search?: SearchPersistence;
|
|
794
827
|
readonly auditOutbox?: AuditOutboxPersistence;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Desired channel fields. Omit a field to retain its previous value, or use null to clear it. */
|
|
2
|
+
export interface ChannelDesire {
|
|
3
|
+
displayName?: string | null;
|
|
4
|
+
policy?: string | null;
|
|
5
|
+
lifecycle?: "open" | "suspended" | "retired";
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** An unconfirmed channel edit. Its version is the wire change ID. */
|
|
9
|
+
export interface PendingChange {
|
|
10
|
+
readonly channel: string;
|
|
11
|
+
readonly version: number;
|
|
12
|
+
readonly desire: ChannelDesire;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Durable channel intents, also available inside an Agent persistence transaction. */
|
|
16
|
+
export interface ChannelPersistence {
|
|
17
|
+
/** Merges the provided fields into the pending intent and allocates a new version. */
|
|
18
|
+
desire(channel: string, desire: ChannelDesire): Promise<PendingChange>;
|
|
19
|
+
pendingChange(channel: string): Promise<PendingChange | undefined>;
|
|
20
|
+
pendingChanges(): Promise<PendingChange[]>;
|
|
21
|
+
/** Clears only the version confirmed by the harness. */
|
|
22
|
+
confirmChange(channel: string, version: number): Promise<boolean>;
|
|
23
|
+
}
|
package/src/persistence/index.ts
CHANGED
|
@@ -56,6 +56,7 @@ export type {
|
|
|
56
56
|
MessageRecord,
|
|
57
57
|
AgentMeteringCommitInput,
|
|
58
58
|
MeteringCommitInput,
|
|
59
|
+
MeteringOperationIdentity,
|
|
59
60
|
MeteringPersistence,
|
|
60
61
|
MeteringRecordListOptions,
|
|
61
62
|
MeteringRecordPage,
|
|
@@ -117,5 +118,8 @@ export type { SqliteAgentPersistenceConfig } from "./sqlite-backend.ts";
|
|
|
117
118
|
export { SQLITE_AGENT_SCHEMA_VERSION } from "./sqlite-schema.ts";
|
|
118
119
|
|
|
119
120
|
export type { MediaStore, MediaInfo, StoredMedia } from "../media/store.ts";
|
|
121
|
+
export type { ChannelPersistence } from "./channels.ts";
|
|
120
122
|
|
|
121
123
|
export type { SharedFile, SharedFilePage, SharedFileQuery, SharedFilesPersistence } from "../media/files.ts";
|
|
124
|
+
|
|
125
|
+
export type * from "./worker-delivery-contract.ts";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export function protocolMethod(message: unknown): string | undefined {
|
|
2
|
+
if (message === null || Array.isArray(message) || typeof message !== "object") return undefined;
|
|
3
|
+
const method = (message as { readonly method?: unknown }).method;
|
|
4
|
+
return typeof method === "string" ? method : undefined;
|
|
5
|
+
}
|