@miadi/tide 0.2.2 → 0.3.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/README.md +65 -3
- package/package.json +2 -2
- package/src/client.ts +54 -3
- package/src/herdr.ts +310 -30
- package/src/index.ts +17 -0
- package/src/steer-gate.ts +245 -0
package/README.md
CHANGED
|
@@ -68,15 +68,77 @@ they reset on herdr restart, and a stale id fails loudly with `pane_not_found`.
|
|
|
68
68
|
verbs: `runInHerdrPane`, `readHerdrPane` (recent-unwrapped text), `renameHerdrPane` (sets the
|
|
69
69
|
durable label), `waitForHerdrOutput` (typed `TideHerdrWaitOutputResult`),
|
|
70
70
|
`waitForHerdrAgentStatus` (typed `TideHerdrAgentStatusEvent` — live hits print an event
|
|
71
|
-
envelope), `listHerdrPanes/Workspaces/Tabs
|
|
72
|
-
|
|
73
|
-
`
|
|
71
|
+
envelope), `listHerdrPanes/Workspaces/Tabs`, and `getHerdrInventory({ includeTabs? })` — the
|
|
72
|
+
one-call snapshot (`TideHerdrInventory`: workspaces + panes, tabs on request) behind
|
|
73
|
+
`GET /api/tide/herdr`, so cockpit routes stay thin. `peek(pane, lines, { multiplexer: "herdr" })`
|
|
74
|
+
reads herdr scrollback through the stable peek verb. Pane-id segments are alphanumeric
|
|
75
|
+
(`w2:pE` past `p9`). Binary resolution: `TIDE_HERDR_BIN` → `herdr` on `PATH`.
|
|
74
76
|
|
|
75
77
|
> **Readiness: `live-verified`.** Smoked against a real herdr 0.7.4 instance (EP137
|
|
76
78
|
> herdr-smoke lane, 2026-07-16) — inventory parsing, send-text/send-keys, pane run, read,
|
|
77
79
|
> wait output (hit + timeout exit codes), agent-status, and label→id resolution — in
|
|
78
80
|
> addition to the injected-runner tests in `test/herdr.test.ts`.
|
|
79
81
|
|
|
82
|
+
#### Observer inventory + capability advertisement (EP152, live-verified)
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { getHerdrSnapshot, describeHerdrCapabilities } from "@miadi/tide"
|
|
86
|
+
|
|
87
|
+
const snap = await getHerdrSnapshot()
|
|
88
|
+
// `herdr api snapshot` — the whole observer inventory in ONE socket round-trip
|
|
89
|
+
// (socket method session.snapshot): workspaces, tabs, panes, detected agents,
|
|
90
|
+
// the focus triple, and the server's version/protocol. Read-only, consistent
|
|
91
|
+
// (no tearing across a workspace/tab/pane list stitch).
|
|
92
|
+
|
|
93
|
+
const caps = await describeHerdrCapabilities()
|
|
94
|
+
// `herdr api schema --json` — capability advertisement DERIVED from the live
|
|
95
|
+
// schema document: { available, protocol, schema_version, methods[] } plus
|
|
96
|
+
// deterministic boolean views (inventory, snapshot, labels, agents,
|
|
97
|
+
// wait_output, wait_events, lifecycle_advertised). `lifecycle_authorized` is
|
|
98
|
+
// constant false: the server ADVERTISING workspace.close does not authorize
|
|
99
|
+
// this client to drive it — that flips only when the closure-receipts ladder
|
|
100
|
+
// lands as code. Never throws: a failed probe returns { available: false,
|
|
101
|
+
// reason } — safe for /api/tide/health.
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Live receipts (herdr 0.7.4, protocol 16, EP152 2026-07-18): 85 advertised socket
|
|
105
|
+
methods, all seven derived flags true, snapshot of 7 workspaces / 22 tabs / 44
|
|
106
|
+
panes / 21 agents. That smoke also showed pane ids go **alphanumeric** past `p9`
|
|
107
|
+
(`w2:pE`, `w7:pA`) — herdr's own schema types `pane_id` as a plain string — so the
|
|
108
|
+
client id pattern accepts the family agreed with `@miadi/tide-contract` 0.2.3:
|
|
109
|
+
`w[0-9A-Za-z]+:p[0-9A-Za-z]+` (the dashed legacy form stays digits-only).
|
|
110
|
+
|
|
111
|
+
#### Steer gate — ACTIVE_CONTROLLER + TTY + live target (EP152 wave-2)
|
|
112
|
+
|
|
113
|
+
Every steer **execution** (`sendKeys` tmux + herdr, `sendKeysViaHerdr`,
|
|
114
|
+
`runInHerdrPane`) passes the 3-part gate ported from the Python runtime's
|
|
115
|
+
`tide operator send --run` boundary (`src/steer-gate.ts`):
|
|
116
|
+
|
|
117
|
+
1. **live-resolved target** — the pane must appear in the CURRENT multiplexer
|
|
118
|
+
inventory (`tmux list-panes -a` / `herdr pane list`; label resolution counts
|
|
119
|
+
as live proof);
|
|
120
|
+
2. **ACTIVE_CONTROLLER posture** — `mode: controller` in
|
|
121
|
+
`${MIADI_HOME|~/.miadi/navigator}/config.yml`, with the controller TTL lease
|
|
122
|
+
applied on every read (an expired lease reads as observer, fail-closed);
|
|
123
|
+
3. **interactive local TTY** — or `TIDE_ALLOW_NON_INTERACTIVE_RUN=1` set by an
|
|
124
|
+
approval-queue-fronted service after its own review.
|
|
125
|
+
|
|
126
|
+
A refused steer throws `TideError` naming **every** failed check and never
|
|
127
|
+
touches the multiplexer. Plan builders (`buildSendKeysPlan`,
|
|
128
|
+
`buildHerdrSendKeysPlan`) stay ungated — dry-run is the covenant's default
|
|
129
|
+
posture. `evaluateSteerGate`/`requireSteerGate`/`readNavigatorPosture` are
|
|
130
|
+
exported for `/api/tide/health`-style surfaces. The `gate` option injects
|
|
131
|
+
probes (tests, first-party wiring); it cannot disable the gate, and overrides
|
|
132
|
+
are only accepted when branded by `trustSteerGateProbes()` — which is NOT on
|
|
133
|
+
the package surface (direct module import only; the brand is a module-private
|
|
134
|
+
non-enumerable Symbol, so JSON/request-derived gate options are structurally
|
|
135
|
+
refused).
|
|
136
|
+
|
|
137
|
+
Label hardening (same wave): resolution is NFC-normalized, label-only (the
|
|
138
|
+
`title` fallback is gone), **duplicate labels are a hard refusal**, and
|
|
139
|
+
`{ workspace: "w7" }` scopes resolution. Wrong-multiplexer dispatch fails
|
|
140
|
+
loudly in both directions (a herdr-shaped id on the tmux path and vice versa).
|
|
141
|
+
|
|
80
142
|
`getTerminals` and `detect` are the read-only surface behind `GET /api/tide/terminals`
|
|
81
143
|
and `GET /api/tide/detect` — the typed half of operator-terminal triage and manual
|
|
82
144
|
domain assignment (jgwill/Miadi#382). The write-back half (assign a pane to a domain)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@miadi/tide",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Typed client boundary for the ironsilk `tide` runtime. Daemon Unix-socket transport with CLI fallback.",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"src"
|
|
16
16
|
],
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@miadi/tide-contract": "0.2.
|
|
18
|
+
"@miadi/tide-contract": "0.2.4"
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
|
21
21
|
"test": "d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && node --test \"$d\"/packages/tide/test/*.test.js"
|
package/src/client.ts
CHANGED
|
@@ -41,8 +41,16 @@ import {
|
|
|
41
41
|
TideDaemonError,
|
|
42
42
|
} from "./socket"
|
|
43
43
|
import { TideError } from "./errors"
|
|
44
|
-
import {
|
|
44
|
+
import {
|
|
45
|
+
HERDR_PANE_ID_PATTERN,
|
|
46
|
+
buildHerdrSendKeysPlan,
|
|
47
|
+
readHerdrPane,
|
|
48
|
+
resolveHerdrPaneId,
|
|
49
|
+
sendKeysViaHerdr,
|
|
50
|
+
} from "./herdr"
|
|
45
51
|
import type { HerdrCommandRunner } from "./herdr"
|
|
52
|
+
import { requireSteerGate, acceptGateOverrides } from "./steer-gate"
|
|
53
|
+
import type { SteerGateOverrides } from "./steer-gate"
|
|
46
54
|
|
|
47
55
|
const pExecFile = promisify(execFile)
|
|
48
56
|
|
|
@@ -221,8 +229,11 @@ export interface PeekOptions extends TideRunOptions {
|
|
|
221
229
|
*/
|
|
222
230
|
export async function peek(pane: string, lines = 30, opts: PeekOptions = {}): Promise<TidePeekResult> {
|
|
223
231
|
if (opts.multiplexer === "herdr") {
|
|
224
|
-
|
|
225
|
-
|
|
232
|
+
// Resolve the label here so the result reports the CURRENT pane id, not
|
|
233
|
+
// the raw (possibly empty) pane argument. Same CLI cost: one list + one read.
|
|
234
|
+
const target = opts.paneLabel ? await resolveHerdrPaneId(opts.paneLabel, opts) : pane
|
|
235
|
+
const text = await readHerdrPane(target, lines, { ...opts, paneLabel: undefined })
|
|
236
|
+
return { multiplexer: "herdr", pane: target, lines: text.split("\n"), text }
|
|
226
237
|
}
|
|
227
238
|
return runTideJson<TidePeekResult>(
|
|
228
239
|
["operator", "peek", `%${pane}`, "--lines", String(lines), "--format", "json"],
|
|
@@ -295,6 +306,27 @@ export interface SendKeysOptions extends TideRunOptions {
|
|
|
295
306
|
paneLabel?: string
|
|
296
307
|
/** herdr only: injected command runner (tests). */
|
|
297
308
|
runner?: HerdrCommandRunner
|
|
309
|
+
/**
|
|
310
|
+
* Steer-gate probe overrides (test seam / cockpit injection). The gate
|
|
311
|
+
* itself cannot be disabled — these only answer its three questions
|
|
312
|
+
* (live target, ACTIVE_CONTROLLER posture, interactive TTY). See
|
|
313
|
+
* steer-gate.ts (EP152 wave-2 W1).
|
|
314
|
+
*/
|
|
315
|
+
gate?: SteerGateOverrides
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Steer-gate liveness probe for the tmux path: the `%N` target must appear in
|
|
320
|
+
* the CURRENT `tmux list-panes -a` inventory (the direct-transport analog of
|
|
321
|
+
* the Python gate's `resolution_status == "resolved"`). Read-only.
|
|
322
|
+
*/
|
|
323
|
+
async function tmuxTargetResolved(
|
|
324
|
+
target: string,
|
|
325
|
+
bin: string,
|
|
326
|
+
runOpts: { timeout: number; cwd?: string },
|
|
327
|
+
): Promise<boolean> {
|
|
328
|
+
const { stdout } = await pExecFile(bin, ["list-panes", "-a", "-F", "#{pane_id}"], runOpts)
|
|
329
|
+
return stdout.split("\n").some((line) => line.trim() === target)
|
|
298
330
|
}
|
|
299
331
|
|
|
300
332
|
/**
|
|
@@ -327,6 +359,11 @@ export function buildSendKeysPlan(
|
|
|
327
359
|
* separate `C-m` submits it. If the literal step succeeds but the submit step
|
|
328
360
|
* fails, the text is already on the pane's prompt (unsubmitted) — the thrown
|
|
329
361
|
* `TideError` names which step failed so the caller can surface that partial state.
|
|
362
|
+
*
|
|
363
|
+
* Execution is steer-gated (EP152 wave-2 W1, both multiplexers): live-resolved
|
|
364
|
+
* target + ACTIVE_CONTROLLER posture + interactive TTY (or approval-fronted
|
|
365
|
+
* `TIDE_ALLOW_NON_INTERACTIVE_RUN=1`) — the same 3-part boundary as
|
|
366
|
+
* `tide operator send --run`. `buildSendKeysPlan` stays ungated (dry-run).
|
|
330
367
|
*/
|
|
331
368
|
export async function sendKeys(
|
|
332
369
|
pane: string,
|
|
@@ -345,10 +382,24 @@ export async function sendKeys(
|
|
|
345
382
|
`sendKeys: "paneLabel"/"runner" are herdr-only options — pass multiplexer: "herdr"`,
|
|
346
383
|
)
|
|
347
384
|
}
|
|
385
|
+
// Wrong-multiplexer dispatch assertion (EP152 wave-2 W2): a herdr-shaped id
|
|
386
|
+
// on the tmux path would be blindly %-prefixed into a bogus tmux target
|
|
387
|
+
// ("%w1:p2") — or worse, parse as tmux session:window syntax. Fail loudly.
|
|
388
|
+
if (HERDR_PANE_ID_PATTERN.test(pane.trim())) {
|
|
389
|
+
throw new TideError(
|
|
390
|
+
`"${pane.trim()}" is a herdr pane id but the tmux path was selected — pass multiplexer:"herdr" to steer herdr panes`,
|
|
391
|
+
)
|
|
392
|
+
}
|
|
348
393
|
const submit = opts.submit ?? true
|
|
349
394
|
const plan = buildSendKeysPlan(pane, message, submit)
|
|
350
395
|
const bin = resolveTmuxBin()
|
|
351
396
|
const runOpts = { timeout: opts.timeoutMs ?? 10_000, cwd: opts.cwd }
|
|
397
|
+
const gate = acceptGateOverrides(opts.gate)
|
|
398
|
+
await requireSteerGate({
|
|
399
|
+
...gate,
|
|
400
|
+
target: plan.target,
|
|
401
|
+
resolveTarget: gate.resolveTarget ?? (() => tmuxTargetResolved(plan.target, bin, runOpts)),
|
|
402
|
+
})
|
|
352
403
|
try {
|
|
353
404
|
await pExecFile(bin, plan.literal_command, runOpts)
|
|
354
405
|
} catch (err) {
|
package/src/herdr.ts
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
// wait output <id> --match … [--regex] --timeout ms (JSON)
|
|
14
14
|
// wait agent-status <id> --status … --timeout ms (JSON)
|
|
15
15
|
// workspace list | tab list --workspace <id> | pane list (JSON)
|
|
16
|
+
// api snapshot one-call observer inventory (JSON)
|
|
17
|
+
// api schema --json capability advertisement source (JSON)
|
|
16
18
|
//
|
|
17
19
|
// herdr pane ids are "w<N>:p<M>" (e.g. "w1:p2") as of herdr 0.7; the legacy
|
|
18
20
|
// dashed "1-2" form is still accepted for older releases. Live smoke against
|
|
@@ -33,11 +35,16 @@ import { promisify } from "node:util"
|
|
|
33
35
|
import type {
|
|
34
36
|
TideAgentStatus,
|
|
35
37
|
TideHerdrAgentStatusEvent,
|
|
38
|
+
TideHerdrInventory,
|
|
36
39
|
TideHerdrPaneInfo,
|
|
37
40
|
TideHerdrSendKeysResult,
|
|
41
|
+
TideHerdrTabInfo,
|
|
38
42
|
TideHerdrWaitOutputResult,
|
|
43
|
+
TideHerdrWorkspaceInfo,
|
|
39
44
|
} from "@miadi/tide-contract"
|
|
40
45
|
import { TideError } from "./errors"
|
|
46
|
+
import { requireSteerGate, acceptGateOverrides } from "./steer-gate"
|
|
47
|
+
import type { SteerGateOverrides } from "./steer-gate"
|
|
41
48
|
import type { TideRunOptions } from "./client"
|
|
42
49
|
|
|
43
50
|
const pExecFile = promisify(execFile)
|
|
@@ -123,14 +130,24 @@ function parseHerdrJson<T>(stdout: string, what: string): T {
|
|
|
123
130
|
// ── Pane targets and label→id resolution ────────────────────────────────────
|
|
124
131
|
|
|
125
132
|
// "w1:p2" is the live herdr 0.7 format; the dashed "1-2" form is legacy.
|
|
126
|
-
|
|
133
|
+
// BOTH segments are ALPHANUMERIC, not digits-only: live herdr 0.7.4 (EP152,
|
|
134
|
+
// 2026-07-18) lists ids like "w2:pE" and "w2:pQ" once a workspace has grown
|
|
135
|
+
// past p9, and herdr's own API schema (`herdr api schema --json`, protocol 16)
|
|
136
|
+
// types pane_id as a plain string with no pattern. This is the ONE pattern
|
|
137
|
+
// family agreed with the tide-contract lineage (npm 0.2.3, EP152 wave-2
|
|
138
|
+
// reconciliation): w[0-9A-Za-z]+:p[0-9A-Za-z]+. The legacy dashed form stays
|
|
139
|
+
// digits-only as observed on older releases.
|
|
140
|
+
export const HERDR_PANE_ID_PATTERN = /^(w[0-9A-Za-z]+:p[0-9A-Za-z]+|[0-9]+-[0-9]+)$/
|
|
127
141
|
|
|
128
142
|
/** Validate a herdr pane id (e.g. "w1:p2"). Unlike tmux there is no `%` prefix to add. */
|
|
129
143
|
export function normalizeHerdrPaneTarget(pane: string): string {
|
|
130
144
|
const trimmed = pane.trim()
|
|
131
145
|
if (!HERDR_PANE_ID_PATTERN.test(trimmed)) {
|
|
146
|
+
const tmuxHint = /^%?[0-9]+$/.test(trimmed)
|
|
147
|
+
? `; "${trimmed}" looks like a tmux pane id — pass multiplexer:"tmux" (or omit multiplexer) for tmux panes`
|
|
148
|
+
: ""
|
|
132
149
|
throw new TideError(
|
|
133
|
-
`invalid herdr pane id "${pane}" (expected "w<workspace>:p<pane>", e.g. "w1:p2"); herdr ids are session-scoped — pass paneLabel to resolve by label instead`,
|
|
150
|
+
`invalid herdr pane id "${pane}" (expected "w<workspace>:p<pane>", e.g. "w1:p2"); herdr ids are session-scoped — pass paneLabel to resolve by label instead${tmuxHint}`,
|
|
134
151
|
)
|
|
135
152
|
}
|
|
136
153
|
return trimmed
|
|
@@ -139,23 +156,18 @@ export function normalizeHerdrPaneTarget(pane: string): string {
|
|
|
139
156
|
/**
|
|
140
157
|
* One row from `herdr pane list` — the covenant shape (tide-contract 0.2.2's
|
|
141
158
|
* `TideHerdrPaneInfo`) plus a `title` field tolerated for other herdr builds
|
|
142
|
-
* (live 0.7.4 rows never carry it; resolution
|
|
159
|
+
* (live 0.7.4 rows never carry it; label→id resolution is label-ONLY — the
|
|
160
|
+
* title fallback was removed by the EP152 wave-2 W2 hardening).
|
|
143
161
|
*/
|
|
144
162
|
export interface HerdrPaneInfo extends TideHerdrPaneInfo {
|
|
145
163
|
title?: string
|
|
146
164
|
}
|
|
147
165
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
label?: string
|
|
151
|
-
[key: string]: unknown
|
|
152
|
-
}
|
|
166
|
+
/** One row from `herdr workspace list` — the covenant shape (tide-contract 0.2.3). */
|
|
167
|
+
export type HerdrWorkspaceInfo = TideHerdrWorkspaceInfo
|
|
153
168
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
label?: string
|
|
157
|
-
[key: string]: unknown
|
|
158
|
-
}
|
|
169
|
+
/** One row from `herdr tab list` — the covenant shape (tide-contract 0.2.3). */
|
|
170
|
+
export type HerdrTabInfo = TideHerdrTabInfo
|
|
159
171
|
|
|
160
172
|
// herdr JSON envelopes nest payloads under `result` (the same nesting
|
|
161
173
|
// hermes-conductor parses in src/mux/backends/herdr.ts:
|
|
@@ -191,34 +203,258 @@ export async function listHerdrTabs(workspace: string, opts: HerdrRunOptions = {
|
|
|
191
203
|
return unwrapList<HerdrTabInfo>(parseHerdrJson<unknown>(stdout, "tab list"), "tabs", "tab list")
|
|
192
204
|
}
|
|
193
205
|
|
|
206
|
+
export interface HerdrInventoryOptions extends HerdrRunOptions {
|
|
207
|
+
/** Also list tabs per workspace (extra CLI spawns) and annotate each with its workspace_id. */
|
|
208
|
+
includeTabs?: boolean
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* One-call herdr inventory snapshot for cockpit surfaces: workspaces + panes
|
|
213
|
+
* (and tabs on request) through a single verb, so route handlers stay thin.
|
|
214
|
+
* Pane rows already carry workspace_id/tab_id/label/agent_status/cwd on live
|
|
215
|
+
* 0.7.4 — the UI can group panes by workspace without the tabs leg.
|
|
216
|
+
*/
|
|
217
|
+
export async function getHerdrInventory(opts: HerdrInventoryOptions = {}): Promise<TideHerdrInventory> {
|
|
218
|
+
const [workspaces, panes] = await Promise.all([listHerdrWorkspaces(opts), listHerdrPanes(opts)])
|
|
219
|
+
const inventory: TideHerdrInventory = {
|
|
220
|
+
multiplexer: "herdr",
|
|
221
|
+
captured_at: new Date().toISOString(),
|
|
222
|
+
workspaces,
|
|
223
|
+
panes,
|
|
224
|
+
}
|
|
225
|
+
if (opts.includeTabs) {
|
|
226
|
+
const perWorkspace = await Promise.all(
|
|
227
|
+
workspaces
|
|
228
|
+
.map((ws) => ws.workspace_id)
|
|
229
|
+
.filter((id): id is string => typeof id === "string" && id.length > 0)
|
|
230
|
+
.map(async (id) => (await listHerdrTabs(id, opts)).map((tab) => ({ ...tab, workspace_id: id }))),
|
|
231
|
+
)
|
|
232
|
+
inventory.tabs = perWorkspace.flat()
|
|
233
|
+
}
|
|
234
|
+
return inventory
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── Daemon-facing observer inventory + capability advertisement (EP152) ─────
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The `result.snapshot` payload of `herdr api snapshot` — the whole observer
|
|
241
|
+
* inventory in ONE round-trip over the herdr unix socket (socket method
|
|
242
|
+
* `session.snapshot`): every workspace, tab, pane, and detected agent, plus
|
|
243
|
+
* the focus triple and the server's version/protocol. Loosely typed like
|
|
244
|
+
* HerdrPaneInfo: the named fields are the ones observed live on herdr 0.7.4
|
|
245
|
+
* (EP152, 2026-07-18); unknown fields pass through.
|
|
246
|
+
*/
|
|
247
|
+
export interface HerdrSnapshot {
|
|
248
|
+
version?: string
|
|
249
|
+
protocol?: number
|
|
250
|
+
focused_workspace_id?: string | null
|
|
251
|
+
focused_tab_id?: string | null
|
|
252
|
+
focused_pane_id?: string | null
|
|
253
|
+
workspaces?: HerdrWorkspaceInfo[]
|
|
254
|
+
tabs?: HerdrTabInfo[]
|
|
255
|
+
panes?: HerdrPaneInfo[]
|
|
256
|
+
/** Panes with a detected agent — same row shape as `panes`, minus `scroll`. */
|
|
257
|
+
agents?: HerdrPaneInfo[]
|
|
258
|
+
layouts?: unknown[]
|
|
259
|
+
[key: string]: unknown
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* `herdr api snapshot` — the smallest daemon-facing observer inventory:
|
|
264
|
+
* read-only, one CLI call, one socket round-trip underneath. Prefer this over
|
|
265
|
+
* stitching `workspace list` + `tab list` + `pane list` when a whole-instance
|
|
266
|
+
* view is needed (the three-call stitch can tear across concurrent changes;
|
|
267
|
+
* the snapshot is one consistent read).
|
|
268
|
+
*/
|
|
269
|
+
export async function getHerdrSnapshot(opts: HerdrRunOptions = {}): Promise<HerdrSnapshot> {
|
|
270
|
+
const { stdout } = await runHerdr(["api", "snapshot"], opts)
|
|
271
|
+
const payload = parseHerdrJson<unknown>(stdout, "api snapshot")
|
|
272
|
+
const env = payload as { result?: { snapshot?: unknown }; snapshot?: unknown } | null
|
|
273
|
+
const snap = env?.result?.snapshot ?? env?.snapshot
|
|
274
|
+
if (!snap || typeof snap !== "object" || Array.isArray(snap)) {
|
|
275
|
+
throw new TideError("herdr api snapshot returned an unexpected JSON shape")
|
|
276
|
+
}
|
|
277
|
+
return snap as HerdrSnapshot
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Capability advertisement for the herdr backend, DERIVED live from
|
|
282
|
+
* `herdr api schema --json` (a bare JSON-schema document: protocol,
|
|
283
|
+
* schema_version, and `schemas.request.oneOf[*].properties.method.const` —
|
|
284
|
+
* 85 socket methods on herdr 0.7.4 / protocol 16). Nothing here is
|
|
285
|
+
* hard-coded per herdr version: a herdr that gains or loses a method
|
|
286
|
+
* advertises differently. The boolean views are deterministic reads over
|
|
287
|
+
* `methods` in the MISSION vocabulary (inventory / snapshot / labels /
|
|
288
|
+
* agents / wait / lifecycle).
|
|
289
|
+
*/
|
|
290
|
+
export interface HerdrCapabilities {
|
|
291
|
+
multiplexer: "herdr"
|
|
292
|
+
/** False when the schema probe failed (binary missing, server down, bad JSON). */
|
|
293
|
+
available: boolean
|
|
294
|
+
/** Binary the probe used (TIDE_HERDR_BIN → "herdr" on PATH). */
|
|
295
|
+
binary: string
|
|
296
|
+
/** Socket protocol number from the schema document (16 on herdr 0.7.4). */
|
|
297
|
+
protocol: number | null
|
|
298
|
+
schema_version: number | null
|
|
299
|
+
/** Sorted socket method ids, e.g. "pane.list", "session.snapshot". */
|
|
300
|
+
methods: string[]
|
|
301
|
+
/** Why the probe failed, when `available` is false. */
|
|
302
|
+
reason?: string
|
|
303
|
+
/** workspace.list + tab.list + pane.list */
|
|
304
|
+
inventory: boolean
|
|
305
|
+
/** session.snapshot (the one-call observer inventory above) */
|
|
306
|
+
snapshot: boolean
|
|
307
|
+
/** pane.rename — durable labels for session-scoped pane ids */
|
|
308
|
+
labels: boolean
|
|
309
|
+
/** agent.list — detected-agent inventory with agent_status */
|
|
310
|
+
agents: boolean
|
|
311
|
+
/** pane.wait_for_output */
|
|
312
|
+
wait_output: boolean
|
|
313
|
+
/** events.wait — event subscription (agent-status waits ride on it) */
|
|
314
|
+
wait_events: boolean
|
|
315
|
+
/**
|
|
316
|
+
* workspace.create + tab.create + pane.split + pane.close are ADVERTISED by
|
|
317
|
+
* the server schema. Advertised is not authorized (W10b): the server
|
|
318
|
+
* answering a method exists says nothing about whether this client may
|
|
319
|
+
* drive it.
|
|
320
|
+
*/
|
|
321
|
+
lifecycle_advertised: boolean
|
|
322
|
+
/**
|
|
323
|
+
* Whether THIS CLIENT is authorized to drive lifecycle mutation
|
|
324
|
+
* (create/split/close). Constant `false`: the EP152 safety ladder
|
|
325
|
+
* (G0 observe → … → G4 close) and William's per-unit gate exist as mission
|
|
326
|
+
* law, not yet as code — no lifecycle verb ships in @miadi/tide until the
|
|
327
|
+
* closure-receipts contract does. Flips only with that implementation.
|
|
328
|
+
*/
|
|
329
|
+
lifecycle_authorized: false
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function extractSchemaMethods(doc: unknown): {
|
|
333
|
+
protocol: number | null
|
|
334
|
+
schema_version: number | null
|
|
335
|
+
methods: string[]
|
|
336
|
+
} {
|
|
337
|
+
const d = doc as {
|
|
338
|
+
protocol?: unknown
|
|
339
|
+
schema_version?: unknown
|
|
340
|
+
schemas?: { request?: { oneOf?: unknown } }
|
|
341
|
+
} | null
|
|
342
|
+
const variants = d?.schemas?.request?.oneOf
|
|
343
|
+
if (!Array.isArray(variants)) {
|
|
344
|
+
throw new TideError("herdr api schema returned an unexpected JSON shape (no schemas.request.oneOf)")
|
|
345
|
+
}
|
|
346
|
+
const methods = new Set<string>()
|
|
347
|
+
for (const v of variants) {
|
|
348
|
+
const m = (v as { properties?: { method?: { const?: unknown } } } | null)?.properties?.method?.const
|
|
349
|
+
if (typeof m === "string") methods.add(m)
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
protocol: typeof d?.protocol === "number" ? d.protocol : null,
|
|
353
|
+
schema_version: typeof d?.schema_version === "number" ? d.schema_version : null,
|
|
354
|
+
methods: [...methods].sort(),
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Probe the live herdr for its advertised capabilities. NEVER throws — a
|
|
360
|
+
* failed probe returns `available: false` with a `reason`, so cockpit health
|
|
361
|
+
* endpoints can call this unconditionally next to describeTransport().
|
|
362
|
+
*/
|
|
363
|
+
export async function describeHerdrCapabilities(opts: HerdrRunOptions = {}): Promise<HerdrCapabilities> {
|
|
364
|
+
const binary = resolveHerdrBin()
|
|
365
|
+
const unavailable = (reason: string): HerdrCapabilities => ({
|
|
366
|
+
multiplexer: "herdr",
|
|
367
|
+
available: false,
|
|
368
|
+
binary,
|
|
369
|
+
protocol: null,
|
|
370
|
+
schema_version: null,
|
|
371
|
+
methods: [],
|
|
372
|
+
reason,
|
|
373
|
+
inventory: false,
|
|
374
|
+
snapshot: false,
|
|
375
|
+
labels: false,
|
|
376
|
+
agents: false,
|
|
377
|
+
wait_output: false,
|
|
378
|
+
wait_events: false,
|
|
379
|
+
lifecycle_advertised: false,
|
|
380
|
+
lifecycle_authorized: false,
|
|
381
|
+
})
|
|
382
|
+
try {
|
|
383
|
+
const { stdout } = await runHerdr(["api", "schema", "--json"], opts)
|
|
384
|
+
const { protocol, schema_version, methods } = extractSchemaMethods(
|
|
385
|
+
parseHerdrJson<unknown>(stdout, "api schema"),
|
|
386
|
+
)
|
|
387
|
+
const has = (m: string) => methods.includes(m)
|
|
388
|
+
return {
|
|
389
|
+
multiplexer: "herdr",
|
|
390
|
+
available: true,
|
|
391
|
+
binary,
|
|
392
|
+
protocol,
|
|
393
|
+
schema_version,
|
|
394
|
+
methods,
|
|
395
|
+
inventory: has("workspace.list") && has("tab.list") && has("pane.list"),
|
|
396
|
+
snapshot: has("session.snapshot"),
|
|
397
|
+
labels: has("pane.rename"),
|
|
398
|
+
agents: has("agent.list"),
|
|
399
|
+
wait_output: has("pane.wait_for_output"),
|
|
400
|
+
wait_events: has("events.wait"),
|
|
401
|
+
lifecycle_advertised:
|
|
402
|
+
has("workspace.create") && has("tab.create") && has("pane.split") && has("pane.close"),
|
|
403
|
+
lifecycle_authorized: false,
|
|
404
|
+
}
|
|
405
|
+
} catch (err) {
|
|
406
|
+
return unavailable(err instanceof Error ? err.message : String(err))
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export interface HerdrResolveOptions extends HerdrRunOptions {
|
|
411
|
+
/**
|
|
412
|
+
* Scope label resolution to one workspace (`workspace_id`, e.g. "w7").
|
|
413
|
+
* Labels are only unique per operator discipline, not by herdr — scoping
|
|
414
|
+
* shrinks the collision surface (EP152 wave-2 W2 hardening).
|
|
415
|
+
*/
|
|
416
|
+
workspace?: string
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Labels compare NFC-normalized: "é" typed composed and decomposed must be the same pane. */
|
|
420
|
+
const nfc = (s: string) => s.normalize("NFC")
|
|
421
|
+
|
|
194
422
|
/**
|
|
195
423
|
* Resolve a durable pane label to the CURRENT herdr pane id via `pane list`.
|
|
196
424
|
* Runs before every action when a label is given — herdr ids are
|
|
197
425
|
* session-scoped (a herdr restart resets them), so a cached id can go stale.
|
|
198
426
|
* Live 0.7.4: a stale id fails loudly with pane_not_found (ids are never
|
|
199
|
-
* reused within a session); `pane rename` sets the `label` field matched here
|
|
427
|
+
* reused within a session); `pane rename` sets the `label` field matched here
|
|
428
|
+
* (matching is label-only — live 0.7.4 rows carry no `title` field, and the
|
|
429
|
+
* old title fallback could silently hit an unrelated pane on other builds).
|
|
430
|
+
*
|
|
431
|
+
* Hardening (EP152 wave-2 W2, adversarial findings): matching is
|
|
432
|
+
* NFC-normalized, and a DUPLICATE label is a hard refusal — first-match on an
|
|
433
|
+
* order-unstable inventory could steer the wrong agent. Rename the panes or
|
|
434
|
+
* scope with `{ workspace }`.
|
|
200
435
|
*/
|
|
201
|
-
export async function resolveHerdrPaneId(paneLabel: string, opts:
|
|
202
|
-
const label = paneLabel.trim()
|
|
436
|
+
export async function resolveHerdrPaneId(paneLabel: string, opts: HerdrResolveOptions = {}): Promise<string> {
|
|
437
|
+
const label = nfc(paneLabel.trim())
|
|
203
438
|
const panes = await listHerdrPanes(opts)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (matches.length === 0
|
|
439
|
+
const scoped = opts.workspace ? panes.filter((p) => p.workspace_id === opts.workspace) : panes
|
|
440
|
+
const matches = scoped.filter((p) => typeof p.label === "string" && nfc(p.label) === label)
|
|
441
|
+
const where = opts.workspace ? ` in workspace ${opts.workspace}` : ""
|
|
442
|
+
if (matches.length === 0 || !matches[0]?.pane_id) {
|
|
443
|
+
throw new TideError(`no herdr pane labeled "${paneLabel.trim()}"${where} in \`herdr pane list\``)
|
|
444
|
+
}
|
|
208
445
|
if (matches.length > 1) {
|
|
209
|
-
const
|
|
446
|
+
const seen = matches
|
|
447
|
+
.map((p) => `${p.pane_id ?? "?"} (workspace ${p.workspace_id ?? "?"})`)
|
|
448
|
+
.join(", ")
|
|
210
449
|
throw new TideError(
|
|
211
|
-
`
|
|
450
|
+
`duplicate herdr pane label "${paneLabel.trim()}"${where}: ${seen} — refusing first-match steering; ` +
|
|
451
|
+
"rename the panes (`herdr pane rename`) or scope the resolution with { workspace }",
|
|
212
452
|
)
|
|
213
453
|
}
|
|
214
|
-
|
|
215
|
-
if (!match?.pane_id) {
|
|
216
|
-
throw new TideError(`no herdr pane labeled "${label}" in \`herdr pane list\``)
|
|
217
|
-
}
|
|
218
|
-
return match.pane_id
|
|
454
|
+
return matches[0].pane_id
|
|
219
455
|
}
|
|
220
456
|
|
|
221
|
-
export interface HerdrTargetOptions extends
|
|
457
|
+
export interface HerdrTargetOptions extends HerdrResolveOptions {
|
|
222
458
|
/**
|
|
223
459
|
* Durable pane label; when set it wins over the pane id argument and is
|
|
224
460
|
* re-resolved to the current id at action time.
|
|
@@ -237,6 +473,12 @@ function resolveTarget(pane: string, opts: HerdrTargetOptions): Promise<string>
|
|
|
237
473
|
export interface HerdrSendKeysOptions extends HerdrTargetOptions {
|
|
238
474
|
/** Send a real Enter key after the literal text. Default true (mirrors the tmux path). */
|
|
239
475
|
submit?: boolean
|
|
476
|
+
/**
|
|
477
|
+
* Steer-gate probe overrides (test seam / cockpit injection). The gate
|
|
478
|
+
* itself cannot be disabled — these only answer its questions. See
|
|
479
|
+
* steer-gate.ts (EP152 wave-2 W1).
|
|
480
|
+
*/
|
|
481
|
+
gate?: SteerGateOverrides
|
|
240
482
|
}
|
|
241
483
|
|
|
242
484
|
/**
|
|
@@ -277,12 +519,29 @@ export function buildHerdrSendKeysPlan(
|
|
|
277
519
|
return makeHerdrSendKeysPlan(normalizeHerdrPaneTarget(pane), message, submit, paneLabel)
|
|
278
520
|
}
|
|
279
521
|
|
|
522
|
+
/**
|
|
523
|
+
* Liveness probe for the steer gate: label resolution IS live proof (herdr
|
|
524
|
+
* just returned the id); a raw id must appear in the current `pane list`.
|
|
525
|
+
*/
|
|
526
|
+
function herdrTargetResolved(target: string, viaLabel: boolean, opts: HerdrRunOptions): () => Promise<boolean> {
|
|
527
|
+
if (viaLabel) return async () => true
|
|
528
|
+
return async () => {
|
|
529
|
+
const panes = await listHerdrPanes(opts)
|
|
530
|
+
return panes.some((p) => p.pane_id === target)
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
280
534
|
/**
|
|
281
535
|
* Steer a herdr pane: type `message` via `herdr pane send-text`, then submit a
|
|
282
536
|
* real Enter via `herdr pane send-keys … Enter` unless `submit: false`. Same
|
|
283
537
|
* two-step semantics as the tmux path: if the literal step succeeds but the
|
|
284
538
|
* submit step fails, the text is left on the pane unsubmitted and the thrown
|
|
285
539
|
* TideError names which step failed.
|
|
540
|
+
*
|
|
541
|
+
* Execution is steer-gated (EP152 wave-2 W1): live-resolved target +
|
|
542
|
+
* ACTIVE_CONTROLLER posture + interactive TTY (or approval-fronted override)
|
|
543
|
+
* — the same 3-part boundary as `tide operator send --run`. Plan builders
|
|
544
|
+
* stay ungated (dry-run is the default posture of the covenant).
|
|
286
545
|
*/
|
|
287
546
|
export async function sendKeysViaHerdr(
|
|
288
547
|
pane: string,
|
|
@@ -291,6 +550,12 @@ export async function sendKeysViaHerdr(
|
|
|
291
550
|
): Promise<TideHerdrSendKeysResult> {
|
|
292
551
|
// resolveTarget validates caller-supplied ids and trusts label-resolved ones.
|
|
293
552
|
const target = await resolveTarget(pane, opts)
|
|
553
|
+
const gate = acceptGateOverrides(opts.gate)
|
|
554
|
+
await requireSteerGate({
|
|
555
|
+
...gate,
|
|
556
|
+
target,
|
|
557
|
+
resolveTarget: gate.resolveTarget ?? herdrTargetResolved(target, opts.paneLabel !== undefined, opts),
|
|
558
|
+
})
|
|
294
559
|
const plan = makeHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel)
|
|
295
560
|
const runner = makeRunner(opts)
|
|
296
561
|
const bin = resolveHerdrBin()
|
|
@@ -331,13 +596,28 @@ export async function renameHerdrPane(
|
|
|
331
596
|
await runHerdr(["pane", "rename", target, label], opts)
|
|
332
597
|
}
|
|
333
598
|
|
|
334
|
-
|
|
599
|
+
export interface HerdrRunInPaneOptions extends HerdrTargetOptions {
|
|
600
|
+
/** Steer-gate probe overrides — see HerdrSendKeysOptions.gate. */
|
|
601
|
+
gate?: SteerGateOverrides
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* `herdr pane run <id> <command>` — send the text and a real Enter in one
|
|
606
|
+
* request. Steer-gated like sendKeysViaHerdr (W1-adjacent: same mutation
|
|
607
|
+
* power, same boundary — an ungated `pane run` would make the gate decorative).
|
|
608
|
+
*/
|
|
335
609
|
export async function runInHerdrPane(
|
|
336
610
|
pane: string,
|
|
337
611
|
command: string,
|
|
338
|
-
opts:
|
|
612
|
+
opts: HerdrRunInPaneOptions = {},
|
|
339
613
|
): Promise<void> {
|
|
340
614
|
const target = await resolveTarget(pane, opts)
|
|
615
|
+
const gate = acceptGateOverrides(opts.gate)
|
|
616
|
+
await requireSteerGate({
|
|
617
|
+
...gate,
|
|
618
|
+
target,
|
|
619
|
+
resolveTarget: gate.resolveTarget ?? herdrTargetResolved(target, opts.paneLabel !== undefined, opts),
|
|
620
|
+
})
|
|
341
621
|
await runHerdr(["pane", "run", target, command], opts)
|
|
342
622
|
}
|
|
343
623
|
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,23 @@ export * from "./types"
|
|
|
2
2
|
export * from "./socket"
|
|
3
3
|
export * from "./client"
|
|
4
4
|
export * from "./herdr"
|
|
5
|
+
// steer-gate: explicit exports — trustSteerGateProbes/acceptGateOverrides are
|
|
6
|
+
// deliberately NOT on the package surface (W10a: the test seam must be a
|
|
7
|
+
// direct-module import, never a consumer API).
|
|
8
|
+
export {
|
|
9
|
+
STEER_BOUNDARY,
|
|
10
|
+
resolveNavigatorDir,
|
|
11
|
+
readNavigatorPosture,
|
|
12
|
+
evaluateSteerGate,
|
|
13
|
+
requireSteerGate,
|
|
14
|
+
} from "./steer-gate"
|
|
15
|
+
export type {
|
|
16
|
+
SteerPostureMode,
|
|
17
|
+
SteerPosture,
|
|
18
|
+
SteerGateOverrides,
|
|
19
|
+
SteerGateInputs,
|
|
20
|
+
SteerGateDecision,
|
|
21
|
+
} from "./steer-gate"
|
|
5
22
|
export type {
|
|
6
23
|
EpisodeLaneTopology,
|
|
7
24
|
TideLaneCheckpoint,
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// Steer-layer approval gate for @miadi/tide — the TypeScript port of the
|
|
2
|
+
// Python runtime's 3-part guarded-send gate (EP152 wave-2 W1; adversarial
|
|
3
|
+
// finding: sendKeys/sendKeysViaHerdr executed with no posture, no TTY, no
|
|
4
|
+
// approval artifact while `tide operator send --run` enforced all three).
|
|
5
|
+
//
|
|
6
|
+
// Python source of record (runtime/tide-runtime):
|
|
7
|
+
// terminal_send.py SEND_BOUNDARY — the covenant string, reproduced below
|
|
8
|
+
// cli.py operator_send / _require_controller_execution — enforcement order:
|
|
9
|
+
// 1. resolution_status == "resolved" (target visible in LIVE inventory)
|
|
10
|
+
// 2. cfg.mode == NavigatorMode.ACTIVE_CONTROLLER (wire value "controller"
|
|
11
|
+
// in ${MIADI_HOME|~/.miadi/navigator}/config.yml; observer default)
|
|
12
|
+
// 3. stdin.isatty() OR TIDE_ALLOW_NON_INTERACTIVE_RUN=1 (Tide Studio /
|
|
13
|
+
// approval-queue-fronted services set the env after their own review)
|
|
14
|
+
// config.py _controller_ttl_expired — a controller lease older than
|
|
15
|
+
// controller.ttl_minutes (default 30, 0 = no expiry) counts as observer.
|
|
16
|
+
// Python persists that downgrade when IT loads config; this reader cannot
|
|
17
|
+
// write, so it applies the same expiry arithmetic on every read.
|
|
18
|
+
//
|
|
19
|
+
// The gate is multiplexer-agnostic: callers (tmux client.ts, herdr herdr.ts)
|
|
20
|
+
// compute target liveness their own way and pass the probes in. Every probe
|
|
21
|
+
// is injectable (the test seam); none of the injection points can DISABLE the
|
|
22
|
+
// gate — they only answer its three questions.
|
|
23
|
+
|
|
24
|
+
import { readFileSync } from "node:fs"
|
|
25
|
+
import { homedir } from "node:os"
|
|
26
|
+
import { join } from "node:path"
|
|
27
|
+
|
|
28
|
+
import { TideError } from "./errors"
|
|
29
|
+
|
|
30
|
+
/** Verbatim covenant string from terminal_send.py (SEND_BOUNDARY). */
|
|
31
|
+
export const STEER_BOUNDARY =
|
|
32
|
+
"explicit target, reviewed message source, dry-run by default, " +
|
|
33
|
+
"ACTIVE_CONTROLLER + interactive local TTY required for send"
|
|
34
|
+
|
|
35
|
+
/** Wire values from tide_runtime.models.NavigatorMode ("controller", not "active_controller"). */
|
|
36
|
+
export type SteerPostureMode = "observer" | "controller" | "unknown"
|
|
37
|
+
|
|
38
|
+
export interface SteerPosture {
|
|
39
|
+
/** Effective mode after TTL arithmetic — an expired controller lease reads as "observer". */
|
|
40
|
+
mode: SteerPostureMode
|
|
41
|
+
/** Where the posture came from (config path, or "default: observer" when absent). */
|
|
42
|
+
source: string
|
|
43
|
+
enabled_at?: string
|
|
44
|
+
ttl_minutes?: number
|
|
45
|
+
/** True when config said "controller" but the lease exceeded ttl_minutes. */
|
|
46
|
+
expired?: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Injectable probes answering the gate's three questions. Absent probes fall
|
|
51
|
+
* back to the real host: config.yml posture, process.stdin TTY, process.env.
|
|
52
|
+
* `resolveTarget` has NO default — liveness is multiplexer-specific and the
|
|
53
|
+
* calling transport must supply it.
|
|
54
|
+
*/
|
|
55
|
+
export interface SteerGateOverrides {
|
|
56
|
+
readPosture?: () => SteerPosture | Promise<SteerPosture>
|
|
57
|
+
isInteractive?: () => boolean
|
|
58
|
+
env?: Record<string, string | undefined>
|
|
59
|
+
/** Override the transport's liveness probe (tests / pre-verified callers). */
|
|
60
|
+
resolveTarget?: () => boolean | Promise<boolean>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface SteerGateInputs extends SteerGateOverrides {
|
|
64
|
+
/** Human-readable target, only used in refusal reasons. */
|
|
65
|
+
target: string
|
|
66
|
+
/** Is the target visible in the LIVE multiplexer inventory right now? */
|
|
67
|
+
resolveTarget: () => boolean | Promise<boolean>
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface SteerGateDecision {
|
|
71
|
+
allowed: boolean
|
|
72
|
+
/** Every failed check, in Python enforcement order; empty when allowed. */
|
|
73
|
+
reasons: string[]
|
|
74
|
+
posture: SteerPosture
|
|
75
|
+
target_resolved: boolean
|
|
76
|
+
interactive_tty: boolean
|
|
77
|
+
non_interactive_override: boolean
|
|
78
|
+
boundary: string
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function expandHome(p: string): string {
|
|
82
|
+
if (p === "~") return homedir()
|
|
83
|
+
if (p.startsWith("~/")) return join(homedir(), p.slice(2))
|
|
84
|
+
return p
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `${MIADI_HOME || ~/.miadi/navigator}` — mirrors tide_runtime.paths.get_config_dir(). */
|
|
88
|
+
export function resolveNavigatorDir(env: Record<string, string | undefined> = process.env): string {
|
|
89
|
+
const override = env.MIADI_HOME?.trim()
|
|
90
|
+
return override ? expandHome(override) : join(homedir(), ".miadi", "navigator")
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const QUOTE = /^['"]|['"]$/g
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Read `mode:` and the `controller:` lease block from config.yml. NOT a YAML
|
|
97
|
+
* parser — a line reader for exactly the two keys tide writes via
|
|
98
|
+
* yaml.safe_dump(default_flow_style=False): a top-level scalar and one
|
|
99
|
+
* two-key nested block. Anything unreadable degrades to the Python default
|
|
100
|
+
* (observer), never to controller.
|
|
101
|
+
*/
|
|
102
|
+
export function readNavigatorPosture(env: Record<string, string | undefined> = process.env): SteerPosture {
|
|
103
|
+
const dir = resolveNavigatorDir(env)
|
|
104
|
+
const path = join(dir, "config.yml")
|
|
105
|
+
let text: string
|
|
106
|
+
try {
|
|
107
|
+
text = readFileSync(path, "utf8")
|
|
108
|
+
} catch {
|
|
109
|
+
return { mode: "observer", source: `default: observer (no readable ${path})` }
|
|
110
|
+
}
|
|
111
|
+
let rawMode: string | undefined
|
|
112
|
+
let ttl: number | undefined
|
|
113
|
+
let enabledAt: string | undefined
|
|
114
|
+
let inController = false
|
|
115
|
+
for (const line of text.split("\n")) {
|
|
116
|
+
const topLevel = /^[^\s#]/.test(line)
|
|
117
|
+
if (topLevel) inController = /^controller:\s*$/.test(line)
|
|
118
|
+
const mode = line.match(/^mode:\s*(.+?)\s*$/)
|
|
119
|
+
if (mode) rawMode = mode[1].replace(QUOTE, "")
|
|
120
|
+
if (inController && !topLevel) {
|
|
121
|
+
const t = line.match(/^\s+ttl_minutes:\s*(.+?)\s*$/)
|
|
122
|
+
if (t) ttl = Number(t[1].replace(QUOTE, ""))
|
|
123
|
+
const e = line.match(/^\s+enabled_at:\s*(.+?)\s*$/)
|
|
124
|
+
if (e) enabledAt = e[1].replace(QUOTE, "")
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const mode: SteerPostureMode =
|
|
128
|
+
rawMode === "controller" ? "controller" : rawMode === "observer" || rawMode === undefined ? "observer" : "unknown"
|
|
129
|
+
const posture: SteerPosture = { mode, source: path }
|
|
130
|
+
if (enabledAt !== undefined) posture.enabled_at = enabledAt
|
|
131
|
+
if (ttl !== undefined && Number.isFinite(ttl)) posture.ttl_minutes = ttl
|
|
132
|
+
// config.py _controller_ttl_expired: controller + ttl>0 + parseable stamp
|
|
133
|
+
// older than the lease ⇒ effective observer. An unparseable stamp with a
|
|
134
|
+
// positive TTL also expires (fail closed), matching Python's None-parse path.
|
|
135
|
+
if (mode === "controller") {
|
|
136
|
+
const ttlMin = posture.ttl_minutes ?? 30
|
|
137
|
+
if (ttlMin > 0) {
|
|
138
|
+
const enabled = Date.parse(posture.enabled_at ?? "")
|
|
139
|
+
if (Number.isNaN(enabled) || Date.now() - enabled > ttlMin * 60_000) {
|
|
140
|
+
posture.mode = "observer"
|
|
141
|
+
posture.expired = true
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return posture
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Answer the three gate questions. Never throws — the decision carries every
|
|
150
|
+
* failed check so cockpits can show the whole story at once (the Python CLI
|
|
151
|
+
* exits on the first failure; a JSON boundary wants all of them).
|
|
152
|
+
*/
|
|
153
|
+
export async function evaluateSteerGate(inputs: SteerGateInputs): Promise<SteerGateDecision> {
|
|
154
|
+
const env = inputs.env ?? process.env
|
|
155
|
+
const posture = await (inputs.readPosture ? inputs.readPosture() : readNavigatorPosture(env))
|
|
156
|
+
const interactive = inputs.isInteractive ? inputs.isInteractive() : process.stdin.isTTY === true
|
|
157
|
+
const override = env.TIDE_ALLOW_NON_INTERACTIVE_RUN === "1"
|
|
158
|
+
let resolved = false
|
|
159
|
+
try {
|
|
160
|
+
resolved = await inputs.resolveTarget()
|
|
161
|
+
} catch {
|
|
162
|
+
resolved = false // an unreachable inventory cannot prove a live target
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const reasons: string[] = []
|
|
166
|
+
if (!resolved) {
|
|
167
|
+
reasons.push(
|
|
168
|
+
`steer target ${inputs.target} is not currently resolved in the live multiplexer inventory — ` +
|
|
169
|
+
"list panes/terminals and retry with a visible target",
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
if (posture.mode !== "controller") {
|
|
173
|
+
reasons.push(
|
|
174
|
+
`steer execution requires ACTIVE_CONTROLLER posture (mode: controller); current posture is ` +
|
|
175
|
+
`"${posture.mode}"${posture.expired ? " (controller lease expired)" : ""} — ` +
|
|
176
|
+
"run `tide mode controller` from a local interactive terminal first",
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
if (!interactive && !override) {
|
|
180
|
+
reasons.push(
|
|
181
|
+
"steer execution requires an interactive local terminal (TTY), or TIDE_ALLOW_NON_INTERACTIVE_RUN=1 " +
|
|
182
|
+
"set by an approval-queue-fronted service after its own review",
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
allowed: reasons.length === 0,
|
|
187
|
+
reasons,
|
|
188
|
+
posture,
|
|
189
|
+
target_resolved: resolved,
|
|
190
|
+
interactive_tty: interactive,
|
|
191
|
+
non_interactive_override: override,
|
|
192
|
+
boundary: STEER_BOUNDARY,
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Evaluate and THROW a TideError naming every failed check when refused. */
|
|
197
|
+
export async function requireSteerGate(inputs: SteerGateInputs): Promise<SteerGateDecision> {
|
|
198
|
+
const decision = await evaluateSteerGate(inputs)
|
|
199
|
+
if (!decision.allowed) {
|
|
200
|
+
throw new TideError(`steer gate refused (${STEER_BOUNDARY}): ${decision.reasons.join("; ")}`)
|
|
201
|
+
}
|
|
202
|
+
return decision
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ── Trusted-override brand (EP152 wave-2 W10a) ──────────────────────────────
|
|
206
|
+
//
|
|
207
|
+
// The injectable probes are a test seam, and a seam is a channel: any caller
|
|
208
|
+
// that answers all three questions affirmatively — or merely smuggles
|
|
209
|
+
// `env: {TIDE_ALLOW_NON_INTERACTIVE_RUN:"1"}` in JSON-derived options — walks
|
|
210
|
+
// through the gate (W8 adversarial finding, verified live). Overrides are
|
|
211
|
+
// therefore only ACCEPTED when branded by trustSteerGateProbes(), which is
|
|
212
|
+
// deliberately NOT re-exported from the package surface (src/index.ts): tests
|
|
213
|
+
// and first-party wiring reach it via a direct module import; JSON cannot
|
|
214
|
+
// carry the brand (a module-private Symbol on a non-enumerable property), so
|
|
215
|
+
// request-derived gate options are structurally refused.
|
|
216
|
+
|
|
217
|
+
const TRUSTED_PROBES = Symbol("miadi.tide.steer-gate.trusted-probes")
|
|
218
|
+
|
|
219
|
+
/** Brand probe overrides as trusted. NOT exported from the package surface — import from the module directly (test seam / first-party wiring only). */
|
|
220
|
+
export function trustSteerGateProbes(overrides: SteerGateOverrides): SteerGateOverrides {
|
|
221
|
+
const branded: SteerGateOverrides = { ...overrides }
|
|
222
|
+
Object.defineProperty(branded, TRUSTED_PROBES, { value: true, enumerable: false })
|
|
223
|
+
return branded
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function isTrustedSteerGateProbes(gate: SteerGateOverrides): boolean {
|
|
227
|
+
return (gate as Record<PropertyKey, unknown>)[TRUSTED_PROBES] === true
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Admission check for `opts.gate` at the transport boundary: absent → real
|
|
232
|
+
* host probes; branded → accepted; anything else → loud refusal (a gate
|
|
233
|
+
* override that reaches a steer verb without the brand is either a bug or an
|
|
234
|
+
* injection — both deserve a named failure, not a silent bypass or ignore).
|
|
235
|
+
*/
|
|
236
|
+
export function acceptGateOverrides(gate: SteerGateOverrides | undefined): SteerGateOverrides {
|
|
237
|
+
if (gate === undefined) return {}
|
|
238
|
+
if (!isTrustedSteerGateProbes(gate)) {
|
|
239
|
+
throw new TideError(
|
|
240
|
+
"steer gate overrides refused: not branded by trustSteerGateProbes() — " +
|
|
241
|
+
"request-derived or untrusted gate options cannot answer the gate's questions",
|
|
242
|
+
)
|
|
243
|
+
}
|
|
244
|
+
return gate
|
|
245
|
+
}
|