@miadi/tide 0.1.4 → 0.2.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 CHANGED
@@ -55,6 +55,21 @@ 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"` (unverified-live)
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 (`"1-2"`) are compact and **non-durable** — pass `paneLabel` and the client
65
+ re-resolves label → current id via `herdr pane list` before **every** action. Additional verbs:
66
+ `runInHerdrPane`, `readHerdrPane` (recent-unwrapped text), `waitForHerdrOutput`,
67
+ `waitForHerdrAgentStatus`, `listHerdrPanes/Workspaces/Tabs`. Binary resolution:
68
+ `TIDE_HERDR_BIN` → `herdr` on `PATH`.
69
+
70
+ > **Readiness: `unverified-live`.** The herdr transport is proven against injected command
71
+ > runners in `test/herdr.test.ts` only; no live smoke inside a herdr instance has run yet.
72
+
58
73
  `getTerminals` and `detect` are the read-only surface behind `GET /api/tide/terminals`
59
74
  and `GET /api/tide/detect` — the typed half of operator-terminal triage and manual
60
75
  domain assignment (jgwill/Miadi#382). The write-back half (assign a pane to a domain)
@@ -66,6 +81,7 @@ is deferred to the runtime + a guarded route.
66
81
  |---|---|
67
82
  | One-shot CLI (`tide … --format json`, `execFile` arg-arrays, no shell) | **implemented** |
68
83
  | Daemon + Unix-domain-socket transport (`miadi.tide.daemon.v2`) | **implemented** (`src/socket.ts`) |
84
+ | herdr CLI transport (`src/herdr.ts`, `multiplexer: "herdr"`) | **unverified-live** (runner-mocked tests only) |
69
85
  | Schema-first contract (`tide-api.schema.json` → generated types) | planned |
70
86
 
71
87
  ### 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.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"
@@ -14,8 +14,11 @@
14
14
  "files": [
15
15
  "src"
16
16
  ],
17
+ "dependencies": {
18
+ "@miadi/tide-contract": "0.2.0"
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: unverified-live).
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 compact and non-durable).
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,319 @@
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 ("1-2") are compact and NON-DURABLE — they can change when
18
+ // panes, tabs, or workspaces close. Every action therefore re-resolves
19
+ // `paneLabel` → current pane id at action time (never cached) when a label is
20
+ // provided.
21
+ //
22
+ // READINESS: unverified-live — exercised against injected runners in
23
+ // test/herdr.test.ts only; no live smoke inside a herdr instance has run yet.
24
+
25
+ import { execFile } from "node:child_process"
26
+ import { promisify } from "node:util"
27
+
28
+ import type { TideAgentStatus, TideHerdrSendKeysResult } from "@miadi/tide-contract"
29
+ import { TideError } from "./errors"
30
+ import type { TideRunOptions } from "./client"
31
+
32
+ const pExecFile = promisify(execFile)
33
+
34
+ export interface HerdrCommandResult {
35
+ stdout: string
36
+ stderr: string
37
+ }
38
+
39
+ /** Injected command runner — the mock seam for tests (no live herdr needed). */
40
+ export type HerdrCommandRunner = (
41
+ executable: string,
42
+ args: readonly string[],
43
+ ) => Promise<HerdrCommandResult>
44
+
45
+ export interface HerdrRunOptions extends TideRunOptions {
46
+ /** Injected command runner; defaults to `execFile` against the herdr binary. */
47
+ runner?: HerdrCommandRunner
48
+ }
49
+
50
+ /** Resolve the herdr binary: `TIDE_HERDR_BIN` env → `herdr` (on PATH). */
51
+ export function resolveHerdrBin(): string {
52
+ return process.env.TIDE_HERDR_BIN?.trim() || "herdr"
53
+ }
54
+
55
+ function makeRunner(opts: HerdrRunOptions): HerdrCommandRunner {
56
+ if (opts.runner) return opts.runner
57
+ return async (executable, args) => {
58
+ const { stdout, stderr } = await pExecFile(executable, args as string[], {
59
+ timeout: opts.timeoutMs ?? 10_000,
60
+ cwd: opts.cwd,
61
+ maxBuffer: 8 * 1024 * 1024,
62
+ })
63
+ return { stdout, stderr }
64
+ }
65
+ }
66
+
67
+ /** Run one herdr CLI command, wrapping failures in TideError. */
68
+ async function runHerdr(args: string[], opts: HerdrRunOptions): Promise<HerdrCommandResult> {
69
+ const runner = makeRunner(opts)
70
+ try {
71
+ return await runner(resolveHerdrBin(), args)
72
+ } catch (err) {
73
+ const msg = err instanceof Error ? err.message : String(err)
74
+ throw new TideError(`herdr ${args.join(" ")} failed: ${msg}`, err)
75
+ }
76
+ }
77
+
78
+ function parseHerdrJson<T>(stdout: string, what: string): T {
79
+ try {
80
+ return JSON.parse(stdout) as T
81
+ } catch (err) {
82
+ throw new TideError(`herdr ${what} returned non-JSON output`, err)
83
+ }
84
+ }
85
+
86
+ // ── Pane targets and label→id resolution ────────────────────────────────────
87
+
88
+ export const HERDR_PANE_ID_PATTERN = /^[0-9]+-[0-9]+$/
89
+
90
+ /** Validate a herdr pane id (e.g. "1-2"). Unlike tmux there is no `%` prefix to add. */
91
+ export function normalizeHerdrPaneTarget(pane: string): string {
92
+ const trimmed = pane.trim()
93
+ if (!HERDR_PANE_ID_PATTERN.test(trimmed)) {
94
+ throw new TideError(
95
+ `invalid herdr pane id "${pane}" (expected "<workspace>-<pane>", e.g. "1-2"); herdr ids are non-durable — pass paneLabel to resolve by label instead`,
96
+ )
97
+ }
98
+ return trimmed
99
+ }
100
+
101
+ /** One row from `herdr pane list`. Loosely typed pending a herdr JSON schema. */
102
+ export interface HerdrPaneInfo {
103
+ pane_id?: string
104
+ label?: string
105
+ title?: string
106
+ focused?: boolean
107
+ agent_status?: TideAgentStatus | string
108
+ [key: string]: unknown
109
+ }
110
+
111
+ export interface HerdrWorkspaceInfo {
112
+ workspace_id?: string
113
+ label?: string
114
+ [key: string]: unknown
115
+ }
116
+
117
+ export interface HerdrTabInfo {
118
+ tab_id?: string
119
+ label?: string
120
+ [key: string]: unknown
121
+ }
122
+
123
+ // herdr JSON envelopes nest payloads under `result` (the same nesting
124
+ // hermes-conductor parses in src/mux/backends/herdr.ts:
125
+ // result.workspace.workspace_id, result.root_pane.pane_id, result.pane.pane_id).
126
+ // Bare-object and bare-array shapes are tolerated for forward compatibility.
127
+ function unwrapList<T>(payload: unknown, key: "panes" | "workspaces" | "tabs", what: string): T[] {
128
+ if (Array.isArray(payload)) return payload as T[]
129
+ const env = payload as { result?: Record<string, unknown>; [k: string]: unknown } | null
130
+ const nested = env?.result?.[key] ?? env?.[key]
131
+ if (Array.isArray(nested)) return nested as T[]
132
+ throw new TideError(`herdr ${what} returned an unexpected JSON shape`)
133
+ }
134
+
135
+ /** `herdr pane list` — JSON inventory of panes across workspaces. */
136
+ export async function listHerdrPanes(opts: HerdrRunOptions = {}): Promise<HerdrPaneInfo[]> {
137
+ const { stdout } = await runHerdr(["pane", "list"], opts)
138
+ return unwrapList<HerdrPaneInfo>(parseHerdrJson<unknown>(stdout, "pane list"), "panes", "pane list")
139
+ }
140
+
141
+ /** `herdr workspace list` — JSON inventory of workspaces. */
142
+ export async function listHerdrWorkspaces(opts: HerdrRunOptions = {}): Promise<HerdrWorkspaceInfo[]> {
143
+ const { stdout } = await runHerdr(["workspace", "list"], opts)
144
+ return unwrapList<HerdrWorkspaceInfo>(
145
+ parseHerdrJson<unknown>(stdout, "workspace list"),
146
+ "workspaces",
147
+ "workspace list",
148
+ )
149
+ }
150
+
151
+ /** `herdr tab list --workspace <id>` — JSON inventory of tabs in a workspace. */
152
+ export async function listHerdrTabs(workspace: string, opts: HerdrRunOptions = {}): Promise<HerdrTabInfo[]> {
153
+ const { stdout } = await runHerdr(["tab", "list", "--workspace", workspace], opts)
154
+ return unwrapList<HerdrTabInfo>(parseHerdrJson<unknown>(stdout, "tab list"), "tabs", "tab list")
155
+ }
156
+
157
+ /**
158
+ * Resolve a durable pane label to the CURRENT herdr pane id via `pane list`.
159
+ * Runs before every action when a label is given — herdr ids compact when
160
+ * panes close, so a cached id may silently point at a different pane.
161
+ */
162
+ export async function resolveHerdrPaneId(paneLabel: string, opts: HerdrRunOptions = {}): Promise<string> {
163
+ const label = paneLabel.trim()
164
+ const panes = await listHerdrPanes(opts)
165
+ const match = panes.find((p) => p.label === label || p.title === label)
166
+ if (!match?.pane_id) {
167
+ throw new TideError(`no herdr pane labeled "${label}" in \`herdr pane list\``)
168
+ }
169
+ return match.pane_id
170
+ }
171
+
172
+ export interface HerdrTargetOptions extends HerdrRunOptions {
173
+ /**
174
+ * Durable pane label; when set it wins over the pane id argument and is
175
+ * re-resolved to the current id at action time.
176
+ */
177
+ paneLabel?: string
178
+ }
179
+
180
+ function resolveTarget(pane: string, opts: HerdrTargetOptions): Promise<string> {
181
+ return opts.paneLabel
182
+ ? resolveHerdrPaneId(opts.paneLabel, opts)
183
+ : Promise.resolve(normalizeHerdrPaneTarget(pane))
184
+ }
185
+
186
+ // ── Steer (send-keys) ───────────────────────────────────────────────────────
187
+
188
+ export interface HerdrSendKeysOptions extends HerdrTargetOptions {
189
+ /** Send a real Enter key after the literal text. Default true (mirrors the tmux path). */
190
+ submit?: boolean
191
+ }
192
+
193
+ /**
194
+ * Build the exact herdr CLI argv pair for a steer WITHOUT executing it. Pure —
195
+ * the herdr counterpart of buildSendKeysPlan(). `pane` must already be a
196
+ * resolved herdr pane id; label→id resolution happens in sendKeysViaHerdr().
197
+ */
198
+ export function buildHerdrSendKeysPlan(
199
+ pane: string,
200
+ message: string,
201
+ submit = true,
202
+ paneLabel?: string,
203
+ ): TideHerdrSendKeysResult {
204
+ const target = normalizeHerdrPaneTarget(pane)
205
+ const plan: TideHerdrSendKeysResult = {
206
+ multiplexer: "herdr",
207
+ target,
208
+ message,
209
+ submitted: submit,
210
+ literal_command: ["pane", "send-text", target, message],
211
+ submit_command: submit ? ["pane", "send-keys", target, "Enter"] : null,
212
+ }
213
+ if (paneLabel !== undefined) plan.pane_label = paneLabel
214
+ return plan
215
+ }
216
+
217
+ /**
218
+ * Steer a herdr pane: type `message` via `herdr pane send-text`, then submit a
219
+ * real Enter via `herdr pane send-keys … Enter` unless `submit: false`. Same
220
+ * two-step semantics as the tmux path: if the literal step succeeds but the
221
+ * submit step fails, the text is left on the pane unsubmitted and the thrown
222
+ * TideError names which step failed.
223
+ */
224
+ export async function sendKeysViaHerdr(
225
+ pane: string,
226
+ message: string,
227
+ opts: HerdrSendKeysOptions = {},
228
+ ): Promise<TideHerdrSendKeysResult> {
229
+ const target = await resolveTarget(pane, opts)
230
+ const plan = buildHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel)
231
+ const runner = makeRunner(opts)
232
+ const bin = resolveHerdrBin()
233
+ try {
234
+ await runner(bin, plan.literal_command)
235
+ } catch (err) {
236
+ const msg = err instanceof Error ? err.message : String(err)
237
+ throw new TideError(`herdr pane send-text to ${plan.target} failed (typing literal text): ${msg}`, err)
238
+ }
239
+ if (plan.submit_command) {
240
+ try {
241
+ await runner(bin, plan.submit_command)
242
+ } catch (err) {
243
+ const msg = err instanceof Error ? err.message : String(err)
244
+ throw new TideError(
245
+ `herdr pane send-keys to ${plan.target} failed (submitting Enter; literal text was typed but left unsubmitted): ${msg}`,
246
+ err,
247
+ )
248
+ }
249
+ }
250
+ return { ...plan, sent_at: new Date().toISOString() }
251
+ }
252
+
253
+ // ── Other transport verbs ───────────────────────────────────────────────────
254
+
255
+ /** `herdr pane run <id> <command>` — send the text and a real Enter in one request. */
256
+ export async function runInHerdrPane(
257
+ pane: string,
258
+ command: string,
259
+ opts: HerdrTargetOptions = {},
260
+ ): Promise<void> {
261
+ const target = await resolveTarget(pane, opts)
262
+ await runHerdr(["pane", "run", target, command], opts)
263
+ }
264
+
265
+ /**
266
+ * `herdr pane read <id> --source recent-unwrapped --lines N` — recent terminal
267
+ * text with soft wraps joined back together. Plain text output, not JSON —
268
+ * returned as-is.
269
+ */
270
+ export async function readHerdrPane(
271
+ pane: string,
272
+ lines = 30,
273
+ opts: HerdrTargetOptions = {},
274
+ ): Promise<string> {
275
+ const target = await resolveTarget(pane, opts)
276
+ const { stdout } = await runHerdr(
277
+ ["pane", "read", target, "--source", "recent-unwrapped", "--lines", String(lines)],
278
+ opts,
279
+ )
280
+ return stdout
281
+ }
282
+
283
+ export interface HerdrWaitOptions extends HerdrTargetOptions {
284
+ /** Treat `match` as a regular expression (`--regex`). */
285
+ regex?: boolean
286
+ /** herdr-side wait timeout in ms (`--timeout`). */
287
+ waitTimeoutMs?: number
288
+ }
289
+
290
+ /** `herdr wait output <id> --match … --timeout …` — blocks until the text appears. JSON result. */
291
+ export async function waitForHerdrOutput(
292
+ pane: string,
293
+ match: string,
294
+ opts: HerdrWaitOptions = {},
295
+ ): Promise<unknown> {
296
+ const target = await resolveTarget(pane, opts)
297
+ const waitMs = opts.waitTimeoutMs ?? 30_000
298
+ const args = ["wait", "output", target, "--match", match]
299
+ if (opts.regex) args.push("--regex")
300
+ args.push("--timeout", String(waitMs))
301
+ // Child-process timeout must outlive the herdr-side wait.
302
+ const { stdout } = await runHerdr(args, { ...opts, timeoutMs: opts.timeoutMs ?? waitMs + 5_000 })
303
+ return parseHerdrJson<unknown>(stdout, "wait output")
304
+ }
305
+
306
+ /** `herdr wait agent-status <id> --status … --timeout …` — blocks until the agent reaches the status. JSON result. */
307
+ export async function waitForHerdrAgentStatus(
308
+ pane: string,
309
+ status: TideAgentStatus,
310
+ opts: HerdrWaitOptions = {},
311
+ ): Promise<unknown> {
312
+ const target = await resolveTarget(pane, opts)
313
+ const waitMs = opts.waitTimeoutMs ?? 60_000
314
+ const { stdout } = await runHerdr(
315
+ ["wait", "agent-status", target, "--status", status, "--timeout", String(waitMs)],
316
+ { ...opts, timeoutMs: opts.timeoutMs ?? waitMs + 5_000 },
317
+ )
318
+ return parseHerdrJson<unknown>(stdout, "wait agent-status")
319
+ }
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"