@miadi/tide 0.1.4 → 0.2.1

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 CHANGED
@@ -55,6 +55,25 @@ prompt for a human to review and submit. `buildSendKeysPlan(...)` returns the ex
55
55
  pair without executing — used for the cockpit's inline command preview. The tmux binary is
56
56
  resolved via `TIDE_TMUX_BIN` -> `tmux` on `PATH`.
57
57
 
58
+ ### herdr transport — `multiplexer: "herdr"` (live-verified)
59
+
60
+ `sendKeys(pane, message, { multiplexer: "herdr" })` dispatches to the herdr CLI transport
61
+ (`src/herdr.ts`): `herdr pane send-text` types the text, `herdr pane send-keys … Enter` submits
62
+ (`submit: false` skips it, same toggle as tmux). The result is the herdr variant of the
63
+ `TideSendKeysResult` union from `@miadi/tide-contract` (`multiplexer: "herdr"`, herdr CLI argv).
64
+ herdr pane ids (`"w1:p2"` as of herdr 0.7; legacy `"1-2"` accepted) are **session-scoped** —
65
+ they reset on herdr restart, and a stale id fails loudly with `pane_not_found`. Pass `paneLabel`
66
+ (set via `herdr pane rename`) and the client re-resolves label → current id via
67
+ `herdr pane list` before **every** action. Additional verbs:
68
+ `runInHerdrPane`, `readHerdrPane` (recent-unwrapped text), `waitForHerdrOutput`,
69
+ `waitForHerdrAgentStatus`, `listHerdrPanes/Workspaces/Tabs`. Binary resolution:
70
+ `TIDE_HERDR_BIN` → `herdr` on `PATH`.
71
+
72
+ > **Readiness: `live-verified`.** Smoked against a real herdr 0.7.4 instance (EP137
73
+ > herdr-smoke lane, 2026-07-16) — inventory parsing, send-text/send-keys, pane run, read,
74
+ > wait output (hit + timeout exit codes), agent-status, and label→id resolution — in
75
+ > addition to the injected-runner tests in `test/herdr.test.ts`.
76
+
58
77
  `getTerminals` and `detect` are the read-only surface behind `GET /api/tide/terminals`
59
78
  and `GET /api/tide/detect` — the typed half of operator-terminal triage and manual
60
79
  domain assignment (jgwill/Miadi#382). The write-back half (assign a pane to a domain)
@@ -66,6 +85,7 @@ is deferred to the runtime + a guarded route.
66
85
  |---|---|
67
86
  | One-shot CLI (`tide … --format json`, `execFile` arg-arrays, no shell) | **implemented** |
68
87
  | Daemon + Unix-domain-socket transport (`miadi.tide.daemon.v2`) | **implemented** (`src/socket.ts`) |
88
+ | herdr CLI transport (`src/herdr.ts`, `multiplexer: "herdr"`) | **live-verified** (herdr 0.7.4, EP137 smoke + runner-mocked tests) |
69
89
  | Schema-first contract (`tide-api.schema.json` → generated types) | planned |
70
90
 
71
91
  ### How transport selection works
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
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"
@@ -14,8 +14,11 @@
14
14
  "files": [
15
15
  "src"
16
16
  ],
17
+ "dependencies": {
18
+ "@miadi/tide-contract": "0.2.1"
19
+ },
17
20
  "scripts": {
18
- "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\"/test/*.test.js"
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"
19
22
  },
20
23
  "keywords": [
21
24
  "miadi",
package/src/client.ts CHANGED
@@ -12,22 +12,37 @@
12
12
 
13
13
  import { execFile } from "node:child_process"
14
14
  import { promisify } from "node:util"
15
+ import { readFile } from "node:fs/promises"
16
+ import { join } from "node:path"
17
+ import { homedir } from "node:os"
15
18
 
16
19
  import type {
17
20
  ContextSnapshot,
21
+ Multiplexer,
18
22
  TideTerminalsResult,
19
23
  TideDetectResult,
20
24
  TidePeekResult,
21
25
  TideSendResult,
22
26
  TideSteerResult,
23
27
  TideSendKeysResult,
28
+ TideTmuxSendKeysResult,
24
29
  } from "./types"
30
+ import type {
31
+ EpisodeLaneTopology,
32
+ TideLaneCheckpoint,
33
+ TideResumeLink,
34
+ TideAudioManifestLink,
35
+ TidePendingApproval,
36
+ } from "@miadi/tide-contract"
25
37
  import {
26
38
  daemonRequest,
27
39
  isSocketAvailable,
28
40
  resolveSocketPath,
29
41
  TideDaemonError,
30
42
  } from "./socket"
43
+ import { TideError } from "./errors"
44
+ import { sendKeysViaHerdr } from "./herdr"
45
+ import type { HerdrCommandRunner } from "./herdr"
31
46
 
32
47
  const pExecFile = promisify(execFile)
33
48
 
@@ -63,14 +78,9 @@ export function resetTideBinCache(): void {
63
78
  cachedBin = null
64
79
  }
65
80
 
66
- export class TideError extends Error {
67
- readonly cause?: unknown
68
- constructor(message: string, cause?: unknown) {
69
- super(message)
70
- this.name = "TideError"
71
- this.cause = cause
72
- }
73
- }
81
+ // TideError now lives in errors.ts (so herdr.ts can throw it without an import
82
+ // cycle); re-exported here to keep the public surface unchanged.
83
+ export { TideError }
74
84
 
75
85
  export interface TideRunOptions {
76
86
  timeoutMs?: number
@@ -254,6 +264,19 @@ export interface SendKeysOptions extends TideRunOptions {
254
264
  * review and press Enter — the "send Enter after content" cockpit toggle.
255
265
  */
256
266
  submit?: boolean
267
+ /**
268
+ * Terminal multiplexer to drive. Absent or "tmux" keeps the historical
269
+ * direct `tmux send-keys` path unchanged; "herdr" dispatches to the herdr
270
+ * CLI transport (herdr.ts — READINESS: live-verified on herdr 0.7.4).
271
+ */
272
+ multiplexer?: Multiplexer
273
+ /**
274
+ * herdr only: durable pane label, re-resolved to the current pane id at
275
+ * action time (herdr ids are session-scoped and reset on herdr restart).
276
+ */
277
+ paneLabel?: string
278
+ /** herdr only: injected command runner (tests). */
279
+ runner?: HerdrCommandRunner
257
280
  }
258
281
 
259
282
  /**
@@ -265,7 +288,7 @@ export function buildSendKeysPlan(
265
288
  pane: string,
266
289
  message: string,
267
290
  submit = true,
268
- ): TideSendKeysResult {
291
+ ): TideTmuxSendKeysResult {
269
292
  const target = normalizePaneTarget(pane)
270
293
  return {
271
294
  target,
@@ -292,6 +315,11 @@ export async function sendKeys(
292
315
  message: string,
293
316
  opts: SendKeysOptions = {},
294
317
  ): Promise<TideSendKeysResult> {
318
+ // Dispatch on the multiplexer discriminator; absent means "tmux", keeping
319
+ // the historical path byte-for-byte.
320
+ if (opts.multiplexer === "herdr") {
321
+ return sendKeysViaHerdr(pane, message, opts)
322
+ }
295
323
  const submit = opts.submit ?? true
296
324
  const plan = buildSendKeysPlan(pane, message, submit)
297
325
  const bin = resolveTmuxBin()
@@ -315,3 +343,135 @@ export async function sendKeys(
315
343
  }
316
344
  return { ...plan, sent_at: new Date().toISOString() }
317
345
  }
346
+
347
+ // ── Episode-aware verbs ────────────────────────────────────────────────────
348
+
349
+ /** Resolve episode lanes from `.miadi/tide.yaml` or a per-episode `tide-lanes.json`. */
350
+ export async function getEpisodeLanes(
351
+ episodeId: string,
352
+ opts: TideRunOptions = {},
353
+ ): Promise<EpisodeLaneTopology> {
354
+ const miadi_home = process.env.MIADI_HOME || join(homedir(), ".miadi", "navigator")
355
+ const tidesLanesPath = join(miadi_home, "episodes", episodeId, "tide-lanes.json")
356
+
357
+ try {
358
+ const content = await readFile(tidesLanesPath, "utf-8")
359
+ const data = JSON.parse(content) as EpisodeLaneTopology
360
+ return data
361
+ } catch {
362
+ throw new TideError(
363
+ `Could not load episode lanes from ${tidesLanesPath}; ensure .miadi/tide.yaml or tide-lanes.json exists for episode ${episodeId}`,
364
+ )
365
+ }
366
+ }
367
+
368
+ /** Load a lane checkpoint (returns null if absent). */
369
+ export async function getLaneCheckpoint(
370
+ episodeId: string,
371
+ laneId: string,
372
+ opts: TideRunOptions = {},
373
+ ): Promise<TideLaneCheckpoint | null> {
374
+ const miadi_home = process.env.MIADI_HOME || join(homedir(), ".miadi", "navigator")
375
+ const checkpointPath = join(miadi_home, "episodes", episodeId, "checkpoints", `${laneId}.json`)
376
+
377
+ try {
378
+ const content = await readFile(checkpointPath, "utf-8")
379
+ const data = JSON.parse(content) as TideLaneCheckpoint
380
+ return data
381
+ } catch {
382
+ return null
383
+ }
384
+ }
385
+
386
+ /** Load resume link for an episode (returns null if no RESUME.md found). */
387
+ export async function getResumeLink(
388
+ episodeFolder: string,
389
+ opts: TideRunOptions = {},
390
+ ): Promise<TideResumeLink | null> {
391
+ const resumePath = join(episodeFolder, "RESUME.md")
392
+
393
+ try {
394
+ const content = await readFile(resumePath, "utf-8")
395
+ const lines = content.split("\n")
396
+ const summaryEnd = Math.min(300, content.length)
397
+ const summaryExcerpt = content.substring(0, summaryEnd).trimEnd()
398
+
399
+ const episodeId =
400
+ episodeFolder.split("/").find((p) => p.startsWith("miadi-episode-")) || "unknown"
401
+
402
+ return {
403
+ episode_id: episodeId,
404
+ episode_folder: episodeFolder,
405
+ resume_path: resumePath,
406
+ summary_excerpt: summaryExcerpt,
407
+ commit_sha: null,
408
+ produced_at: new Date().toISOString(),
409
+ }
410
+ } catch {
411
+ return null
412
+ }
413
+ }
414
+
415
+ /** Load audio manifest link (returns null if no AUDIO-MANIFEST.md found). */
416
+ export async function getAudioManifestLink(
417
+ episodeFolder: string,
418
+ opts: TideRunOptions = {},
419
+ ): Promise<TideAudioManifestLink | null> {
420
+ const manifestPath = join(episodeFolder, "AUDIO-MANIFEST.md")
421
+
422
+ try {
423
+ const content = await readFile(manifestPath, "utf-8")
424
+ const mp3Count = (content.match(/mp3_path:/g) || []).length
425
+ const lastMp3Match = content.match(/mp3_path:\s*`?([^`\n]+)`?/g)?.pop()
426
+ const lastMp3Path = lastMp3Match
427
+ ? lastMp3Match.replace("mp3_path:", "").trim().replace(/[`]/g, "")
428
+ : null
429
+ const lastTgMatch = content.match(/telegram_message_id:\s*`?([^\s`\n]+)`?/g)?.pop()
430
+ const lastTgId = lastTgMatch
431
+ ? lastTgMatch.replace("telegram_message_id:", "").trim().replace(/[`]/g, "")
432
+ : null
433
+
434
+ const episodeId =
435
+ episodeFolder.split("/").find((p) => p.startsWith("miadi-episode-")) || "unknown"
436
+
437
+ return {
438
+ episode_id: episodeId,
439
+ episode_folder: episodeFolder,
440
+ manifest_path: manifestPath,
441
+ entry_count: mp3Count,
442
+ last_mp3_path: lastMp3Path,
443
+ last_telegram_message_id: lastTgId,
444
+ updated_at: new Date().toISOString(),
445
+ }
446
+ } catch {
447
+ return null
448
+ }
449
+ }
450
+
451
+ /** List pending approvals for an episode (returns [] if absent). */
452
+ export async function listPendingApprovals(
453
+ episodeId: string,
454
+ opts: TideRunOptions = {},
455
+ ): Promise<TidePendingApproval[]> {
456
+ const miadi_home = process.env.MIADI_HOME || join(homedir(), ".miadi", "navigator")
457
+ const approvalsPath = join(miadi_home, "episodes", episodeId, "pending-approvals.json")
458
+
459
+ try {
460
+ const content = await readFile(approvalsPath, "utf-8")
461
+ const data = JSON.parse(content) as TidePendingApproval[]
462
+ return data
463
+ } catch {
464
+ return []
465
+ }
466
+ }
467
+
468
+ /** Build a steer plan with lane context (wraps buildSendKeysPlan, adds lane_id). */
469
+ export function buildEpisodeSteerPlan(
470
+ laneId: string,
471
+ pane: string,
472
+ message: string,
473
+ submit = true,
474
+ ): ReturnType<typeof buildSendKeysPlan> & { lane_id: string } {
475
+ const plan = buildSendKeysPlan(pane, message, submit)
476
+ return { ...plan, lane_id: laneId }
477
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,12 @@
1
+ // Shared error type for the @miadi/tide client — split out of client.ts so the
2
+ // herdr transport (herdr.ts) can throw it without a client ↔ herdr import
3
+ // cycle. Public surface is unchanged: client.ts re-exports TideError.
4
+
5
+ export class TideError extends Error {
6
+ readonly cause?: unknown
7
+ constructor(message: string, cause?: unknown) {
8
+ super(message)
9
+ this.name = "TideError"
10
+ this.cause = cause
11
+ }
12
+ }
package/src/herdr.ts ADDED
@@ -0,0 +1,366 @@
1
+ // Herdr transport for @miadi/tide — the sibling of the direct tmux send-keys
2
+ // path in client.ts. herdr's workspace/tab/pane/wait commands talk to the
3
+ // running herdr instance over a local unix socket; this module invokes them
4
+ // via `execFile` with ARGUMENT ARRAYS (no shell), or via an injected
5
+ // `HerdrCommandRunner` (the test seam — mirrors hermes-conductor's
6
+ // MuxCommandRunner in src/mux/backends/types.ts).
7
+ //
8
+ // Verbs driven here:
9
+ // pane send-text <id> <text> type literal text, no Enter (silent)
10
+ // pane send-keys <id> Enter press a real Enter key (silent)
11
+ // pane run <id> <command> text + Enter in one request (silent)
12
+ // pane read <id> --source recent-unwrapped --lines N (text)
13
+ // wait output <id> --match … [--regex] --timeout ms (JSON)
14
+ // wait agent-status <id> --status … --timeout ms (JSON)
15
+ // workspace list | tab list --workspace <id> | pane list (JSON)
16
+ //
17
+ // herdr pane ids are "w<N>:p<M>" (e.g. "w1:p2") as of herdr 0.7; the legacy
18
+ // dashed "1-2" form is still accepted for older releases. Live smoke against
19
+ // herdr 0.7.4 (EP137) showed ids are monotonic within a session — they do NOT
20
+ // compact or get reused when panes close, and a stale id fails loudly with
21
+ // {"error":{"code":"pane_not_found"}}. They are still session-scoped (a herdr
22
+ // restart resets them), so every action re-resolves `paneLabel` → current pane
23
+ // id at action time (never cached) when a label is provided; `pane rename`
24
+ // sets the `label` field that resolution matches on.
25
+ //
26
+ // READINESS: live-verified — smoked against a real herdr 0.7.4 instance
27
+ // (EP137 herdr-smoke lane, 2026-07-16) in addition to the injected-runner
28
+ // tests in test/herdr.test.ts.
29
+
30
+ import { execFile } from "node:child_process"
31
+ import { promisify } from "node:util"
32
+
33
+ import type { TideAgentStatus, TideHerdrSendKeysResult } from "@miadi/tide-contract"
34
+ import { TideError } from "./errors"
35
+ import type { TideRunOptions } from "./client"
36
+
37
+ const pExecFile = promisify(execFile)
38
+
39
+ export interface HerdrCommandResult {
40
+ stdout: string
41
+ stderr: string
42
+ }
43
+
44
+ /** Injected command runner — the mock seam for tests (no live herdr needed). */
45
+ export type HerdrCommandRunner = (
46
+ executable: string,
47
+ args: readonly string[],
48
+ ) => Promise<HerdrCommandResult>
49
+
50
+ export interface HerdrRunOptions extends TideRunOptions {
51
+ /** Injected command runner; defaults to `execFile` against the herdr binary. */
52
+ runner?: HerdrCommandRunner
53
+ }
54
+
55
+ /** Resolve the herdr binary: `TIDE_HERDR_BIN` env → `herdr` (on PATH). */
56
+ export function resolveHerdrBin(): string {
57
+ return process.env.TIDE_HERDR_BIN?.trim() || "herdr"
58
+ }
59
+
60
+ function makeRunner(opts: HerdrRunOptions): HerdrCommandRunner {
61
+ if (opts.runner) return opts.runner
62
+ return async (executable, args) => {
63
+ const { stdout, stderr } = await pExecFile(executable, args as string[], {
64
+ timeout: opts.timeoutMs ?? 10_000,
65
+ cwd: opts.cwd,
66
+ maxBuffer: 8 * 1024 * 1024,
67
+ })
68
+ return { stdout, stderr }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Detail line for a failed runner call WITHOUT echoing argv values: node's
74
+ * execFile error message embeds the full command line ("Command failed: herdr
75
+ * pane send-text <id> <text> …") — the very values these TideError messages
76
+ * redact (live EP137 finding; mocks never hit this because injected errors
77
+ * carry custom messages). Prefer the child's stderr (herdr's own diagnostic,
78
+ * e.g. its {"error":…} JSON), then the message with any "Command failed: …"
79
+ * line stripped, then exit metadata.
80
+ */
81
+ function describeRunnerError(err: unknown): string {
82
+ const e = err as Partial<{ stderr: unknown; code: unknown; signal: unknown }> | null
83
+ const stderr = typeof e?.stderr === "string" ? e.stderr.trim() : ""
84
+ if (stderr) return stderr
85
+ const raw = err instanceof Error ? err.message : String(err)
86
+ const stripped = raw.replace(/^Command failed:[^\n]*\n?/, "").trim()
87
+ if (stripped) return stripped
88
+ const meta = [
89
+ e?.code != null ? `exit code ${String(e.code)}` : null,
90
+ typeof e?.signal === "string" && e.signal ? `killed by ${e.signal}` : null,
91
+ ].filter(Boolean)
92
+ return meta.length ? meta.join(", ") : "command failed"
93
+ }
94
+
95
+ /** Run one herdr CLI command, wrapping failures in TideError. */
96
+ async function runHerdr(args: string[], opts: HerdrRunOptions): Promise<HerdrCommandResult> {
97
+ const runner = makeRunner(opts)
98
+ try {
99
+ return await runner(resolveHerdrBin(), args)
100
+ } catch (err) {
101
+ const verb = args.length >= 2 ? `${args[0]} ${args[1]}` : "operation"
102
+ throw new TideError(`herdr ${verb} failed: ${describeRunnerError(err)}`, err)
103
+ }
104
+ }
105
+
106
+ function parseHerdrJson<T>(stdout: string, what: string): T {
107
+ try {
108
+ return JSON.parse(stdout) as T
109
+ } catch (err) {
110
+ throw new TideError(`herdr ${what} returned non-JSON output`, err)
111
+ }
112
+ }
113
+
114
+ // ── Pane targets and label→id resolution ────────────────────────────────────
115
+
116
+ // "w1:p2" is the live herdr 0.7 format; the dashed "1-2" form is legacy.
117
+ export const HERDR_PANE_ID_PATTERN = /^(w[0-9]+:p[0-9]+|[0-9]+-[0-9]+)$/
118
+
119
+ /** Validate a herdr pane id (e.g. "w1:p2"). Unlike tmux there is no `%` prefix to add. */
120
+ export function normalizeHerdrPaneTarget(pane: string): string {
121
+ const trimmed = pane.trim()
122
+ if (!HERDR_PANE_ID_PATTERN.test(trimmed)) {
123
+ throw new TideError(
124
+ `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`,
125
+ )
126
+ }
127
+ return trimmed
128
+ }
129
+
130
+ /**
131
+ * One row from `herdr pane list`. Loosely typed; the named fields below are
132
+ * the ones observed live on herdr 0.7.4. `label` only appears after
133
+ * `herdr pane rename`; `title` is tolerated for other herdr builds.
134
+ */
135
+ export interface HerdrPaneInfo {
136
+ pane_id?: string
137
+ label?: string
138
+ title?: string
139
+ focused?: boolean
140
+ agent_status?: TideAgentStatus | string
141
+ workspace_id?: string
142
+ tab_id?: string
143
+ cwd?: string
144
+ terminal_title?: string
145
+ terminal_title_stripped?: string
146
+ [key: string]: unknown
147
+ }
148
+
149
+ export interface HerdrWorkspaceInfo {
150
+ workspace_id?: string
151
+ label?: string
152
+ [key: string]: unknown
153
+ }
154
+
155
+ export interface HerdrTabInfo {
156
+ tab_id?: string
157
+ label?: string
158
+ [key: string]: unknown
159
+ }
160
+
161
+ // herdr JSON envelopes nest payloads under `result` (the same nesting
162
+ // hermes-conductor parses in src/mux/backends/herdr.ts:
163
+ // result.workspace.workspace_id, result.root_pane.pane_id, result.pane.pane_id).
164
+ // Bare-object and bare-array shapes are tolerated for forward compatibility.
165
+ function unwrapList<T>(payload: unknown, key: "panes" | "workspaces" | "tabs", what: string): T[] {
166
+ if (Array.isArray(payload)) return payload as T[]
167
+ const env = payload as { result?: Record<string, unknown>; [k: string]: unknown } | null
168
+ const nested = env?.result?.[key] ?? env?.[key]
169
+ if (Array.isArray(nested)) return nested as T[]
170
+ throw new TideError(`herdr ${what} returned an unexpected JSON shape`)
171
+ }
172
+
173
+ /** `herdr pane list` — JSON inventory of panes across workspaces. */
174
+ export async function listHerdrPanes(opts: HerdrRunOptions = {}): Promise<HerdrPaneInfo[]> {
175
+ const { stdout } = await runHerdr(["pane", "list"], opts)
176
+ return unwrapList<HerdrPaneInfo>(parseHerdrJson<unknown>(stdout, "pane list"), "panes", "pane list")
177
+ }
178
+
179
+ /** `herdr workspace list` — JSON inventory of workspaces. */
180
+ export async function listHerdrWorkspaces(opts: HerdrRunOptions = {}): Promise<HerdrWorkspaceInfo[]> {
181
+ const { stdout } = await runHerdr(["workspace", "list"], opts)
182
+ return unwrapList<HerdrWorkspaceInfo>(
183
+ parseHerdrJson<unknown>(stdout, "workspace list"),
184
+ "workspaces",
185
+ "workspace list",
186
+ )
187
+ }
188
+
189
+ /** `herdr tab list --workspace <id>` — JSON inventory of tabs in a workspace. */
190
+ export async function listHerdrTabs(workspace: string, opts: HerdrRunOptions = {}): Promise<HerdrTabInfo[]> {
191
+ const { stdout } = await runHerdr(["tab", "list", "--workspace", workspace], opts)
192
+ return unwrapList<HerdrTabInfo>(parseHerdrJson<unknown>(stdout, "tab list"), "tabs", "tab list")
193
+ }
194
+
195
+ /**
196
+ * Resolve a durable pane label to the CURRENT herdr pane id via `pane list`.
197
+ * Runs before every action when a label is given — herdr ids are
198
+ * session-scoped (a herdr restart resets them), so a cached id can go stale.
199
+ * Live 0.7.4: a stale id fails loudly with pane_not_found (ids are never
200
+ * reused within a session); `pane rename` sets the `label` field matched here.
201
+ */
202
+ export async function resolveHerdrPaneId(paneLabel: string, opts: HerdrRunOptions = {}): Promise<string> {
203
+ const label = paneLabel.trim()
204
+ const panes = await listHerdrPanes(opts)
205
+ const match = panes.find((p) => p.label === label || p.title === label)
206
+ if (!match?.pane_id) {
207
+ throw new TideError(`no herdr pane labeled "${label}" in \`herdr pane list\``)
208
+ }
209
+ return match.pane_id
210
+ }
211
+
212
+ export interface HerdrTargetOptions extends HerdrRunOptions {
213
+ /**
214
+ * Durable pane label; when set it wins over the pane id argument and is
215
+ * re-resolved to the current id at action time.
216
+ */
217
+ paneLabel?: string
218
+ }
219
+
220
+ function resolveTarget(pane: string, opts: HerdrTargetOptions): Promise<string> {
221
+ return opts.paneLabel
222
+ ? resolveHerdrPaneId(opts.paneLabel, opts)
223
+ : Promise.resolve(normalizeHerdrPaneTarget(pane))
224
+ }
225
+
226
+ // ── Steer (send-keys) ───────────────────────────────────────────────────────
227
+
228
+ export interface HerdrSendKeysOptions extends HerdrTargetOptions {
229
+ /** Send a real Enter key after the literal text. Default true (mirrors the tmux path). */
230
+ submit?: boolean
231
+ }
232
+
233
+ /**
234
+ * Build the exact herdr CLI argv pair for a steer WITHOUT executing it. Pure —
235
+ * the herdr counterpart of buildSendKeysPlan(). `pane` must already be a
236
+ * resolved herdr pane id; label→id resolution happens in sendKeysViaHerdr().
237
+ */
238
+ export function buildHerdrSendKeysPlan(
239
+ pane: string,
240
+ message: string,
241
+ submit = true,
242
+ paneLabel?: string,
243
+ ): TideHerdrSendKeysResult {
244
+ const target = normalizeHerdrPaneTarget(pane)
245
+ const plan: TideHerdrSendKeysResult = {
246
+ multiplexer: "herdr",
247
+ target,
248
+ message,
249
+ submitted: submit,
250
+ literal_command: ["pane", "send-text", target, message],
251
+ submit_command: submit ? ["pane", "send-keys", target, "Enter"] : null,
252
+ }
253
+ if (paneLabel !== undefined) plan.pane_label = paneLabel
254
+ return plan
255
+ }
256
+
257
+ /**
258
+ * Steer a herdr pane: type `message` via `herdr pane send-text`, then submit a
259
+ * real Enter via `herdr pane send-keys … Enter` unless `submit: false`. Same
260
+ * two-step semantics as the tmux path: if the literal step succeeds but the
261
+ * submit step fails, the text is left on the pane unsubmitted and the thrown
262
+ * TideError names which step failed.
263
+ */
264
+ export async function sendKeysViaHerdr(
265
+ pane: string,
266
+ message: string,
267
+ opts: HerdrSendKeysOptions = {},
268
+ ): Promise<TideHerdrSendKeysResult> {
269
+ const target = await resolveTarget(pane, opts)
270
+ const plan = buildHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel)
271
+ const runner = makeRunner(opts)
272
+ const bin = resolveHerdrBin()
273
+ try {
274
+ await runner(bin, plan.literal_command)
275
+ } catch (err) {
276
+ throw new TideError(
277
+ `herdr pane send-text to ${plan.target} failed (typing literal text): ${describeRunnerError(err)}`,
278
+ err,
279
+ )
280
+ }
281
+ if (plan.submit_command) {
282
+ try {
283
+ await runner(bin, plan.submit_command)
284
+ } catch (err) {
285
+ throw new TideError(
286
+ `herdr pane send-keys to ${plan.target} failed (submitting Enter; literal text was typed but left unsubmitted): ${describeRunnerError(err)}`,
287
+ err,
288
+ )
289
+ }
290
+ }
291
+ return { ...plan, sent_at: new Date().toISOString() }
292
+ }
293
+
294
+ // ── Other transport verbs ───────────────────────────────────────────────────
295
+
296
+ /** `herdr pane run <id> <command>` — send the text and a real Enter in one request. */
297
+ export async function runInHerdrPane(
298
+ pane: string,
299
+ command: string,
300
+ opts: HerdrTargetOptions = {},
301
+ ): Promise<void> {
302
+ const target = await resolveTarget(pane, opts)
303
+ await runHerdr(["pane", "run", target, command], opts)
304
+ }
305
+
306
+ /**
307
+ * `herdr pane read <id> --source recent-unwrapped --lines N` — recent terminal
308
+ * text with soft wraps joined back together. Plain text output, not JSON —
309
+ * returned as-is.
310
+ */
311
+ export async function readHerdrPane(
312
+ pane: string,
313
+ lines = 30,
314
+ opts: HerdrTargetOptions = {},
315
+ ): Promise<string> {
316
+ const target = await resolveTarget(pane, opts)
317
+ const { stdout } = await runHerdr(
318
+ ["pane", "read", target, "--source", "recent-unwrapped", "--lines", String(lines)],
319
+ opts,
320
+ )
321
+ return stdout
322
+ }
323
+
324
+ export interface HerdrWaitOptions extends HerdrTargetOptions {
325
+ /** Treat `match` as a regular expression (`--regex`). */
326
+ regex?: boolean
327
+ /** herdr-side wait timeout in ms (`--timeout`). */
328
+ waitTimeoutMs?: number
329
+ }
330
+
331
+ /** `herdr wait output <id> --match … --timeout …` — blocks until the text appears. JSON result. */
332
+ export async function waitForHerdrOutput(
333
+ pane: string,
334
+ match: string,
335
+ opts: HerdrWaitOptions = {},
336
+ ): Promise<unknown> {
337
+ const target = await resolveTarget(pane, opts)
338
+ const waitMs = opts.waitTimeoutMs ?? 30_000
339
+ const args = ["wait", "output", target, "--match", match]
340
+ if (opts.regex) args.push("--regex")
341
+ args.push("--timeout", String(waitMs))
342
+ // Child-process timeout must outlive the herdr-side wait.
343
+ const { stdout } = await runHerdr(args, { ...opts, timeoutMs: opts.timeoutMs ?? waitMs + 5_000 })
344
+ return parseHerdrJson<unknown>(stdout, "wait output")
345
+ }
346
+
347
+ /**
348
+ * `herdr wait agent-status <id> --status … --timeout …` — blocks until the
349
+ * agent reaches the status. On a hit, herdr 0.7.4 prints an EVENT envelope
350
+ * ({"event":"pane.agent_status_changed","data":{pane_id, workspace_id,
351
+ * agent_status}}), not a result envelope; on timeout it exits 1 with plain
352
+ * text on stderr, which surfaces here as a TideError.
353
+ */
354
+ export async function waitForHerdrAgentStatus(
355
+ pane: string,
356
+ status: TideAgentStatus,
357
+ opts: HerdrWaitOptions = {},
358
+ ): Promise<unknown> {
359
+ const target = await resolveTarget(pane, opts)
360
+ const waitMs = opts.waitTimeoutMs ?? 60_000
361
+ const { stdout } = await runHerdr(
362
+ ["wait", "agent-status", target, "--status", status, "--timeout", String(waitMs)],
363
+ { ...opts, timeoutMs: opts.timeoutMs ?? waitMs + 5_000 },
364
+ )
365
+ return parseHerdrJson<unknown>(stdout, "wait agent-status")
366
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,15 @@
1
1
  export * from "./types"
2
2
  export * from "./socket"
3
3
  export * from "./client"
4
+ export * from "./herdr"
5
+ export type {
6
+ EpisodeLaneTopology,
7
+ TideLaneCheckpoint,
8
+ TideResumeLink,
9
+ TideAudioManifestLink,
10
+ TidePendingApproval,
11
+ ObserverControllerPosture,
12
+ EpisodeLaneRole,
13
+ EpisodeLaneVerificationState,
14
+ EpisodeLane,
15
+ } from "@miadi/tide-contract"
package/src/types.ts CHANGED
@@ -1,116 +1,27 @@
1
1
  // Typed contract for the ironsilk `tide` runtime (`--format json` output).
2
2
  //
3
- // Source of truth today: runtime/tide-runtime/tide_runtime/models.py
4
- // (`ContextSnapshot.to_dict()`, `TerminalContext`). When the schema-first
5
- // contract lands (`tide-api.schema.json`), these types are regenerated, not
6
- // hand-edited. See README.md.
7
-
8
- /**
9
- * A single tmux pane observed by the context engine (R2).
10
- * NOTE: `domain_confidence` is an integer 0–100 (models.py thresholds:
11
- * 40 display / 50 observer-focus / 70 controller-focus / 80 auto-action),
12
- * NOT a 0–1 float. The web ConfidenceBar must read it on the 0–100 scale.
13
- */
14
- export interface TerminalContext {
15
- tmux_pane: string // e.g. "%56"
16
- pid: number
17
- cwd: string
18
- domain_id: string | null
19
- domain_confidence: number // 0–100 (int)
20
- is_active: boolean
21
- recent_commands: string[]
22
- captured_at: string
23
- }
24
-
25
- /** Normalized desktop window event (ECF). Loosely typed pending schema. */
26
- export interface WindowEvent {
27
- window_id?: string
28
- app?: string
29
- title?: string
30
- domain_id?: string | null
31
- domain_confidence?: number
32
- [key: string]: unknown
33
- }
34
-
35
- /** Full environment context snapshot returned by `tide context --format json` (R2). */
36
- export interface ContextSnapshot {
37
- snapshot_id: string
38
- timestamp: string
39
- domain_summary: Record<string, number>
40
- terminals: TerminalContext[]
41
- desktop_windows?: WindowEvent[]
42
- editor_buffers?: string[]
43
- }
44
-
45
- /** `tide operator terminals --format json`. Read-only terminal inventory. */
46
- export interface TideTerminalTarget {
47
- terminal_id: string
48
- session_id: string
49
- session_name: string
50
- window_id: string
51
- window_name: string
52
- pane_id: string
53
- cwd: string
54
- pane_active: boolean
55
- session_attached: number
56
- pid: number
57
- command: string
58
- domain_id: string | null
59
- domain_confidence: number
60
- attach_command: string
61
- switch_command: string
62
- select_pane_command: string
63
- }
64
-
65
- export type TideTerminalsResult = TideTerminalTarget[]
66
-
67
- /** `tide detect --format json`. Null means no domain match. */
68
- export interface TideDetectMatch {
69
- domain_id: string
70
- confidence: number
71
- signal_type: string
72
- source_detail: string
73
- }
74
-
75
- export type TideDetectResult = TideDetectMatch | null
76
-
77
- /** `tide operator peek <pane> --format json`. Shape per runtime; loose pending schema. */
78
- export interface TidePeekResult {
79
- pane?: string
80
- lines?: string[]
81
- [key: string]: unknown
82
- }
83
-
84
- /** `tide operator steer-proposal <pane> --format json`. Loose pending schema. */
85
- export interface TideSteerResult {
86
- [key: string]: unknown
87
- }
88
-
89
- /** `tide operator send <pane> --run --format json`. Loose pending schema. */
90
- export interface TideSendResult {
91
- [key: string]: unknown
92
- }
93
-
94
- /**
95
- * Result of a direct `tmux send-keys` performed by `sendKeys()`/`buildSendKeysPlan()`.
96
- * This is the simple, robust transport the operator cockpit uses to steer a pane
97
- * without the heavier reviewed-proposal pipeline.
98
- *
99
- * `submitted` reflects the "send Enter after content" toggle: when false, the
100
- * literal text is typed into the pane but NOT submitted (no trailing `C-m`),
101
- * leaving it on the prompt for the human to review and press Enter themselves.
102
- */
103
- export interface TideSendKeysResult {
104
- /** Resolved tmux pane target, always `%`-prefixed (e.g. "%56"). */
105
- target: string
106
- /** The literal text typed into the pane. */
107
- message: string
108
- /** Whether a trailing Enter (`C-m`) was sent after the literal text. */
109
- submitted: boolean
110
- /** Exact `tmux send-keys -l` argv used to type the literal text (no shell). */
111
- literal_command: string[]
112
- /** Exact `tmux send-keys … C-m` argv used to submit, or null when `submitted` is false. */
113
- submit_command: string[] | null
114
- /** ISO timestamp the keys were sent (omitted on a dry-run plan). */
115
- sent_at?: string
116
- }
3
+ // As of @miadi/tide-contract 0.2.0 the shared shapes live in the contract
4
+ // package (schema-first covenant: schema/tide-api.schema.json and its
5
+ // src/index.ts are edited in lockstep; jgwill/Miadi#378 tracks generating them
6
+ // instead of hand-syncing). This module re-exports them so `@miadi/tide`
7
+ // keeps its historical surface — including `TideSendKeysResult`, which is now
8
+ // a union discriminated on `multiplexer` (absent means "tmux", so pre-0.2.0
9
+ // producers and consumers compile unchanged).
10
+
11
+ export type {
12
+ Multiplexer,
13
+ TideAgentStatus,
14
+ TerminalContext,
15
+ WindowEvent,
16
+ ContextSnapshot,
17
+ TideTerminalTarget,
18
+ TideTerminalsResult,
19
+ TideDetectMatch,
20
+ TideDetectResult,
21
+ TidePeekResult,
22
+ TideSteerResult,
23
+ TideSendResult,
24
+ TideTmuxSendKeysResult,
25
+ TideHerdrSendKeysResult,
26
+ TideSendKeysResult,
27
+ } from "@miadi/tide-contract"