@miadi/tide 0.6.11 → 0.6.13

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/client.ts +164 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.6.11",
3
+ "version": "0.6.13",
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"
package/src/client.ts CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { execFile } from "node:child_process"
14
14
  import { promisify } from "node:util"
15
+ import { existsSync } from "node:fs"
15
16
  import { readFile } from "node:fs/promises"
16
17
  import { join } from "node:path"
17
18
  import { homedir } from "node:os"
@@ -1072,6 +1073,127 @@ export async function setSessionTeam(session: string, team: string | null, opts:
1072
1073
  }
1073
1074
  }
1074
1075
 
1076
+ // ── A session on a team (jgwill/Miadi#936) ─────────────────────────────────
1077
+ //
1078
+ // `mct new` (@miadi/chronicle-tui) is the one path that starts a session on a team, for a person at
1079
+ // a terminal, in the chronicle browser and from the cockpit: the session, its team declared before
1080
+ // the agent starts, the agent named after it, the primer pasted once it is ready. These two run
1081
+ // it with --json: `teamStartChoices` reads what a start is chosen from, `startTeamSession` asks
1082
+ // for the plan, and with `run` starts the plan whose fingerprint was shown.
1083
+
1084
+ export interface TeamStartTeam {
1085
+ id: string
1086
+ name: string | null
1087
+ level: string | null
1088
+ human_lead: string | null
1089
+ agent_lead: string | null
1090
+ sessions: string[]
1091
+ folders: string[]
1092
+ name_patterns: string[]
1093
+ summary: string | null
1094
+ }
1095
+
1096
+ export interface TeamStartLaunch {
1097
+ launch: string
1098
+ bypass: boolean
1099
+ }
1100
+
1101
+ export interface TeamStartChoices {
1102
+ file: string | null
1103
+ error?: string
1104
+ teams: TeamStartTeam[]
1105
+ launches: TeamStartLaunch[]
1106
+ }
1107
+
1108
+ export interface TeamSessionOptions extends TideRunOptions {
1109
+ team: string
1110
+ session: string
1111
+ cwd: string
1112
+ /** A name `teamStartChoices` offers, or null for a shell alone. */
1113
+ launch: string | null
1114
+ remote?: boolean
1115
+ /** The first prompt, pasted once the agent is ready. */
1116
+ prompt?: string | null
1117
+ /** Start it; without this the answer is the plan. */
1118
+ run?: boolean
1119
+ /** With `run`: the fingerprint of the plan that was shown. */
1120
+ expect?: string
1121
+ }
1122
+
1123
+ export interface TeamSessionAnswer {
1124
+ state: "ready" | "refused" | "changed" | "started"
1125
+ reason?: string
1126
+ team?: { id: string; name: string | null }
1127
+ session?: string
1128
+ cwd?: string
1129
+ launch?: string | null
1130
+ agent?: string | null
1131
+ bypass?: boolean
1132
+ remote?: boolean
1133
+ primer?: boolean
1134
+ commands?: string[]
1135
+ fingerprint?: string
1136
+ pane?: string | null
1137
+ primer_file?: string | null
1138
+ }
1139
+
1140
+ /** `MIADI_MCT_BIN`, else the checkout the app itself runs from, else `mct` on PATH. */
1141
+ function resolveMct(): { bin: string; prefix: string[] } {
1142
+ const named = process.env.MIADI_MCT_BIN?.trim()
1143
+ if (named) return { bin: named, prefix: [] }
1144
+ const checkout = join(process.cwd(), "packages", "chronicle-tui", "dist", "mct.js")
1145
+ if (existsSync(checkout)) return { bin: process.execPath, prefix: [checkout] }
1146
+ return { bin: "mct", prefix: [] }
1147
+ }
1148
+
1149
+ /**
1150
+ * Run `mct`, keeping its JSON whatever it exits with: a refusal is exit 4 and still an answer.
1151
+ * `input` is its standard input: a person's first prompt, which on a command line every Unix user
1152
+ * of the host could read in /proc.
1153
+ */
1154
+ async function runMct<T>(args: string[], timeoutMs: number, input?: string): Promise<T> {
1155
+ const { bin, prefix } = resolveMct()
1156
+ const startedAt = Date.now()
1157
+ let stdout: string
1158
+ let stderr = ""
1159
+ try {
1160
+ const run = pExecFile(bin, [...prefix, ...args], { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })
1161
+ run.child.stdin?.end(input ?? "")
1162
+ ;({ stdout } = await run)
1163
+ } catch (err) {
1164
+ const e = err as ExecFileFailure & { code?: unknown; killed?: boolean; stdout?: string }
1165
+ if (e.code === "ENOENT") throw new TideError(`mct is not built in this checkout and not on PATH (${bin}): build @miadi/chronicle-tui, or name it with MIADI_MCT_BIN`, err)
1166
+ if (typeof e.code !== "number" || e.killed) throw classifyExecFailure(bin, args, err, Date.now() - startedAt, timeoutMs)
1167
+ stdout = String(e.stdout ?? "")
1168
+ stderr = String(e.stderr ?? "")
1169
+ }
1170
+ try {
1171
+ return JSON.parse(stdout) as T
1172
+ } catch {
1173
+ const said = `${stderr}${stdout}`.trim().split("\n")[0]
1174
+ if (/Unknown option|Unexpected list/.test(said)) throw new TideError(`${[bin, ...prefix].join(" ")} is older than @miadi/chronicle-tui 0.23.1: ${said}`)
1175
+ throw new TideError(said || `${bin} gave no answer to ${args.join(" ")}`)
1176
+ }
1177
+ }
1178
+
1179
+ /** The teams, in their own words, and what this host may launch: `mct list --json`. */
1180
+ export function teamStartChoices(opts: TideRunOptions = {}): Promise<TeamStartChoices> {
1181
+ return runMct<TeamStartChoices>(["list", "--json"], opts.timeoutMs ?? 10_000)
1182
+ }
1183
+
1184
+ /** The plan to start a session on a team, or with `run` the session started and its pane: `mct new --json`. */
1185
+ export function startTeamSession(opts: TeamSessionOptions): Promise<TeamSessionAnswer> {
1186
+ const args = ["new", opts.team, opts.session, "--cwd", opts.cwd, "--json"]
1187
+ if (opts.launch === null) args.push("--no-launch")
1188
+ else args.push("--launch", opts.launch)
1189
+ if (opts.remote && opts.launch !== null) args.push("--remote")
1190
+ const prompt = opts.launch !== null && opts.prompt ? opts.prompt : undefined
1191
+ if (prompt !== undefined) args.push("--prompt-file", "-")
1192
+ if (!opts.run) args.push("--dry-run")
1193
+ else if (opts.expect) args.push("--expect", opts.expect)
1194
+ return runMct<TeamSessionAnswer>(args, opts.timeoutMs ?? 30_000, prompt)
1195
+ }
1196
+
1075
1197
  // ── Drafts being prepared (jgwill/Miadi#691, Episode 548 S2 and H3) ─────────
1076
1198
  //
1077
1199
  // `tide drafts list --json` prints one object per open draft, without its words.
@@ -1274,3 +1396,45 @@ export async function unreadyDraft(ref: string, opts: TideRunOptions & { by?: st
1274
1396
  const closed = /^tide\.draft\.unreadied\s+([0-9a-f]+)/.exec(line)?.[1]
1275
1397
  return { id: closed ?? id.replace(/^draft:/, ""), line }
1276
1398
  }
1399
+
1400
+ /** A draft's words, for its author alone (Episode 548 PT1). */
1401
+ export interface TideDraftWords {
1402
+ id: string
1403
+ version: number
1404
+ text: string
1405
+ }
1406
+
1407
+ /** A draft id as `tide drafts list` prints it: hex, exact. */
1408
+ const DRAFT_ID_EXACT = /^[0-9a-f]{4,64}$/
1409
+
1410
+ /**
1411
+ * The words of one open draft: `tide drafts list --json --text`, keeping the one row
1412
+ * whose id is exactly `id`. Null when tide holds no such open draft. The other rows'
1413
+ * words are dropped here, and nothing of any row is logged or put in an error: a
1414
+ * failure carries tide's stderr, never its stdout.
1415
+ */
1416
+ export async function draftWords(id: string, opts: TideRunOptions = {}): Promise<TideDraftWords | null> {
1417
+ if (!DRAFT_ID_EXACT.test(id)) throw new TideError(`"${id}" is not a draft id: hex, as tide drafts list prints it`)
1418
+ const bin = await resolveTideBin()
1419
+ const args = ["drafts", "list", "--json", "--text"]
1420
+ const timeoutMs = opts.timeoutMs ?? 15_000
1421
+ const startedAt = Date.now()
1422
+ let stdout: string
1423
+ try {
1424
+ ;({ stdout } = await pExecFile(bin, args, { timeout: timeoutMs, cwd: opts.cwd, maxBuffer: 16 * 1024 * 1024 }))
1425
+ } catch (err) {
1426
+ throw classifyExecFailure(bin, args, err, Date.now() - startedAt, timeoutMs)
1427
+ }
1428
+ for (const line of stdout.split("\n")) {
1429
+ if (!line.includes(`"${id}"`)) continue
1430
+ let row: Record<string, unknown>
1431
+ try {
1432
+ row = JSON.parse(line) as Record<string, unknown>
1433
+ } catch {
1434
+ continue
1435
+ }
1436
+ if (row.id !== id || typeof row.text !== "string") continue
1437
+ return { id, version: typeof row.version === "number" ? row.version : 0, text: row.text }
1438
+ }
1439
+ return null
1440
+ }