@palettelab/cli 0.3.69 → 0.3.71

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.
@@ -0,0 +1,763 @@
1
+ "use strict"
2
+
3
+ // `pltt agent`: drive the Palette Build Agent (the App Builder's coding agent) from a terminal, CI or an ACP editor —
4
+ // change a built app and follow the change to its end, follow and steer a build session, answer its permission asks
5
+ // and questions, inspect its diff, context, subagents and inbox, fork, export and import it, and write the Palette app
6
+ // contract (AGENTS.md) into a local project so any coding agent (Claude Code, Codex and others) follows the same rules
7
+ // as the hosted builder. Everything goes through /api/v1/build-sessions on the selected environment (lib/agent-client).
8
+
9
+ const fs = require("fs")
10
+ const path = require("path")
11
+ const readline = require("readline")
12
+ const { once } = require("events")
13
+ const { setTimeout: sleep } = require("timers/promises")
14
+ const { parseFlags } = require("../environments")
15
+ const { connect, locate, untilIdle } = require("../agent-client")
16
+ const { AcpServer } = require("../acp")
17
+
18
+ const USAGE = `usage:
19
+ pltt agent run --app <id> "<change>" [--format json|text] [--timeout <s>]
20
+ change a built app and follow it to the end
21
+ (exit 0 done, 2 stopped short, 1 error)
22
+ pltt agent edit --app <id> "<change>" [--follow] start a change (steers the agent when it is working)
23
+ pltt agent attach <session> follow live, answer permission asks and questions,
24
+ type to steer, /exit to leave
25
+ pltt agent terminal <session> [--attach <terminal>]
26
+ an interactive shell in the session's build sandbox
27
+ (Ctrl-] closes it; needs Node 22 or later)
28
+ pltt agent terminals <session> [--read] [--lines <n>]
29
+ its terminals, or the newest one's last lines
30
+ pltt agent acp --app <id> Agent Client Protocol server on stdio (Zed and other editors)
31
+ pltt agent sessions --app <id> [--archived] [--limit <n>]
32
+ list an app's build sessions
33
+ pltt agent show <session> the session and its transcript
34
+ pltt agent log <session> [--follow] [--after <seq>]
35
+ replay the event log; --follow streams it until the round ends
36
+ pltt agent prompt <session> "<message>" [--queue]
37
+ steer a session at its next step (an idle one wakes up)
38
+ pltt agent wait <session> [--timeout <s>] until the session stops (exit 0 done, 2 stopped short)
39
+ pltt agent interrupt <session> stop the running round at its next step
40
+ pltt agent revert <session> <step> undo the running round's work from a step on
41
+ pltt agent unrevert <session> put back what the last revert undid
42
+ pltt agent compact <session> summarise the session's earlier work now
43
+ pltt agent diff <session> [--stat] every file the session changed, as patches or a stat table
44
+ pltt agent context <session> how full its requests are, its usage and model
45
+ pltt agent children <session> the subagent sessions it started
46
+ pltt agent inbox <session> messages it has not read yet
47
+ pltt agent cancel <session> <item> take back an unread message
48
+ pltt agent deliver <session> <item> steer|queue read it at the next step, or after the round
49
+ pltt agent permissions <session> open permission asks
50
+ pltt agent permit <session> <request> once|always|reject [message]
51
+ pltt agent questions <session> open questions
52
+ pltt agent answer <session> <question> "<answer>"
53
+ pltt agent fork <session> [--seq <n>] [--title <t>]
54
+ pltt agent export <session> [--sanitize] [-o <file>]
55
+ pltt agent import --app <id> <file>
56
+ pltt agent rename <session> "<title>"
57
+ pltt agent archive <session> [--undo]
58
+ pltt agent delete <session> delete an idle session, its log and its subagents' sessions
59
+ pltt agent move <session> --app <id> move a session to another of your apps
60
+ pltt agent artifacts <session> what the agent published for you
61
+ pltt agent artifact <session> <artifact> [-o <dir>]
62
+ print an artifact's entry file, or write all its files to <dir>
63
+ pltt agent schedules <session> its schedules and their next runs
64
+ pltt agent schedule <session> <schedule> pause|resume|delete
65
+ pltt agent skills the skills a session can load (or invoke as /<skill>)
66
+ pltt agent models [query] the models a subagent can run on
67
+ pltt agent mcp the MCP servers the agent can use, with their tools
68
+ pltt agent config the Build Agent's effective settings
69
+ pltt agent plugins hook-bus plugins (changed plugin files reload)
70
+ pltt agent api <METHOD> <path> [json] a raw call under /api/v1/build-sessions
71
+ pltt agent agents the agents a session can run
72
+ pltt agent commands the slash commands a message can start with
73
+ pltt agent init [dir] [--force] write AGENTS.md (the Palette app contract) into a project
74
+ Common: --env <name>; --json prints each response (and each event) as one JSON line.`
75
+
76
+ // How a run ended, as an exit code: 0 done, 2 stopped short (or still running), 1 anything else.
77
+ const STOPPED_SHORT = ["blocked", "declined", "stalled", "gate_rounds", "steps", "timeout", "tokens", "output_limit"]
78
+ function exitCode(state) {
79
+ if (!state.done) return 2
80
+ if (state.last_stop === "done") return 0
81
+ return STOPPED_SHORT.includes(state.last_stop) ? 2 : 1
82
+ }
83
+
84
+ function option(rest, name) {
85
+ const at = rest.indexOf(name)
86
+ if (at < 0) return undefined
87
+ const value = rest[at + 1]
88
+ rest.splice(at, 2)
89
+ return value
90
+ }
91
+
92
+ function flag(rest, name) {
93
+ const at = rest.indexOf(name)
94
+ if (at >= 0) rest.splice(at, 1)
95
+ return at >= 0
96
+ }
97
+
98
+ function positiveInt(value, name) {
99
+ const n = Number.parseInt(value, 10)
100
+ if (!(n > 0)) throw new Error(`${name} must be a positive number\n${USAGE}`)
101
+ return n
102
+ }
103
+
104
+ function firstLine(value, max = 160) {
105
+ return String(value || "").split("\n")[0].slice(0, max)
106
+ }
107
+
108
+ function describe(event) {
109
+ const d = event.data || {}
110
+ switch (event.type) {
111
+ case "message.user":
112
+ case "message.synthetic":
113
+ return `${event.type === "message.user" ? "owner" : "harness"}: ${d.description || firstLine(d.text)}`
114
+ case "tool.called":
115
+ return (d.calls || []).length ? `step ${d.step}: ${(d.calls || []).map((c) => c.name).join(", ")}` : null
116
+ case "tool.success":
117
+ case "tool.failed":
118
+ if (d.reconciled) return ` x ${d.reconciled.length} call(s) a stopped worker left running`
119
+ return ` ${event.type === "tool.failed" ? "x" : "ok"} ${d.name}: ${firstLine(d.output)}`
120
+ case "step.ended": {
121
+ const files = (d.files || []).map((f) => `${f.file} +${f.additions || 0} -${f.deletions || 0}`)
122
+ return files.length ? ` changed: ${files.join(", ")}` : null
123
+ }
124
+ case "text.ended":
125
+ return d.text ? `agent: ${String(d.text).slice(0, 400)}` : null
126
+ case "gate.ended":
127
+ return d.count ? `checks: ${d.count} problem(s) — ${(d.problems || [])[0] || ""}`.slice(0, 220) : "checks: all pass"
128
+ case "judge.ended":
129
+ return `review: ${d.verdict}${d.reason ? ` — ${firstLine(d.reason, 200)}` : ""}`
130
+ case "subagent.started":
131
+ return `subagent ${d.agent}${d.background ? " (background)" : ""}: ${d.description || ""} [${d.child}]`
132
+ case "subagent.ended":
133
+ return `subagent ${d.child} ended: ${d.stop}`
134
+ case "job.started":
135
+ return `background ${d.kind} started: ${d.label || d.id}`
136
+ case "job.ended":
137
+ return `background ${d.kind} ${d.state}: ${d.id}`
138
+ case "permission.asked":
139
+ return `permission asked (${d.id}): ${d.action} ${d.resource}`
140
+ case "permission.replied":
141
+ return `permission ${d.id}: ${d.reply}`
142
+ case "question.asked":
143
+ return `question (${d.id}): ${d.question}${(d.options || []).length ? ` [${d.options.join(" / ")}]` : ""}`
144
+ case "question.replied":
145
+ return `question ${d.id}: ${d.answered ? "answered" : "no answer"}`
146
+ case "compaction.started":
147
+ return "compacting the context…"
148
+ case "compaction.ended":
149
+ return "context compacted (earlier work summarised)"
150
+ case "compaction.skipped":
151
+ return `compaction skipped: ${d.reason}`
152
+ case "revert.committed":
153
+ return `undone from step ${d.step}: ${(d.files || []).join(", ") || "no files"}`
154
+ case "revert.cleared":
155
+ return `put back: ${(d.files || []).join(", ") || "no files"}`
156
+ case "revert.failed":
157
+ return `revert failed: ${d.reason}`
158
+ case "model.switched":
159
+ return `model: ${d.from} → ${d.to}`
160
+ case "agent.switched":
161
+ return `agent: ${d.agent}`
162
+ case "session.renamed":
163
+ return `renamed: ${d.title}`
164
+ case "session.woken":
165
+ return `woken by a message (${d.status})`
166
+ case "round.ended":
167
+ return `round ended: ${d.stop || d.status} after ${d.steps} step(s)`
168
+ case "inbox.enqueued":
169
+ return `queued for the agent: ${String(d.text || "").slice(0, 160)}`
170
+ case "inbox.cancelled":
171
+ return `message ${d.id} taken back`
172
+ case "artifact.created":
173
+ case "artifact.updated":
174
+ return `artifact ${d.id}: ${d.title}${event.type === "artifact.updated" ? " (updated)" : ""}`
175
+ case "artifact.deleted":
176
+ return `artifact ${d.id} deleted`
177
+ case "schedule.created":
178
+ case "schedule.fired":
179
+ case "schedule.paused":
180
+ case "schedule.resumed":
181
+ case "schedule.deleted":
182
+ return `schedule ${d.id} ${event.type.split(".")[1]}${d.next_due_at ? `, next ${d.next_due_at}` : ""}`
183
+ case "session.moved":
184
+ return `moved to app ${d.to}`
185
+ case "skill.activated":
186
+ return `skill ${d.name}${d.by === "owner" ? " (you asked)" : ""}`
187
+ case "shell.ended":
188
+ return `you ran: ${String(d.command || "").slice(0, 120)}${d.failed ? " (failed)" : ""}`
189
+ case "cache.warmed":
190
+ return null
191
+ default:
192
+ return null
193
+ }
194
+ }
195
+
196
+ function printer(json, log) {
197
+ return (event) => {
198
+ const line = json ? JSON.stringify(event) : describe(event)
199
+ if (line) log(line)
200
+ }
201
+ }
202
+
203
+ // `log`: replay the durable log; live, stream it until the round running now ends (a round.ended in the replay is
204
+ // history, not the end).
205
+ async function follow(client, sessionId, { after = 0, live = true, print, signal }) {
206
+ let last = after
207
+ let synced = false
208
+ for await (const event of client.log(sessionId, { after, follow: live, signal })) {
209
+ if (event.type === "log.synced") {
210
+ if (!live) return { last: event.seq, stop: null }
211
+ synced = true
212
+ continue
213
+ }
214
+ last = event.seq ?? last
215
+ print(event)
216
+ if (event.type === "round.ended" && synced) return { last, stop: (event.data || {}).stop || (event.data || {}).status }
217
+ }
218
+ return { last, stop: null }
219
+ }
220
+
221
+ function editLine(result) {
222
+ if (result.status === "steered") return `sent to the running agent (${result.session_id})`
223
+ return result.status === "queued" ? "queued after the running build" : "edit started"
224
+ }
225
+
226
+ function promptLine(result) {
227
+ if (result.status === "queued") return "[pltt] queued — another build of this app is running; this session picks the message up as soon as that build ends"
228
+ if (result.status) return "[pltt] the session wakes up to make the change"
229
+ return result.running ? "[pltt] sent — the agent picks it up between two steps" : "[pltt] waiting — the session is not running now; its next round starts with it"
230
+ }
231
+
232
+ // `run` (and `edit --follow`): send the change, follow its session until it is idle, exit by how it stopped. Never
233
+ // attends: a permission ask is decided unattended (denied) by the server.
234
+ async function runChange(client, { app, text, json, log, timeout }) {
235
+ const signal = AbortSignal.timeout(timeout * 1000)
236
+ let session = null
237
+ let state
238
+ try {
239
+ const { sessions: before } = await client.sessions(app, { limit: 100 })
240
+ const result = await client.edit(app, text)
241
+ log(json ? JSON.stringify(result) : `[pltt] ${editLine(result)}`)
242
+ const found = await locate(client, app, result, before, signal)
243
+ session = found.session
244
+ if (!json) log(`[pltt] following ${session}`)
245
+ state = await untilIdle(client, session, { after: found.after, signal, onEvent: printer(json, log) })
246
+ } catch (err) {
247
+ if (!signal.aborted) throw err
248
+ state = session ? await client.wait(session, 1) : { status: null, done: false, last_stop: null }
249
+ }
250
+ const outcome = !state.done ? `still running after ${timeout}s` : state.last_stop === "done" ? "done" : `stopped: ${state.last_stop}`
251
+ log(json ? JSON.stringify(state) : `[pltt] ${outcome}${state.summary ? ` — ${state.summary}` : ""}`)
252
+ process.exitCode = exitCode(state)
253
+ }
254
+
255
+ // What a line typed into `attach` does, given the oldest open ask (a permission ask or a question; null when none):
256
+ // { exit } | { permit: {id, reply, message?} } | { answer: {id, answer} } | { prompt } | { again } | null.
257
+ function attachReply(ask, line) {
258
+ const text = String(line).trim()
259
+ if (text === "/exit") return { exit: true }
260
+ if (!text) return null
261
+ if (!ask) return { prompt: text }
262
+ if (ask.kind === "question") {
263
+ const options = ask.options || []
264
+ const n = Number(text)
265
+ return { answer: { id: ask.id, answer: Number.isInteger(n) && n >= 1 && n <= options.length ? options[n - 1] : text } }
266
+ }
267
+ const [word, ...words] = text.split(/\s+/)
268
+ const reply = { o: "once", once: "once", a: "always", always: "always", r: "reject", reject: "reject" }[word.toLowerCase().replace(/[:,]$/, "")]
269
+ if (!reply) return { again: true }
270
+ const message = reply === "reject" ? words.join(" ") : ""
271
+ return { permit: { id: ask.id, reply, ...(message ? { message } : {}) } }
272
+ }
273
+
274
+ function askLine(ask) {
275
+ if (ask.kind === "question") {
276
+ return `${ask.question}\n${(ask.options || []).map((o, i) => ` ${i + 1}. ${o}\n`).join("")}answer (number or text): `
277
+ }
278
+ return `Allow ${ask.action} on ${ask.resource}? [o]nce/[a]lways/[r]eject: `
279
+ }
280
+
281
+ // `attach`: a line-mode follower. Attends (so asks wait for the owner), prompts for each open ask, and sends any other
282
+ // line as a steering message. Leaves on /exit or the end of input.
283
+ async function attach(client, sessionId, { log }) {
284
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
285
+ const controller = new AbortController()
286
+ const asks = [] // open permission asks and questions, oldest first
287
+ let synced = false
288
+ const promptNext = () => {
289
+ rl.setPrompt(asks[0] ? askLine(asks[0]) : "")
290
+ if (synced && asks[0]) rl.prompt()
291
+ }
292
+ const attend = () => client.attend(sessionId).catch((err) => log(`[pltt] attend failed: ${err.message}`))
293
+ attend()
294
+ const timer = setInterval(attend, 30_000)
295
+ rl.on("line", async (line) => {
296
+ const action = attachReply(asks[0] || null, line) || {}
297
+ if (action.exit) return rl.close()
298
+ try {
299
+ if (action.again) log("[pltt] answer o (once), a (always) or r (reject), optionally followed by a message")
300
+ if (action.permit) {
301
+ asks.shift()
302
+ await client.permit(sessionId, action.permit.id, action.permit.reply, action.permit.message)
303
+ }
304
+ if (action.answer) {
305
+ asks.shift()
306
+ await client.answer(sessionId, action.answer.id, action.answer.answer)
307
+ }
308
+ if (action.prompt) log(promptLine(await client.prompt(sessionId, action.prompt)))
309
+ } catch (err) {
310
+ log(`[pltt] ${err.message}`)
311
+ }
312
+ promptNext()
313
+ })
314
+ rl.on("close", () => controller.abort())
315
+ let after = 0
316
+ try {
317
+ while (!controller.signal.aborted) {
318
+ for await (const event of client.log(sessionId, { after, follow: true, signal: controller.signal })) {
319
+ if (event.type === "log.synced") {
320
+ synced = true
321
+ promptNext()
322
+ continue
323
+ }
324
+ after = event.seq ?? after
325
+ const d = event.data || {}
326
+ if (event.type === "permission.asked" || event.type === "question.asked") asks.push({ kind: event.type.split(".")[0], ...d })
327
+ if (event.type === "permission.replied" || event.type === "question.replied") {
328
+ const at = asks.findIndex((ask) => ask.id === d.id)
329
+ if (at >= 0) asks.splice(at, 1)
330
+ }
331
+ const line = describe(event)
332
+ if (line) log(line)
333
+ if (synced && /^(permission|question)\.(asked|replied)$/.test(event.type)) promptNext()
334
+ }
335
+ await sleep(1000, undefined, { signal: controller.signal }) // the stream dropped: reconnect
336
+ }
337
+ } catch (err) {
338
+ if (!controller.signal.aborted) throw err
339
+ } finally {
340
+ clearInterval(timer)
341
+ rl.close()
342
+ process.stdin.destroy() // a closed readline still holds an open stdin pipe, and with it the process
343
+ }
344
+ }
345
+
346
+ // `terminal`: an interactive shell in the session's build sandbox. Keys go to it raw and its output is written as it
347
+ // comes, so the local terminal draws it; a resize follows the window. Ctrl-] closes it. A dropped connection (a proxy's
348
+ // connection limit, a network blip) reconnects and resumes after the last frame it showed, so nothing is drawn twice.
349
+ // Resolves with the shell's exit code (1 when it did not exit by itself).
350
+ async function terminal(client, sessionId, { attachTo, stdin, stdout, log, WS = globalThis.WebSocket, retries = 5, backoffMs = 500 }) {
351
+ if (typeof WS !== "function") throw new Error("pltt agent terminal needs Node 22 or later (its built-in WebSocket)")
352
+ const size = () => ({ cols: stdout.columns || 100, rows: stdout.rows || 30 })
353
+ let entry = { id: attachTo }
354
+ if (!attachTo) {
355
+ entry = await client.openTerminal(sessionId, size())
356
+ log(entry.start === "queued" ? "[pltt] the terminal opens when the app's running build ends"
357
+ : entry.start === "opening" ? "[pltt] the terminal opens at the agent's next step"
358
+ : "[pltt] starting the terminal (Ctrl-] closes it)")
359
+ }
360
+ let socket = null
361
+ let last = "0" // the stream id of the last frame shown: a reconnect resumes after it
362
+ let ended = null
363
+ const held = [] // keys typed while reconnecting: sent once the new connection opens, never dropped
364
+ const send = (frame) => {
365
+ if (socket && socket.readyState === 1) socket.send(JSON.stringify(frame))
366
+ else held.push(frame)
367
+ }
368
+ const onKey = (chunk) => {
369
+ const keys = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
370
+ if (keys.length === 1 && keys[0] === 0x1d) return send({ t: "close" }) // Ctrl-]
371
+ send({ t: "in", d: keys.toString("utf8") })
372
+ }
373
+ const onResize = () => send({ t: "resize", ...size() })
374
+ if (stdin.isTTY) stdin.setRawMode(true)
375
+ stdin.on("data", onKey)
376
+ stdin.resume()
377
+ stdout.on("resize", onResize)
378
+ try {
379
+ for (let tries = 0; ;) {
380
+ const { ticket } = await client.terminalTicket(sessionId, entry.id)
381
+ const code = await new Promise((resolve) => {
382
+ socket = new WS(client.terminalUrl(sessionId, entry.id, ticket, last))
383
+ socket.onopen = () => {
384
+ tries = 0
385
+ onResize()
386
+ for (const frame of held.splice(0)) send(frame)
387
+ }
388
+ socket.onmessage = (message) => {
389
+ const frame = JSON.parse(typeof message.data === "string" ? message.data : Buffer.from(message.data).toString())
390
+ if (frame.i) last = frame.i
391
+ if (frame.t === "out") stdout.write(frame.d)
392
+ if (frame.t === "exit") {
393
+ ended = frame
394
+ socket.close()
395
+ }
396
+ }
397
+ socket.onerror = () => {} // onclose follows with the reason
398
+ socket.onclose = (event) => resolve(event.code)
399
+ })
400
+ if (ended) break
401
+ if (code === 4401) throw new Error("the terminal refused the connection: sign in again (pltt login)")
402
+ if (code === 4404) throw new Error(`no terminal ${entry.id} in session ${sessionId}`)
403
+ if (tries >= retries) break
404
+ tries += 1
405
+ await sleep(Math.min(8000, backoffMs * 2 ** tries))
406
+ }
407
+ } finally {
408
+ stdin.off("data", onKey)
409
+ stdout.off("resize", onResize)
410
+ if (stdin.isTTY) stdin.setRawMode(false)
411
+ stdin.pause()
412
+ }
413
+ const how = ended ? `ended (${ended.reason}${ended.code != null ? `, exit ${ended.code}` : ""})${ended.message ? `: ${ended.message}` : ""}`
414
+ : `connection lost (it may still be open: pltt agent terminal ${sessionId} --attach ${entry.id})`
415
+ log(`\r\n[pltt] terminal ${entry.id} ${how}`)
416
+ return ended && Number.isInteger(ended.code) && ended.reason === "exited" ? ended.code : 1
417
+ }
418
+
419
+ // `acp`: JSON-RPC on stdio. stdout carries protocol messages only; everything else goes to stderr.
420
+ async function serveAcp(client, app) {
421
+ let closed = false
422
+ const server = new AcpServer({
423
+ client,
424
+ app,
425
+ write: (message) => closed || process.stdout.write(`${JSON.stringify(message)}\n`),
426
+ log: (line) => process.stderr.write(`[pltt acp] ${line}\n`),
427
+ })
428
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })
429
+ rl.on("line", (line) => server.receive(line))
430
+ await once(rl, "close")
431
+ closed = true
432
+ server.close()
433
+ }
434
+
435
+ function sessionRow(s) {
436
+ return `${s.id} ${String(s.kind).padEnd(7)} ${String(s.status).padEnd(11)} ${String((s.state || {}).last_stop || "").padEnd(12)} ${s.title || ""}${(s.state || {}).archived ? " (archived)" : ""}`
437
+ }
438
+
439
+ function diffStat(data, log) {
440
+ const files = data.files || []
441
+ if (!files.length) return log("no changes")
442
+ const width = Math.max(...files.map((f) => f.file.length))
443
+ const plus = files.map((f) => `+${f.additions}`)
444
+ const minus = files.map((f) => `-${f.deletions}`)
445
+ const plusWidth = Math.max(...plus.map((s) => s.length))
446
+ const minusWidth = Math.max(...minus.map((s) => s.length))
447
+ files.forEach((f, i) => {
448
+ const note = f.status === "deleted" ? " (deleted)" : f.status === "added" ? " (new)" : ""
449
+ log(` ${f.file.padEnd(width)} | ${plus[i].padStart(plusWidth)} ${minus[i].padEnd(minusWidth)}${note}`.trimEnd())
450
+ })
451
+ log(` ${files.length} file${files.length === 1 ? "" : "s"} changed, +${data.additions} -${data.deletions}`)
452
+ }
453
+
454
+ async function run(argv, { cwd = process.cwd(), log = console.log, stdin = process.stdin, stdout = process.stdout } = {}) {
455
+ const [sub, ...args] = argv
456
+ const { flags, rest } = parseFlags(args)
457
+ const json = flags.json
458
+ if (!sub || sub === "help" || sub === "--help") {
459
+ log(USAGE)
460
+ return
461
+ }
462
+ const client = sub === "init" ? null : connect(cwd, flags)
463
+ // Raw response as one JSON line with --json, else the text form.
464
+ const out = (data, text) => (json ? log(JSON.stringify(data)) : text(data))
465
+ const need = (...values) => {
466
+ if (values.some((v) => v === undefined || v === "")) throw new Error(USAGE)
467
+ }
468
+ const [id, ...words] = rest
469
+
470
+ switch (sub) {
471
+ case "init": {
472
+ const force = flag(rest, "--force")
473
+ const dir = path.resolve(cwd, rest[0] || ".")
474
+ const target = path.join(dir, "AGENTS.md")
475
+ if (fs.existsSync(target) && !force) throw new Error(`${target} exists — pass --force to replace it`)
476
+ const { content } = await connect(cwd, flags).contract()
477
+ fs.mkdirSync(dir, { recursive: true })
478
+ fs.writeFileSync(target, content)
479
+ log(json ? JSON.stringify({ path: target, bytes: Buffer.byteLength(content) }) : `[pltt] wrote ${target}`)
480
+ return
481
+ }
482
+ case "sessions": {
483
+ const app = option(rest, "--app")
484
+ const limit = option(rest, "--limit")
485
+ need(app)
486
+ const { sessions } = await client.sessions(app, { limit: limit && positiveInt(limit, "--limit"), archived: flag(rest, "--archived") })
487
+ if (json) return sessions.forEach((s) => log(JSON.stringify(s)))
488
+ return sessions.forEach((s) => log(sessionRow(s)))
489
+ }
490
+ case "show": {
491
+ need(id)
492
+ const data = await client.session(id)
493
+ if (json) return log(JSON.stringify(data))
494
+ const s = data.session
495
+ log(`${s.id} (${s.kind}, ${s.status}) — ${s.title || ""}`)
496
+ for (const m of data.messages) {
497
+ if (m.type === "assistant") {
498
+ for (const c of m.data.tool_calls || []) log(` ${c.status === "error" ? "x" : "ok"} ${c.name} ${JSON.stringify(c.input).slice(0, 120)}`)
499
+ if (m.data.text) log(`agent: ${m.data.text.slice(0, 400)}`)
500
+ } else if (m.type === "compaction") {
501
+ log("[checkpoint] " + String(m.data.summary || "").split("\n").slice(0, 3).join(" ").slice(0, 200))
502
+ } else {
503
+ log(`${m.type === "user" ? "owner" : "harness"}: ${m.data.description || firstLine(m.data.text, 200)}`)
504
+ }
505
+ }
506
+ return
507
+ }
508
+ case "log": {
509
+ const after = Number.parseInt(option(rest, "--after") || "0", 10) || 0
510
+ const live = flag(rest, "--follow")
511
+ need(rest[0])
512
+ const controller = new AbortController()
513
+ const onInt = () => {
514
+ controller.abort()
515
+ process.exitCode = 130
516
+ }
517
+ process.once("SIGINT", onInt)
518
+ try {
519
+ const { stop } = await follow(client, rest[0], { after, live, print: printer(json, log), signal: controller.signal })
520
+ if (live && stop && !["done", "idle"].includes(stop)) process.exitCode = 1
521
+ } catch (err) {
522
+ if (err.name !== "AbortError") throw err
523
+ } finally {
524
+ process.removeListener("SIGINT", onInt)
525
+ }
526
+ return
527
+ }
528
+ case "run":
529
+ case "edit": {
530
+ const app = option(rest, "--app")
531
+ const format = option(rest, "--format")
532
+ const timeout = option(rest, "--timeout")
533
+ const followIt = flag(rest, "--follow") || sub === "run"
534
+ need(app, rest[0])
535
+ const text = rest.join(" ")
536
+ if (followIt) return runChange(client, { app, text, json: json || format === "json", log, timeout: timeout ? positiveInt(timeout, "--timeout") : 1800 })
537
+ return out(await client.edit(app, text), (result) => log(`[pltt] ${editLine(result)}`))
538
+ }
539
+ case "attach":
540
+ need(id)
541
+ return attach(client, id, { log })
542
+ case "terminal": {
543
+ const attachTo = option(rest, "--attach")
544
+ need(rest[0])
545
+ process.exitCode = await terminal(client, rest[0], { attachTo, stdin, stdout, log })
546
+ return
547
+ }
548
+ case "terminals": {
549
+ const read = flag(rest, "--read")
550
+ const lines = option(rest, "--lines")
551
+ need(rest[0])
552
+ if (read) {
553
+ const { data } = await client.readTerminal(rest[0], lines ? positiveInt(lines, "--lines") : 100)
554
+ if (json) return log(JSON.stringify(data))
555
+ return log(data ? data.text || "(nothing shown yet)" : "no terminal in this session")
556
+ }
557
+ const { terminals } = await client.terminals(rest[0])
558
+ if (json) return log(JSON.stringify(terminals))
559
+ if (!terminals.length) return log("no terminals")
560
+ for (const t of terminals) log(`${t.id} ${t.status}${t.reason ? ` (${t.reason})` : ""} ${t.cols}x${t.rows}${t.title ? ` ${t.title}` : ""}`)
561
+ return
562
+ }
563
+ case "acp": {
564
+ const app = option(rest, "--app")
565
+ need(app)
566
+ return serveAcp(client, app)
567
+ }
568
+ case "prompt": {
569
+ const queue = flag(rest, "--queue")
570
+ const [sessionId, ...message] = rest
571
+ need(sessionId, message[0])
572
+ const result = await client.prompt(sessionId, message.join(" "), { delivery: queue ? "queue" : "steer" })
573
+ return out(result, (r) => log(promptLine(r)))
574
+ }
575
+ case "wait": {
576
+ const timeout = option(rest, "--timeout")
577
+ need(rest[0])
578
+ const end = Date.now() + (timeout ? positiveInt(timeout, "--timeout") : 60) * 1000
579
+ let state
580
+ do {
581
+ // Chunks of at most 120 s: one HTTP request stays well inside fetch's own timeouts.
582
+ state = await client.wait(rest[0], Math.min(120, Math.max(1, Math.ceil((end - Date.now()) / 1000))))
583
+ } while (!state.done && Date.now() < end)
584
+ out(state, (s) => log(`[pltt] ${s.done ? `${s.status}: ${s.last_stop}` : "still running"}${s.summary ? ` — ${s.summary}` : ""}`))
585
+ process.exitCode = exitCode(state)
586
+ return
587
+ }
588
+ case "interrupt":
589
+ need(id)
590
+ return out(await client.interrupt(id), (r) => log(r.interrupted ? "[pltt] the round stops at its next step" : "[pltt] the session is not running"))
591
+ case "revert": {
592
+ need(id)
593
+ const result = await client.revert(id, positiveInt(words[0], "step"))
594
+ return out(result, (r) => log(`[pltt] the agent undoes its work from step ${r.step} at its next step`))
595
+ }
596
+ case "unrevert":
597
+ need(id)
598
+ return out(await client.unrevert(id), (r) =>
599
+ log(`[pltt] the undone work is put back ${r.running ? "at the next step" : "when the session next runs"}`))
600
+ case "compact":
601
+ need(id)
602
+ return out(await client.compact(id), (r) =>
603
+ log(`[pltt] the session is summarised ${r.running ? "at its next step" : "at the start of its next round"}`))
604
+ case "diff": {
605
+ const stat = flag(rest, "--stat")
606
+ need(rest[0])
607
+ const data = await client.diff(rest[0])
608
+ if (json) return log(JSON.stringify(data))
609
+ if (stat) return diffStat(data, log)
610
+ for (const f of data.files) {
611
+ if (!f.patches.length) log(`# ${f.file}: +${f.additions} -${f.deletions} (patch not kept)`)
612
+ for (const p of f.patches) log(p.patch.replace(/\n$/, ""))
613
+ }
614
+ return
615
+ }
616
+ case "context":
617
+ need(id)
618
+ return out(await client.context(id), (data) => {
619
+ const c = data.context || {}
620
+ const u = data.usage || {}
621
+ log(`model ${data.model || "-"}`)
622
+ if (c.target) log(`context ${c.bytes} of ${c.target} bytes (${Math.round((100 * c.bytes) / c.target)}%), ${c.messages} messages, ${c.tools} tools, room ${c.room}`)
623
+ log(`usage ${u.input || 0} in, ${u.output || 0} out, ${u.cache_read || 0} cached, ${u.calls || 0} calls`)
624
+ })
625
+ case "children":
626
+ need(id)
627
+ return out(await client.children(id), (data) => data.sessions.forEach((s) => log(sessionRow(s))))
628
+ case "inbox":
629
+ need(id)
630
+ return out(await client.inbox(id), (data) =>
631
+ data.items.forEach((item) => log(`${item.id} ${String(item.delivery).padEnd(5)} ${firstLine(item.text)}`)))
632
+ case "cancel":
633
+ need(id, words[0])
634
+ return out(await client.cancel(id, words[0]), () => log(`[pltt] ${words[0]} taken back`))
635
+ case "deliver":
636
+ need(id, words[0])
637
+ if (!["steer", "queue"].includes(words[1])) throw new Error(USAGE)
638
+ return out(await client.deliver(id, words[0], words[1]), (r) =>
639
+ log(`[pltt] ${r.id} is read ${r.delivery === "steer" ? "at the next step" : "after the round"}`))
640
+ case "permissions":
641
+ need(id)
642
+ return out(await client.permissions(id), (data) => data.permissions.forEach((p) => log(`${p.id} ${p.action} ${p.resource}`)))
643
+ case "permit": {
644
+ need(id, words[0])
645
+ const [request, reply, ...message] = words
646
+ if (!["once", "always", "reject"].includes(reply)) throw new Error(USAGE)
647
+ return out(await client.permit(id, request, reply, message.join(" ")), () => log(`[pltt] ${request}: ${reply}`))
648
+ }
649
+ case "questions":
650
+ need(id)
651
+ return out(await client.questions(id), (data) =>
652
+ data.questions.forEach((question) => {
653
+ log(`${question.id} ${question.question}`)
654
+ ;(question.options || []).forEach((o, i) => log(` ${i + 1}. ${o}`))
655
+ }))
656
+ case "answer":
657
+ need(id, words[0], words[1])
658
+ return out(await client.answer(id, words[0], words.slice(1).join(" ")), () => log(`[pltt] answered ${words[0]}`))
659
+ case "fork": {
660
+ const seq = option(rest, "--seq")
661
+ const title = option(rest, "--title")
662
+ need(rest[0])
663
+ const result = await client.fork(rest[0], { seq: seq && positiveInt(seq, "--seq"), title })
664
+ return out(result, (r) => log(`[pltt] forked into ${r.session_id}`))
665
+ }
666
+ case "export": {
667
+ const file = option(rest, "-o")
668
+ const sanitize = flag(rest, "--sanitize")
669
+ need(rest[0])
670
+ const document = await client.exportSession(rest[0], { sanitize })
671
+ if (!file) return log(json ? JSON.stringify(document) : JSON.stringify(document, null, 2))
672
+ const target = path.resolve(cwd, file)
673
+ fs.writeFileSync(target, `${JSON.stringify(document, null, 2)}\n`)
674
+ return log(json ? JSON.stringify({ path: target, bytes: fs.statSync(target).size }) : `[pltt] wrote ${target}`)
675
+ }
676
+ case "import": {
677
+ const app = option(rest, "--app")
678
+ need(app, rest[0])
679
+ const document = JSON.parse(fs.readFileSync(path.resolve(cwd, rest[0]), "utf8"))
680
+ return out(await client.importSession(app, document), (r) => log(`[pltt] imported as ${r.session_id}`))
681
+ }
682
+ case "rename":
683
+ need(id, words[0])
684
+ return out(await client.update(id, { title: words.join(" ") }), (r) => log(`[pltt] renamed ${id}: ${r.session.title}`))
685
+ case "archive": {
686
+ const undo = flag(rest, "--undo")
687
+ need(rest[0])
688
+ return out(await client.update(rest[0], { archived: !undo }), () => log(`[pltt] ${undo ? "restored" : "archived"} ${rest[0]}`))
689
+ }
690
+ case "delete":
691
+ need(rest[0])
692
+ return out(await client.remove(rest[0]), () => log(`[pltt] deleted ${rest[0]}`))
693
+ case "move": {
694
+ const app = option(rest, "--app")
695
+ need(rest[0], app)
696
+ return out(await client.move(rest[0], app), (r) => log(`[pltt] moved ${r.session_id} to app ${r.app_id}`))
697
+ }
698
+ case "artifacts":
699
+ need(id)
700
+ return out(await client.artifacts(id), (data) =>
701
+ data.artifacts.length
702
+ ? data.artifacts.forEach((a) => log(`${a.id} ${a.title} (${a.entry}, ${a.files.length} file${a.files.length === 1 ? "" : "s"}, ${a.bytes} bytes)`))
703
+ : log("[pltt] no artifacts"))
704
+ case "artifact": {
705
+ const dir = option(rest, "-o")
706
+ const [session, artifact] = rest
707
+ need(session, artifact)
708
+ const data = await client.artifact(session, artifact)
709
+ if (json) return log(JSON.stringify(data))
710
+ if (!dir) return log(data.artifact.files[data.artifact.entry])
711
+ for (const [rel, text] of Object.entries(data.artifact.files)) {
712
+ const target = path.resolve(cwd, dir, rel)
713
+ if (!target.startsWith(path.resolve(cwd, dir) + path.sep)) throw new Error(`refusing to write outside ${dir}: ${rel}`)
714
+ fs.mkdirSync(path.dirname(target), { recursive: true })
715
+ fs.writeFileSync(target, text)
716
+ }
717
+ return log(`[pltt] wrote ${Object.keys(data.artifact.files).length} file(s) to ${path.resolve(cwd, dir)}`)
718
+ }
719
+ case "schedules":
720
+ need(id)
721
+ return out(await client.schedules(id), (data) =>
722
+ data.schedules.length
723
+ ? data.schedules.forEach((s) => log(`${s.id} [${s.status}] ${s.name} next ${s.next_due_at || "-"} runs ${s.runs || 0}`))
724
+ : log("[pltt] no schedules"))
725
+ case "schedule": {
726
+ const [session, schedule, action] = rest
727
+ need(session, schedule, action)
728
+ if (!["pause", "resume", "delete"].includes(action)) throw new Error(USAGE)
729
+ return out(await client.schedule(session, schedule, action), () => log(`[pltt] ${schedule}: ${action}d`))
730
+ }
731
+ case "skills":
732
+ return out(await client.skills(), (data) => data.skills.forEach((k) => log(`${k.name.padEnd(20)} ${firstLine(k.description)}`)))
733
+ case "models":
734
+ return out(await client.models(rest.join(" ")), (data) => data.models.forEach((m) => log(`${m.id.padEnd(26)} ${m.label} (${m.provider})`)))
735
+ case "mcp":
736
+ return out(await client.mcp(), (data) =>
737
+ data.servers.length
738
+ ? data.servers.forEach((m) => log(`${m.name}: ${m.error ? `unavailable (${m.error})` : `${(m.tools || []).length} tools, ${(m.resources || []).length} resources, ${(m.prompts || []).length} prompts`}`))
739
+ : log("[pltt] no MCP servers are configured"))
740
+ case "config":
741
+ return out(await client.config(), (data) => Object.entries(data.config).forEach(([k, v]) => log(`${k.padEnd(20)} ${JSON.stringify(v)}`)))
742
+ case "plugins":
743
+ return out(await client.plugins(), (data) =>
744
+ data.plugins.forEach((p) => log(`${p.name.padEnd(20)} ${(p.points || []).join(", ") || "-"}${p.error ? ` ERROR ${p.error}` : ""}`)))
745
+ case "api": {
746
+ const [method, route, body] = rest
747
+ need(method, route)
748
+ return log(JSON.stringify(await client.raw(method, route, body ? JSON.parse(body) : undefined), null, json ? 0 : 2))
749
+ }
750
+ case "agents":
751
+ return out(await client.agents(), (data) =>
752
+ data.agents.forEach((a) => log(`${a.name.padEnd(12)} ${String(a.mode).padEnd(9)}${a.read_only ? "read-only " : ""}${firstLine(a.description)}`)))
753
+ case "commands":
754
+ return out(await client.commands(), (data) =>
755
+ data.commands.forEach((c) => log(`/${c.name.padEnd(14)} ${firstLine(c.description)}${c.source === "builtin" ? "" : ` (${c.source})`}`)))
756
+ default:
757
+ throw new Error(`unknown agent command "${sub}"\n${USAGE}`)
758
+ }
759
+ }
760
+
761
+ module.exports = run
762
+ module.exports.describe = describe
763
+ module.exports.attachReply = attachReply