@miadi/tide 0.2.1 → 0.2.3

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
@@ -64,10 +64,15 @@ resolved via `TIDE_TMUX_BIN` -> `tmux` on `PATH`.
64
64
  herdr pane ids (`"w1:p2"` as of herdr 0.7; legacy `"1-2"` accepted) are **session-scoped** —
65
65
  they reset on herdr restart, and a stale id fails loudly with `pane_not_found`. Pass `paneLabel`
66
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`.
67
+ `herdr pane list` before **every** action; duplicate labels throw rather than guess. Additional
68
+ verbs: `runInHerdrPane`, `readHerdrPane` (recent-unwrapped text), `renameHerdrPane` (sets the
69
+ durable label), `waitForHerdrOutput` (typed `TideHerdrWaitOutputResult`),
70
+ `waitForHerdrAgentStatus` (typed `TideHerdrAgentStatusEvent` — live hits print an event
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`.
71
76
 
72
77
  > **Readiness: `live-verified`.** Smoked against a real herdr 0.7.4 instance (EP137
73
78
  > herdr-smoke lane, 2026-07-16) — inventory parsing, send-text/send-keys, pane run, read,
@@ -114,11 +119,13 @@ Newline-delimited JSON over a Unix socket. Request
114
119
  (mirrors the runtime's `get_config_dir()`). Binary resolution for the CLI fallback:
115
120
  `TIDE_BIN` → `which tide` → legacy `/home/jgi/anaconda3/bin/tide`.
116
121
 
117
- ## Operator-cockpit surface (next)
122
+ ## Operator-cockpit surface
118
123
 
119
- `describeTransport()` + `pingDaemon()` are the building blocks for a `GET /api/tide/health`
120
- endpoint so a Hermes/Ava/Miadi session can see *which transport is live and whether the daemon is
121
- answering* before it reads context or proposes a steer. See the foundations plan.
124
+ `describeTransport()` + `pingDaemon()` back the shipped `GET /api/tide/health` route, so a
125
+ Hermes/Ava/Miadi session can see *which transport is live and whether the daemon is answering*
126
+ before it reads context or proposes a steer. The cockpit routes (`steer`, `peek`, `detect`,
127
+ `terminals`) are still tmux-only — herdr reachability from `/api/tide/*` is tracked in
128
+ jgwill/Miadi#494.
122
129
 
123
130
  ## Tests
124
131
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
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.1"
18
+ "@miadi/tide-contract": "0.2.3"
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,7 +41,13 @@ import {
41
41
  TideDaemonError,
42
42
  } from "./socket"
43
43
  import { TideError } from "./errors"
44
- import { sendKeysViaHerdr } from "./herdr"
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"
46
52
 
47
53
  const pExecFile = promisify(execFile)
@@ -204,8 +210,29 @@ export function detect(opts: DetectOptions = {}): Promise<TideDetectResult> {
204
210
  return runTideJson<TideDetectResult>(args, { timeoutMs: 8_000, ...opts })
205
211
  }
206
212
 
207
- /** Operator cockpit — read scrollback for a pane without attaching. `pane` is the numeric index (no `%`). */
208
- export function peek(pane: string, lines = 30, opts?: TideRunOptions): Promise<TidePeekResult> {
213
+ export interface PeekOptions extends TideRunOptions {
214
+ /** Absent or "tmux" keeps the historical tide-runtime peek; "herdr" reads via `herdr pane read`. */
215
+ multiplexer?: Multiplexer
216
+ /** herdr only: durable pane label, re-resolved to the current pane id at action time. */
217
+ paneLabel?: string
218
+ /** herdr only: injected command runner (tests). */
219
+ runner?: HerdrCommandRunner
220
+ }
221
+
222
+ /**
223
+ * Operator cockpit — read scrollback for a pane without attaching. tmux path:
224
+ * `pane` is the numeric index (no `%`). herdr path (`multiplexer: "herdr"`):
225
+ * `pane` is a herdr pane id (or pass `paneLabel`), and the recent-unwrapped
226
+ * text comes back split into `lines`.
227
+ */
228
+ export async function peek(pane: string, lines = 30, opts: PeekOptions = {}): Promise<TidePeekResult> {
229
+ if (opts.multiplexer === "herdr") {
230
+ // Resolve the label here so the result reports the CURRENT pane id, not
231
+ // the raw (possibly empty) pane argument. Same CLI cost: one list + one read.
232
+ const target = opts.paneLabel ? await resolveHerdrPaneId(opts.paneLabel, opts) : pane
233
+ const text = await readHerdrPane(target, lines, { ...opts, paneLabel: undefined })
234
+ return { multiplexer: "herdr", pane: target, lines: text.split("\n"), text }
235
+ }
209
236
  return runTideJson<TidePeekResult>(
210
237
  ["operator", "peek", `%${pane}`, "--lines", String(lines), "--format", "json"],
211
238
  { timeoutMs: 8_000, ...opts },
@@ -320,6 +347,13 @@ export async function sendKeys(
320
347
  if (opts.multiplexer === "herdr") {
321
348
  return sendKeysViaHerdr(pane, message, opts)
322
349
  }
350
+ // herdr-only options on the tmux path would silently steer the raw tmux
351
+ // pane — the wrong-pane hazard labels exist to prevent. Fail loudly instead.
352
+ if (opts.paneLabel !== undefined || opts.runner !== undefined) {
353
+ throw new TideError(
354
+ `sendKeys: "paneLabel"/"runner" are herdr-only options — pass multiplexer: "herdr"`,
355
+ )
356
+ }
323
357
  const submit = opts.submit ?? true
324
358
  const plan = buildSendKeysPlan(pane, message, submit)
325
359
  const bin = resolveTmuxBin()
@@ -465,13 +499,21 @@ export async function listPendingApprovals(
465
499
  }
466
500
  }
467
501
 
468
- /** Build a steer plan with lane context (wraps buildSendKeysPlan, adds lane_id). */
502
+ /**
503
+ * Build a steer plan with lane context (adds lane_id). Dispatches on the
504
+ * pane-target format: contract-legal herdr targets like "w1:p2" (see
505
+ * `EpisodeLane.pane_target`) get a herdr plan — the tmux normalizer would
506
+ * otherwise mangle them into garbage like "%w1:p2". The two id grammars are
507
+ * disjoint (tmux: `%?digits`), so format detection is unambiguous.
508
+ */
469
509
  export function buildEpisodeSteerPlan(
470
510
  laneId: string,
471
511
  pane: string,
472
512
  message: string,
473
513
  submit = true,
474
- ): ReturnType<typeof buildSendKeysPlan> & { lane_id: string } {
475
- const plan = buildSendKeysPlan(pane, message, submit)
514
+ ): TideSendKeysResult & { lane_id: string } {
515
+ const plan = HERDR_PANE_ID_PATTERN.test(pane.trim())
516
+ ? buildHerdrSendKeysPlan(pane, message, submit)
517
+ : buildSendKeysPlan(pane, message, submit)
476
518
  return { ...plan, lane_id: laneId }
477
519
  }
package/src/herdr.ts CHANGED
@@ -30,7 +30,16 @@
30
30
  import { execFile } from "node:child_process"
31
31
  import { promisify } from "node:util"
32
32
 
33
- import type { TideAgentStatus, TideHerdrSendKeysResult } from "@miadi/tide-contract"
33
+ import type {
34
+ TideAgentStatus,
35
+ TideHerdrAgentStatusEvent,
36
+ TideHerdrInventory,
37
+ TideHerdrPaneInfo,
38
+ TideHerdrSendKeysResult,
39
+ TideHerdrTabInfo,
40
+ TideHerdrWaitOutputResult,
41
+ TideHerdrWorkspaceInfo,
42
+ } from "@miadi/tide-contract"
34
43
  import { TideError } from "./errors"
35
44
  import type { TideRunOptions } from "./client"
36
45
 
@@ -83,7 +92,10 @@ function describeRunnerError(err: unknown): string {
83
92
  const stderr = typeof e?.stderr === "string" ? e.stderr.trim() : ""
84
93
  if (stderr) return stderr
85
94
  const raw = err instanceof Error ? err.message : String(err)
86
- const stripped = raw.replace(/^Command failed:[^\n]*\n?/, "").trim()
95
+ // A "Command failed:" message embeds the full argv — possibly across several
96
+ // lines when the steered text contains newlines — so discard it entirely
97
+ // rather than stripping just the first line.
98
+ const stripped = raw.startsWith("Command failed:") ? "" : raw.trim()
87
99
  if (stripped) return stripped
88
100
  const meta = [
89
101
  e?.code != null ? `exit code ${String(e.code)}` : null,
@@ -114,7 +126,10 @@ function parseHerdrJson<T>(stdout: string, what: string): T {
114
126
  // ── Pane targets and label→id resolution ────────────────────────────────────
115
127
 
116
128
  // "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]+)$/
129
+ // Segments are ALPHANUMERIC, not just digits — live 0.7.4 allocates pane
130
+ // suffixes past p9 as letters (w2:pE, w2:pJ observed in the EP137 follow-up
131
+ // inventory), so a digits-only pattern strands every pane beyond the ninth.
132
+ export const HERDR_PANE_ID_PATTERN = /^(w[0-9A-Za-z]+:p[0-9A-Za-z]+|[0-9]+-[0-9]+)$/
118
133
 
119
134
  /** Validate a herdr pane id (e.g. "w1:p2"). Unlike tmux there is no `%` prefix to add. */
120
135
  export function normalizeHerdrPaneTarget(pane: string): string {
@@ -128,35 +143,19 @@ export function normalizeHerdrPaneTarget(pane: string): string {
128
143
  }
129
144
 
130
145
  /**
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.
146
+ * One row from `herdr pane list` — the covenant shape (tide-contract 0.2.2's
147
+ * `TideHerdrPaneInfo`) plus a `title` field tolerated for other herdr builds
148
+ * (live 0.7.4 rows never carry it; resolution matches it only as a fallback).
134
149
  */
135
- export interface HerdrPaneInfo {
136
- pane_id?: string
137
- label?: string
150
+ export interface HerdrPaneInfo extends TideHerdrPaneInfo {
138
151
  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
152
  }
148
153
 
149
- export interface HerdrWorkspaceInfo {
150
- workspace_id?: string
151
- label?: string
152
- [key: string]: unknown
153
- }
154
+ /** One row from `herdr workspace list` — the covenant shape (tide-contract 0.2.3). */
155
+ export type HerdrWorkspaceInfo = TideHerdrWorkspaceInfo
154
156
 
155
- export interface HerdrTabInfo {
156
- tab_id?: string
157
- label?: string
158
- [key: string]: unknown
159
- }
157
+ /** One row from `herdr tab list` — the covenant shape (tide-contract 0.2.3). */
158
+ export type HerdrTabInfo = TideHerdrTabInfo
160
159
 
161
160
  // herdr JSON envelopes nest payloads under `result` (the same nesting
162
161
  // hermes-conductor parses in src/mux/backends/herdr.ts:
@@ -192,6 +191,37 @@ export async function listHerdrTabs(workspace: string, opts: HerdrRunOptions = {
192
191
  return unwrapList<HerdrTabInfo>(parseHerdrJson<unknown>(stdout, "tab list"), "tabs", "tab list")
193
192
  }
194
193
 
194
+ export interface HerdrInventoryOptions extends HerdrRunOptions {
195
+ /** Also list tabs per workspace (extra CLI spawns) and annotate each with its workspace_id. */
196
+ includeTabs?: boolean
197
+ }
198
+
199
+ /**
200
+ * One-call herdr inventory snapshot for cockpit surfaces: workspaces + panes
201
+ * (and tabs on request) through a single verb, so route handlers stay thin.
202
+ * Pane rows already carry workspace_id/tab_id/label/agent_status/cwd on live
203
+ * 0.7.4 — the UI can group panes by workspace without the tabs leg.
204
+ */
205
+ export async function getHerdrInventory(opts: HerdrInventoryOptions = {}): Promise<TideHerdrInventory> {
206
+ const [workspaces, panes] = await Promise.all([listHerdrWorkspaces(opts), listHerdrPanes(opts)])
207
+ const inventory: TideHerdrInventory = {
208
+ multiplexer: "herdr",
209
+ captured_at: new Date().toISOString(),
210
+ workspaces,
211
+ panes,
212
+ }
213
+ if (opts.includeTabs) {
214
+ const perWorkspace = await Promise.all(
215
+ workspaces
216
+ .map((ws) => ws.workspace_id)
217
+ .filter((id): id is string => typeof id === "string" && id.length > 0)
218
+ .map(async (id) => (await listHerdrTabs(id, opts)).map((tab) => ({ ...tab, workspace_id: id }))),
219
+ )
220
+ inventory.tabs = perWorkspace.flat()
221
+ }
222
+ return inventory
223
+ }
224
+
195
225
  /**
196
226
  * Resolve a durable pane label to the CURRENT herdr pane id via `pane list`.
197
227
  * Runs before every action when a label is given — herdr ids are
@@ -202,7 +232,17 @@ export async function listHerdrTabs(workspace: string, opts: HerdrRunOptions = {
202
232
  export async function resolveHerdrPaneId(paneLabel: string, opts: HerdrRunOptions = {}): Promise<string> {
203
233
  const label = paneLabel.trim()
204
234
  const panes = await listHerdrPanes(opts)
205
- const match = panes.find((p) => p.label === label || p.title === label)
235
+ // Two passes: an explicit `pane rename` label always beats a title
236
+ // coincidence, regardless of pane order.
237
+ let matches = panes.filter((p) => p.label === label)
238
+ if (matches.length === 0) matches = panes.filter((p) => p.title === label)
239
+ if (matches.length > 1) {
240
+ const ids = matches.map((p) => p.pane_id ?? "?").join(", ")
241
+ throw new TideError(
242
+ `ambiguous herdr pane label "${label}" — matches panes ${ids}; rename panes to unique labels`,
243
+ )
244
+ }
245
+ const match = matches[0]
206
246
  if (!match?.pane_id) {
207
247
  throw new TideError(`no herdr pane labeled "${label}" in \`herdr pane list\``)
208
248
  }
@@ -231,17 +271,17 @@ export interface HerdrSendKeysOptions extends HerdrTargetOptions {
231
271
  }
232
272
 
233
273
  /**
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().
274
+ * Assemble the steer plan for an ALREADY-TRUSTED target — no validation. Ids
275
+ * herdr itself just returned (label resolution) must pass through unchecked:
276
+ * re-validating them against HERDR_PANE_ID_PATTERN is the regression class
277
+ * that broke 0.2.0 when live 0.7 ids arrived.
237
278
  */
238
- export function buildHerdrSendKeysPlan(
239
- pane: string,
279
+ function makeHerdrSendKeysPlan(
280
+ target: string,
240
281
  message: string,
241
- submit = true,
282
+ submit: boolean,
242
283
  paneLabel?: string,
243
284
  ): TideHerdrSendKeysResult {
244
- const target = normalizeHerdrPaneTarget(pane)
245
285
  const plan: TideHerdrSendKeysResult = {
246
286
  multiplexer: "herdr",
247
287
  target,
@@ -254,6 +294,20 @@ export function buildHerdrSendKeysPlan(
254
294
  return plan
255
295
  }
256
296
 
297
+ /**
298
+ * Build the exact herdr CLI argv pair for a steer WITHOUT executing it. Pure —
299
+ * the herdr counterpart of buildSendKeysPlan(). `pane` is caller-supplied and
300
+ * therefore validated; label→id resolution happens in sendKeysViaHerdr().
301
+ */
302
+ export function buildHerdrSendKeysPlan(
303
+ pane: string,
304
+ message: string,
305
+ submit = true,
306
+ paneLabel?: string,
307
+ ): TideHerdrSendKeysResult {
308
+ return makeHerdrSendKeysPlan(normalizeHerdrPaneTarget(pane), message, submit, paneLabel)
309
+ }
310
+
257
311
  /**
258
312
  * Steer a herdr pane: type `message` via `herdr pane send-text`, then submit a
259
313
  * real Enter via `herdr pane send-keys … Enter` unless `submit: false`. Same
@@ -266,8 +320,9 @@ export async function sendKeysViaHerdr(
266
320
  message: string,
267
321
  opts: HerdrSendKeysOptions = {},
268
322
  ): Promise<TideHerdrSendKeysResult> {
323
+ // resolveTarget validates caller-supplied ids and trusts label-resolved ones.
269
324
  const target = await resolveTarget(pane, opts)
270
- const plan = buildHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel)
325
+ const plan = makeHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel)
271
326
  const runner = makeRunner(opts)
272
327
  const bin = resolveHerdrBin()
273
328
  try {
@@ -293,6 +348,20 @@ export async function sendKeysViaHerdr(
293
348
 
294
349
  // ── Other transport verbs ───────────────────────────────────────────────────
295
350
 
351
+ /**
352
+ * `herdr pane rename <id> <label>` — set the durable label that label→id
353
+ * resolution matches. The one command the whole re-resolution design rests on:
354
+ * without a rename, live 0.7.4 pane rows carry no `label` field at all.
355
+ */
356
+ export async function renameHerdrPane(
357
+ pane: string,
358
+ label: string,
359
+ opts: HerdrTargetOptions = {},
360
+ ): Promise<void> {
361
+ const target = await resolveTarget(pane, opts)
362
+ await runHerdr(["pane", "rename", target, label], opts)
363
+ }
364
+
296
365
  /** `herdr pane run <id> <command>` — send the text and a real Enter in one request. */
297
366
  export async function runInHerdrPane(
298
367
  pane: string,
@@ -333,15 +402,20 @@ export async function waitForHerdrOutput(
333
402
  pane: string,
334
403
  match: string,
335
404
  opts: HerdrWaitOptions = {},
336
- ): Promise<unknown> {
405
+ ): Promise<TideHerdrWaitOutputResult> {
337
406
  const target = await resolveTarget(pane, opts)
338
407
  const waitMs = opts.waitTimeoutMs ?? 30_000
339
408
  const args = ["wait", "output", target, "--match", match]
340
409
  if (opts.regex) args.push("--regex")
341
410
  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")
411
+ // Child-process timeout must outlive the herdr-side wait — even when the
412
+ // caller passed a smaller generic timeoutMs, which would otherwise SIGTERM
413
+ // herdr mid-wait.
414
+ const { stdout } = await runHerdr(args, {
415
+ ...opts,
416
+ timeoutMs: Math.max(opts.timeoutMs ?? 0, waitMs + 5_000),
417
+ })
418
+ return parseHerdrJson<TideHerdrWaitOutputResult>(stdout, "wait output")
345
419
  }
346
420
 
347
421
  /**
@@ -355,12 +429,12 @@ export async function waitForHerdrAgentStatus(
355
429
  pane: string,
356
430
  status: TideAgentStatus,
357
431
  opts: HerdrWaitOptions = {},
358
- ): Promise<unknown> {
432
+ ): Promise<TideHerdrAgentStatusEvent> {
359
433
  const target = await resolveTarget(pane, opts)
360
434
  const waitMs = opts.waitTimeoutMs ?? 60_000
361
435
  const { stdout } = await runHerdr(
362
436
  ["wait", "agent-status", target, "--status", status, "--timeout", String(waitMs)],
363
- { ...opts, timeoutMs: opts.timeoutMs ?? waitMs + 5_000 },
437
+ { ...opts, timeoutMs: Math.max(opts.timeoutMs ?? 0, waitMs + 5_000) },
364
438
  )
365
- return parseHerdrJson<unknown>(stdout, "wait agent-status")
439
+ return parseHerdrJson<TideHerdrAgentStatusEvent>(stdout, "wait agent-status")
366
440
  }