@ziptie-soft/orca-local-decider 0.0.0 → 1.0.0

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.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * The local-decider panel: a thin renderer of what the worker reports. Every gateway call goes
3
+ * through `plugin.request`; the panel never holds a token and never calls `fetch`.
4
+ */
5
+ import {
6
+ atom,
7
+ Badge,
8
+ Button,
9
+ Callout,
10
+ Card,
11
+ Code,
12
+ Collapsible,
13
+ EmptyState,
14
+ Heading,
15
+ IconButton,
16
+ KeyValue,
17
+ Link,
18
+ plugin,
19
+ RadioGroup,
20
+ read,
21
+ Row,
22
+ set,
23
+ shell,
24
+ Stack,
25
+ Text,
26
+ type OrcaNode,
27
+ type PanelContext,
28
+ } from 'orca';
29
+
30
+ import type { PolicyMode } from '../gateway.ts';
31
+ import {
32
+ PANEL_CHANGED,
33
+ PANEL_REQUESTS,
34
+ type ActionResult,
35
+ type CommandRiskStats,
36
+ type PanelState,
37
+ } from '../panel-protocol.ts';
38
+ import {
39
+ actionReason,
40
+ gatewayRows,
41
+ healthBadge,
42
+ modeLine,
43
+ modeOptions,
44
+ offlineStart,
45
+ pickedMode,
46
+ pluginRows,
47
+ statsRows,
48
+ } from './model.ts';
49
+
50
+ const GUIDE_URL =
51
+ 'https://github.com/ziptie-soft/local-decider/blob/master/packages/orca-plugin/README.md';
52
+ const START_TIMEOUT_MS = 60_000;
53
+
54
+ const stateAtom = atom<PanelState | null>(null);
55
+ const busyAtom = atom<string | null>(null);
56
+ const noticeAtom = atom<ActionResult | null>(null);
57
+ const statsAtom = atom<CommandRiskStats | null>(null);
58
+ const pickedAtom = atom<PolicyMode | null>(null);
59
+
60
+ async function ask(name: string, input?: Record<string, string>): Promise<unknown> {
61
+ return plugin.request(name, input, { timeoutMs: START_TIMEOUT_MS });
62
+ }
63
+
64
+ /** Run one request with the buttons disabled; a failure becomes the notice. */
65
+ async function run(label: string, action: () => Promise<void>): Promise<void> {
66
+ if (read(busyAtom) !== null) return;
67
+ set(busyAtom, label);
68
+ try {
69
+ await action();
70
+ } catch (error) {
71
+ set(noticeAtom, { ok: false, message: String(error) });
72
+ } finally {
73
+ set(busyAtom, null);
74
+ }
75
+ }
76
+
77
+ async function refreshState(name: string): Promise<void> {
78
+ set(stateAtom, (await ask(name)) as PanelState);
79
+ }
80
+
81
+ async function act(name: string, input: Record<string, string>): Promise<void> {
82
+ set(noticeAtom, (await ask(name, input)) as ActionResult);
83
+ await refreshState(PANEL_REQUESTS.state);
84
+ }
85
+
86
+ function loadStats(): Promise<void> {
87
+ return run('stats', async () => {
88
+ set(statsAtom, (await ask(PANEL_REQUESTS.stats)) as CommandRiskStats | null);
89
+ });
90
+ }
91
+
92
+ export function setup(ctx: PanelContext): void {
93
+ ctx.subscriptions.push(plugin.on(PANEL_CHANGED, (payload) => set(stateAtom, payload as never)));
94
+ void run('refresh', () => refreshState(PANEL_REQUESTS.state));
95
+ }
96
+
97
+ function Header(props: { state: PanelState; busy: boolean }): OrcaNode {
98
+ const badge = healthBadge(props.state);
99
+ return (
100
+ <Row justify="between" align="center">
101
+ <Heading level={2}>local-decider</Heading>
102
+ <Row gap="sm" align="center">
103
+ <Badge tone={badge.tone}>{badge.text}</Badge>
104
+ <IconButton
105
+ icon="refresh"
106
+ label="Refresh"
107
+ disabled={props.busy}
108
+ onPress={() => run('refresh', () => refreshState(PANEL_REQUESTS.refresh))}
109
+ />
110
+ </Row>
111
+ </Row>
112
+ );
113
+ }
114
+
115
+ function OfflineNotice(props: { state: PanelState; busy: boolean }): OrcaNode {
116
+ if (props.state.health !== 'offline') return null;
117
+ const start = offlineStart(props.state);
118
+ return (
119
+ <Callout tone="warning" title="The gateway is not running">
120
+ <Stack gap="sm">
121
+ {props.state.launch === undefined ? null : <Text>{props.state.launch}</Text>}
122
+ {start.note === undefined ? null : <Text>{start.note}</Text>}
123
+ <Row gap="sm">
124
+ {start.canStart ? (
125
+ <Button
126
+ icon="play"
127
+ disabled={props.busy}
128
+ onPress={() => run('start', () => refreshState(PANEL_REQUESTS.start))}
129
+ >
130
+ Start the gateway
131
+ </Button>
132
+ ) : null}
133
+ <Link onPress={() => shell.openExternal(GUIDE_URL)}>Install guide</Link>
134
+ </Row>
135
+ </Stack>
136
+ </Callout>
137
+ );
138
+ }
139
+
140
+ function GatewayCard(props: { state: PanelState; busy: boolean }): OrcaNode {
141
+ const reason = actionReason(props.state);
142
+ const off = props.busy || reason !== undefined;
143
+ return (
144
+ <Card title="Gateway">
145
+ <Stack gap="sm">
146
+ <KeyValue items={gatewayRows(props.state)} />
147
+ <Row gap="sm">
148
+ <Button
149
+ disabled={off}
150
+ onPress={() => run('engine', () => act(PANEL_REQUESTS.engine, { action: 'load' }))}
151
+ >
152
+ Load model
153
+ </Button>
154
+ <Button
155
+ disabled={off}
156
+ onPress={() => run('engine', () => act(PANEL_REQUESTS.engine, { action: 'unload' }))}
157
+ >
158
+ Unload model
159
+ </Button>
160
+ </Row>
161
+ {reason === undefined ? null : <Text muted>{reason}</Text>}
162
+ </Stack>
163
+ </Card>
164
+ );
165
+ }
166
+
167
+ function CommandRiskCard(props: { state: PanelState; busy: boolean }): OrcaNode {
168
+ const { state } = props;
169
+ const reason = actionReason(state);
170
+ const picked = pickedMode(state, read(pickedAtom));
171
+ return (
172
+ <Card title="Command risk">
173
+ <Stack gap="sm">
174
+ <Row gap="sm" align="center">
175
+ <Text>Gateway mode</Text>
176
+ <Badge>{modeLine(state.gatewayMode)}</Badge>
177
+ </Row>
178
+ <RadioGroup
179
+ label="Mode"
180
+ {...(picked === undefined ? {} : { value: picked })}
181
+ options={modeOptions()}
182
+ disabled={state.control !== 'ok'}
183
+ onChange={(value) => set(pickedAtom, value as PolicyMode)}
184
+ />
185
+ <Callout tone="warning">
186
+ This changes command-risk for every client of this gateway: Claude Code hooks, Codex, pi
187
+ and Paseo.
188
+ </Callout>
189
+ <Row gap="sm">
190
+ <Button
191
+ disabled={props.busy || reason !== undefined || picked === undefined}
192
+ onPress={() =>
193
+ picked === undefined
194
+ ? undefined
195
+ : run('mode', () => act(PANEL_REQUESTS.policyMode, { mode: picked }))
196
+ }
197
+ >
198
+ Apply
199
+ </Button>
200
+ </Row>
201
+ {reason === undefined ? null : <Text muted>{reason}</Text>}
202
+ <Text muted>The "When unsure" setting applies only in act mode.</Text>
203
+ </Stack>
204
+ </Card>
205
+ );
206
+ }
207
+
208
+ function StatsCard(props: { busy: boolean }): OrcaNode {
209
+ const view = statsRows(read(statsAtom));
210
+ return (
211
+ <Card title="Last 7 days" description="All clients of this gateway">
212
+ <Stack gap="sm">
213
+ {view.empty === undefined ? (
214
+ <KeyValue items={view.rows} />
215
+ ) : (
216
+ <Text muted>{view.empty}</Text>
217
+ )}
218
+ <Row gap="sm">
219
+ <Button disabled={props.busy} onPress={() => loadStats()}>
220
+ Load stats
221
+ </Button>
222
+ </Row>
223
+ </Stack>
224
+ </Card>
225
+ );
226
+ }
227
+
228
+ function PluginCard(props: { state: PanelState }): OrcaNode {
229
+ return (
230
+ <Card title="This plugin" description="Change these in Settings → Plugins → local-decider">
231
+ <KeyValue items={pluginRows(props.state)} />
232
+ </Card>
233
+ );
234
+ }
235
+
236
+ const CLI_COMMANDS = [
237
+ 'local-decider engine list',
238
+ 'local-decider engine use <id>',
239
+ 'local-decider bench',
240
+ 'local-decider policies use command-risk command-risk-binary',
241
+ 'local-decider stats',
242
+ 'local-decider config path',
243
+ ];
244
+
245
+ function MoreSettings(): OrcaNode {
246
+ return (
247
+ <Collapsible title="More settings">
248
+ <Stack gap="sm">
249
+ <Text muted>The rest is set from a terminal with the local-decider CLI:</Text>
250
+ {CLI_COMMANDS.map((command) => (
251
+ <Code block>{command}</Code>
252
+ ))}
253
+ <Link onPress={() => shell.openExternal(GUIDE_URL)}>Plugin guide</Link>
254
+ </Stack>
255
+ </Collapsible>
256
+ );
257
+ }
258
+
259
+ export default function Panel(): OrcaNode {
260
+ const state = read(stateAtom);
261
+ const busy = read(busyAtom) !== null;
262
+ const notice = read(noticeAtom);
263
+ if (state === null) return <EmptyState title="Checking the gateway" />;
264
+ return (
265
+ <Stack gap="md">
266
+ <Header state={state} busy={busy} />
267
+ <OfflineNotice state={state} busy={busy} />
268
+ {notice === null ? null : (
269
+ <Callout tone={notice.ok ? 'success' : 'danger'}>{notice.message}</Callout>
270
+ )}
271
+ <GatewayCard state={state} busy={busy} />
272
+ <CommandRiskCard state={state} busy={busy} />
273
+ <StatsCard busy={busy} />
274
+ <PluginCard state={state} />
275
+ <MoreSettings />
276
+ </Stack>
277
+ );
278
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The worker's side of the panel: `orca.panels.handle` for the six requests the panel makes. Each
3
+ * handler validates its input, calls a `Runtime`-style method and returns plain JSON. The panel
4
+ * never sees a token and never reaches the gateway itself.
5
+ */
6
+ import type { Disposable, OrcaWorker } from './orca-types.ts';
7
+ import {
8
+ isEngineInput,
9
+ isPolicyModeInput,
10
+ PANEL_REQUESTS,
11
+ type ActionResult,
12
+ type CommandRiskStats,
13
+ type EngineInput,
14
+ type PanelState,
15
+ type PolicyModeInput,
16
+ } from './panel-protocol.ts';
17
+
18
+ /** What the panel API needs from the worker. */
19
+ export interface PanelRuntime {
20
+ panelState(): PanelState;
21
+ refresh(): Promise<PanelState>;
22
+ start(): Promise<PanelState>;
23
+ applyMode(input: PolicyModeInput): Promise<ActionResult>;
24
+ loadEngine(input: EngineInput): Promise<ActionResult>;
25
+ stats(): Promise<CommandRiskStats | null>;
26
+ }
27
+
28
+ const REJECTED: ActionResult = { ok: false, message: 'invalid request' };
29
+
30
+ function num(v: unknown): number | undefined {
31
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : undefined;
32
+ }
33
+
34
+ function counts(v: unknown): Record<string, number> {
35
+ if (typeof v !== 'object' || v === null) return {};
36
+ const pairs = Object.entries(v).filter(([, n]) => num(n) !== undefined);
37
+ return Object.fromEntries(pairs) as Record<string, number>;
38
+ }
39
+
40
+ function isCommandRisk(row: unknown): row is Record<string, unknown> {
41
+ return (
42
+ typeof row === 'object' &&
43
+ row !== null &&
44
+ (row as { policy?: unknown }).policy === 'command-risk'
45
+ );
46
+ }
47
+
48
+ /** The `command-risk` row of `/v1/stats`, or null when it is missing or malformed. */
49
+ export function statsRow(rows: readonly unknown[] | null): CommandRiskStats | null {
50
+ const row = rows?.find(isCommandRisk);
51
+ if (row === undefined) return null;
52
+ const decisions = num(row['decisions']);
53
+ if (decisions === undefined) return null;
54
+ const p50 = num(row['latencyP50Ms']);
55
+ const p95 = num(row['latencyP95Ms']);
56
+ return {
57
+ decisions,
58
+ enforced: num(row['enforced']) ?? 0,
59
+ actions: counts(row['actions']),
60
+ errors: num(row['errors']) ?? 0,
61
+ busy: num(row['busy']) ?? 0,
62
+ ...(p50 === undefined ? {} : { p50Ms: p50 }),
63
+ ...(p95 === undefined ? {} : { p95Ms: p95 }),
64
+ };
65
+ }
66
+
67
+ /** Register the panel's handlers; the caller disposes them with the worker. */
68
+ export function registerPanelApi(orca: OrcaWorker, rt: PanelRuntime): Disposable[] {
69
+ const panels = orca.panels;
70
+ if (panels === undefined) return [];
71
+ return [
72
+ panels.handle(PANEL_REQUESTS.state, () => rt.panelState()),
73
+ panels.handle(PANEL_REQUESTS.refresh, () => rt.refresh()),
74
+ panels.handle(PANEL_REQUESTS.start, () => rt.start()),
75
+ panels.handle(PANEL_REQUESTS.policyMode, (input) =>
76
+ isPolicyModeInput(input) ? rt.applyMode(input) : REJECTED,
77
+ ),
78
+ panels.handle(PANEL_REQUESTS.engine, (input) =>
79
+ isEngineInput(input) ? rt.loadEngine(input) : REJECTED,
80
+ ),
81
+ panels.handle(PANEL_REQUESTS.stats, () => rt.stats()),
82
+ ];
83
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * What the local-decider panel and the worker say to each other (`plugin.request`, `orca.panels`).
3
+ * Plain types and guards only, so the panel can import it. A token never appears here.
4
+ */
5
+ import type { GatewayHealth, PolicyMode } from './gateway.ts';
6
+ import type { AskAction, GateMode, RoutingSetting, TurnOutcomeSetting } from './settings.ts';
7
+ import type { Health } from './status.ts';
8
+
9
+ export const PANEL_REQUESTS = {
10
+ state: 'ld.state',
11
+ refresh: 'ld.refresh',
12
+ start: 'ld.start',
13
+ policyMode: 'ld.policy-mode',
14
+ engine: 'ld.engine',
15
+ stats: 'ld.stats',
16
+ } as const;
17
+
18
+ /** Posted by the worker whenever the status changes; the payload is a `PanelState`. */
19
+ export const PANEL_CHANGED = 'ld.changed';
20
+
21
+ export type ControlState = 'ok' | 'no-token' | 'remote';
22
+
23
+ export interface PanelState {
24
+ readonly health: Health;
25
+ readonly mode: GateMode;
26
+ readonly askAction: AskAction;
27
+ readonly gatewayMode: PolicyMode | 'unknown';
28
+ /** The gateway's `routing` mode: act applies routes to launches, shadow only records them. */
29
+ readonly routingMode: PolicyMode | 'unknown';
30
+ /** The gateway's `turn-outcome` mode: act shows notifications, shadow only records decisions. */
31
+ readonly turnOutcomeMode: PolicyMode | 'unknown';
32
+ readonly url: string;
33
+ readonly transport: 'socket' | 'tcp';
34
+ readonly control: ControlState;
35
+ readonly gateway?: GatewayHealth;
36
+ readonly lastDecision?: string;
37
+ /** What routing did with the last agent launch. */
38
+ readonly lastRoute?: string;
39
+ readonly launch?: string;
40
+ /** Launched Claude Code agents from which no agent status arrived (their hooks are hidden). */
41
+ readonly hooksMissing?: number;
42
+ readonly settings: {
43
+ readonly timeoutMs: number;
44
+ readonly autoStart: boolean;
45
+ readonly preloadModel: boolean;
46
+ readonly routing: RoutingSetting;
47
+ readonly turnOutcome: TurnOutcomeSetting;
48
+ };
49
+ }
50
+
51
+ /** The `command-risk` row of `GET /v1/stats`, cut down to what the panel shows. */
52
+ export interface CommandRiskStats {
53
+ readonly decisions: number;
54
+ readonly enforced: number;
55
+ readonly actions: Readonly<Record<string, number>>;
56
+ readonly errors: number;
57
+ /** Decisions the gateway turned away because it was busy; 0 when the gateway does not say. */
58
+ readonly busy: number;
59
+ readonly p50Ms?: number;
60
+ readonly p95Ms?: number;
61
+ }
62
+
63
+ export interface ActionResult {
64
+ readonly ok: boolean;
65
+ readonly message: string;
66
+ }
67
+
68
+ export interface PolicyModeInput {
69
+ readonly mode: PolicyMode;
70
+ }
71
+
72
+ export interface EngineInput {
73
+ readonly action: 'load' | 'unload';
74
+ }
75
+
76
+ function isRecord(x: unknown): x is Record<string, unknown> {
77
+ return typeof x === 'object' && x !== null && !Array.isArray(x);
78
+ }
79
+
80
+ export function isPolicyModeInput(x: unknown): x is PolicyModeInput {
81
+ return isRecord(x) && (x['mode'] === 'off' || x['mode'] === 'shadow' || x['mode'] === 'act');
82
+ }
83
+
84
+ export function isEngineInput(x: unknown): x is EngineInput {
85
+ return isRecord(x) && (x['action'] === 'load' || x['action'] === 'unload');
86
+ }
package/src/routing.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { createBreaker } from './breaker.ts';
2
+ import { projectLabel } from './core/permission-input.ts';
3
+ /**
4
+ * `agent.launch.before` → the gateway's `routing` policy: pick the model (and reasoning effort)
5
+ * an agent Orca is about to start gets, from its launch prompt. The gateway maps the chosen
6
+ * `route:<preset>` through config.yaml `routing.presets.orca`, whose `model` is `<agent>/<model>`
7
+ * (`claude/sonnet`, `codex/gpt-6.1-sol`), whose optional `models` add more `<agent>/<model>`
8
+ * entries (so one preset can route both agents) and whose `thinking` becomes the reasoning effort.
9
+ *
10
+ * Fail-open like Paseo's routing: Orca waits at most 2 s for a hook, so a route is applied only
11
+ * when the gateway's `routing` policy is in act mode and answers within `ROUTE_BUDGET_MS`. In
12
+ * shadow (or an unknown mode) the decision is recorded without holding up the launch. A route only
13
+ * changes the model and the effort: a preset's `mode` and `profile` are ignored, so a route can
14
+ * never change the agent's permissions, and a launch takes the first entry for its own agent (a
15
+ * preset with none for it is skipped). After a reply
16
+ * that is not a decision, act routing is skipped for `BREAKER_MS` so launches are not slowed.
17
+ */
18
+ import { cutText } from './core/truncate.ts';
19
+ import {
20
+ isDecision,
21
+ type DecideBody,
22
+ type DecideReply,
23
+ type Decision,
24
+ type GatewayClient,
25
+ type PolicyMode,
26
+ } from './gateway.ts';
27
+ import {
28
+ isSafeValue,
29
+ joinCommand,
30
+ modelOf,
31
+ parseLaunch,
32
+ promptOf,
33
+ routableAgent,
34
+ withEffort,
35
+ withModel,
36
+ type Launch,
37
+ } from './launch-command.ts';
38
+ import type { LaunchBeforeEvent } from './orca-types.ts';
39
+ import type { Settings } from './settings.ts';
40
+
41
+ export const ROUTING_POLICY = 'routing';
42
+ /** Orca stops waiting for one plugin's hook after 2 s. Counted from the start of `route`. */
43
+ export const ROUTE_BUDGET_MS = 1800;
44
+ /** Below this the gateway cannot decide in time, so the call is not sent. */
45
+ const MIN_DECIDE_MS = 300;
46
+ const CWD_TIMEOUT_MS = 200;
47
+ /** A shadow decision holds nothing up, so it may take as long as a cold model needs. */
48
+ const SHADOW_TIMEOUT_MS = 30_000;
49
+ const PROMPT_CHARS = 6000;
50
+
51
+ export interface RouterDeps {
52
+ readonly settings: () => Settings;
53
+ readonly gateway: () => GatewayClient;
54
+ readonly cwdFor: (workspaceId: string | null, timeoutMs: number) => Promise<string | undefined>;
55
+ /** The gateway's `routing` mode, as last read; decides whether the launch waits. */
56
+ readonly routingMode: () => PolicyMode | 'unknown';
57
+ readonly now: () => number;
58
+ /** Told what routing did with one launch, for the panel and the log. Never holds the prompt. */
59
+ readonly onRoute?: (note: string) => void;
60
+ /** Told what the gateway answered to an act-mode route (a decision, a refusal, or null). */
61
+ readonly onReply?: (reply: DecideReply) => void;
62
+ }
63
+
64
+ export interface Router {
65
+ /** The new command, or undefined to launch unchanged. Never throws. */
66
+ route(event: LaunchBeforeEvent): Promise<string | undefined>;
67
+ }
68
+
69
+ /** What a preset sends this launch to; `effort` is unset when the preset sets no thinking. */
70
+ export interface LaunchTarget {
71
+ readonly model: string;
72
+ readonly effort?: string;
73
+ }
74
+
75
+ function str(value: unknown): string | undefined {
76
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
77
+ }
78
+
79
+ /** The `<agent>/<model>` entries of a route: `model`, then `models`; non-strings are dropped. */
80
+ function entriesOf(r: Record<string, unknown>): string[] {
81
+ const extra = Array.isArray(r['models']) ? (r['models'] as unknown[]) : [];
82
+ return [r['model'], ...extra].flatMap((v) => {
83
+ const entry = str(v);
84
+ return entry === undefined ? [] : [entry];
85
+ });
86
+ }
87
+
88
+ /**
89
+ * The target in the gateway's `route`, for `agent`; a string says why there is none. The first of
90
+ * `model`, then `models`, whose agent prefix is `agent` is used. An entry without an agent prefix
91
+ * is refused when nothing else matches: routing never switches the CLI.
92
+ */
93
+ export function targetFor(route: unknown, agent: string): LaunchTarget | string {
94
+ if (typeof route !== 'object' || route === null) return 'no preset is mapped';
95
+ const r = route as Record<string, unknown>;
96
+ const entries = entriesOf(r);
97
+ if (entries.length === 0) return 'the preset sets no model';
98
+ const own = entries.find((e) => e.indexOf('/') !== -1 && e.slice(0, e.indexOf('/')) === agent);
99
+ if (own === undefined) {
100
+ const bare = entries.find((e) => !e.includes('/'));
101
+ if (bare !== undefined) return `preset model ${bare} names no agent (use ${agent}/${bare})`;
102
+ const agents = [...new Set(entries.map((e) => e.slice(0, e.indexOf('/'))))];
103
+ return `preset is for ${agents.join(', ')}`;
104
+ }
105
+ const id = own.slice(own.indexOf('/') + 1);
106
+ const effort = str(r['thinking']);
107
+ if (!isSafeValue(id) || (effort !== undefined && !isSafeValue(effort))) {
108
+ return 'preset model or thinking has unsupported characters';
109
+ }
110
+ return effort === undefined ? { model: id } : { model: id, effort };
111
+ }
112
+
113
+ function applyTarget(launch: Launch, target: LaunchTarget): string {
114
+ const routed = withModel(launch, target.model);
115
+ return joinCommand(
116
+ (target.effort === undefined ? routed : withEffort(routed, target.effort)).words,
117
+ );
118
+ }
119
+
120
+ function routeBody(event: LaunchBeforeEvent, launch: Launch, cwd: string | undefined): DecideBody {
121
+ const model = modelOf(launch);
122
+ return {
123
+ harness: 'orca',
124
+ ...(event.terminalId === undefined ? {} : { sessionId: event.terminalId }),
125
+ input: {
126
+ ...(cwd === undefined ? {} : { project: projectLabel(cwd) }),
127
+ prompt: cutText(promptOf(launch), PROMPT_CHARS, 'ends'),
128
+ },
129
+ ...(cwd === undefined ? {} : { workspace: { cwd } }),
130
+ ...(model === undefined ? {} : { models: { requested: `${launch.agent}/${model}` } }),
131
+ };
132
+ }
133
+
134
+ /** Whether an act-mode decision may change the launch. */
135
+ function enforced(reply: Decision): boolean {
136
+ return reply.enforced && reply.mode === 'act' && reply.error === undefined;
137
+ }
138
+
139
+ export function createRouter(deps: RouterDeps): Router {
140
+ const breaker = createBreaker(deps.now);
141
+
142
+ function note(text: string): undefined {
143
+ deps.onRoute?.(text);
144
+ return undefined;
145
+ }
146
+
147
+ /** Record the decision without waiting: nothing will be applied. */
148
+ function shadow(body: DecideBody): undefined {
149
+ void deps
150
+ .gateway()
151
+ .decide(ROUTING_POLICY, body, SHADOW_TIMEOUT_MS)
152
+ .then((reply) => {
153
+ if (isDecision(reply)) note(`${reply.action} (shadow, not applied)`);
154
+ })
155
+ .catch(() => {});
156
+ return undefined;
157
+ }
158
+
159
+ async function act(
160
+ body: DecideBody,
161
+ launch: Launch,
162
+ started: number,
163
+ ): Promise<string | undefined> {
164
+ const left = ROUTE_BUDGET_MS - (deps.now() - started);
165
+ if (left < MIN_DECIDE_MS) return note('skipped: no time left to decide');
166
+ const reply = await deps.gateway().decide(ROUTING_POLICY, body, left);
167
+ if (!isDecision(reply)) breaker.trip();
168
+ deps.onReply?.(reply);
169
+ if (!isDecision(reply)) return note('skipped: the gateway did not answer in time');
170
+ if (!enforced(reply)) return note(`${reply.action} (not enforced)`);
171
+ if (!reply.action.startsWith('route:')) return note(`${reply.action}: no route chosen`);
172
+ const target = targetFor(reply.route, launch.agent);
173
+ if (typeof target === 'string') return note(`${reply.action}: ${target}`);
174
+ const effort = target.effort === undefined ? '' : `, effort ${target.effort}`;
175
+ note(`${reply.action} → ${launch.agent}/${target.model}${effort}`);
176
+ return applyTarget(launch, target);
177
+ }
178
+
179
+ async function route(event: LaunchBeforeEvent): Promise<string | undefined> {
180
+ const settings = deps.settings();
181
+ if (settings.mode === 'off' || settings.routing === 'off') return undefined;
182
+ const agent = routableAgent(event.agent);
183
+ const launch = agent === null ? null : parseLaunch(agent, event.command);
184
+ const mode = deps.routingMode();
185
+ if (launch === null || mode === 'off') return undefined;
186
+ const started = deps.now();
187
+ if (mode === 'act' && breaker.isOpen(started)) {
188
+ return note('skipped: the gateway failed a recent decision');
189
+ }
190
+ const cwd = await deps.cwdFor(event.workspaceId, CWD_TIMEOUT_MS);
191
+ const body = routeBody(event, launch, cwd);
192
+ return mode === 'act' ? act(body, launch, started) : shadow(body);
193
+ }
194
+
195
+ return {
196
+ async route(event) {
197
+ try {
198
+ return await route(event);
199
+ } catch {
200
+ return undefined;
201
+ }
202
+ },
203
+ };
204
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The `terminal.send` decision. Orca fires the hook when Orca, its CLI or a plugin is about to type
3
+ * text into a terminal (a person typing is never hooked). Text that would run as a shell command
4
+ * is checked against the deterministic guard only; no model is asked. Text for an agent's own TUI
5
+ * is a prompt, not a command, and other hooks cover it. Any failure passes.
6
+ */
7
+ import { guardHit, guardResult, type DenyResult } from './guard-result.ts';
8
+ import type { TerminalSendEvent } from './orca-types.ts';
9
+ import type { Settings } from './settings.ts';
10
+
11
+ export interface SendGuardDeps {
12
+ readonly settings: () => Settings;
13
+ /** True for a terminal an agent still runs in. */
14
+ readonly isAgentTerminal: (terminalId: string) => Promise<boolean>;
15
+ }
16
+
17
+ export interface SendGuard {
18
+ check(event: TerminalSendEvent): Promise<DenyResult>;
19
+ }
20
+
21
+ /** Text typed by Orca on someone's behalf runs when it is submitted, or holds a line break. */
22
+ function isChecked(event: TerminalSendEvent): boolean {
23
+ if (event.inputKind !== 'driving') return false;
24
+ return event.enter || (typeof event.text === 'string' && /[\r\n]/.test(event.text));
25
+ }
26
+
27
+ export function createSendGuard(deps: SendGuardDeps): SendGuard {
28
+ return {
29
+ async check(event) {
30
+ try {
31
+ const settings = deps.settings();
32
+ if (settings.mode === 'off' || !isChecked(event)) return undefined;
33
+ if (typeof event.text !== 'string' || (await deps.isAgentTerminal(event.terminalId))) {
34
+ return undefined;
35
+ }
36
+ const hit = guardHit(event.text);
37
+ return hit === null ? undefined : guardResult(hit, settings);
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ },
42
+ };
43
+ }