@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.
- package/CHANGELOG.md +26 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +346 -1
- package/images/cover.png +0 -0
- package/images/icon.png +0 -0
- package/orca-plugin.json +218 -0
- package/package.json +45 -5
- package/src/agent-terminals.ts +88 -0
- package/src/bounded.ts +22 -0
- package/src/breaker.ts +28 -0
- package/src/core/canonical.ts +24 -0
- package/src/core/guard.ts +503 -0
- package/src/core/ids.ts +2 -0
- package/src/core/input-cap.ts +71 -0
- package/src/core/permission-input.ts +42 -0
- package/src/core/shell.ts +586 -0
- package/src/core/subject.ts +244 -0
- package/src/core/truncate.ts +203 -0
- package/src/gate.ts +155 -0
- package/src/gateway.ts +289 -0
- package/src/guard-result.ts +28 -0
- package/src/hook-watch.ts +76 -0
- package/src/launch-command.ts +274 -0
- package/src/launcher/launch.ts +892 -0
- package/src/launcher/local-token.ts +26 -0
- package/src/launcher/socket-path.ts +24 -0
- package/src/launcher/transport.ts +141 -0
- package/src/orca-types.ts +107 -0
- package/src/panel/model.ts +205 -0
- package/src/panel/orca-panel.d.ts +90 -0
- package/src/panel/panel.tsx +278 -0
- package/src/panel-api.ts +83 -0
- package/src/panel-protocol.ts +86 -0
- package/src/routing.ts +204 -0
- package/src/send-guard.ts +43 -0
- package/src/settings.ts +82 -0
- package/src/status.ts +146 -0
- package/src/turn-key.ts +13 -0
- package/src/turn-outcome.ts +199 -0
- package/src/worker.ts +521 -0
- package/src/workspaces.ts +87 -0
- package/src/wrapper-env.ts +19 -0
package/src/settings.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's settings, as declared in `orca-plugin.json` `contributes.settings`. Orca checks the
|
|
3
|
+
* declared types, but a value is still parsed defensively: anything unusable falls back to its
|
|
4
|
+
* default. The token is never a setting; it comes from `LOCAL_DECIDER_TOKEN`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type GateMode = 'off' | 'guard';
|
|
8
|
+
/** When the status bar item shows: only on a problem, always (an icon), or never. */
|
|
9
|
+
export type StatusBarDisplay = 'problems' | 'always' | 'off';
|
|
10
|
+
/** What the plugin does when the guard or the model says "ask the person". */
|
|
11
|
+
export type AskAction = 'pass' | 'deny';
|
|
12
|
+
/** Whether agent launches are sent to the gateway's `routing` policy. */
|
|
13
|
+
export type RoutingSetting = 'on' | 'off';
|
|
14
|
+
/** Whether the end of an agent's turn is sent to the gateway's `turn-outcome` policy. */
|
|
15
|
+
export type TurnOutcomeSetting = 'on' | 'off';
|
|
16
|
+
|
|
17
|
+
export interface Settings {
|
|
18
|
+
readonly mode: GateMode;
|
|
19
|
+
readonly askAction: AskAction;
|
|
20
|
+
readonly routing: RoutingSetting;
|
|
21
|
+
readonly turnOutcome: TurnOutcomeSetting;
|
|
22
|
+
readonly statusBar: StatusBarDisplay;
|
|
23
|
+
/** Gateway base URL. */
|
|
24
|
+
readonly url: string;
|
|
25
|
+
/** True when no URL was set, so the gateway's local socket may be used. */
|
|
26
|
+
readonly defaultEndpoint: boolean;
|
|
27
|
+
/** Time the gateway gets for one decision; Orca stops waiting for a hook after 2 s. */
|
|
28
|
+
readonly timeoutMs: number;
|
|
29
|
+
readonly autoStart: boolean;
|
|
30
|
+
/** Load the gateway's model when the plugin starts, so the first decision is not cold. */
|
|
31
|
+
readonly preloadModel: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_URL = 'http://127.0.0.1:8765';
|
|
35
|
+
const MIN_TIMEOUT_MS = 200;
|
|
36
|
+
const MAX_TIMEOUT_MS = 1700;
|
|
37
|
+
const DEFAULT_TIMEOUT_MS = 1500;
|
|
38
|
+
|
|
39
|
+
export const DEFAULT_SETTINGS: Settings = {
|
|
40
|
+
mode: 'guard',
|
|
41
|
+
askAction: 'pass',
|
|
42
|
+
routing: 'on',
|
|
43
|
+
turnOutcome: 'on',
|
|
44
|
+
statusBar: 'problems',
|
|
45
|
+
url: DEFAULT_URL,
|
|
46
|
+
defaultEndpoint: true,
|
|
47
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
48
|
+
autoStart: true,
|
|
49
|
+
preloadModel: false,
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function pick<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
|
|
53
|
+
return allowed.find((a) => a === value) ?? fallback;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function timeoutOf(value: unknown): number {
|
|
57
|
+
return typeof value === 'number' &&
|
|
58
|
+
Number.isInteger(value) &&
|
|
59
|
+
value >= MIN_TIMEOUT_MS &&
|
|
60
|
+
value <= MAX_TIMEOUT_MS
|
|
61
|
+
? value
|
|
62
|
+
: DEFAULT_TIMEOUT_MS;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Settings from what `orca.settings.get()` returned; never throws. */
|
|
66
|
+
export function parseSettings(raw: unknown): Settings {
|
|
67
|
+
const values: Record<string, unknown> =
|
|
68
|
+
typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {};
|
|
69
|
+
const url = typeof values['gatewayUrl'] === 'string' ? values['gatewayUrl'].trim() : '';
|
|
70
|
+
return {
|
|
71
|
+
mode: pick(values['mode'], ['off', 'guard'], DEFAULT_SETTINGS.mode),
|
|
72
|
+
askAction: pick(values['askAction'], ['pass', 'deny'], DEFAULT_SETTINGS.askAction),
|
|
73
|
+
routing: pick(values['routing'], ['on', 'off'], DEFAULT_SETTINGS.routing),
|
|
74
|
+
turnOutcome: pick(values['turnOutcome'], ['on', 'off'], DEFAULT_SETTINGS.turnOutcome),
|
|
75
|
+
statusBar: pick(values['statusBar'], ['problems', 'always', 'off'], DEFAULT_SETTINGS.statusBar),
|
|
76
|
+
url: url === '' ? DEFAULT_URL : url,
|
|
77
|
+
defaultEndpoint: url === '',
|
|
78
|
+
timeoutMs: timeoutOf(values['timeoutMs']),
|
|
79
|
+
autoStart: typeof values['autoStart'] === 'boolean' ? values['autoStart'] : true,
|
|
80
|
+
preloadModel: values['preloadModel'] === true,
|
|
81
|
+
};
|
|
82
|
+
}
|
package/src/status.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/** The status bar item's text, tone and tooltip, and the `local-decider.status` command's text. */
|
|
2
|
+
import type { DecideReply, GatewayHealth, PolicyMode } from './gateway.ts';
|
|
3
|
+
import type { GateMode, StatusBarDisplay } from './settings.ts';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `/health` status, `offline` when the gateway did not answer, `rejected` when it answers but
|
|
7
|
+
* refuses decide calls, `unknown` before the first check.
|
|
8
|
+
*/
|
|
9
|
+
export type Health = 'ok' | 'degraded' | 'down' | 'offline' | 'rejected' | 'unknown';
|
|
10
|
+
export type Tone = 'neutral' | 'accent' | 'success' | 'warning' | 'danger';
|
|
11
|
+
|
|
12
|
+
export interface StatusView {
|
|
13
|
+
readonly text: string;
|
|
14
|
+
readonly tone: Tone;
|
|
15
|
+
readonly tooltip: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface StatusState {
|
|
19
|
+
readonly mode: GateMode;
|
|
20
|
+
readonly health: Health;
|
|
21
|
+
readonly url: string;
|
|
22
|
+
readonly gatewayMode: PolicyMode | 'unknown';
|
|
23
|
+
readonly gateway?: GatewayHealth | undefined;
|
|
24
|
+
readonly lastDecision?: string | undefined;
|
|
25
|
+
readonly launch?: string | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function healthOf(status: string | null): Health {
|
|
29
|
+
if (status === null) return 'offline';
|
|
30
|
+
return status === 'ok' || status === 'degraded' || status === 'down' ? status : 'degraded';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const TONES: Readonly<Record<Health, Tone>> = {
|
|
34
|
+
ok: 'success',
|
|
35
|
+
degraded: 'warning',
|
|
36
|
+
down: 'danger',
|
|
37
|
+
offline: 'warning',
|
|
38
|
+
rejected: 'warning',
|
|
39
|
+
unknown: 'neutral',
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** The health a decide reply shows. A decision clears offline and rejected. */
|
|
43
|
+
export function replyHealth(reply: DecideReply, current: Health): Health {
|
|
44
|
+
if (reply === null) return 'offline';
|
|
45
|
+
if ('rejected' in reply) return 'rejected';
|
|
46
|
+
return current === 'offline' || current === 'rejected' ? 'ok' : current;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `/health` cannot see a refusal, so a poll that reaches the gateway keeps `rejected`. */
|
|
50
|
+
export function polledHealth(polled: Health, current: Health): Health {
|
|
51
|
+
return current === 'rejected' && polled !== 'offline' ? 'rejected' : polled;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What the gateway's command-risk mode means for a call. */
|
|
55
|
+
export function modeMeaning(mode: PolicyMode | 'unknown'): string {
|
|
56
|
+
switch (mode) {
|
|
57
|
+
case 'act':
|
|
58
|
+
return 'model refuses risky calls';
|
|
59
|
+
case 'shadow':
|
|
60
|
+
return 'model only records';
|
|
61
|
+
case 'off':
|
|
62
|
+
return 'model off';
|
|
63
|
+
default:
|
|
64
|
+
return 'unknown';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function tooltipOf(state: StatusState): string {
|
|
69
|
+
if (state.mode === 'off') return 'local-decider: off';
|
|
70
|
+
if (state.health === 'rejected') {
|
|
71
|
+
return `local-decider: the gateway refuses this plugin's calls; only the guard is active. Run "local-decider: Show status".`;
|
|
72
|
+
}
|
|
73
|
+
if (state.health === 'ok') {
|
|
74
|
+
return `local-decider: guard on; command-risk in ${state.gatewayMode} (${modeMeaning(state.gatewayMode)})`;
|
|
75
|
+
}
|
|
76
|
+
return `local-decider: guarding Claude Code tool calls, gateway ${state.health}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function labelOf(state: StatusState): string {
|
|
80
|
+
if (state.mode === 'off') return state.mode;
|
|
81
|
+
if (state.health === 'ok') return state.gatewayMode === 'act' ? 'guard+model' : state.mode;
|
|
82
|
+
return state.health === 'unknown' ? state.mode : state.health;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A health the person should look at; `unknown` (before the first check) is not one. */
|
|
86
|
+
export function isProblem(health: Health): boolean {
|
|
87
|
+
return (
|
|
88
|
+
health === 'degraded' || health === 'offline' || health === 'rejected' || health === 'down'
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function statusView(state: StatusState): StatusView {
|
|
93
|
+
const off = state.mode === 'off';
|
|
94
|
+
return {
|
|
95
|
+
text: `ld: ${labelOf(state)}`,
|
|
96
|
+
tone: off ? 'neutral' : TONES[state.health],
|
|
97
|
+
tooltip: tooltipOf(state),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The `statusBar.update` params for `display`: hidden, an icon alone (accent while the
|
|
102
|
+
* model enforces, else the health tone), or the icon and text. Plugin mode `off` is always hidden. */
|
|
103
|
+
export function statusParams(
|
|
104
|
+
id: string,
|
|
105
|
+
state: StatusState,
|
|
106
|
+
display: StatusBarDisplay,
|
|
107
|
+
): Record<string, unknown> {
|
|
108
|
+
if (display === 'off' || state.mode === 'off') return { id, visible: false };
|
|
109
|
+
const problem = isProblem(state.health);
|
|
110
|
+
if (display === 'problems' && !problem) return { id, visible: false };
|
|
111
|
+
const view = statusView(state);
|
|
112
|
+
const enforcing = state.health === 'ok' && state.gatewayMode === 'act';
|
|
113
|
+
const tone = enforcing ? 'accent' : view.tone;
|
|
114
|
+
return { id, icon: 'zap', ...view, tone, text: problem ? view.text : '', visible: true };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const REJECTED_HINT =
|
|
118
|
+
'hint: the gateway refused the call. The orca harness needs a gateway released after ' +
|
|
119
|
+
'3.4.0 (update it, then local-decider gateway ensure); HTTP 401 or 403 means check ' +
|
|
120
|
+
'LOCAL_DECIDER_TOKEN and the gateway URL.';
|
|
121
|
+
|
|
122
|
+
const SHADOW_HINT =
|
|
123
|
+
"hint: the model's verdicts are only recorded; switch with the panel or `local-decider: Enforce command-risk`.";
|
|
124
|
+
|
|
125
|
+
function engineLine(gateway: GatewayHealth | undefined): string | undefined {
|
|
126
|
+
if (gateway?.engine === undefined && gateway?.model === undefined) return undefined;
|
|
127
|
+
const state = gateway.engineState === undefined ? '' : ` (${gateway.engineState})`;
|
|
128
|
+
return `engine: ${gateway.engine ?? '?'} · ${gateway.model ?? '?'}${state}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A few lines for the status command; never includes the token. */
|
|
132
|
+
export function statusReport(state: StatusState): string {
|
|
133
|
+
const lines = [
|
|
134
|
+
`local-decider mode: ${state.mode}`,
|
|
135
|
+
`gateway: ${state.url} (${state.health})`,
|
|
136
|
+
`last decision: ${state.lastDecision ?? 'none yet'}`,
|
|
137
|
+
`command-risk: ${state.gatewayMode}`,
|
|
138
|
+
];
|
|
139
|
+
const engine = engineLine(state.gateway);
|
|
140
|
+
if (engine !== undefined) lines.push(engine);
|
|
141
|
+
if (state.mode !== 'off' && state.gatewayMode === 'shadow') lines.push(SHADOW_HINT);
|
|
142
|
+
if (state.health === 'rejected') lines.push(REJECTED_HINT);
|
|
143
|
+
if (state.launch !== undefined) lines.push(`last start: ${state.launch}`);
|
|
144
|
+
lines.push('panel: open the local-decider panel in the right sidebar to change the gateway.');
|
|
145
|
+
return lines.join('\n');
|
|
146
|
+
}
|
package/src/turn-key.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const MAX_PANE_KEY_CHARS = 512;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The turn key for an Orca pane (`DecideRequest.turn.key`): a hash of its pane key, so the hooks
|
|
7
|
+
* and the Orca plugin name one agent turn the same way. `undefined` for an empty or overlong
|
|
8
|
+
* value. `packages/core/src/turn-key.ts` holds an identical copy (the plugin cannot import core); both tests pin the output.
|
|
9
|
+
*/
|
|
10
|
+
export function turnKeyOfPane(paneKey: string): string | undefined {
|
|
11
|
+
if (paneKey === '' || paneKey.length > MAX_PANE_KEY_CHARS) return undefined;
|
|
12
|
+
return `orca-pane-${createHash('sha256').update(paneKey).digest('hex').slice(0, 40)}`;
|
|
13
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent.status.changed` → the gateway's `turn-outcome` policy: when an agent in an Orca terminal
|
|
3
|
+
* ends its turn (working → done or waiting), read the end of the terminal, ask whether the turn
|
|
4
|
+
* is done, needs input, is stuck or failed, and, when the decision is enforced and says `notify`,
|
|
5
|
+
* show an Orca notification.
|
|
6
|
+
*
|
|
7
|
+
* Nothing waits on it and it never throws. The terminal text goes only to the gateway (which
|
|
8
|
+
* redacts it before the engine); it never reaches a notification or a log line. The notification
|
|
9
|
+
* carries the answer, the agent's title and the decision's reason.
|
|
10
|
+
*/
|
|
11
|
+
import { setBounded } from './bounded.ts';
|
|
12
|
+
import { cutText } from './core/truncate.ts';
|
|
13
|
+
import { isDecision, type DecideBody, type Decision, type GatewayClient } from './gateway.ts';
|
|
14
|
+
import type { AgentStatusEvent } from './orca-types.ts';
|
|
15
|
+
import type { Settings } from './settings.ts';
|
|
16
|
+
import { turnKeyOfPane } from './turn-key.ts';
|
|
17
|
+
import type { HostCall } from './workspaces.ts';
|
|
18
|
+
|
|
19
|
+
export const TURN_POLICY = 'turn-outcome';
|
|
20
|
+
/** Lines read from the terminal. */
|
|
21
|
+
const READ_LINES = 200;
|
|
22
|
+
/** Lines of those that make up the final message. */
|
|
23
|
+
const LAST_LINES = 40;
|
|
24
|
+
const HISTORY_CHARS = 12_000;
|
|
25
|
+
const LAST_CHARS = 3000;
|
|
26
|
+
const REASON_CHARS = 200;
|
|
27
|
+
const TITLE_CHARS = 80;
|
|
28
|
+
/** The gateway may need a cold model; nothing waits on it. */
|
|
29
|
+
const DECIDE_TIMEOUT_MS = 10_000;
|
|
30
|
+
const CWD_TIMEOUT_MS = 200;
|
|
31
|
+
/** At most one decision per terminal in this time. */
|
|
32
|
+
export const COOLDOWN_MS = 30_000;
|
|
33
|
+
/**
|
|
34
|
+
* Wait this long after a turn ends before deciding, so the Claude Code or Codex `Stop` hook of the
|
|
35
|
+
* same pane usually decides first and this notification reuses its answer.
|
|
36
|
+
*/
|
|
37
|
+
export const TURN_SHARE_DELAY_MS = 1500;
|
|
38
|
+
/** Outcomes where the person stopped the agent: nothing to tell them. */
|
|
39
|
+
const STOPPED = new Set(['cancellation', 'superseded', 'interruption']);
|
|
40
|
+
const ANSI = new RegExp(
|
|
41
|
+
String.raw`\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[@-Z\\-_])`,
|
|
42
|
+
'g',
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
export interface TurnWatcherDeps {
|
|
46
|
+
readonly settings: () => Settings;
|
|
47
|
+
readonly gateway: () => GatewayClient;
|
|
48
|
+
readonly cwdFor: (workspaceId: string | null, timeoutMs: number) => Promise<string | undefined>;
|
|
49
|
+
/** Orca host call: `terminal.read` and `notifications.show`. */
|
|
50
|
+
readonly call: HostCall;
|
|
51
|
+
readonly now: () => number;
|
|
52
|
+
/** Resolves after `ms`; defaults to a timer. Tests inject their own. */
|
|
53
|
+
readonly delay?: (ms: number) => Promise<void>;
|
|
54
|
+
/** Told what one turn came to, for the log. Never holds terminal text. */
|
|
55
|
+
readonly onOutcome?: (note: string) => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface TurnWatcher {
|
|
59
|
+
/** Feed one `agent.status.changed`. Returns at once; never throws. */
|
|
60
|
+
onStatus(event: AgentStatusEvent): void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function sleep(ms: number): Promise<void> {
|
|
64
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function str(value: unknown): string | undefined {
|
|
68
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The terminal's lines as `terminal.read` returned them, without escape sequences. */
|
|
72
|
+
function linesOf(reply: unknown): string[] | undefined {
|
|
73
|
+
const lines = (reply as { lines?: unknown } | null)?.lines;
|
|
74
|
+
if (!Array.isArray(lines) || !lines.every((l) => typeof l === 'string')) return undefined;
|
|
75
|
+
return lines.map((l: string) => l.replace(ANSI, '').trimEnd());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The decision body: the end of the terminal as `history`, its last lines as `lastMessage`. */
|
|
79
|
+
function turnBody(
|
|
80
|
+
terminalId: string,
|
|
81
|
+
lines: readonly string[],
|
|
82
|
+
cwd: string | undefined,
|
|
83
|
+
paneKey: string | undefined,
|
|
84
|
+
): DecideBody {
|
|
85
|
+
const key = paneKey === undefined ? undefined : turnKeyOfPane(paneKey);
|
|
86
|
+
return {
|
|
87
|
+
harness: 'orca',
|
|
88
|
+
sessionId: terminalId,
|
|
89
|
+
input: {
|
|
90
|
+
history: cutText(lines.join('\n').trim(), HISTORY_CHARS, 'tail'),
|
|
91
|
+
lastMessage: cutText(lines.slice(-LAST_LINES).join('\n').trim(), LAST_CHARS, 'tail'),
|
|
92
|
+
},
|
|
93
|
+
...(cwd === undefined ? {} : { workspace: { cwd } }),
|
|
94
|
+
...(key === undefined ? {} : { turn: { key } }),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The `outcome` answer: `done`, `needs_input`, `stuck`, `failed`. */
|
|
99
|
+
function answerOf(reply: Decision): string | undefined {
|
|
100
|
+
return str((reply.answers['outcome'] as { answer?: unknown } | undefined)?.answer);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const FALLBACK_BODY: Readonly<Record<string, string>> = {
|
|
104
|
+
needs_input: 'The agent is waiting for your input.',
|
|
105
|
+
stuck: 'The agent looks stuck.',
|
|
106
|
+
failed: 'The agent reports a failure.',
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* One line for the notification: the decision's reason when the gateway sends one (its response
|
|
111
|
+
* has no such field today), else a fixed sentence for the answer. Never terminal text.
|
|
112
|
+
*/
|
|
113
|
+
function bodyOf(reply: Decision, answer: string): string {
|
|
114
|
+
const reason = str((reply as { reason?: unknown }).reason);
|
|
115
|
+
return reason === undefined
|
|
116
|
+
? (FALLBACK_BODY[answer] ?? 'This turn needs your attention.')
|
|
117
|
+
: cutText(reason.replace(/\s+/g, ' '), REASON_CHARS, 'head');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isNotify(reply: Decision): boolean {
|
|
121
|
+
return reply.enforced && reply.mode === 'act' && reply.action === 'notify';
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function createTurnWatcher(deps: TurnWatcherDeps): TurnWatcher {
|
|
125
|
+
const lastState = new Map<string, string>();
|
|
126
|
+
const lastAsked = new Map<string, number>();
|
|
127
|
+
|
|
128
|
+
function enabled(): boolean {
|
|
129
|
+
const settings = deps.settings();
|
|
130
|
+
return settings.mode !== 'off' && settings.turnOutcome !== 'off';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** True when this event is a turn ending that is worth a decision; records the state either way. */
|
|
134
|
+
function turnEnded(event: AgentStatusEvent): event is AgentStatusEvent & { terminalId: string } {
|
|
135
|
+
const key = str(event.paneKey) ?? str(event.terminalId);
|
|
136
|
+
const state = str(event.state);
|
|
137
|
+
if (key === undefined || state === undefined) return false;
|
|
138
|
+
const before = lastState.get(key);
|
|
139
|
+
setBounded(lastState, key, state);
|
|
140
|
+
if (before !== 'working' || (state !== 'done' && state !== 'waiting')) return false;
|
|
141
|
+
const outcome = event.mainAgent?.outcome;
|
|
142
|
+
return str(event.terminalId) !== undefined && !(outcome !== undefined && STOPPED.has(outcome));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** True while the terminal's last decision is within the cooldown. */
|
|
146
|
+
function cooling(terminalId: string): boolean {
|
|
147
|
+
const last = lastAsked.get(terminalId);
|
|
148
|
+
return last !== undefined && deps.now() - last < COOLDOWN_MS;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function notify(event: AgentStatusEvent, reply: Decision, answer: string): Promise<void> {
|
|
152
|
+
const title = cutText(str(event.title) ?? 'agent', TITLE_CHARS, 'head');
|
|
153
|
+
await deps.call('notifications.show', {
|
|
154
|
+
title: `local-decider: ${title} ${answer.replace(/_/g, ' ')}`,
|
|
155
|
+
body: bodyOf(reply, answer),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function decide(event: AgentStatusEvent, terminalId: string): Promise<void> {
|
|
160
|
+
if (cooling(terminalId)) return;
|
|
161
|
+
const read = await deps.call('terminal.read', { terminalId, maxLines: READ_LINES });
|
|
162
|
+
const lines = linesOf(read);
|
|
163
|
+
if (lines === undefined || lines.every((l) => l === '')) return;
|
|
164
|
+
// Claim the slot before the awaits below, so a second event cannot ask for the same turn.
|
|
165
|
+
if (cooling(terminalId)) return;
|
|
166
|
+
setBounded(lastAsked, terminalId, deps.now());
|
|
167
|
+
const cwd = await deps.cwdFor(event.workspaceId ?? null, CWD_TIMEOUT_MS);
|
|
168
|
+
const reply = await deps
|
|
169
|
+
.gateway()
|
|
170
|
+
.decide(TURN_POLICY, turnBody(terminalId, lines, cwd, str(event.paneKey)), DECIDE_TIMEOUT_MS);
|
|
171
|
+
if (!isDecision(reply)) return;
|
|
172
|
+
const answer = answerOf(reply) ?? 'unknown';
|
|
173
|
+
if (!isNotify(reply)) {
|
|
174
|
+
deps.onOutcome?.(`turn-outcome ${answer} (${reply.mode}, ${reply.action})`);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
await notify(event, reply, answer);
|
|
178
|
+
deps.onOutcome?.(`turn-outcome ${answer} (notified)`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function handle(event: AgentStatusEvent): Promise<void> {
|
|
182
|
+
if (!turnEnded(event) || !enabled()) return;
|
|
183
|
+
const key = str(event.paneKey) ?? event.terminalId;
|
|
184
|
+
await (deps.delay ?? sleep)(TURN_SHARE_DELAY_MS);
|
|
185
|
+
// Working again: this was not the end of the turn after all.
|
|
186
|
+
if (lastState.get(key) === 'working') return;
|
|
187
|
+
await decide(event, event.terminalId);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
onStatus(event) {
|
|
192
|
+
try {
|
|
193
|
+
handle(event).catch(() => {});
|
|
194
|
+
} catch {
|
|
195
|
+
// a failing watcher never reaches the status handler
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|