@adhdev/daemon-core 0.9.82-rc.21 → 0.9.82-rc.210
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/dist/boot/daemon-lifecycle.d.ts +1 -0
- package/dist/boot/process-hardening.d.ts +50 -0
- package/dist/chat/source-machine.d.ts +166 -0
- package/dist/chat/source-resolver.d.ts +104 -0
- package/dist/chat/subscription-updates.d.ts +1 -0
- package/dist/cli-adapter-types.d.ts +23 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +29 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +3 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +1 -2
- package/dist/cli-adapters/terminal-screen.d.ts +2 -11
- package/dist/commands/cli-manager.d.ts +2 -1
- package/dist/commands/handler.d.ts +110 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +32 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +72 -1
- package/dist/git/git-commands.d.ts +9 -1
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-types.d.ts +2 -0
- package/dist/index.d.ts +46 -11
- package/dist/index.js +35171 -15756
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +34878 -15556
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +36 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +90 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +151 -0
- package/dist/mesh/mesh-events-pending.d.ts +33 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +14 -0
- package/dist/mesh/mesh-events.d.ts +5 -40
- package/dist/mesh/mesh-fast-forward.d.ts +41 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-missions.d.ts +58 -0
- package/dist/mesh/mesh-refine-status.d.ts +26 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-runtime-store.d.ts +324 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-work-queue.d.ts +137 -6
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +215 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
- package/dist/providers/acp-provider-instance.d.ts +2 -0
- package/dist/providers/approval-utils.d.ts +13 -0
- package/dist/providers/cli-provider-instance.d.ts +39 -3
- package/dist/providers/contracts.d.ts +130 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/dispatcher.d.ts +27 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +12 -0
- package/dist/providers/provider-instance.d.ts +13 -1
- package/dist/providers/provider-loader.d.ts +26 -4
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +52 -0
- package/dist/providers/spec/cli-adapter.d.ts +101 -0
- package/dist/providers/spec/driver.d.ts +225 -0
- package/dist/providers/spec/evaluator.d.ts +54 -0
- package/dist/providers/spec/loader.d.ts +15 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/schema.gen.d.ts +2025 -0
- package/dist/providers/spec/types.d.ts +302 -0
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +48 -0
- package/dist/repo-mesh-types.d.ts +109 -1
- package/dist/sessions/registry.d.ts +3 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +42 -1
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +1 -0
- package/dist/types.d.ts +5 -0
- package/package.json +6 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/boot/daemon-lifecycle.ts +22 -10
- package/src/boot/process-hardening.ts +89 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +20 -1
- package/src/cli-adapter-types.d.ts +1 -0
- package/src/cli-adapter-types.ts +22 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1138 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +673 -1139
- package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
- package/src/cli-adapters/provider-cli-parse.ts +13 -0
- package/src/cli-adapters/provider-cli-runtime.ts +3 -1
- package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
- package/src/cli-adapters/provider-cli-shared.ts +59 -11
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +35 -29
- package/src/cli-adapters/terminal-backends/types.ts +1 -3
- package/src/cli-adapters/terminal-screen.ts +11 -81
- package/src/commands/chat-commands.ts +1787 -60
- package/src/commands/cli-manager.ts +283 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +4198 -557
- package/src/config/chat-history.ts +95 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +280 -2
- package/src/config/recent-activity.ts +8 -2
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/detection/ide-detector.ts +26 -16
- package/src/git/git-commands.ts +42 -12
- package/src/git/git-diff.ts +53 -0
- package/src/git/git-status.ts +35 -6
- package/src/git/git-types.ts +2 -0
- package/src/git/git-worktree.ts +8 -1
- package/src/index.ts +126 -10
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/logger.ts +2 -1
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +218 -31
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +437 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +1404 -0
- package/src/mesh/mesh-events-pending.ts +371 -0
- package/src/mesh/mesh-events-stale.ts +283 -0
- package/src/mesh/mesh-events-utils.ts +161 -0
- package/src/mesh/mesh-events.ts +24 -908
- package/src/mesh/mesh-fast-forward.ts +438 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
- package/src/mesh/mesh-ledger.ts +587 -102
- package/src/mesh/mesh-missions.ts +151 -0
- package/src/mesh/mesh-refine-status.ts +144 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-runtime-store.ts +1305 -0
- package/src/mesh/mesh-task-stats.ts +154 -0
- package/src/mesh/mesh-work-queue.ts +490 -166
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +403 -0
- package/src/mesh/worktree-bootstrap-config.ts +326 -0
- package/src/providers/acp-provider-instance.ts +15 -1
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +4 -11
- package/src/providers/cli-provider-instance.ts +833 -64
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +141 -6
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +19 -5
- package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +419 -0
- package/src/providers/native-history/dispatcher.ts +340 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +30 -0
- package/src/providers/provider-instance.ts +10 -1
- package/src/providers/provider-loader.ts +582 -50
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +138 -0
- package/src/providers/spec/cli-adapter.ts +626 -0
- package/src/providers/spec/driver.ts +912 -0
- package/src/providers/spec/evaluator.ts +597 -0
- package/src/providers/spec/loader.ts +324 -0
- package/src/providers/spec/native-history-executor.ts +939 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/schema.gen.ts +691 -0
- package/src/providers/spec/schema.json +341 -0
- package/src/providers/spec/types.ts +356 -0
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +425 -0
- package/src/providers/version-archive.ts +38 -20
- package/src/repo-mesh-types.ts +119 -1
- package/src/sessions/registry.ts +3 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.ts +45 -1
- package/src/status/builders.ts +24 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +15 -0
- package/src/status/snapshot.ts +84 -25
- package/src/system/host-memory.ts +29 -12
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SpecDriver — the single fixed script that turns a CliSpec + a
|
|
3
|
+
* TerminalAdapter into the dashboard-facing wire protocol.
|
|
4
|
+
*
|
|
5
|
+
* Wire (dashboard ↔ daemon):
|
|
6
|
+
*
|
|
7
|
+
* dashboard → daemon:
|
|
8
|
+
* { kind: 'send_message', text }
|
|
9
|
+
* { kind: 'click_control', control_id, payload? }
|
|
10
|
+
* { kind: 'click_modal_button', index }
|
|
11
|
+
* { kind: 'attach_image', blob, mime }
|
|
12
|
+
* { kind: 'resize', cols, rows }
|
|
13
|
+
* { kind: 'cancel' }
|
|
14
|
+
* { kind: 'shutdown' }
|
|
15
|
+
*
|
|
16
|
+
* daemon → dashboard:
|
|
17
|
+
* { kind: 'pty_data', chunk }
|
|
18
|
+
* { kind: 'state_changed',
|
|
19
|
+
* state: { id, label, title },
|
|
20
|
+
* modal: null | { title, buttons: [{ index, label }] },
|
|
21
|
+
* controls: [{ id, label, action_type }] }
|
|
22
|
+
* { kind: 'notification', id, title, body }
|
|
23
|
+
* { kind: 'delegate', id, task }
|
|
24
|
+
* { kind: 'spec_trace', entries: [...] }
|
|
25
|
+
* { kind: 'exit', exit_code }
|
|
26
|
+
*
|
|
27
|
+
* Hot reload: spec.json is watched. A reload re-evaluates and emits a
|
|
28
|
+
* fresh state_changed; no PTY restart is required.
|
|
29
|
+
*
|
|
30
|
+
* Delegate timers: after_duration_ms is enforced here (the evaluator
|
|
31
|
+
* is stateless). A timer is armed when a delegate's when_state is
|
|
32
|
+
* entered and cancelled when it changes.
|
|
33
|
+
*/
|
|
34
|
+
'use strict';
|
|
35
|
+
|
|
36
|
+
import * as fs from 'node:fs';
|
|
37
|
+
import * as os from 'node:os';
|
|
38
|
+
import * as path from 'node:path';
|
|
39
|
+
import { TerminalAdapter, type TerminalAdapterOpts } from './adapter.js';
|
|
40
|
+
import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
|
|
41
|
+
import { DEFAULT_SESSION_HOST_COLS, DEFAULT_SESSION_HOST_ROWS } from '@adhdev/session-host-core';
|
|
42
|
+
import { evaluate, type SpecEvaluation, type TraceEntry } from './evaluator.js';
|
|
43
|
+
import { loadSpec } from './loader.js';
|
|
44
|
+
import type { CliSpec, Control, DelegateTrigger, SectionDef } from './types.js';
|
|
45
|
+
import { LOG } from '../../logging/logger.js';
|
|
46
|
+
|
|
47
|
+
export type DashboardEvent =
|
|
48
|
+
| { kind: 'pty_data'; chunk: string }
|
|
49
|
+
| { kind: 'state_changed'; state: { id: string; label: string; title: string | null };
|
|
50
|
+
modal: { title: string | null; buttons: { index: number; label: string }[] } | null;
|
|
51
|
+
controls: { id: string; label: string; action_type: string }[] }
|
|
52
|
+
| { kind: 'notification'; id: string; title: string; body: string }
|
|
53
|
+
| { kind: 'delegate'; id: string; task: string }
|
|
54
|
+
| { kind: 'spec_trace'; entries: TraceEntry[] }
|
|
55
|
+
| { kind: 'exit'; exit_code: number }
|
|
56
|
+
| { kind: 'spec_error'; errors: string[] };
|
|
57
|
+
|
|
58
|
+
export type DashboardCommand =
|
|
59
|
+
| { kind: 'send_message'; text: string }
|
|
60
|
+
| { kind: 'pty_write'; data: string }
|
|
61
|
+
| { kind: 'click_control'; control_id: string; payload?: unknown }
|
|
62
|
+
| { kind: 'click_modal_button'; index: number }
|
|
63
|
+
| { kind: 'attach_image'; blob: string; mime: string }
|
|
64
|
+
| { kind: 'resize'; cols: number; rows: number }
|
|
65
|
+
| { kind: 'cancel' }
|
|
66
|
+
| { kind: 'shutdown' };
|
|
67
|
+
|
|
68
|
+
export interface SpecDriverOpts {
|
|
69
|
+
specPath: string;
|
|
70
|
+
workingDir: string;
|
|
71
|
+
extraEnv?: Record<string, string>;
|
|
72
|
+
cols?: number;
|
|
73
|
+
rows?: number;
|
|
74
|
+
/** Set false to skip the spec.json fs.watch. */
|
|
75
|
+
hotReload?: boolean;
|
|
76
|
+
/** Set true to forward trace entries on every state_changed. */
|
|
77
|
+
emitTrace?: boolean;
|
|
78
|
+
/** Inject the daemon's PTY transport (typically SessionHostPtyTransportFactory). */
|
|
79
|
+
transportFactory?: PtyTransportFactory;
|
|
80
|
+
/**
|
|
81
|
+
* Extra CLI args appended to spec.spawn_args. Used by the daemon to
|
|
82
|
+
* pass per-launch arguments like `--session-id <uuid>` so the agent
|
|
83
|
+
* uses the daemon's providerSessionId instead of generating its own.
|
|
84
|
+
*/
|
|
85
|
+
extraCliArgs?: string[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** How long after start() to ignore "idle" readings before treating one
|
|
89
|
+
* as a real prompt-ready signal. Most TUIs paint a banner + tool list +
|
|
90
|
+
* status line on startup that can briefly score as "no state matches →
|
|
91
|
+
* default idle"; firing a send_keys into that buffer gets the input
|
|
92
|
+
* wiped when the banner clears. 2s covers the slow agents (hermes,
|
|
93
|
+
* agy) without delaying snappy ones (claude/codex) by much. */
|
|
94
|
+
const STARTUP_GRACE_MS = 2500;
|
|
95
|
+
|
|
96
|
+
/** Min time to stay in busy after the evaluator last reports it. Most TUIs
|
|
97
|
+
* flicker their busy spinner on and off as layout reflows (claude streams
|
|
98
|
+
* body text in the same region where the spinner lives, so the spinner
|
|
99
|
+
* disappears mid-response and the footer-only frames score as idle). The
|
|
100
|
+
* hold turns short idle gaps inside a single turn into "still busy", at
|
|
101
|
+
* the cost of looking busy for a couple seconds after a turn actually
|
|
102
|
+
* ends. Pick something long enough to cover the longest claude streaming
|
|
103
|
+
* gap we've observed (~5s between spinner refreshes) without dragging
|
|
104
|
+
* the post-turn idle indication noticeably. */
|
|
105
|
+
const BUSY_HOLD_MS = 6000;
|
|
106
|
+
|
|
107
|
+
/** Minimum delay between the prompt body and the submit_key in send_message.
|
|
108
|
+
* Claude / antigravity specs ship without an explicit delay_ms_before_submit
|
|
109
|
+
* and their TUIs sometimes drop the `\r` event when it arrives in the same
|
|
110
|
+
* PTY chunk as the text body — the prompt sits visible in the input field
|
|
111
|
+
* but is never submitted until the user hits Enter manually. 200ms matches
|
|
112
|
+
* codex's explicit setting and is barely perceptible to a human caller. */
|
|
113
|
+
const SUBMIT_DELAY_FLOOR_MS = 200;
|
|
114
|
+
|
|
115
|
+
function countNewlines(s: string): number {
|
|
116
|
+
let n = 0;
|
|
117
|
+
for (let i = 0; i < s.length; i += 1) if (s.charCodeAt(i) === 10) n += 1;
|
|
118
|
+
return n;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Pick the effective delay (ms) to wait between writing the prompt body and
|
|
123
|
+
* writing the submit_key. Exported for tests; production callers go through
|
|
124
|
+
* actuallySendMessage. Floors to SUBMIT_DELAY_FLOOR_MS so specs that omit
|
|
125
|
+
* delay_ms_before_submit (e.g. claude, antigravity) still get baseline
|
|
126
|
+
* protection against the paste→submit race. Adds line-count bonus so
|
|
127
|
+
* multi-line prompts get more settling time on TUIs that re-render per
|
|
128
|
+
* embedded `\n`.
|
|
129
|
+
*/
|
|
130
|
+
export function resolveSubmitDelayMs(specBeforeSubmit: number | undefined, text: string): number {
|
|
131
|
+
const lines = countNewlines(text);
|
|
132
|
+
const linesBonus = Math.min(800, lines * 80);
|
|
133
|
+
const spec = typeof specBeforeSubmit === 'number' && specBeforeSubmit > 0 ? specBeforeSubmit : 0;
|
|
134
|
+
return Math.max(spec, SUBMIT_DELAY_FLOOR_MS + linesBonus);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function matchesCompletionIdleRule(spec: CliSpec, ev: SpecEvaluation, screen: string): string | null {
|
|
138
|
+
const rule = spec.debounce?.completion_idle_after;
|
|
139
|
+
if (!rule?.regex) return null;
|
|
140
|
+
const haystack = rule.section
|
|
141
|
+
? ev.sections.find(section => section.id === rule.section)?.text ?? ''
|
|
142
|
+
: screen;
|
|
143
|
+
if (!haystack) return null;
|
|
144
|
+
try {
|
|
145
|
+
const regex = new RegExp(rule.regex, rule.flags || '');
|
|
146
|
+
const matched = regex.test(haystack);
|
|
147
|
+
// Return the regex pattern as the stable key rather than the match
|
|
148
|
+
// text. The match text often contains a live counter (e.g. "Compacted
|
|
149
|
+
// for 1m 6s") that changes every second, which would reset
|
|
150
|
+
// completionIdleFirstSeenAt on every PTY frame and prevent the hold
|
|
151
|
+
// window from ever expiring.
|
|
152
|
+
return matched ? rule.regex : null;
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function matchesCompletionIdleTargetState(
|
|
159
|
+
spec: CliSpec,
|
|
160
|
+
ev: SpecEvaluation,
|
|
161
|
+
screen: string,
|
|
162
|
+
cursor?: { row: number; col: number },
|
|
163
|
+
): boolean {
|
|
164
|
+
// Test whether the idle/default state's when-condition actually matches
|
|
165
|
+
// the current screen, WITHOUT the default fallback. We don't want to
|
|
166
|
+
// return true just because no other state matched (which is what
|
|
167
|
+
// evaluate() does via its default_state fallback).
|
|
168
|
+
const targetId = spec.default_state ?? 'idle';
|
|
169
|
+
const target = spec.states.find(state => state.id === targetId)
|
|
170
|
+
?? spec.states.find(state => state.id === 'idle');
|
|
171
|
+
if (!target) return false;
|
|
172
|
+
|
|
173
|
+
// Re-use the resolved sections already computed by evaluate().
|
|
174
|
+
const sections = ev.sections;
|
|
175
|
+
const cleanScreen = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l).join('\n');
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
// Import the condition evaluator — but we need it as a module-level fn.
|
|
179
|
+
// Instead, call evaluate() and check: if the evaluator chose the target
|
|
180
|
+
// via an *explicit* state match (not fallback), return true.
|
|
181
|
+
// We detect a fallback via trace: the fallback emits "(no state matched".
|
|
182
|
+
const result = evaluate(spec, screen, cursor);
|
|
183
|
+
const wasFallback = result.trace.some(t => t.text.startsWith('(no state matched'));
|
|
184
|
+
return result.state.id === targetId && !wasFallback;
|
|
185
|
+
} catch {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export class SpecDriver {
|
|
191
|
+
private spec!: CliSpec;
|
|
192
|
+
private adapter!: TerminalAdapter;
|
|
193
|
+
private listeners = new Set<(ev: DashboardEvent) => void>();
|
|
194
|
+
private currentStateId: string | null = null;
|
|
195
|
+
/** Have we ever seen the spec's idle state *after* the startup grace
|
|
196
|
+
* window? Until we do, the agent's startup banner may still be
|
|
197
|
+
* painting and any send_message we forward to the PTY will be wiped
|
|
198
|
+
* when the banner clears the screen. Queue + drain on first valid
|
|
199
|
+
* idle. */
|
|
200
|
+
private idleSeenOnce = false;
|
|
201
|
+
private startedAtMs = 0;
|
|
202
|
+
private pendingSends: string[] = [];
|
|
203
|
+
private currentEval: SpecEvaluation | null = null;
|
|
204
|
+
private pickerInProgress: { control_id: string; phase: 'waiting'; spec: Control } | null = null;
|
|
205
|
+
private delegateTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
206
|
+
/** Timestamp of the last time the evaluator returned busy. Used to debounce
|
|
207
|
+
* the busy → idle transition (see reevaluate). */
|
|
208
|
+
private lastBusyAt = 0;
|
|
209
|
+
/** The exact busy state object we last saw — held alongside lastBusyAt so
|
|
210
|
+
* the hold can re-emit the same { id: 'busy', label, title } payload the
|
|
211
|
+
* dashboard already learned about. currentEval can't fill this role
|
|
212
|
+
* because the evaluator already moved past busy by the time the hold
|
|
213
|
+
* kicks in. */
|
|
214
|
+
private lastBusyState: SpecEvaluation['state'] | null = null;
|
|
215
|
+
/** Timestamp of the last time we entered a modal state (approval/picker or
|
|
216
|
+
* any non-busy non-idle state). Used to suppress brief busy blips that
|
|
217
|
+
* appear while the modal is still on screen — Claude Code streams body
|
|
218
|
+
* text that transiently shows a spinner even while an approval modal is
|
|
219
|
+
* visible, causing rapid approval→busy→approval flicker on the dashboard. */
|
|
220
|
+
private lastModalAt = 0;
|
|
221
|
+
/** The modal state snapshot held across busy blips. */
|
|
222
|
+
private lastModalState: SpecEvaluation['state'] | null = null;
|
|
223
|
+
/** Timestamp of when we last *exited* a modal state (approval/picker → idle
|
|
224
|
+
* or directly via completion_idle_after). Used to suppress completion_idle_after
|
|
225
|
+
* firings that were queued before the modal appeared and expire immediately
|
|
226
|
+
* after the modal is dismissed — without this the agent appears idle even
|
|
227
|
+
* though it is still generating. */
|
|
228
|
+
private lastModalExitAt = 0;
|
|
229
|
+
private completionIdleFirstSeenAt = 0;
|
|
230
|
+
private completionIdleKey = '';
|
|
231
|
+
/** Previous screen lines — passed to evaluate() for `changed` condition detection. */
|
|
232
|
+
private prevScreenLines: string[] = [];
|
|
233
|
+
/** Timer that re-runs evaluate() once the hold window expires. Needed
|
|
234
|
+
* because the PTY stops emitting once the agent finishes; without an
|
|
235
|
+
* explicit wake-up there's nothing to trigger the busy → idle
|
|
236
|
+
* downshift. */
|
|
237
|
+
private busyExpiryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
238
|
+
/** Set true while reevaluate() is invoked from busyExpiryTimer callback. */
|
|
239
|
+
private busyExpiryFired = false;
|
|
240
|
+
/** Pending idle-commit timer. Armed when the evaluator first returns idle;
|
|
241
|
+
* fires after idle_hold_ms if no non-idle reading has cancelled it. */
|
|
242
|
+
private idleHoldTimer: ReturnType<typeof setTimeout> | null = null;
|
|
243
|
+
/** State snapshot captured when the idle hold was armed — emitted on commit. */
|
|
244
|
+
private pendingIdleState: SpecEvaluation['state'] | null = null;
|
|
245
|
+
private specWatcher: fs.FSWatcher | null = null;
|
|
246
|
+
/** Ring buffer of committed state transitions (max 50). */
|
|
247
|
+
private stateHistory: Array<{
|
|
248
|
+
stateId: string;
|
|
249
|
+
label: string;
|
|
250
|
+
at: number;
|
|
251
|
+
durationMs: number;
|
|
252
|
+
reason: string;
|
|
253
|
+
matchedStateId?: string;
|
|
254
|
+
matchedRules?: string[];
|
|
255
|
+
debounceKind?: string;
|
|
256
|
+
idleHoldMs?: number;
|
|
257
|
+
busyHoldMs?: number;
|
|
258
|
+
}> = [];
|
|
259
|
+
private prevStateAt = 0;
|
|
260
|
+
|
|
261
|
+
constructor(private readonly opts: SpecDriverOpts) {
|
|
262
|
+
this.loadSpecOrThrow();
|
|
263
|
+
this.adapter = new TerminalAdapter(
|
|
264
|
+
this.buildAdapterOpts(),
|
|
265
|
+
{
|
|
266
|
+
init: () => this.emitInitialState(),
|
|
267
|
+
on_pty_data: (chunk) => this.emit({ kind: 'pty_data', chunk }),
|
|
268
|
+
on_screen_changed: () => this.reevaluate(),
|
|
269
|
+
on_exit: ({ exitCode }) => this.handleExit(exitCode),
|
|
270
|
+
},
|
|
271
|
+
);
|
|
272
|
+
if (this.opts.hotReload !== false) this.armSpecWatcher();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Subscribe to outbound events. Returns an unsubscribe fn. */
|
|
276
|
+
subscribe(listener: (ev: DashboardEvent) => void): () => void {
|
|
277
|
+
this.listeners.add(listener);
|
|
278
|
+
return () => { this.listeners.delete(listener); };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
start(): void {
|
|
282
|
+
this.startedAtMs = Date.now();
|
|
283
|
+
this.adapter.start();
|
|
284
|
+
// Make sure we always re-evaluate once the startup grace has
|
|
285
|
+
// expired. Without an explicit wake-up the PTY can go quiet
|
|
286
|
+
// immediately after the banner paints (agy: the screen stays at
|
|
287
|
+
// the input prompt forever), there's no on_screen_changed event
|
|
288
|
+
// to trigger reevaluate, and any send_message we queued during
|
|
289
|
+
// the grace window would never drain.
|
|
290
|
+
const graceMs = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
|
|
291
|
+
setTimeout(() => this.reevaluate(), graceMs + 100);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
dispatch(cmd: DashboardCommand): void {
|
|
295
|
+
switch (cmd.kind) {
|
|
296
|
+
case 'send_message': this.handleSendMessage(cmd.text); return;
|
|
297
|
+
case 'pty_write': this.adapter.send_keys(cmd.data); return;
|
|
298
|
+
case 'click_control': this.handleClickControl(cmd.control_id, cmd.payload); return;
|
|
299
|
+
case 'click_modal_button': this.handleClickModalButton(cmd.index); return;
|
|
300
|
+
case 'attach_image': this.handleAttachImage(cmd.blob, cmd.mime); return;
|
|
301
|
+
case 'resize': this.adapter.resize(cmd.cols, cmd.rows); return;
|
|
302
|
+
case 'cancel': this.adapter.send_keys('\x03'); return;
|
|
303
|
+
case 'shutdown': this.shutdown(); return;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
snapshot(): string {
|
|
308
|
+
return this.adapter.snapshot();
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
getCursorPosition(): { row: number; col: number } {
|
|
312
|
+
return this.adapter.getCursorPosition();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
shutdown(): void {
|
|
316
|
+
for (const t of this.delegateTimers.values()) clearTimeout(t);
|
|
317
|
+
this.delegateTimers.clear();
|
|
318
|
+
this.cancelIdleHold();
|
|
319
|
+
if (this.busyExpiryTimer) { clearTimeout(this.busyExpiryTimer); this.busyExpiryTimer = null; }
|
|
320
|
+
this.specWatcher?.close();
|
|
321
|
+
this.adapter.kill();
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private cancelIdleHold(): void {
|
|
325
|
+
if (this.idleHoldTimer) { clearTimeout(this.idleHoldTimer); this.idleHoldTimer = null; }
|
|
326
|
+
this.pendingIdleState = null;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private pushHistory(stateId: string, label: string, meta?: {
|
|
330
|
+
reason?: string;
|
|
331
|
+
matchedStateId?: string;
|
|
332
|
+
matchedRules?: string[];
|
|
333
|
+
debounceKind?: string;
|
|
334
|
+
idleHoldMs?: number;
|
|
335
|
+
busyHoldMs?: number;
|
|
336
|
+
}): void {
|
|
337
|
+
const now = Date.now();
|
|
338
|
+
const durationMs = this.prevStateAt > 0 ? now - this.prevStateAt : 0;
|
|
339
|
+
this.prevStateAt = now;
|
|
340
|
+
this.stateHistory.push({
|
|
341
|
+
stateId,
|
|
342
|
+
label,
|
|
343
|
+
at: now,
|
|
344
|
+
durationMs,
|
|
345
|
+
reason: meta?.reason ?? 'eval_match',
|
|
346
|
+
...(meta?.matchedStateId !== undefined ? { matchedStateId: meta.matchedStateId } : {}),
|
|
347
|
+
...(meta?.matchedRules !== undefined ? { matchedRules: meta.matchedRules } : {}),
|
|
348
|
+
...(meta?.debounceKind !== undefined ? { debounceKind: meta.debounceKind } : {}),
|
|
349
|
+
...(meta?.idleHoldMs !== undefined ? { idleHoldMs: meta.idleHoldMs } : {}),
|
|
350
|
+
...(meta?.busyHoldMs !== undefined ? { busyHoldMs: meta.busyHoldMs } : {}),
|
|
351
|
+
});
|
|
352
|
+
if (this.stateHistory.length > 50) this.stateHistory.shift();
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
getStateHistory(): ReadonlyArray<{
|
|
356
|
+
stateId: string;
|
|
357
|
+
label: string;
|
|
358
|
+
at: number;
|
|
359
|
+
durationMs: number;
|
|
360
|
+
reason: string;
|
|
361
|
+
matchedStateId?: string;
|
|
362
|
+
matchedRules?: string[];
|
|
363
|
+
debounceKind?: string;
|
|
364
|
+
idleHoldMs?: number;
|
|
365
|
+
busyHoldMs?: number;
|
|
366
|
+
}> {
|
|
367
|
+
return this.stateHistory;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
getLastBusyAt(): number { return this.lastBusyAt; }
|
|
371
|
+
hasIdleHoldPending(): boolean { return this.idleHoldTimer !== null; }
|
|
372
|
+
getSpecPath(): string { return this.opts.specPath; }
|
|
373
|
+
getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null {
|
|
374
|
+
if (!this.completionIdleKey || !this.completionIdleFirstSeenAt) return null;
|
|
375
|
+
const rule = this.spec.debounce?.completion_idle_after;
|
|
376
|
+
if (!rule) return null;
|
|
377
|
+
return {
|
|
378
|
+
active: true,
|
|
379
|
+
ageMs: Date.now() - this.completionIdleFirstSeenAt,
|
|
380
|
+
holdMs: rule.hold_ms ?? 0,
|
|
381
|
+
forceAfterMs: typeof rule.force_after_ms === 'number' ? rule.force_after_ms : 0,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
getScreen(): string { return this.adapter.snapshot(); }
|
|
385
|
+
getSections(): Array<{ id: string; text: string }> | null {
|
|
386
|
+
try {
|
|
387
|
+
const screen = this.adapter.snapshot();
|
|
388
|
+
const ev = evaluate(this.spec, screen, undefined);
|
|
389
|
+
return ev.sections.map(s => ({ id: s.id, text: s.text }));
|
|
390
|
+
} catch { return null; }
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ────────────────────────────────────────────────────────────────────
|
|
394
|
+
// Loading & adapter wiring
|
|
395
|
+
// ────────────────────────────────────────────────────────────────────
|
|
396
|
+
|
|
397
|
+
private loadSpecOrThrow(): void {
|
|
398
|
+
const res = loadSpec(this.opts.specPath);
|
|
399
|
+
if (!res.ok) throw new Error(`spec invalid: ${res.errors.join('; ')}`);
|
|
400
|
+
this.spec = res.spec;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private buildAdapterOpts(): TerminalAdapterOpts {
|
|
404
|
+
const baseArgs = this.spec.spawn_args ?? [];
|
|
405
|
+
const extra = this.opts.extraCliArgs ?? [];
|
|
406
|
+
return {
|
|
407
|
+
binary: this.spec.binary,
|
|
408
|
+
args: [...baseArgs, ...extra],
|
|
409
|
+
cwd: this.opts.workingDir,
|
|
410
|
+
env: { ...(this.spec.env ?? {}), ...(this.opts.extraEnv ?? {}) },
|
|
411
|
+
cols: this.opts.cols ?? DEFAULT_SESSION_HOST_COLS,
|
|
412
|
+
rows: this.opts.rows ?? DEFAULT_SESSION_HOST_ROWS,
|
|
413
|
+
transportFactory: this.opts.transportFactory,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private armSpecWatcher(): void {
|
|
418
|
+
try {
|
|
419
|
+
// Watch the parent directory so we catch atomic replacements
|
|
420
|
+
// (cp, install scripts) that create a new inode — a file-level
|
|
421
|
+
// watch misses those on macOS because the original inode is gone.
|
|
422
|
+
const dir = path.dirname(this.opts.specPath);
|
|
423
|
+
const base = path.basename(this.opts.specPath);
|
|
424
|
+
this.specWatcher = fs.watch(dir, { persistent: false }, (_event, filename) => {
|
|
425
|
+
if (filename && filename !== base) return;
|
|
426
|
+
const res = loadSpec(this.opts.specPath);
|
|
427
|
+
if (!res.ok) { this.emit({ kind: 'spec_error', errors: res.errors }); return; }
|
|
428
|
+
this.spec = res.spec;
|
|
429
|
+
this.reevaluate(/*forceEmit*/ true);
|
|
430
|
+
});
|
|
431
|
+
} catch { /* watch is best-effort */ }
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// ────────────────────────────────────────────────────────────────────
|
|
435
|
+
// Evaluation pipeline
|
|
436
|
+
// ────────────────────────────────────────────────────────────────────
|
|
437
|
+
|
|
438
|
+
private emitInitialState(): void {
|
|
439
|
+
// Start with an empty-screen evaluation so the dashboard immediately
|
|
440
|
+
// knows about the default state.
|
|
441
|
+
this.reevaluate(true);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Re-arm the timer that wakes the driver up after BUSY_HOLD_MS so it
|
|
445
|
+
* can decide whether to downshift to idle. Always uses the most recent
|
|
446
|
+
* hold value so a spec hot-reload that shortens the hold takes effect
|
|
447
|
+
* on the next busy entry. Safe to call repeatedly; only the last call
|
|
448
|
+
* fires. */
|
|
449
|
+
private scheduleBusyExpiry(holdMs: number): void {
|
|
450
|
+
if (this.busyExpiryTimer) clearTimeout(this.busyExpiryTimer);
|
|
451
|
+
this.busyExpiryTimer = setTimeout(() => {
|
|
452
|
+
this.busyExpiryTimer = null;
|
|
453
|
+
LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] busyExpiry fired holdMs=${holdMs}`);
|
|
454
|
+
this.busyExpiryFired = true;
|
|
455
|
+
this.reevaluate();
|
|
456
|
+
this.busyExpiryFired = false;
|
|
457
|
+
}, Math.max(holdMs + 50, 100));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
private reevaluate(forceEmit = false): void {
|
|
461
|
+
const screen = this.adapter.snapshot();
|
|
462
|
+
const cursor = this.adapter.getCursorPosition();
|
|
463
|
+
const ev = evaluate(this.spec, screen, cursor, this.prevScreenLines.length > 0 ? this.prevScreenLines : undefined);
|
|
464
|
+
// Update prevScreenLines for next evaluation's `changed` condition detection.
|
|
465
|
+
this.prevScreenLines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
|
|
466
|
+
|
|
467
|
+
// Busy hold: many TUIs flicker between busy and idle every frame
|
|
468
|
+
// (claude in particular — its token counter appears and disappears
|
|
469
|
+
// as the layout reflows). Once we see busy, hold that state for
|
|
470
|
+
// BUSY_HOLD_MS before allowing a downshift to idle. Any state
|
|
471
|
+
// *other* than idle clears the hold immediately (approval is
|
|
472
|
+
// strictly more interesting than busy, so it shouldn't be held
|
|
473
|
+
// back). The hold lives on the driver, not the evaluator, so the
|
|
474
|
+
// spec author doesn't have to think about debouncing.
|
|
475
|
+
let evState = ev.state;
|
|
476
|
+
const busyHoldMs = this.spec.debounce?.busy_hold_ms ?? BUSY_HOLD_MS;
|
|
477
|
+
if (this.currentStateId === 'busy' && evState.id === 'idle') {
|
|
478
|
+
const ageMs = Date.now() - this.lastBusyAt;
|
|
479
|
+
if (ageMs < busyHoldMs) {
|
|
480
|
+
// Pin to the last seen busy state directly — currentEval can
|
|
481
|
+
// already be idle at this point (it tracks the previous tick,
|
|
482
|
+
// which during the flicker is just as likely to be idle as
|
|
483
|
+
// busy), so we can't rely on it to recover the busy label.
|
|
484
|
+
evState = this.lastBusyState ?? evState;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
// Modal hold: when in a modal state (approval, picker, etc.) a brief
|
|
488
|
+
// busy reading should not interrupt the modal. Claude Code streams
|
|
489
|
+
// body content while the approval modal is visible, causing a spinner
|
|
490
|
+
// to appear transiently — without this hold, the dashboard sees a
|
|
491
|
+
// rapid modal→busy→modal flicker and the approval UI disappears and
|
|
492
|
+
// reappears every few seconds. Apply the same busy_hold_ms window:
|
|
493
|
+
// if the modal was entered recently and the evaluator now returns
|
|
494
|
+
// busy, stay in the modal state until the hold expires or a non-busy
|
|
495
|
+
// non-modal reading arrives.
|
|
496
|
+
const idleStateId = this.spec.default_state ?? 'idle';
|
|
497
|
+
const isModalState = (id: string | null) =>
|
|
498
|
+
id !== null && id !== 'busy' && id !== idleStateId;
|
|
499
|
+
if (isModalState(this.currentStateId) && evState.id === 'busy') {
|
|
500
|
+
const ageMs = Date.now() - this.lastModalAt;
|
|
501
|
+
if (ageMs < busyHoldMs && this.lastModalState) {
|
|
502
|
+
evState = this.lastModalState;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
const completionIdleRule = this.spec.debounce?.completion_idle_after;
|
|
506
|
+
let busyWakeMs = busyHoldMs;
|
|
507
|
+
// Don't fire completion_idle_after while in a modal state (approval,
|
|
508
|
+
// picker, etc.) or within a grace period after leaving one. Two cases:
|
|
509
|
+
// 1. Modal still active: the hold window may have expired so evState
|
|
510
|
+
// resolves to busy, but the user is still looking at the approval screen.
|
|
511
|
+
// 2. Modal just dismissed: the timer may have been queued *before* the
|
|
512
|
+
// approval appeared and its hold expires immediately after dismissal,
|
|
513
|
+
// causing a false-idle even though the agent is still generating.
|
|
514
|
+
const postModalGraceMs = busyHoldMs;
|
|
515
|
+
const now = Date.now();
|
|
516
|
+
const recentlyInModal = isModalState(this.currentStateId) || (this.lastModalAt > 0 && now - this.lastModalAt < postModalGraceMs);
|
|
517
|
+
const recentlyLeftModal = !recentlyInModal && this.lastModalExitAt > 0 && now - this.lastModalExitAt < postModalGraceMs;
|
|
518
|
+
if (evState.id === 'busy' && completionIdleRule && !recentlyInModal && !recentlyLeftModal) {
|
|
519
|
+
const completionKey = matchesCompletionIdleRule(this.spec, ev, screen);
|
|
520
|
+
if (completionKey) {
|
|
521
|
+
const now = Date.now();
|
|
522
|
+
if (completionKey !== this.completionIdleKey) {
|
|
523
|
+
this.completionIdleKey = completionKey;
|
|
524
|
+
this.completionIdleFirstSeenAt = now;
|
|
525
|
+
LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] completion_idle_after matched: key="${completionKey}"`);
|
|
526
|
+
}
|
|
527
|
+
const holdMs = Math.max(0, completionIdleRule.hold_ms || 0);
|
|
528
|
+
const forceAfterMs = typeof completionIdleRule.force_after_ms === 'number'
|
|
529
|
+
? completionIdleRule.force_after_ms
|
|
530
|
+
: null;
|
|
531
|
+
const ageMs = now - this.completionIdleFirstSeenAt;
|
|
532
|
+
if (ageMs >= holdMs) {
|
|
533
|
+
const targetMatches = matchesCompletionIdleTargetState(this.spec, ev, screen, cursor);
|
|
534
|
+
const forced = !targetMatches && forceAfterMs !== null && ageMs >= holdMs + forceAfterMs;
|
|
535
|
+
LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] completion_idle_after hold expired ageMs=${ageMs} targetState=${targetMatches} forced=${forced} screenTail="${screen.split(/\r?\n/).slice(-3).join('\\n').slice(-200)}"`);
|
|
536
|
+
if (targetMatches || forced) {
|
|
537
|
+
const idle = this.spec.states.find(state => state.id === this.spec.default_state)
|
|
538
|
+
?? this.spec.states.find(state => state.id === 'idle');
|
|
539
|
+
evState = idle
|
|
540
|
+
? { id: idle.id, label: idle.label, title: null }
|
|
541
|
+
: { id: 'idle', label: 'Ready', title: null };
|
|
542
|
+
} else {
|
|
543
|
+
busyWakeMs = Math.min(busyWakeMs, 1000);
|
|
544
|
+
}
|
|
545
|
+
} else {
|
|
546
|
+
busyWakeMs = Math.min(busyWakeMs, Math.max(holdMs - ageMs, 0));
|
|
547
|
+
}
|
|
548
|
+
} else {
|
|
549
|
+
this.completionIdleKey = '';
|
|
550
|
+
this.completionIdleFirstSeenAt = 0;
|
|
551
|
+
}
|
|
552
|
+
} else if (evState.id !== 'busy') {
|
|
553
|
+
this.completionIdleKey = '';
|
|
554
|
+
this.completionIdleFirstSeenAt = 0;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
if (evState.id === 'busy') {
|
|
558
|
+
this.lastBusyAt = Date.now();
|
|
559
|
+
this.lastBusyState = evState;
|
|
560
|
+
// Cancel any pending idle commit — non-idle reading invalidates it.
|
|
561
|
+
this.cancelIdleHold();
|
|
562
|
+
// Reset completion_idle_after tracking only when the completion
|
|
563
|
+
// marker is NOT present. If the marker is on screen (key is set
|
|
564
|
+
// by the block above), clearing it here would restart the hold
|
|
565
|
+
// window on every PTY frame and the hold would never expire.
|
|
566
|
+
// Only reset when the marker disappeared (key is empty), meaning
|
|
567
|
+
// a new tool-output burst arrived that pushed the marker off
|
|
568
|
+
// screen — in that case the old firstSeenAt is stale and should
|
|
569
|
+
// restart when the marker reappears.
|
|
570
|
+
//
|
|
571
|
+
// Also reset on busy re-entry (transitioning back from a non-busy
|
|
572
|
+
// state). The previous generation may have set completionIdleKey
|
|
573
|
+
// and firstSeenAt; without this reset the hold window appears
|
|
574
|
+
// instantly expired on the new generation's first PTY frame that
|
|
575
|
+
// re-matches the same completion regex key, causing a false-idle
|
|
576
|
+
// before the new generation has a chance to run.
|
|
577
|
+
if (!this.completionIdleKey || this.currentStateId !== 'busy') {
|
|
578
|
+
this.completionIdleKey = '';
|
|
579
|
+
this.completionIdleFirstSeenAt = 0;
|
|
580
|
+
}
|
|
581
|
+
// Schedule a re-evaluation when the hold window expires. PTYs
|
|
582
|
+
// typically stop emitting once the agent stops printing (the
|
|
583
|
+
// footer settles), so without an explicit timer the driver
|
|
584
|
+
// never wakes up to downshift to idle and the dashboard sees
|
|
585
|
+
// status stuck at generating long after the turn ended.
|
|
586
|
+
this.scheduleBusyExpiry(busyWakeMs);
|
|
587
|
+
} else if (evState.id !== this.currentStateId && evState.id !== 'busy') {
|
|
588
|
+
// Non-busy modal states (approval, picker, signing_in) also cancel
|
|
589
|
+
// any in-flight idle hold — they are higher-priority than idle.
|
|
590
|
+
if (evState.id !== (this.spec.default_state ?? 'idle')) {
|
|
591
|
+
this.cancelIdleHold();
|
|
592
|
+
}
|
|
593
|
+
// Track the modal entry timestamp so the modal-hold above can
|
|
594
|
+
// suppress brief busy blips while the modal is still on screen.
|
|
595
|
+
if (isModalState(evState.id)) {
|
|
596
|
+
this.lastModalAt = Date.now();
|
|
597
|
+
this.lastModalState = evState;
|
|
598
|
+
} else {
|
|
599
|
+
// Leaving modal territory (going to idle) — clear the hold,
|
|
600
|
+
// but record the exit time so completion_idle_after can be
|
|
601
|
+
// suppressed during the grace period after dismissal.
|
|
602
|
+
if (this.lastModalAt > 0) this.lastModalExitAt = Date.now();
|
|
603
|
+
this.lastModalAt = 0;
|
|
604
|
+
this.lastModalState = null;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// Idle hold: if idle_hold_ms is set, don't commit idle immediately.
|
|
609
|
+
// Arm a timer; if a non-idle reading arrives before it fires, cancel.
|
|
610
|
+
const idleHoldMs = this.spec.debounce?.idle_hold_ms ?? 0;
|
|
611
|
+
const isIdleState = evState.id === (this.spec.default_state ?? 'idle');
|
|
612
|
+
if (isIdleState && idleHoldMs > 0 && this.currentStateId !== evState.id) {
|
|
613
|
+
if (!this.idleHoldTimer) {
|
|
614
|
+
this.pendingIdleState = evState;
|
|
615
|
+
const capturedEv = ev;
|
|
616
|
+
const capturedMatchedRules = extractMatchedRules(ev);
|
|
617
|
+
this.idleHoldTimer = setTimeout(() => {
|
|
618
|
+
this.idleHoldTimer = null;
|
|
619
|
+
const committed = this.pendingIdleState;
|
|
620
|
+
this.pendingIdleState = null;
|
|
621
|
+
if (!committed) return;
|
|
622
|
+
LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] idleHold committed after ${idleHoldMs}ms`);
|
|
623
|
+
this.currentStateId = committed.id;
|
|
624
|
+
this.currentEval = capturedEv;
|
|
625
|
+
this.pushHistory(committed.id, committed.label, {
|
|
626
|
+
reason: 'idle_hold_committed',
|
|
627
|
+
matchedStateId: capturedEv.state.id,
|
|
628
|
+
matchedRules: capturedMatchedRules,
|
|
629
|
+
debounceKind: 'idle_hold',
|
|
630
|
+
idleHoldMs,
|
|
631
|
+
});
|
|
632
|
+
this.emit({
|
|
633
|
+
kind: 'state_changed',
|
|
634
|
+
state: committed,
|
|
635
|
+
modal: null,
|
|
636
|
+
controls: capturedEv.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
|
|
637
|
+
});
|
|
638
|
+
this.armOrCancelDelegateTimers(committed.id);
|
|
639
|
+
if (this.opts.emitTrace) this.emit({ kind: 'spec_trace', entries: capturedEv.trace });
|
|
640
|
+
}, idleHoldMs);
|
|
641
|
+
}
|
|
642
|
+
// Don't fall through to the normal changed/emit path for idle.
|
|
643
|
+
this.currentEval = ev;
|
|
644
|
+
const graceMs2 = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
|
|
645
|
+
if (!this.idleSeenOnce && Date.now() - this.startedAtMs >= graceMs2) {
|
|
646
|
+
this.idleSeenOnce = true;
|
|
647
|
+
const queued = this.pendingSends.splice(0);
|
|
648
|
+
for (const text of queued) setTimeout(() => this.actuallySendMessage(text), 50);
|
|
649
|
+
}
|
|
650
|
+
if (this.pickerInProgress) this.tryAdvancePicker(screen);
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const changed = forceEmit
|
|
655
|
+
|| evState.id !== this.currentStateId
|
|
656
|
+
|| !shallowSameModal(ev, this.currentEval)
|
|
657
|
+
|| !shallowSameControls(ev, this.currentEval);
|
|
658
|
+
|
|
659
|
+
// Picker state tracking — if a picker is waiting for its
|
|
660
|
+
// wait_for cue and now sees it, complete the picker flow.
|
|
661
|
+
if (this.pickerInProgress) this.tryAdvancePicker(screen);
|
|
662
|
+
|
|
663
|
+
this.currentEval = ev;
|
|
664
|
+
// First time we ever see idle (or any non-busy non-startup state),
|
|
665
|
+
// flush any queued send_message calls that arrived before the
|
|
666
|
+
// agent finished painting its banner. Subsequent idle/busy
|
|
667
|
+
// toggles don't retrigger.
|
|
668
|
+
// Wait at least the spec's startup_grace_ms after start() so we
|
|
669
|
+
// don't treat a transient "matches no state, default idle"
|
|
670
|
+
// reading during the banner paint as a real idle. After that,
|
|
671
|
+
// the first non-busy observation is a real prompt-ready signal
|
|
672
|
+
// and we drain any queued send_message calls.
|
|
673
|
+
const graceMs = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
|
|
674
|
+
const sinceStart = Date.now() - this.startedAtMs;
|
|
675
|
+
if (!this.idleSeenOnce && evState.id !== 'busy' && sinceStart >= graceMs) {
|
|
676
|
+
this.idleSeenOnce = true;
|
|
677
|
+
const queued = this.pendingSends.splice(0);
|
|
678
|
+
for (const text of queued) {
|
|
679
|
+
setTimeout(() => this.actuallySendMessage(text), 50);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (changed) {
|
|
683
|
+
this.currentStateId = evState.id;
|
|
684
|
+
const matchedRules = extractMatchedRules(ev);
|
|
685
|
+
// Determine reason and debounce kind for this transition
|
|
686
|
+
let transitionReason: string;
|
|
687
|
+
let debounceKind: string;
|
|
688
|
+
let transitionBusyHoldMs: number | undefined;
|
|
689
|
+
if (forceEmit) {
|
|
690
|
+
transitionReason = 'forceEmit';
|
|
691
|
+
debounceKind = 'none';
|
|
692
|
+
} else if (evState.id !== ev.state.id) {
|
|
693
|
+
// evState was overridden — completion_idle_after forced idle
|
|
694
|
+
transitionReason = 'completion_idle_after';
|
|
695
|
+
debounceKind = 'completion_idle_after';
|
|
696
|
+
} else if (this.busyExpiryFired) {
|
|
697
|
+
// busyExpiryTimer woke us up and hold has now expired
|
|
698
|
+
transitionReason = 'busy_hold_expired';
|
|
699
|
+
debounceKind = 'busy_hold';
|
|
700
|
+
transitionBusyHoldMs = busyHoldMs;
|
|
701
|
+
} else {
|
|
702
|
+
transitionReason = 'eval_match';
|
|
703
|
+
debounceKind = 'none';
|
|
704
|
+
}
|
|
705
|
+
this.pushHistory(evState.id, evState.label, {
|
|
706
|
+
reason: transitionReason,
|
|
707
|
+
matchedStateId: ev.state.id,
|
|
708
|
+
matchedRules,
|
|
709
|
+
debounceKind,
|
|
710
|
+
...(transitionBusyHoldMs !== undefined ? { busyHoldMs: transitionBusyHoldMs } : {}),
|
|
711
|
+
});
|
|
712
|
+
this.emit({
|
|
713
|
+
kind: 'state_changed',
|
|
714
|
+
state: evState,
|
|
715
|
+
modal: ev.modal ? { title: ev.modal.title, buttons: ev.modal.buttons.map(b => ({ index: b.index, label: b.label })) } : null,
|
|
716
|
+
controls: ev.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
|
|
717
|
+
});
|
|
718
|
+
for (const n of ev.notifications) this.emit({ kind: 'notification', id: n.id, title: n.title, body: n.body });
|
|
719
|
+
this.armOrCancelDelegateTimers(evState.id);
|
|
720
|
+
if (this.opts.emitTrace) this.emit({ kind: 'spec_trace', entries: ev.trace });
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
private armOrCancelDelegateTimers(currentStateId: string): void {
|
|
725
|
+
for (const d of this.spec.delegate ?? []) {
|
|
726
|
+
const armed = this.delegateTimers.has(d.id);
|
|
727
|
+
const shouldFire = d.when_state === currentStateId;
|
|
728
|
+
if (shouldFire && !armed) {
|
|
729
|
+
const delay = d.after_duration_ms ?? 0;
|
|
730
|
+
const t = setTimeout(() => { this.fireDelegate(d); this.delegateTimers.delete(d.id); }, delay);
|
|
731
|
+
this.delegateTimers.set(d.id, t);
|
|
732
|
+
} else if (!shouldFire && armed) {
|
|
733
|
+
clearTimeout(this.delegateTimers.get(d.id)!);
|
|
734
|
+
this.delegateTimers.delete(d.id);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
private fireDelegate(d: DelegateTrigger): void {
|
|
740
|
+
const ev = this.currentEval;
|
|
741
|
+
const task = (d.task_template)
|
|
742
|
+
.replace(/\{node\}/g, os.hostname())
|
|
743
|
+
.replace(/\{state\.label\}/g, ev?.state.label ?? '')
|
|
744
|
+
.replace(/\{state\.title\}/g, ev?.state.title ?? '')
|
|
745
|
+
.replace(/\{duration_ms\}/g, String(d.after_duration_ms ?? 0));
|
|
746
|
+
this.emit({ kind: 'delegate', id: d.id, task });
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// ────────────────────────────────────────────────────────────────────
|
|
750
|
+
// Dashboard commands
|
|
751
|
+
// ────────────────────────────────────────────────────────────────────
|
|
752
|
+
|
|
753
|
+
private handleSendMessage(text: string): void {
|
|
754
|
+
if (!this.idleSeenOnce) {
|
|
755
|
+
// Agent is still drawing its startup banner. Queue and drain
|
|
756
|
+
// when we see idle so we don't fire keystrokes into a buffer
|
|
757
|
+
// that's about to be cleared.
|
|
758
|
+
this.pendingSends.push(text);
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
this.actuallySendMessage(text);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
private actuallySendMessage(text: string): void {
|
|
765
|
+
const sm = this.spec.send_message;
|
|
766
|
+
const perChar = sm.delay_ms_per_char ?? 0;
|
|
767
|
+
// Floor the gap between text and submit_key. Without this, claude /
|
|
768
|
+
// antigravity specs (which leave delay_ms_before_submit unset)
|
|
769
|
+
// race: text bytes and `\r` arrive back-to-back, the TUI processes
|
|
770
|
+
// the `\r` while still digesting the text input, and the prompt
|
|
771
|
+
// sits visible in the input field but never submits — the user has
|
|
772
|
+
// to press Enter manually. Scale with line count so multi-line
|
|
773
|
+
// pastes (which take longer for the TUI to render) get more
|
|
774
|
+
// settling time.
|
|
775
|
+
const beforeSubmit = resolveSubmitDelayMs(sm.delay_ms_before_submit, text);
|
|
776
|
+
if (perChar === 0) {
|
|
777
|
+
this.adapter.send_keys(text);
|
|
778
|
+
if (beforeSubmit > 0) setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
|
|
779
|
+
else this.adapter.send_keys(sm.submit_key);
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
let i = 0;
|
|
783
|
+
const iv = setInterval(() => {
|
|
784
|
+
if (i >= text.length) {
|
|
785
|
+
clearInterval(iv);
|
|
786
|
+
setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
this.adapter.send_keys(text[i]);
|
|
790
|
+
i += 1;
|
|
791
|
+
}, perChar);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
private handleClickControl(controlId: string, payload?: unknown): void {
|
|
795
|
+
const ctl = (this.spec.control_bar ?? []).find(c => c.id === controlId);
|
|
796
|
+
if (!ctl) return;
|
|
797
|
+
// Reject controls that aren't currently visible.
|
|
798
|
+
const ev = this.currentEval;
|
|
799
|
+
if (ctl.visible_when_state && ev && !ctl.visible_when_state.includes(ev.state.id)) return;
|
|
800
|
+
|
|
801
|
+
const a = ctl.action;
|
|
802
|
+
switch (a.type) {
|
|
803
|
+
case 'send_keys':
|
|
804
|
+
this.adapter.send_keys(a.keys);
|
|
805
|
+
return;
|
|
806
|
+
case 'open_picker':
|
|
807
|
+
this.adapter.send_keys(a.trigger_keys);
|
|
808
|
+
this.pickerInProgress = { control_id: ctl.id, phase: 'waiting', spec: ctl };
|
|
809
|
+
return;
|
|
810
|
+
case 'attach_image': {
|
|
811
|
+
const p = typeof payload === 'object' && payload && (payload as any).path;
|
|
812
|
+
if (typeof p === 'string') {
|
|
813
|
+
const keys = a.keys_template.replace(/\{path\}/g, p);
|
|
814
|
+
this.adapter.send_keys(keys);
|
|
815
|
+
}
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
private handleClickModalButton(index: number): void {
|
|
822
|
+
const m = this.currentEval?.modal;
|
|
823
|
+
if (!m) return;
|
|
824
|
+
const btn = m.buttons.find(b => b.index === index);
|
|
825
|
+
if (!btn) return;
|
|
826
|
+
this.adapter.send_keys(btn.key);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
private handleAttachImage(blob: string, mime: string): void {
|
|
830
|
+
// tempfile_then_keys: write decoded bytes to a temp file, then
|
|
831
|
+
// fire the attach_image control_bar entry with that path.
|
|
832
|
+
const ctl = (this.spec.control_bar ?? []).find(c => c.action.type === 'attach_image');
|
|
833
|
+
if (!ctl || ctl.action.type !== 'attach_image') return;
|
|
834
|
+
const ext = guessExt(mime);
|
|
835
|
+
const tmp = path.join(os.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
|
|
836
|
+
try {
|
|
837
|
+
fs.writeFileSync(tmp, Buffer.from(blob, 'base64'));
|
|
838
|
+
} catch { return; }
|
|
839
|
+
const keys = ctl.action.keys_template.replace(/\{path\}/g, tmp);
|
|
840
|
+
this.adapter.send_keys(keys);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
private tryAdvancePicker(screen: string): void {
|
|
844
|
+
const picker = this.pickerInProgress;
|
|
845
|
+
if (!picker) return;
|
|
846
|
+
const action = picker.spec.action;
|
|
847
|
+
if (action.type !== 'open_picker') return;
|
|
848
|
+
const hay = sectionTextFromSnapshot(this.spec, screen, action.wait_for.section) ?? screen;
|
|
849
|
+
if (!action.wait_for.regex) return;
|
|
850
|
+
const re = new RegExp(action.wait_for.regex, action.wait_for.flags ?? 'i');
|
|
851
|
+
if (!re.test(hay)) return;
|
|
852
|
+
// Cue arrived — the dashboard now sees the picker modal via
|
|
853
|
+
// state_changed. We do NOT auto-submit; the dashboard must call
|
|
854
|
+
// click_modal_button(index). After the modal closes the picker
|
|
855
|
+
// tracking naturally clears the next time the screen settles.
|
|
856
|
+
this.pickerInProgress = null;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
private handleExit(exitCode: number): void {
|
|
860
|
+
this.emit({ kind: 'exit', exit_code: exitCode });
|
|
861
|
+
this.shutdown();
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
private emit(ev: DashboardEvent): void {
|
|
865
|
+
for (const l of this.listeners) {
|
|
866
|
+
try { l(ev); } catch { /* listener side */ }
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function shallowSameModal(a: SpecEvaluation, b: SpecEvaluation | null): boolean {
|
|
872
|
+
if (!b) return false;
|
|
873
|
+
if (!a.modal && !b.modal) return true;
|
|
874
|
+
if (!a.modal || !b.modal) return false;
|
|
875
|
+
if (a.modal.title !== b.modal.title) return false;
|
|
876
|
+
if (a.modal.buttons.length !== b.modal.buttons.length) return false;
|
|
877
|
+
for (let i = 0; i < a.modal.buttons.length; i += 1) {
|
|
878
|
+
if (a.modal.buttons[i].label !== b.modal.buttons[i].label) return false;
|
|
879
|
+
}
|
|
880
|
+
return true;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function shallowSameControls(a: SpecEvaluation, b: SpecEvaluation | null): boolean {
|
|
884
|
+
if (!b) return false;
|
|
885
|
+
if (a.controls.length !== b.controls.length) return false;
|
|
886
|
+
for (let i = 0; i < a.controls.length; i += 1) {
|
|
887
|
+
if (a.controls[i].id !== b.controls[i].id) return false;
|
|
888
|
+
}
|
|
889
|
+
return true;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
function sectionTextFromSnapshot(spec: CliSpec, screen: string, sectionId: string | undefined): string | null {
|
|
893
|
+
if (!sectionId) return null;
|
|
894
|
+
const ev = evaluate(spec, screen);
|
|
895
|
+
return ev.sections.find(s => s.id === sectionId)?.text ?? null;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function guessExt(mime: string): string {
|
|
899
|
+
if (/png/i.test(mime)) return '.png';
|
|
900
|
+
if (/jpe?g/i.test(mime)) return '.jpg';
|
|
901
|
+
if (/gif/i.test(mime)) return '.gif';
|
|
902
|
+
if (/webp/i.test(mime)) return '.webp';
|
|
903
|
+
return '.bin';
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
function extractMatchedRules(ev: SpecEvaluation): string[] {
|
|
907
|
+
if (!Array.isArray(ev.trace)) return [];
|
|
908
|
+
return ev.trace
|
|
909
|
+
.filter(t => t.kind === 'state_match')
|
|
910
|
+
.map(t => t.text)
|
|
911
|
+
.filter(Boolean);
|
|
912
|
+
}
|