@palettelab/cli 0.3.70 → 0.3.72

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