@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/src/worker.ts ADDED
@@ -0,0 +1,521 @@
1
+ /**
2
+ * Orca worker entry (`orca-plugin.json` `main`). It guards Claude Code tool calls made in Orca
3
+ * terminals through the `agent.tool.before` hook, shows the gateway's state in the status bar and
4
+ * offers two commands. The model never runs here: decisions come from the local-decider gateway,
5
+ * and every failure lets the call through to Orca's and Claude Code's own prompts.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ import { createAgentTerminals, type AgentTerminals } from './agent-terminals.ts';
11
+ import { createGate, type Gate } from './gate.ts';
12
+ import {
13
+ createGatewayClient,
14
+ type DecideReply,
15
+ type Decision,
16
+ type GatewayClient,
17
+ type GatewayHealth,
18
+ type PolicyMode,
19
+ type Rejected,
20
+ } from './gateway.ts';
21
+ import { createHookWatch, type HookWatch } from './hook-watch.ts';
22
+ import { routableAgent } from './launch-command.ts';
23
+ import { launchGateway, type LaunchResult } from './launcher/launch.ts';
24
+ import { gatewaySocketPathForEnv } from './launcher/socket-path.ts';
25
+ import type {
26
+ Disposable,
27
+ LaunchBeforeEvent,
28
+ LaunchBeforeResult,
29
+ OrcaWorker,
30
+ TerminalSendEvent,
31
+ } from './orca-types.ts';
32
+ import { registerPanelApi, statsRow } from './panel-api.ts';
33
+ import {
34
+ PANEL_CHANGED,
35
+ type ActionResult,
36
+ type CommandRiskStats,
37
+ type EngineInput,
38
+ type PanelState,
39
+ type PolicyModeInput,
40
+ } from './panel-protocol.ts';
41
+ import { createRouter, ROUTING_POLICY, type Router } from './routing.ts';
42
+ import { createSendGuard, type SendGuard } from './send-guard.ts';
43
+ import { DEFAULT_SETTINGS, parseSettings, type Settings } from './settings.ts';
44
+ import {
45
+ healthOf,
46
+ polledHealth,
47
+ replyHealth,
48
+ statusParams,
49
+ statusReport,
50
+ type Health,
51
+ type StatusState,
52
+ } from './status.ts';
53
+ import { createTurnWatcher, TURN_POLICY, type TurnWatcher } from './turn-outcome.ts';
54
+ import { createWorkspacePaths } from './workspaces.ts';
55
+ import { withWrapperEnv } from './wrapper-env.ts';
56
+
57
+ export const STATUS_ITEM = 'status';
58
+ export const STATUS_COMMAND = 'local-decider.status';
59
+ export const START_COMMAND = 'local-decider.start-gateway';
60
+ export const ACT_COMMAND = 'local-decider.command-risk-act';
61
+ export const SHADOW_COMMAND = 'local-decider.command-risk-shadow';
62
+ const HEALTH_TIMEOUT_MS = 1500;
63
+ const POLICY = 'command-risk';
64
+ const CONTROL_TIMEOUT_MS = 5000;
65
+ const STATS_DAYS = 7;
66
+ /** At most one `ld.changed` post per interval; Orca allows 200 per 10 s. */
67
+ const PANEL_POST_MS = 250;
68
+ const POLL_MS = 60_000;
69
+ const GUIDE_URL =
70
+ 'https://github.com/ziptie-soft/local-decider/blob/master/packages/orca-plugin/README.md';
71
+ /** Used when `package.json` cannot be read; release-please keeps the file current. */
72
+ const FALLBACK_GATEWAY = '3.4.0';
73
+
74
+ export interface WorkerOptions {
75
+ readonly env?: NodeJS.ProcessEnv;
76
+ readonly fetch?: typeof fetch;
77
+ readonly now?: () => number;
78
+ /** Resolves after `ms`, for the end-of-turn wait; defaults to a timer. */
79
+ readonly delay?: (ms: number) => Promise<void>;
80
+ /** Runs `fn` after `ms`; returns a cancel function. Defaults to an unref'd `setTimeout`. */
81
+ readonly after?: (fn: () => void, ms: number) => () => void;
82
+ readonly launch?: typeof launchGateway;
83
+ /** The plugin folder; defaults to the folder above `src/`. */
84
+ readonly root?: string;
85
+ }
86
+
87
+ function readJson(path: string): Record<string, unknown> {
88
+ try {
89
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8'));
90
+ return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};
91
+ } catch {
92
+ return {};
93
+ }
94
+ }
95
+
96
+ function versions(root: string): { plugin: string; gateway: string } {
97
+ const plugin = readJson(join(root, 'orca-plugin.json'))['version'];
98
+ const pinned = (readJson(join(root, 'package.json'))['localDecider'] as { gateway?: unknown })
99
+ ?.gateway;
100
+ return {
101
+ plugin: typeof plugin === 'string' ? plugin : '0.0.0',
102
+ gateway: typeof pinned === 'string' ? pinned : FALLBACK_GATEWAY,
103
+ };
104
+ }
105
+
106
+ function replyLabel(reply: Decision | Rejected): string {
107
+ return 'rejected' in reply
108
+ ? `rejected by the gateway (HTTP ${reply.rejected})`
109
+ : `${reply.action} (${reply.decisionId})`;
110
+ }
111
+
112
+ function defaultAfter(fn: () => void, ms: number): () => void {
113
+ const handle = setTimeout(fn, ms);
114
+ handle.unref();
115
+ return () => clearTimeout(handle);
116
+ }
117
+
118
+ /** The worker's state: settings, gateway client, gate and what the status bar shows. */
119
+ class Runtime {
120
+ settings: Settings = DEFAULT_SETTINGS;
121
+ health: Health = 'unknown';
122
+ gatewayMode: PolicyMode | 'unknown' = 'unknown';
123
+ routingMode: PolicyMode | 'unknown' = 'unknown';
124
+ turnOutcomeMode: PolicyMode | 'unknown' = 'unknown';
125
+ lastRoute: string | undefined;
126
+ gateway: GatewayHealth | undefined;
127
+ lastDecision: string | undefined;
128
+ launch: string | undefined;
129
+ lastPostAt = Number.NEGATIVE_INFINITY;
130
+ postTimer: (() => void) | undefined;
131
+ disposed = false;
132
+ client: GatewayClient;
133
+ readonly gate: Gate;
134
+ readonly sendGuard: SendGuard;
135
+ /** Terminals an agent runs in, from `agent.status.changed`, confirmed by `agents.list`. */
136
+ readonly agentTerminals: AgentTerminals;
137
+ readonly router: Router;
138
+ readonly hookWatch: HookWatch;
139
+ readonly turns: TurnWatcher;
140
+ readonly orca: OrcaWorker;
141
+ readonly options: WorkerOptions;
142
+ readonly version: { plugin: string; gateway: string };
143
+ readonly env: NodeJS.ProcessEnv;
144
+
145
+ constructor(orca: OrcaWorker, options: WorkerOptions) {
146
+ this.orca = orca;
147
+ this.options = options;
148
+ this.env = options.env ?? process.env;
149
+ this.version = versions(options.root ?? join(import.meta.dirname, '..'));
150
+ this.client = this.makeClient();
151
+ const workspaces = createWorkspacePaths((method, params) => orca.host.call(method, params));
152
+ this.gate = createGate({
153
+ settings: () => this.settings,
154
+ gateway: () => this.client,
155
+ cwdFor: (id, ms) => workspaces.cwdFor(id, ms),
156
+ now: options.now ?? Date.now,
157
+ onReply: (reply) => this.onReply(reply),
158
+ });
159
+ this.agentTerminals = createAgentTerminals((method, params) => orca.host.call(method, params));
160
+ this.sendGuard = createSendGuard({
161
+ settings: () => this.settings,
162
+ isAgentTerminal: (id) => this.agentTerminals.isAgent(id),
163
+ });
164
+ this.router = createRouter({
165
+ settings: () => this.settings,
166
+ gateway: () => this.client,
167
+ cwdFor: (id, ms) => workspaces.cwdFor(id, ms),
168
+ routingMode: () => (this.health === 'offline' ? 'off' : this.routingMode),
169
+ now: options.now ?? Date.now,
170
+ onRoute: (note) => this.onRoute(note),
171
+ onReply: (reply) => this.onReply(reply),
172
+ });
173
+ this.hookWatch = createHookWatch({
174
+ after: options.after ?? defaultAfter,
175
+ log: (message) => this.orca.log(message),
176
+ onChange: () => this.postPanel(),
177
+ });
178
+ this.turns = createTurnWatcher({
179
+ settings: () => this.settings,
180
+ gateway: () => this.client,
181
+ cwdFor: (id, ms) => workspaces.cwdFor(id, ms),
182
+ call: (method, params) => orca.host.call(method, params),
183
+ now: options.now ?? Date.now,
184
+ ...(options.delay === undefined ? {} : { delay: options.delay }),
185
+ onOutcome: (note) => this.orca.log(`local-decider: ${note}`),
186
+ });
187
+ }
188
+
189
+ /** `agent.launch.before`: launch with the routed command, or unchanged. */
190
+ async onLaunch(
191
+ event: LaunchBeforeEvent,
192
+ next: (event?: LaunchBeforeEvent) => LaunchBeforeResult,
193
+ ): Promise<LaunchBeforeResult> {
194
+ const command = await this.router.route(event);
195
+ const env = this.launchEnv(event);
196
+ if (command === undefined && env === undefined) return undefined;
197
+ return next({
198
+ ...event,
199
+ ...(command === undefined ? {} : { command }),
200
+ ...(env === undefined ? {} : { env }),
201
+ });
202
+ }
203
+
204
+ /**
205
+ * The launch `env` with the PTY-wrapper switches added, or `undefined` for no change: Mode
206
+ * `off`, nothing to add, or any error. Also starts waiting for a Claude Code agent's hooks.
207
+ */
208
+ launchEnv(event: LaunchBeforeEvent): Record<string, string> | undefined {
209
+ if (this.settings.mode === 'off') return undefined;
210
+ try {
211
+ if (typeof event.terminalId === 'string' && routableAgent(event.agent) === 'claude') {
212
+ this.hookWatch.launched(event.terminalId);
213
+ }
214
+ return withWrapperEnv(event.env);
215
+ } catch {
216
+ return undefined;
217
+ }
218
+ }
219
+
220
+ /** `terminal.send`: refuse a risky shell command typed into a terminal; log only the reason. */
221
+ async onTerminalSend(event: TerminalSendEvent): Promise<{ readonly deny: string } | undefined> {
222
+ const result = await this.sendGuard.check(event);
223
+ if (result !== undefined) {
224
+ this.orca.log(`local-decider: refused a terminal send: ${result.deny}`);
225
+ }
226
+ return result;
227
+ }
228
+
229
+ onRoute(note: string): void {
230
+ this.lastRoute = note;
231
+ this.orca.log(`local-decider: routing ${note}`);
232
+ this.postPanel();
233
+ }
234
+
235
+ makeClient(): GatewayClient {
236
+ return createGatewayClient({
237
+ url: this.settings.url,
238
+ defaultEndpoint: this.settings.defaultEndpoint,
239
+ clientId: `orca/${this.version.plugin}`,
240
+ env: this.env,
241
+ token: this.env['LOCAL_DECIDER_TOKEN'],
242
+ ...(this.options.fetch === undefined ? {} : { fetch: this.options.fetch }),
243
+ });
244
+ }
245
+
246
+ state(): StatusState {
247
+ return {
248
+ mode: this.settings.mode,
249
+ health: this.health,
250
+ gatewayMode: this.health === 'offline' ? 'unknown' : this.gatewayMode,
251
+ gateway: this.gateway,
252
+ url: this.settings.url,
253
+ lastDecision: this.lastDecision,
254
+ launch: this.launch,
255
+ };
256
+ }
257
+
258
+ /** Never awaited by the hook: the decision is already made. */
259
+ onReply(reply: DecideReply): void {
260
+ if (reply !== null) this.lastDecision = replyLabel(reply);
261
+ const health = replyHealth(reply, this.health);
262
+ if (health !== this.health) {
263
+ this.health = health;
264
+ this.showStatus();
265
+ }
266
+ }
267
+
268
+ /** What the panel shows. Never holds a token: it only says whether control calls can go out. */
269
+ panelState(): PanelState {
270
+ const { gateway, lastDecision, lastRoute, launch } = this;
271
+ const silent = this.hookWatch.silent();
272
+ const socket = this.settings.defaultEndpoint && gatewaySocketPathForEnv(this.env) !== null;
273
+ return {
274
+ health: this.health,
275
+ mode: this.settings.mode,
276
+ askAction: this.settings.askAction,
277
+ gatewayMode: this.health === 'offline' ? 'unknown' : this.gatewayMode,
278
+ routingMode: this.health === 'offline' ? 'unknown' : this.routingMode,
279
+ turnOutcomeMode: this.health === 'offline' ? 'unknown' : this.turnOutcomeMode,
280
+ url: this.settings.url,
281
+ transport: socket ? 'socket' : 'tcp',
282
+ control: this.client.control(),
283
+ ...(gateway === undefined ? {} : { gateway }),
284
+ ...(lastDecision === undefined ? {} : { lastDecision }),
285
+ ...(lastRoute === undefined ? {} : { lastRoute }),
286
+ ...(launch === undefined ? {} : { launch }),
287
+ ...(silent === 0 ? {} : { hooksMissing: silent }),
288
+ settings: {
289
+ timeoutMs: this.settings.timeoutMs,
290
+ autoStart: this.settings.autoStart,
291
+ preloadModel: this.settings.preloadModel,
292
+ routing: this.settings.routing,
293
+ turnOutcome: this.settings.turnOutcome,
294
+ },
295
+ };
296
+ }
297
+
298
+ async refresh(): Promise<PanelState> {
299
+ await this.checkHealth();
300
+ return this.panelState();
301
+ }
302
+
303
+ async startForPanel(): Promise<PanelState> {
304
+ await this.start();
305
+ return this.panelState();
306
+ }
307
+
308
+ async applyMode(input: PolicyModeInput): Promise<ActionResult> {
309
+ const result = await this.client.setPolicyMode(POLICY, input.mode, CONTROL_TIMEOUT_MS);
310
+ await this.checkHealth();
311
+ return result.ok
312
+ ? { ok: true, message: `command-risk is now ${input.mode} for every client of this gateway` }
313
+ : { ok: false, message: result.message };
314
+ }
315
+
316
+ async loadEngine(input: EngineInput): Promise<ActionResult> {
317
+ const result = await this.client.engineLoad(input.action, CONTROL_TIMEOUT_MS);
318
+ await this.checkHealth();
319
+ return result.ok
320
+ ? { ok: true, message: `model ${input.action} requested` }
321
+ : { ok: false, message: result.message };
322
+ }
323
+
324
+ async stats(): Promise<CommandRiskStats | null> {
325
+ return statsRow(await this.client.stats(STATS_DAYS, CONTROL_TIMEOUT_MS));
326
+ }
327
+
328
+ /** Post the latest state now, or once the interval since the last post has passed. */
329
+ postPanel(): void {
330
+ if (this.disposed || this.postTimer !== undefined || this.orca.panels === undefined) return;
331
+ const now = this.options.now ?? Date.now;
332
+ const wait = PANEL_POST_MS - (now() - this.lastPostAt);
333
+ if (wait <= 0) {
334
+ this.flushPanel();
335
+ return;
336
+ }
337
+ const after = this.options.after ?? defaultAfter;
338
+ this.postTimer = after(() => {
339
+ this.postTimer = undefined;
340
+ this.flushPanel();
341
+ }, wait);
342
+ }
343
+
344
+ flushPanel(): void {
345
+ if (this.disposed) return;
346
+ this.lastPostAt = (this.options.now ?? Date.now)();
347
+ try {
348
+ this.orca.panels?.post(PANEL_CHANGED, this.panelState());
349
+ } catch {
350
+ // a failing post never reaches the hook or the status bar
351
+ }
352
+ }
353
+
354
+ /** Stop posting: cancel the pending post. */
355
+ dispose(): void {
356
+ this.disposed = true;
357
+ this.hookWatch.dispose();
358
+ this.postTimer?.();
359
+ this.postTimer = undefined;
360
+ }
361
+
362
+ showStatus(): void {
363
+ this.postPanel();
364
+ this.orca.host
365
+ .call('statusBar.update', statusParams(STATUS_ITEM, this.state(), this.settings.statusBar))
366
+ .catch(() => {});
367
+ }
368
+
369
+ async loadSettings(): Promise<void> {
370
+ try {
371
+ this.settings = parseSettings(await this.orca.settings.get());
372
+ } catch {
373
+ this.settings = DEFAULT_SETTINGS;
374
+ }
375
+ this.client = this.makeClient();
376
+ this.health = 'unknown';
377
+ this.gate.reset();
378
+ }
379
+
380
+ async checkHealth(): Promise<Health> {
381
+ const gateway = await this.client.health(HEALTH_TIMEOUT_MS);
382
+ this.gateway = gateway ?? undefined;
383
+ this.health = polledHealth(healthOf(gateway?.status ?? null), this.health);
384
+ if (gateway !== null) {
385
+ [this.gatewayMode, this.routingMode, this.turnOutcomeMode] = await Promise.all([
386
+ this.client.policyMode(POLICY, HEALTH_TIMEOUT_MS),
387
+ this.client.policyMode(ROUTING_POLICY, HEALTH_TIMEOUT_MS),
388
+ this.client.policyMode(TURN_POLICY, HEALTH_TIMEOUT_MS),
389
+ ]);
390
+ }
391
+ if (this.health !== 'offline') this.gate.reset();
392
+ this.showStatus();
393
+ return this.health;
394
+ }
395
+
396
+ async start(): Promise<LaunchResult> {
397
+ const launch = this.options.launch ?? launchGateway;
398
+ const result = await launch({
399
+ url: this.settings.url,
400
+ defaultEndpoint: this.settings.defaultEndpoint,
401
+ clientId: `orca/${this.version.plugin}`,
402
+ env: this.env,
403
+ pinnedVersion: this.version.gateway,
404
+ guideUrl: GUIDE_URL,
405
+ });
406
+ this.launch = `${result.status}: ${result.message}`;
407
+ this.orca.log(`local-decider: gateway ${this.launch}`);
408
+ await this.checkHealth();
409
+ return result;
410
+ }
411
+
412
+ /** Switch the gateway's command-risk mode (gateway-wide) and report what happened. */
413
+ async setGatewayMode(mode: PolicyMode): Promise<string> {
414
+ const result = await this.client.setPolicyMode(POLICY, mode, CONTROL_TIMEOUT_MS);
415
+ if (!result.ok) return `could not switch command-risk: ${result.message}`;
416
+ await this.checkHealth();
417
+ return `command-risk is now ${mode} on ${this.settings.url} (applies to every client of this gateway)`;
418
+ }
419
+
420
+ /** Load the model once, without holding up start-up. Logs only the outcome. */
421
+ preload(): void {
422
+ this.client
423
+ .engineLoad('load', CONTROL_TIMEOUT_MS)
424
+ .then((result) => {
425
+ this.orca.log(`local-decider: preload: ${result.ok ? 'ok' : result.message}`);
426
+ })
427
+ .catch(() => {});
428
+ }
429
+
430
+ /**
431
+ * On activation: start the gateway once if it is not running and auto-start is on, then load
432
+ * the model when asked to.
433
+ */
434
+ async boot(): Promise<void> {
435
+ await this.loadSettings();
436
+ const health = await this.checkHealth();
437
+ if (health === 'offline' && this.settings.mode !== 'off' && this.settings.autoStart) {
438
+ await this.start();
439
+ }
440
+ if (this.settings.preloadModel && this.settings.mode !== 'off' && this.health === 'ok') {
441
+ this.preload();
442
+ }
443
+ }
444
+ }
445
+
446
+ let timer: NodeJS.Timeout | undefined;
447
+ const disposables: Disposable[] = [];
448
+
449
+ /** `agent.status.changed`: remember agent terminals for the send guard, and watch turns end. */
450
+ function trackAgentTerminals(orca: OrcaWorker, rt: Runtime): Disposable[] {
451
+ if (orca.events === undefined) return [];
452
+ return [
453
+ orca.events.on('agent.status.changed', (event) => {
454
+ if (typeof event.terminalId === 'string') {
455
+ rt.agentTerminals.remember(event.terminalId, event.workspaceListId ?? event.workspaceId);
456
+ rt.hookWatch.seen(event.terminalId);
457
+ }
458
+ rt.turns.onStatus(event);
459
+ }),
460
+ ];
461
+ }
462
+
463
+ /** Testable entry: `activate` with injected options. Returns the runtime for tests. */
464
+ export function activateWith(orca: OrcaWorker, options: WorkerOptions = {}): Runtime {
465
+ const rt = new Runtime(orca, options);
466
+ disposables.push(
467
+ { dispose: () => rt.dispose() },
468
+ orca.hooks.on('agent.tool.before', (event) => rt.gate.check(event)),
469
+ orca.hooks.on('agent.launch.before', (event, next) => rt.onLaunch(event, next)),
470
+ orca.hooks.on('terminal.send', (event) => rt.onTerminalSend(event)),
471
+ ...trackAgentTerminals(orca, rt),
472
+ orca.commands.register(STATUS_COMMAND, async () => {
473
+ await rt.checkHealth();
474
+ return statusReport(rt.state());
475
+ }),
476
+ orca.commands.register(ACT_COMMAND, () => rt.setGatewayMode('act')),
477
+ orca.commands.register(SHADOW_COMMAND, () => rt.setGatewayMode('shadow')),
478
+ orca.commands.register(START_COMMAND, async () => {
479
+ const result = await rt.start();
480
+ return `local-decider gateway: ${result.message}`;
481
+ }),
482
+ ...registerPanelApi(orca, {
483
+ panelState: () => rt.panelState(),
484
+ refresh: () => rt.refresh(),
485
+ start: () => rt.startForPanel(),
486
+ applyMode: (input) => rt.applyMode(input),
487
+ loadEngine: (input) => rt.loadEngine(input),
488
+ stats: () => rt.stats(),
489
+ }),
490
+ orca.settings.onDidChange(() => {
491
+ void rt.loadSettings().then(() => {
492
+ rt.showStatus();
493
+ return rt.checkHealth();
494
+ });
495
+ }),
496
+ );
497
+ rt.boot().catch((error: unknown) => {
498
+ orca.log(`local-decider: start-up check failed: ${String(error)}`);
499
+ });
500
+ timer = setInterval(() => {
501
+ void rt.checkHealth();
502
+ }, POLL_MS);
503
+ timer.unref();
504
+ return rt;
505
+ }
506
+
507
+ export default function activate(orca: OrcaWorker): void {
508
+ activateWith(orca);
509
+ }
510
+
511
+ export function deactivate(): void {
512
+ clearInterval(timer);
513
+ timer = undefined;
514
+ for (const d of disposables.splice(0)) {
515
+ try {
516
+ d.dispose();
517
+ } catch {
518
+ // ignored
519
+ }
520
+ }
521
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Maps an Orca workspace id to its folder. A worktree id is `<repoId>::<path>`, so the path is
3
+ * read from the id when it holds one; otherwise it comes from `workspace.list` (`workspace:read`),
4
+ * cached and re-read at most every `REFRESH_MS`, or when an id is missing; a hook never waits for
5
+ * it longer than the timeout it passes. Only local workspaces get a path: the gateway runs on this
6
+ * machine, and Orca does not hook SSH or WSL agents yet.
7
+ */
8
+
9
+ const REFRESH_MS = 30_000;
10
+ const WSL_PATH = /^(?:\\\\wsl\.localhost\\|\\\\wsl\$\\|\/\/wsl\.localhost\/)/i;
11
+
12
+ /** The absolute local path after `::` in a worktree id, if any. */
13
+ export function pathInId(workspaceId: string): string | undefined {
14
+ const at = workspaceId.indexOf('::');
15
+ if (at < 0) return undefined;
16
+ const path = workspaceId.slice(at + 2);
17
+ return path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path) ? path : undefined;
18
+ }
19
+
20
+ export type HostCall = (method: string, params?: unknown) => Promise<unknown>;
21
+
22
+ interface Row {
23
+ readonly id?: unknown;
24
+ readonly path?: unknown;
25
+ readonly hostId?: unknown;
26
+ }
27
+
28
+ function isLocal(row: Row): boolean {
29
+ return (row.hostId === 'local' || row.hostId === null) && typeof row.path === 'string';
30
+ }
31
+
32
+ /** `id → path` for the local rows of a `workspace.list` answer. */
33
+ export function pathsOf(reply: unknown): Map<string, string> {
34
+ const paths = new Map<string, string>();
35
+ const rows = (reply as { workspaces?: unknown } | null)?.workspaces;
36
+ if (!Array.isArray(rows)) return paths;
37
+ for (const row of rows as Row[]) {
38
+ if (typeof row.id !== 'string' || !isLocal(row)) continue;
39
+ const path = row.path as string;
40
+ if (path !== '' && !WSL_PATH.test(path)) paths.set(row.id, path);
41
+ }
42
+ return paths;
43
+ }
44
+
45
+ function within<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {
46
+ let timer: NodeJS.Timeout | undefined;
47
+ const timeout = new Promise<undefined>((resolve) => {
48
+ timer = setTimeout(() => resolve(undefined), ms);
49
+ });
50
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
51
+ }
52
+
53
+ export interface WorkspacePaths {
54
+ readonly refresh: () => Promise<void>;
55
+ readonly cwdFor: (workspaceId: string | null, timeoutMs: number) => Promise<string | undefined>;
56
+ }
57
+
58
+ export function createWorkspacePaths(call: HostCall, now: () => number = Date.now): WorkspacePaths {
59
+ let paths = new Map<string, string>();
60
+ let readAt = Number.NEGATIVE_INFINITY;
61
+ let pending: Promise<void> | null = null;
62
+
63
+ function refresh(): Promise<void> {
64
+ pending ??= call('workspace.list')
65
+ .then((reply) => {
66
+ paths = pathsOf(reply);
67
+ readAt = now();
68
+ })
69
+ .catch(() => {})
70
+ .finally(() => {
71
+ pending = null;
72
+ });
73
+ return pending;
74
+ }
75
+
76
+ return {
77
+ refresh,
78
+ async cwdFor(workspaceId: string | null, timeoutMs: number): Promise<string | undefined> {
79
+ if (workspaceId === null) return undefined;
80
+ const inId = pathInId(workspaceId);
81
+ if (inId !== undefined) return WSL_PATH.test(inId) ? undefined : inId;
82
+ const stale = now() - readAt > REFRESH_MS;
83
+ if (stale || !paths.has(workspaceId)) await within(refresh(), timeoutMs);
84
+ return paths.get(workspaceId);
85
+ },
86
+ };
87
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Environment variables added to every agent launch Orca makes, so a PTY wrapper that starts from
3
+ * the shell's start-up files stays out of the way. Orca accepts agent hooks only from the pane's
4
+ * own agent process; a wrapper puts its own PTY between the pane and the agent, and Orca then
5
+ * drops that agent's hooks. List only variables a wrapper documents as its own off switch.
6
+ */
7
+ export const WRAPPER_ENV: Readonly<Record<string, string>> = { LIG_DISABLE: '1' };
8
+
9
+ /**
10
+ * The launch `env` with the wrapper switches added, or `undefined` when there is nothing to add.
11
+ * A variable the launch already sets keeps its value.
12
+ */
13
+ export function withWrapperEnv(
14
+ env: Readonly<Record<string, string>> | undefined,
15
+ ): Record<string, string> | undefined {
16
+ const current = env ?? {};
17
+ const missing = Object.entries(WRAPPER_ENV).filter(([name]) => !Object.hasOwn(current, name));
18
+ return missing.length === 0 ? undefined : { ...current, ...Object.fromEntries(missing) };
19
+ }