@miadi/tide 0.1.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 ADDED
@@ -0,0 +1,97 @@
1
+ # `@miadi/tide`
2
+
3
+ Typed client boundary between Miadi and the **ironsilk `tide`** runtime (historically
4
+ `hermes-navigator`). The single place the web app talks to `tide` — replacing the per-route
5
+ `exec("/home/jgi/anaconda3/bin/tide …")` calls.
6
+
7
+ Grounded in `foundations/terminal-workspace-orchestration/` (Decision C) and
8
+ `rispecs/hermes-navigator/05-ui-surface.spec.md` (daemon-socket transport).
9
+
10
+ ## Runtime dependency — install `tide`
11
+
12
+ This package is a **client**; it does not bundle the runtime. The `tide` CLI is the
13
+ console entry point of the **`ironsilk`** PyPI package (`[project.scripts]`
14
+ `tide = hermes_navigator.cli:main`). Install / upgrade it in the Python env the
15
+ Next.js server can reach:
16
+
17
+ ```bash
18
+ pip install -U ironsilk # provides the `tide` CLI (currently 0.9.13)
19
+ tide --help # verify
20
+ ```
21
+
22
+ Source for the runtime lives at `/usr/local/src/ironsilk/runtime/` (editable:
23
+ `pip install -e .`). `@miadi/tide` resolves the binary via `TIDE_BIN` →
24
+ `which tide` → legacy `/home/jgi/anaconda3/bin/tide`; set `TIDE_BIN` when `tide`
25
+ is outside the server's `PATH`. The daemon socket is resolved separately via
26
+ `TIDE_SOCKET` (see below).
27
+
28
+ ## Verbs
29
+
30
+ ```ts
31
+ import { getContext, peek, steerProposal, send, pingDaemon, describeTransport, TideError } from "@miadi/tide"
32
+
33
+ const snapshot = await getContext() // R2 live context (daemon socket → CLI fallback)
34
+ const scroll = await peek("56", 80) // operator peek %56 (CLI)
35
+ const proposal = await steerProposal("56", "continue from checkpoint") // (CLI)
36
+ const sent = await send("56", "continue") // guarded --run, controller mode (CLI)
37
+
38
+ const up = await pingDaemon() // daemon liveness (ping → pong)
39
+ const how = describeTransport() // { transport: "socket"|"cli", socketPath, socketAvailable }
40
+ ```
41
+
42
+ ## Transport status
43
+
44
+ | Layer | Status |
45
+ |---|---|
46
+ | One-shot CLI (`tide … --format json`, `execFile` arg-arrays, no shell) | **implemented** |
47
+ | Daemon + Unix-domain-socket transport (`hermes.navigator.daemon.v1`) | **implemented** (`src/socket.ts`) |
48
+ | Schema-first contract (`tide-api.schema.json` → generated types) | planned |
49
+
50
+ ### How transport selection works
51
+
52
+ `getContext()` is transport-aware:
53
+
54
+ - **`auto`** (default): use the daemon socket if it is up; on absence *or* daemon error, fall
55
+ back to the CLI. No Python spawn on the hot path when the daemon is running (~µs socket
56
+ round-trip vs ~200–500 ms CLI spawn).
57
+ - **`socket`**: daemon only — throws `TideDaemonError` if unavailable.
58
+ - **`cli`**: force the CLI.
59
+
60
+ `peek` / `steerProposal` / `send` are **CLI-only**: the daemon exposes `get_context` / `ping` /
61
+ `detect`, not the operator mutation verbs. They join the socket path when the runtime adds those
62
+ actions — verb signatures are the stable surface; only the transport underneath changes.
63
+
64
+ ### Wire protocol (mirrors `hermes_navigator/daemon.py`)
65
+
66
+ Newline-delimited JSON over a Unix socket. Request
67
+ `{contract_version:"hermes.navigator.daemon.v1", request_id, action, payload}` →
68
+ `{contract_version, request_id, ok:true, data}` (or `ok:false, error:{code,message,retryable}}`).
69
+
70
+ ### Socket path resolution
71
+
72
+ `TIDE_SOCKET` (explicit) → `${HNAVIG_HOME || HERMES_HOME || ~/.miadi/navigator}/daemon.sock`
73
+ (mirrors the runtime's `get_config_dir()`). Binary resolution for the CLI fallback:
74
+ `TIDE_BIN` → `which tide` → legacy `/home/jgi/anaconda3/bin/tide`.
75
+
76
+ ## Operator-cockpit surface (next)
77
+
78
+ `describeTransport()` + `pingDaemon()` are the building blocks for a `GET /api/tide/health`
79
+ endpoint so a Hermes/Ava/Miadi session can see *which transport is live and whether the daemon is
80
+ answering* before it reads context or proposes a steer. See the foundations plan.
81
+
82
+ ## Tests
83
+
84
+ ```bash
85
+ cd packages/tide && npm test
86
+ ```
87
+
88
+ Compiles `src` + `test` to `/tmp/miadi-tide-test` (CJS) and runs `node --test`. The suite proves
89
+ socket selection and CLI fallback with a **fake Unix-socket daemon** and a **fake `tide` binary** —
90
+ no live daemon, no live `tide` required.
91
+
92
+ ## App wiring (current)
93
+
94
+ Resolved as **source** via a `tsconfig.json` path alias
95
+ (`"@miadi/tide": ["./packages/tide/src/index.ts"]`) — same pattern as `@miadi/a2a-contracts`,
96
+ no `pnpm install`, no lockfile change. Switch to a `workspace:*` dependency + `dist/` build when a
97
+ real build step is introduced.
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@miadi/tide",
3
+ "version": "0.1.0",
4
+ "description": "Typed client boundary for the ironsilk `tide` runtime. Daemon Unix-socket transport with CLI fallback.",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "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"
16
+ },
17
+ "keywords": [
18
+ "miadi",
19
+ "tide",
20
+ "ironsilk",
21
+ "operator-cockpit"
22
+ ]
23
+ }
package/src/client.ts ADDED
@@ -0,0 +1,191 @@
1
+ // `@miadi/tide` client boundary — the single place Miadi talks to the `tide` runtime.
2
+ //
3
+ // Two transports behind one verb surface:
4
+ // • DAEMON — newline-delimited JSON over the `tide daemon` Unix socket
5
+ // (hermes.navigator.daemon.v1). Preferred for `getContext` when up.
6
+ // • CLI — one-shot `tide <verb> --format json` via `execFile` with ARGUMENT
7
+ // ARRAYS (no shell). Always the fallback; the only path for the
8
+ // operator verbs (`peek`/`steerProposal`/`send`), which the daemon
9
+ // does not expose as socket actions.
10
+ //
11
+ // Verb signatures are the stable surface; transport selection is internal.
12
+
13
+ import { execFile } from "node:child_process"
14
+ import { promisify } from "node:util"
15
+
16
+ import type {
17
+ ContextSnapshot,
18
+ TidePeekResult,
19
+ TideSendResult,
20
+ TideSteerResult,
21
+ } from "./types"
22
+ import {
23
+ daemonRequest,
24
+ isSocketAvailable,
25
+ resolveSocketPath,
26
+ TideDaemonError,
27
+ } from "./socket"
28
+
29
+ const pExecFile = promisify(execFile)
30
+
31
+ /**
32
+ * Legacy absolute path used by the original API routes on Gaia. Kept as the LAST
33
+ * resort so this refactor preserves current behavior even where `tide` is not on
34
+ * the Next.js server's PATH. Prefer `TIDE_BIN` or PATH resolution.
35
+ */
36
+ const LEGACY_TIDE_BIN = "/home/jgi/anaconda3/bin/tide"
37
+
38
+ let cachedBin: Promise<string> | null = null
39
+
40
+ /** Resolve the `tide` binary: `TIDE_BIN` env → `which tide` → legacy path. Cached. */
41
+ export function resolveTideBin(): Promise<string> {
42
+ if (cachedBin) return cachedBin
43
+ cachedBin = (async () => {
44
+ const fromEnv = process.env.TIDE_BIN?.trim()
45
+ if (fromEnv) return fromEnv
46
+ try {
47
+ const { stdout } = await pExecFile("which", ["tide"], { timeout: 3000 })
48
+ const found = stdout.trim().split("\n")[0]?.trim()
49
+ if (found) return found
50
+ } catch {
51
+ // `tide` not on PATH (or `which` unavailable) — fall through to legacy.
52
+ }
53
+ return LEGACY_TIDE_BIN
54
+ })()
55
+ return cachedBin
56
+ }
57
+
58
+ /** Reset the cached binary resolution (tests / env changes). */
59
+ export function resetTideBinCache(): void {
60
+ cachedBin = null
61
+ }
62
+
63
+ export class TideError extends Error {
64
+ readonly cause?: unknown
65
+ constructor(message: string, cause?: unknown) {
66
+ super(message)
67
+ this.name = "TideError"
68
+ this.cause = cause
69
+ }
70
+ }
71
+
72
+ export interface TideRunOptions {
73
+ timeoutMs?: number
74
+ cwd?: string
75
+ }
76
+
77
+ /** Core helper: run `tide <args> --format json`, parse and return JSON, or throw `TideError`. */
78
+ export async function runTideJson<T = unknown>(
79
+ args: string[],
80
+ opts: TideRunOptions = {},
81
+ ): Promise<T> {
82
+ const bin = await resolveTideBin()
83
+ let stdout: string
84
+ try {
85
+ const res = await pExecFile(bin, args, {
86
+ timeout: opts.timeoutMs ?? 10_000,
87
+ cwd: opts.cwd,
88
+ maxBuffer: 8 * 1024 * 1024,
89
+ })
90
+ stdout = res.stdout
91
+ } catch (err) {
92
+ const msg = err instanceof Error ? err.message : String(err)
93
+ throw new TideError(`tide ${args.join(" ")} failed: ${msg}`, err)
94
+ }
95
+ try {
96
+ return JSON.parse(stdout) as T
97
+ } catch (err) {
98
+ throw new TideError(`tide ${args.join(" ")} returned non-JSON output`, err)
99
+ }
100
+ }
101
+
102
+ // ── Transport selection (context) ───────────────────────────────────────────
103
+
104
+ export type TransportMode = "auto" | "socket" | "cli"
105
+
106
+ export interface GetContextOptions extends TideRunOptions {
107
+ /**
108
+ * "auto" (default): use the daemon socket if it is up, otherwise the CLI.
109
+ * "socket": daemon only (throws if unavailable). "cli": force the CLI.
110
+ */
111
+ transport?: TransportMode
112
+ }
113
+
114
+ /** Which transport `getContext()` would use right now — a diagnostic for the operator cockpit. */
115
+ export function describeTransport(): {
116
+ transport: "socket" | "cli"
117
+ socketPath: string
118
+ socketAvailable: boolean
119
+ } {
120
+ const socketPath = resolveSocketPath()
121
+ const socketAvailable = isSocketAvailable(socketPath)
122
+ return { transport: socketAvailable ? "socket" : "cli", socketPath, socketAvailable }
123
+ }
124
+
125
+ /** Liveness probe against the daemon (`ping` → `pong`). False when the socket is down or silent. */
126
+ export async function pingDaemon(timeoutMs = 2_000): Promise<boolean> {
127
+ if (!isSocketAvailable()) return false
128
+ try {
129
+ return (await daemonRequest<string>("ping", {}, { timeoutMs })) === "pong"
130
+ } catch {
131
+ return false
132
+ }
133
+ }
134
+
135
+ // ── Typed verbs ────────────────────────────────────────────────────────────
136
+
137
+ /**
138
+ * R2 — full live context snapshot. Prefers the daemon socket (no Python spawn);
139
+ * falls back to the CLI when the daemon is down or errors (in "auto" mode).
140
+ */
141
+ export async function getContext(opts: GetContextOptions = {}): Promise<ContextSnapshot> {
142
+ const mode = opts.transport ?? "auto"
143
+ if (mode !== "cli" && isSocketAvailable()) {
144
+ try {
145
+ return await daemonRequest<ContextSnapshot>("get_context", {}, { timeoutMs: opts.timeoutMs })
146
+ } catch (err) {
147
+ if (mode === "socket") throw err
148
+ // auto: daemon present but failed — fall through to the CLI transport.
149
+ }
150
+ } else if (mode === "socket") {
151
+ throw new TideDaemonError("daemon socket unavailable", "unavailable")
152
+ }
153
+ return runTideJson<ContextSnapshot>(["context", "--format", "json"], {
154
+ timeoutMs: opts.timeoutMs ?? 10_000,
155
+ cwd: opts.cwd,
156
+ })
157
+ }
158
+
159
+ /** Operator cockpit — read scrollback for a pane without attaching. `pane` is the numeric index (no `%`). */
160
+ export function peek(pane: string, lines = 30, opts?: TideRunOptions): Promise<TidePeekResult> {
161
+ return runTideJson<TidePeekResult>(
162
+ ["operator", "peek", `%${pane}`, "--lines", String(lines), "--format", "json"],
163
+ { timeoutMs: 8_000, ...opts },
164
+ )
165
+ }
166
+
167
+ /** Operator cockpit — build a reviewed steer proposal (no send). `pane` is the numeric index. */
168
+ export function steerProposal(
169
+ pane: string,
170
+ message: string,
171
+ peekLines = 10,
172
+ opts?: TideRunOptions,
173
+ ): Promise<TideSteerResult> {
174
+ return runTideJson<TideSteerResult>(
175
+ [
176
+ "operator", "steer-proposal", `%${pane}`,
177
+ "--message", message,
178
+ "--peek-lines", String(peekLines),
179
+ "--format", "json",
180
+ ],
181
+ { timeoutMs: 10_000, ...opts },
182
+ )
183
+ }
184
+
185
+ /** Operator cockpit — guarded send (`--run`). Requires controller mode on the runtime side. */
186
+ export function send(pane: string, message: string, opts?: TideRunOptions): Promise<TideSendResult> {
187
+ return runTideJson<TideSendResult>(
188
+ ["operator", "send", `%${pane}`, "--message", message, "--run", "--format", "json"],
189
+ { timeoutMs: 10_000, ...opts },
190
+ )
191
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./types"
2
+ export * from "./socket"
3
+ export * from "./client"
package/src/socket.ts ADDED
@@ -0,0 +1,142 @@
1
+ // Daemon transport for `@miadi/tide` — speaks the running `tide daemon`'s
2
+ // versioned Unix-domain-socket protocol so the web layer can read live context
3
+ // without paying a Python interpreter spawn per request.
4
+ //
5
+ // Wire protocol (mirrors hermes_navigator/daemon.py):
6
+ // contract: "hermes.navigator.daemon.v1"
7
+ // transport: newline-delimited JSON over a Unix domain socket
8
+ // request: {contract_version, request_id, action, payload}
9
+ // response: {contract_version, request_id, ok, data} (success)
10
+ // {contract_version, request_id, ok:false, error:{code,message,retryable}}
11
+ // actions: "ping" -> "pong" | "get_context" -> snapshot | "detect" -> match|null
12
+ //
13
+ // Socket path resolution mirrors the runtime's get_config_dir():
14
+ // TIDE_SOCKET (explicit full path)
15
+ // else ${HNAVIG_HOME || HERMES_HOME || ~/.miadi/navigator}/daemon.sock
16
+ //
17
+ // This module never throws synchronously for "daemon absent" — callers test
18
+ // `isSocketAvailable()` and fall back to the CLI transport (see client.ts).
19
+
20
+ import { connect } from "node:net"
21
+ import { randomUUID } from "node:crypto"
22
+ import { statSync } from "node:fs"
23
+ import { homedir } from "node:os"
24
+ import { join } from "node:path"
25
+
26
+ export const DAEMON_CONTRACT_VERSION = "hermes.navigator.daemon.v1"
27
+
28
+ const DEFAULT_DAEMON_TIMEOUT_MS = 5_000
29
+
30
+ function expandHome(p: string): string {
31
+ if (p === "~") return homedir()
32
+ if (p.startsWith("~/")) return join(homedir(), p.slice(2))
33
+ return p
34
+ }
35
+
36
+ /** Resolve the daemon socket path: `TIDE_SOCKET` → `${HNAVIG_HOME|HERMES_HOME|~/.miadi/navigator}/daemon.sock`. */
37
+ export function resolveSocketPath(): string {
38
+ const explicit = process.env.TIDE_SOCKET?.trim()
39
+ if (explicit) return expandHome(explicit)
40
+ const home = process.env.HNAVIG_HOME?.trim() || process.env.HERMES_HOME?.trim()
41
+ const dir = home ? expandHome(home) : join(homedir(), ".miadi", "navigator")
42
+ return join(dir, "daemon.sock")
43
+ }
44
+
45
+ /** True only if `path` exists and is a Unix domain socket (the daemon is plausibly up). */
46
+ export function isSocketAvailable(path: string = resolveSocketPath()): boolean {
47
+ try {
48
+ return statSync(path).isSocket()
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ export interface DaemonEnvelope<T> {
55
+ contract_version?: string
56
+ request_id?: string | null
57
+ ok: boolean
58
+ data?: T
59
+ error?: { code: string; message: string; retryable?: boolean }
60
+ }
61
+
62
+ export class TideDaemonError extends Error {
63
+ readonly code: string
64
+ readonly retryable: boolean
65
+ constructor(message: string, code = "daemon_error", retryable = false) {
66
+ super(message)
67
+ this.name = "TideDaemonError"
68
+ this.code = code
69
+ this.retryable = retryable
70
+ }
71
+ }
72
+
73
+ export interface DaemonRequestOptions {
74
+ socketPath?: string
75
+ timeoutMs?: number
76
+ }
77
+
78
+ /**
79
+ * Send one request to the daemon and resolve its `data`, or reject with a
80
+ * `TideDaemonError`. One request → one newline-delimited response.
81
+ */
82
+ export function daemonRequest<T = unknown>(
83
+ action: string,
84
+ payload: Record<string, unknown> = {},
85
+ opts: DaemonRequestOptions = {},
86
+ ): Promise<T> {
87
+ const socketPath = opts.socketPath ?? resolveSocketPath()
88
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_DAEMON_TIMEOUT_MS
89
+ const envelope = {
90
+ contract_version: DAEMON_CONTRACT_VERSION,
91
+ request_id: randomUUID(),
92
+ action,
93
+ payload,
94
+ }
95
+
96
+ return new Promise<T>((resolve, reject) => {
97
+ const sock = connect(socketPath)
98
+ let buf = ""
99
+ let settled = false
100
+
101
+ const finish = (fn: () => void): void => {
102
+ if (settled) return
103
+ settled = true
104
+ clearTimeout(timer)
105
+ sock.destroy()
106
+ fn()
107
+ }
108
+ const fail = (err: TideDaemonError): void => finish(() => reject(err))
109
+
110
+ const timer = setTimeout(
111
+ () => fail(new TideDaemonError(`daemon request '${action}' timed out after ${timeoutMs}ms`, "timeout", true)),
112
+ timeoutMs,
113
+ )
114
+
115
+ sock.on("connect", () => {
116
+ sock.write(JSON.stringify(envelope) + "\n")
117
+ })
118
+ sock.on("data", (chunk: Buffer) => {
119
+ buf += chunk.toString("utf8")
120
+ const nl = buf.indexOf("\n")
121
+ if (nl === -1) return
122
+ let resp: DaemonEnvelope<T>
123
+ try {
124
+ resp = JSON.parse(buf.slice(0, nl)) as DaemonEnvelope<T>
125
+ } catch {
126
+ return fail(new TideDaemonError(`daemon '${action}' returned non-JSON`, "bad_response"))
127
+ }
128
+ if (!resp.ok) {
129
+ return fail(
130
+ new TideDaemonError(
131
+ resp.error?.message ?? `daemon '${action}' failed`,
132
+ resp.error?.code ?? "error",
133
+ resp.error?.retryable ?? false,
134
+ ),
135
+ )
136
+ }
137
+ finish(() => resolve(resp.data as T))
138
+ })
139
+ sock.on("error", (err: Error) => fail(new TideDaemonError(`daemon socket error: ${err.message}`, "socket_error", true)))
140
+ sock.on("close", () => fail(new TideDaemonError(`daemon closed before responding to '${action}'`, "closed", true)))
141
+ })
142
+ }
package/src/types.ts ADDED
@@ -0,0 +1,60 @@
1
+ // Typed contract for the ironsilk `tide` runtime (`--format json` output).
2
+ //
3
+ // Source of truth today: runtime/hermes-navigator/hermes_navigator/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 peek <pane> --format json`. Shape per runtime; loose pending schema. */
46
+ export interface TidePeekResult {
47
+ pane?: string
48
+ lines?: string[]
49
+ [key: string]: unknown
50
+ }
51
+
52
+ /** `tide operator steer-proposal <pane> --format json`. Loose pending schema. */
53
+ export interface TideSteerResult {
54
+ [key: string]: unknown
55
+ }
56
+
57
+ /** `tide operator send <pane> --run --format json`. Loose pending schema. */
58
+ export interface TideSendResult {
59
+ [key: string]: unknown
60
+ }