@palettelab/cli 0.3.73 → 0.3.75

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 (29) hide show
  1. package/README.md +50 -15
  2. package/backend-sdk/palette_sdk/__init__.py +1 -1
  3. package/backend-sdk/palette_sdk/connections_generated.py +26 -0
  4. package/backend-sdk/palette_sdk/platform_services.py +73 -1
  5. package/backend-sdk/palette_sdk/plugin_context.py +8 -2
  6. package/backend-sdk/pyproject.toml +1 -1
  7. package/docs/python-backend-sdk.md +35 -11
  8. package/lib/acp.js +227 -25
  9. package/lib/agent-client.js +56 -27
  10. package/lib/cli.js +1 -0
  11. package/lib/commands/agent.js +145 -50
  12. package/lib/commands/dev.js +19 -2
  13. package/lib/connection-catalog.json +132 -0
  14. package/lib/dev-simulator.js +29 -14
  15. package/package.json +1 -1
  16. package/template-fallback/backend/pytest.ini +3 -0
  17. package/template-fallback/backend/tests/test_import.py +4 -8
  18. package/template-fallback/package.json +1 -1
  19. package/template-fallback/pyproject.toml +5 -0
  20. package/template-fallback/templates/consumer-app/package.json +1 -1
  21. package/template-fallback/templates/dashboard/package.json +1 -1
  22. package/template-fallback/templates/database/package.json +1 -1
  23. package/template-fallback/templates/external-service/backend/api/main.py +7 -6
  24. package/template-fallback/templates/external-service/package.json +1 -1
  25. package/template-fallback/templates/external-service/palette-plugin.json +7 -0
  26. package/template-fallback/templates/frontend-only/package.json +1 -1
  27. package/template-fallback/templates/next/package.json +1 -1
  28. package/template-fallback/templates/palette-app/package.json +1 -1
  29. package/template-fallback/templates/provider-app/package.json +1 -1
package/lib/acp.js CHANGED
@@ -3,10 +3,15 @@
3
3
  // `pltt agent acp`: an Agent Client Protocol server (JSON-RPC 2.0, one JSON message per line on stdin/stdout), so ACP
4
4
  // editors (Zed and others) drive the hosted Build Agent. A session's first prompt starts an edit of the app given by
5
5
  // --app (the build session is made server side); its next prompts go to that build session. While a prompt runs the
6
- // owner counts as present (attend), so the agent's permission asks reach the editor instead of being denied.
6
+ // owner counts as present (attend), so the agent's permission asks reach the editor instead of being denied. A prompt
7
+ // carries text, embedded files and pictures; in plan mode it gets a plan from the read-only plan agent and leaves the
8
+ // app unchanged. The editor sees the agent's text as it streams, its tool calls with their live output, each step's
9
+ // changes as diffs, its plan and its usage; a message sent while a turn runs goes in as a steer (the
10
+ // `_session/steering` extension), and a second prompt is refused until the turn ends.
7
11
 
8
12
  const crypto = require("crypto")
9
- const { locate, untilIdle } = require("./agent-client")
13
+ const path = require("path")
14
+ const { locate, sessionOf, untilIdle } = require("./agent-client")
10
15
 
11
16
  const KINDS = {
12
17
  read: "read", glob: "read", grep: "read",
@@ -25,24 +30,134 @@ const PERMISSION_OPTIONS = [
25
30
  { optionId: "reject", name: "Reject", kind: "reject_once" },
26
31
  ]
27
32
 
33
+ const PROMPT_CHARS = 20_000 // the platform's limit on one message (the text of a prompt or an edit)
34
+ const CUT = "\n[… cut here: one message to the Build Agent holds at most 20,000 characters]"
35
+ const IMAGE_TYPES = /^image\/(png|jpeg|gif|webp|heic|heif|avif)$/ // the pictures the platform takes
36
+ const IMAGE_B64 = 7_000_000 // one picture's base64 at most (about 5 MB)
37
+ const IMAGES = 6 // pictures one message carries at most
38
+ const MODES = [
39
+ { id: "build", name: "Build", description: "Changes the app: writes the code and runs the checks" },
40
+ { id: "plan", name: "Plan", description: "Reads the app and answers with a plan; changes nothing" },
41
+ ]
42
+
28
43
  const text = (value) => ({ type: "text", text: String(value) })
44
+ const modes = (currentModeId) => ({ currentModeId, availableModes: MODES })
29
45
 
30
46
  function rpcError(code, message) {
31
47
  return Object.assign(new Error(message), { code })
32
48
  }
33
49
 
50
+ // One message from an editor prompt's blocks: its text and its pictures. Text as it is, a link (resource_link) as its
51
+ // name and URI, an embedded file (resource) fenced under its URI, a picture (image) among the message's images. A
52
+ // picture the platform does not take (its type, over 5 MB, past the sixth), a sound or a binary file becomes a note
53
+ // that it was left out. Over the platform's limit the text is cut, with a note. Pictures alone are not a prompt.
54
+ function promptMessage(blocks) {
55
+ const parts = []
56
+ const images = []
57
+ let said = false
58
+ for (const block of (blocks || []).filter(Boolean)) {
59
+ const resource = block.resource || {}
60
+ if (block.type === "text") {
61
+ if (!String(block.text || "").trim()) continue
62
+ parts.push(String(block.text))
63
+ } else if (block.type === "resource_link") {
64
+ parts.push(`${block.name || "Link"}: ${block.uri}`)
65
+ } else if (block.type === "resource" && typeof resource.text === "string") {
66
+ const fence = "`".repeat(Math.max(3, ...(resource.text.match(/`+/g) || []).map((run) => run.length + 1)))
67
+ parts.push(`${resource.uri}:\n${fence}\n${resource.text}\n${fence}`)
68
+ } else if (block.type === "image") {
69
+ const name = String(block.uri || "").split("/").pop().slice(0, 120) || "image"
70
+ const data = String(block.data || "")
71
+ const why = !IMAGE_TYPES.test(block.mimeType || "") ? `the agent does not read ${block.mimeType || "that type"}`
72
+ : data.length < 8 ? "it has no data"
73
+ : data.length > IMAGE_B64 ? "it is over 5 MB"
74
+ : images.length >= IMAGES ? `one message carries at most ${IMAGES} pictures` : null
75
+ if (why) parts.push(`[The owner attached the picture ${name} in the editor; it was left out: ${why}.]`)
76
+ else images.push({ name, mime: block.mimeType, data })
77
+ continue
78
+ } else {
79
+ const what = block.type === "audio" ? "a sound clip" : `the file ${resource.uri || ""}`.trim()
80
+ parts.push(`[The owner attached ${what} in the editor; it was left out, as Build Agent messages take text and pictures only.]`)
81
+ continue
82
+ }
83
+ said = true
84
+ }
85
+ if (!said) throw rpcError(-32602, "the prompt has no text")
86
+ const message = parts.join("\n").trim()
87
+ return {
88
+ text: message.length <= PROMPT_CHARS ? message : message.slice(0, PROMPT_CHARS - CUT.length).replace(/[\uD800-\uDBFF]$/, "") + CUT,
89
+ images,
90
+ }
91
+ }
92
+
93
+ // One file of a step's changes (step.ended files[], with its unified patch) as diff content: each hunk's old and new
94
+ // lines with their context, under the file's path in the editor's folder. ponytail: the changed regions only, not
95
+ // whole files (those live on the platform); hunks follow one another as if adjacent.
96
+ function diff(file, cwd = process.cwd()) {
97
+ const before = []
98
+ const after = []
99
+ let hunk = false
100
+ for (const line of String(file.patch).split("\n")) {
101
+ if (line.startsWith("@@")) hunk = true
102
+ if (!hunk || !/^[ +-]/.test(line)) continue // the ---/+++ header, a hunk header, "\ No newline", a cut note
103
+ if (line[0] !== "+") before.push(line.slice(1))
104
+ if (line[0] !== "-") after.push(line.slice(1))
105
+ }
106
+ return {
107
+ type: "diff",
108
+ path: path.resolve(cwd, file.file),
109
+ oldText: file.status === "added" ? null : before.join("\n"),
110
+ newText: file.status === "deleted" ? "" : after.join("\n"),
111
+ }
112
+ }
113
+
114
+ // round.ended usage ({input, output, cache_read, cache_write}) added to a turn's, as the protocol names it.
115
+ function addUsage(total, u) {
116
+ const sum = total || { inputTokens: 0, outputTokens: 0, totalTokens: 0, cachedReadTokens: 0, cachedWriteTokens: 0 }
117
+ sum.inputTokens += u.input || 0
118
+ sum.outputTokens += u.output || 0
119
+ sum.totalTokens += (u.input || 0) + (u.output || 0)
120
+ sum.cachedReadTokens += u.cache_read || 0
121
+ sum.cachedWriteTokens += u.cache_write || 0
122
+ return sum
123
+ }
124
+
34
125
  // The session/update payloads one Build Agent event becomes (the owner's own messages are only replayed by load).
35
- function updates(event) {
126
+ // `state` is the editor session's: its folder (diff paths are absolute) and the step whose text already streamed in
127
+ // live (text.delta), so that step's whole text, which follows in tool.called or text.ended, is not sent twice.
128
+ function updates(event, state = {}) {
36
129
  const d = event.data || {}
37
130
  switch (event.type) {
131
+ case "text.delta":
132
+ state.streamed = d.step
133
+ return d.text ? [{ sessionUpdate: "agent_message_chunk", content: text(d.text) }] : []
134
+ case "reasoning.delta":
135
+ return d.text ? [{ sessionUpdate: "agent_thought_chunk", content: text(d.text) }] : []
136
+ case "tool.progress": // a running command's newest output
137
+ return [{ sessionUpdate: "tool_call_update", toolCallId: d.id, status: "in_progress", content: [{ type: "content", content: text(d.tail || "") }] }]
38
138
  case "tool.called":
39
- case "text.ended":
139
+ case "text.ended": {
140
+ const said = state.streamed === d.step
141
+ state.streamed = null
40
142
  return [
41
- ...(d.text ? [{ sessionUpdate: "agent_message_chunk", content: text(d.text) }] : []),
143
+ ...(d.text && !said ? [{ sessionUpdate: "agent_message_chunk", content: text(d.text) }] : []),
42
144
  ...(d.calls || []).map((call) => ({
43
145
  sessionUpdate: "tool_call", toolCallId: call.id, title: call.name, kind: KINDS[call.name] || "other", status: "in_progress",
44
146
  })),
45
147
  ]
148
+ }
149
+ case "step.ended": {
150
+ const files = d.files || []
151
+ if (!files.length) return []
152
+ return [{
153
+ sessionUpdate: "tool_call",
154
+ toolCallId: `changes_${event.seq}`,
155
+ title: `Changed ${files.map((f) => f.file).join(", ")}`.slice(0, 200),
156
+ kind: "edit",
157
+ status: "completed",
158
+ content: files.filter((f) => f.patch).map((f) => diff(f, state.cwd)),
159
+ }]
160
+ }
46
161
  case "tool.success":
47
162
  case "tool.failed": {
48
163
  const status = event.type === "tool.success" ? "completed" : "failed"
@@ -66,7 +181,9 @@ class AcpServer {
66
181
  // client: an AgentClient; write(message): sends one JSON-RPC message to the editor; log(line): stderr.
67
182
  constructor({ client, app, write, log = () => {}, attendMs = 30_000 }) {
68
183
  Object.assign(this, { client, app, write, log, attendMs })
69
- this.sessions = new Map() // ACP session id → { build: build session id or null, turn: the running prompt }
184
+ // ACP session id → { build: build session id or null, turn: the running prompt, cwd: the editor's folder, mode:
185
+ // build or plan, streamed }
186
+ this.sessions = new Map()
70
187
  this.replies = new Map() // id of a request we sent the editor → its resolve
71
188
  this.nextId = 1
72
189
  }
@@ -95,13 +212,22 @@ class AcpServer {
95
212
  const methods = {
96
213
  initialize: (params) => (this.capabilities = (params && params.clientCapabilities) || {}, {
97
214
  protocolVersion: 1,
98
- agentCapabilities: { loadSession: true, promptCapabilities: { image: false, audio: false, embeddedContext: false } },
215
+ agentCapabilities: {
216
+ loadSession: true,
217
+ promptCapabilities: { image: true, audio: false, embeddedContext: true },
218
+ sessionCapabilities: { list: {}, resume: {} },
219
+ },
99
220
  authMethods: [],
221
+ _meta: { steering: { supported: true } },
100
222
  }),
101
- "session/new": () => this.newSession(),
223
+ "session/new": (params) => this.newSession(params),
224
+ "session/list": (params) => this.list(params),
102
225
  "session/load": (params) => this.load(params),
226
+ "session/resume": (params) => this.resume(params),
227
+ "session/set_mode": (params) => this.setMode(params),
103
228
  "session/prompt": (params) => this.prompt(params),
104
229
  "session/cancel": (params) => this.cancel(params),
230
+ "_session/steering": (params) => this.steer(params),
105
231
  }
106
232
  const method = methods[message.method]
107
233
  const notification = message.id === undefined // no answer to it, whatever happens
@@ -131,38 +257,84 @@ class AcpServer {
131
257
  this.write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update } })
132
258
  }
133
259
 
134
- newSession() {
260
+ newSession({ cwd } = {}) {
135
261
  const sessionId = `acp_${crypto.randomBytes(8).toString("hex")}`
136
- this.sessions.set(sessionId, { build: null, turn: null })
137
- return { sessionId }
262
+ this.sessions.set(sessionId, { build: null, turn: null, cwd, mode: "build" })
263
+ return { sessionId, modes: modes("build") }
264
+ }
265
+
266
+ // The app's build sessions, subagents' left out: their ids are what session/load and session/resume take.
267
+ async list({ cwd } = {}) {
268
+ const { sessions } = await this.client.sessions(this.app, { limit: 100 })
269
+ return {
270
+ sessions: sessions.filter((s) => !s.parent_id)
271
+ .map((s) => ({ sessionId: s.id, cwd: cwd || process.cwd(), title: s.title || undefined, updatedAt: s.updated_at || undefined })),
272
+ }
138
273
  }
139
274
 
140
- // sessionId is a build session id: its log so far, replayed as session/update notifications.
141
- async load({ sessionId }) {
275
+ // sessionId is a build session id: its log so far, replayed as session/update notifications, then its usage.
276
+ async load({ sessionId, cwd }) {
142
277
  if (!sessionId) throw rpcError(-32602, "sessionId is required")
143
- this.sessions.set(sessionId, { build: sessionId, turn: null })
278
+ const session = { build: sessionId, turn: null, cwd, mode: "build" }
279
+ this.sessions.set(sessionId, session)
144
280
  for await (const event of this.client.log(sessionId, { after: 0, follow: false })) {
145
281
  if (event.type === "log.synced") break
146
282
  if (event.type === "message.user" && (event.data || {}).text) {
147
283
  this.notify(sessionId, { sessionUpdate: "user_message_chunk", content: text(event.data.text) })
148
284
  }
149
- for (const update of updates(event)) this.notify(sessionId, update)
285
+ for (const update of updates(event, session)) this.notify(sessionId, update)
150
286
  }
151
- return null
287
+ await this.usage(sessionId, sessionId).catch((err) => this.log(`usage: ${err.message}`))
288
+ return { modes: modes("build") }
289
+ }
290
+
291
+ // session/resume: a build session again, without the replay (the editor still shows it). One that is not there,
292
+ // or not the caller's, fails on its usage.
293
+ async resume({ sessionId, cwd }) {
294
+ if (!sessionId) throw rpcError(-32602, "sessionId is required")
295
+ await this.usage(sessionId, sessionId)
296
+ this.sessions.set(sessionId, { build: sessionId, turn: null, cwd, mode: "build" })
297
+ return { modes: modes("build") }
298
+ }
299
+
300
+ // session/set_mode: build (the default) or plan, read-only, for the prompts that follow. Refused while a prompt runs:
301
+ // a plan sent into the running round would arrive there as an ordinary message.
302
+ setMode({ sessionId, modeId }) {
303
+ const session = this.sessions.get(sessionId)
304
+ if (!session) throw rpcError(-32602, `unknown session ${sessionId}`)
305
+ if (!MODES.some((mode) => mode.id === modeId)) throw rpcError(-32602, `unknown mode ${modeId}`)
306
+ if (session.turn) throw rpcError(-32600, "the agent is working on a prompt: switch modes when it ends, or cancel it first")
307
+ session.mode = modeId
308
+ this.notify(sessionId, { sessionUpdate: "current_mode_update", currentModeId: modeId })
309
+ return {}
152
310
  }
153
311
 
154
312
  async prompt({ sessionId, prompt = [] }) {
155
313
  const session = this.sessions.get(sessionId)
156
314
  if (!session) throw rpcError(-32602, `unknown session ${sessionId}`)
157
- const words = prompt.filter((block) => block && block.type === "text").map((block) => block.text).join("\n").trim()
158
- if (!words) throw rpcError(-32602, "the prompt has no text")
159
- const turn = { controller: new AbortController(), cancelled: false }
315
+ if (session.turn) {
316
+ throw rpcError(-32600, `session ${sessionId} is still working on a prompt: send more as a steer (_session/steering) or cancel the turn first`)
317
+ }
318
+ const { text: words, images } = promptMessage(prompt)
319
+ const turn = { controller: new AbortController(), cancelled: false, usage: null }
160
320
  session.turn = turn
161
321
  let timer
322
+ let sent
323
+ let before = []
324
+ // The prompt sent, then the build session that carries it out (a steer meanwhile waits for it).
325
+ turn.located = (async () => {
326
+ ;({ sessions: before } = await this.client.sessions(this.app, { limit: 100 }))
327
+ // A plan stays read-only only in a round of its own: sent into a round the agent is running (this session's,
328
+ // or for a first prompt any of the app's) it would arrive as an ordinary message, so it waits for that to end.
329
+ if (session.mode === "plan" && before.some((s) => !s.parent_id && s.status === "busy" && (!session.build || s.id === session.build))) {
330
+ throw rpcError(-32600, "the agent is working on this app now, and a plan stays read-only only in a round of its own: send it when that work ends, or steer the work in build mode")
331
+ }
332
+ const options = { images, agent: session.mode === "plan" ? "plan" : undefined }
333
+ sent = session.build ? await this.client.prompt(session.build, words, options) : await this.client.edit(this.app, words, options)
334
+ return locate(this.client, this.app, sent, before, turn.controller.signal)
335
+ })()
162
336
  try {
163
- const { sessions: before } = await this.client.sessions(this.app, { limit: 100 })
164
- const result = session.build ? await this.client.prompt(session.build, words) : await this.client.edit(this.app, words)
165
- const { session: build, after } = await locate(this.client, this.app, result, before, turn.controller.signal)
337
+ const { session: build, after } = await turn.located
166
338
  session.build = build
167
339
  const attend = () => this.client.attend(build).catch((err) => this.log(`attend: ${err.message}`))
168
340
  attend()
@@ -171,15 +343,18 @@ class AcpServer {
171
343
  after,
172
344
  signal: turn.controller.signal,
173
345
  onEvent: (event) => {
174
- for (const update of updates(event)) this.notify(sessionId, update)
346
+ for (const update of updates(event, session)) this.notify(sessionId, update)
347
+ if (event.type === "round.ended" && (event.data || {}).usage) turn.usage = addUsage(turn.usage, event.data.usage)
175
348
  if (event.type === "permission.asked") this.permission(sessionId, build, event.data || {})
176
349
  if (event.type === "question.asked") this.question(sessionId, build, event.data || {})
177
350
  },
178
351
  })
179
- return { stopReason: turn.cancelled ? "cancelled" : STOP_REASONS[state.last_stop] || "end_turn" }
352
+ await this.usage(sessionId, build).catch((err) => this.log(`usage: ${err.message}`))
353
+ return { stopReason: turn.cancelled ? "cancelled" : STOP_REASONS[state.last_stop] || "end_turn", ...(turn.usage ? { usage: turn.usage } : {}) }
180
354
  } catch (err) {
181
355
  if (!turn.cancelled) throw err
182
- // session/cancel aborted the follow: the round stops at its next step.
356
+ // session/cancel aborted the follow: the round stops at its next step (found first if it was not yet).
357
+ session.build = session.build || (await sessionOf(this.client, this.app, sent, before))
183
358
  if (session.build) await this.client.interrupt(session.build).catch((error) => this.log(`interrupt: ${error.message}`))
184
359
  return { stopReason: "cancelled" }
185
360
  } finally {
@@ -188,6 +363,33 @@ class AcpServer {
188
363
  }
189
364
  }
190
365
 
366
+ // `_session/steering`, an editor extension: a message for the turn running now, read by the agent at its next step
367
+ // (an ordinary message in either mode). With no turn running it starts nothing; the editor sends the message as a
368
+ // prompt instead. A round that ended in the meantime refuses it (wake: false) rather than starting again.
369
+ async steer({ sessionId, prompt = [] }) {
370
+ const session = this.sessions.get(sessionId)
371
+ if (!session) throw rpcError(-32602, `unknown session ${sessionId}`)
372
+ const { text: words, images } = promptMessage(prompt)
373
+ const turn = session.turn
374
+ const noTurn = { outcome: "promptRequired", reason: "noRunningTurn" }
375
+ const build = turn && (session.build || (await turn.located.then((found) => found.session, () => null)))
376
+ if (!build || session.turn !== turn || turn.cancelled) return noTurn
377
+ try {
378
+ await this.client.prompt(build, words, { delivery: "steer", wake: false, images })
379
+ } catch (err) {
380
+ if (err.status === 409) return noTurn
381
+ throw err
382
+ }
383
+ return { outcome: "injected" }
384
+ }
385
+
386
+ // The context meter: how full the build session's requests are, in bytes (which the platform bills as tokens),
387
+ // against the ceiling at which it summarises its earlier work.
388
+ async usage(sessionId, build) {
389
+ const { context = {} } = await this.client.context(build)
390
+ if (context.target) this.notify(sessionId, { sessionUpdate: "usage_update", used: context.bytes || 0, size: context.target })
391
+ }
392
+
191
393
  // Ask the editor, then reply to the build session (a cancelled ask is a reject). Not awaited: the log goes on.
192
394
  async permission(sessionId, build, ask) {
193
395
  try {
@@ -1,8 +1,9 @@
1
1
  "use strict"
2
2
 
3
3
  // The hosted Build Agent API (/api/v1/build-sessions on the selected environment, with its publish token): one
4
- // method per endpoint, for `pltt agent` and its ACP server. Plus the two steps every change goes through: find the
5
- // session that carries it out (locate) and follow that session until it is idle again (untilIdle).
4
+ // method per endpoint, for `pltt agent` and its ACP server. Plus the steps every change goes through: find the
5
+ // session that carries it out (locate), follow its log across dropped connections (followLog) until it is idle again
6
+ // (untilIdle).
6
7
 
7
8
  const crypto = require("crypto")
8
9
  const { setTimeout: sleep } = require("timers/promises")
@@ -35,7 +36,9 @@ class AgentClient {
35
36
  return null
36
37
  })
37
38
  if (res && res.ok) return res.json()
38
- if (res && (res.status < 500 || attempt >= retries)) throw new Error(`${method} ${url} → ${res.status}: ${await res.text()}`)
39
+ if (res && (res.status < 500 || attempt >= retries)) {
40
+ throw Object.assign(new Error(`${method} ${url} → ${res.status}: ${await res.text()}`), { status: res.status })
41
+ }
39
42
  await sleep(300 * (attempt + 1))
40
43
  }
41
44
  }
@@ -44,7 +47,7 @@ class AgentClient {
44
47
  async *events(route, { signal } = {}) {
45
48
  const url = this.base + route
46
49
  const res = await fetch(url, { headers: { Authorization: `Bearer ${this.env.token}`, Accept: "text/event-stream" }, signal })
47
- if (!res.ok) throw new Error(`GET ${url} → ${res.status}: ${await res.text()}`)
50
+ if (!res.ok) throw Object.assign(new Error(`GET ${url} → ${res.status}: ${await res.text()}`), { status: res.status })
48
51
  const decoder = new TextDecoder()
49
52
  let buffer = ""
50
53
  for await (const chunk of res.body) {
@@ -66,11 +69,16 @@ class AgentClient {
66
69
  commands() { return this.request("GET", "/commands") }
67
70
  contract() { return this.request("GET", "/contract/agents-md") }
68
71
  session(id) { return this.request("GET", `/${q(id)}`) }
69
- // A retry of the same call carries the same id, so the server admits the message once.
70
- prompt(id, text, { delivery = "steer", messageId = mintId() } = {}) {
71
- return this.request("POST", `/${q(id)}/prompt`, { text, delivery, id: messageId }, { retries: 2 })
72
+ // A retry of the same call carries the same id, so the server admits the message once. `images`: pictures sent with
73
+ // it ([{name, mime, data: base64}]); `agent: "plan"`: plan the change without making it; `wake: false`: an idle
74
+ // session refuses the message (409) instead of waking up.
75
+ prompt(id, text, { delivery = "steer", messageId = mintId(), images, agent, wake } = {}) {
76
+ const body = { text, delivery, id: messageId, ...(images?.length && { images }), ...(agent && { agent }), ...(wake === false && { wake }) }
77
+ return this.request("POST", `/${q(id)}/prompt`, body, { retries: 2 })
78
+ }
79
+ edit(app, text, { images, agent } = {}) {
80
+ return this.request("POST", `/apps/${q(app)}/edit`, { text, ...(images?.length && { images }), ...(agent && { agent }) })
72
81
  }
73
- edit(app, text) { return this.request("POST", `/apps/${q(app)}/edit`, { text }) }
74
82
  wait(id, timeout = 60) { return this.request("GET", `/${q(id)}/wait?timeout=${timeout}`) }
75
83
  interrupt(id) { return this.request("POST", `/${q(id)}/interrupt`) }
76
84
  compact(id) { return this.request("POST", `/${q(id)}/compact`) }
@@ -105,11 +113,11 @@ class AgentClient {
105
113
  skills() { return this.request("GET", "/skills") }
106
114
  mcp() { return this.request("GET", "/mcp") }
107
115
  models(query = "") { return this.request("GET", `/models${query ? `?q=${q(query)}` : ""}`) }
108
- config() { return this.request("GET", "/config") }
109
- plugins() { return this.request("GET", "/plugins") }
110
116
  // A raw call under /build-sessions, for scripting what has no subcommand.
111
117
  raw(method, route, body) { return this.request(method.toUpperCase(), route.startsWith("/") || route.startsWith("?") ? route : `/${route}`, body) }
112
118
  answer(id, question, answer) { return this.request("POST", `/${q(id)}/questions/${q(question)}`, { answer }) }
119
+ // A side question, answered from the transcript: the session's history stays as it is (billed to the session).
120
+ ask(id, question) { return this.request("POST", `/${q(id)}/ask`, { question }) }
113
121
  log(id, { after = 0, follow = true, signal } = {}) {
114
122
  return this.events(`/${q(id)}/log?after=${after}&follow=${follow}`, { signal })
115
123
  }
@@ -122,11 +130,12 @@ function connect(cwd, flags) {
122
130
  }
123
131
 
124
132
  // The root session that carries out a change just sent (`result` of an edit or a prompt) and the seq its new events
125
- // start after. `before` lists the app's sessions from just before it was sent: a queued change, and an edit that
126
- // started a build, run in a session that is not among them yet.
133
+ // start after: the session the server names (a queued change too, which that session takes up when the running build
134
+ // ends), else the first root session that is not among `before`, the app's sessions from just before it was sent (an
135
+ // edit that started or queued a build of its own).
127
136
  async function locate(client, app, result, before, signal) {
128
137
  const seq = (id) => (before.find((s) => s.id === id) || {}).last_seq || 0
129
- const target = result.status !== "queued" && result.session_id
138
+ const target = result.session_id
130
139
  if (target) {
131
140
  const root = (before.find((s) => s.id === target) || {}).parent_id || target
132
141
  return { session: root, after: seq(root) }
@@ -140,28 +149,48 @@ async function locate(client, app, result, before, signal) {
140
149
  }
141
150
  }
142
151
 
143
- // Follow a session's log from `after` until a round of it ends and GET wait finds the session idle (an edit runs a
144
- // plan round, then its build round, in the same session); a dropped stream reconnects. Resolves with wait's answer.
145
- async function untilIdle(client, id, { after = 0, signal, onEvent }) {
152
+ // The session of a change whose follower was stopped before it found it (Ctrl+C, an editor's cancel), looked for 10 s
153
+ // more so it can still be interrupted. A change queued as a build of its own has none until the running build ends:
154
+ // null.
155
+ async function sessionOf(client, app, result, before) {
156
+ if (!result || (result.status === "queued" && !result.session_id)) return null
157
+ return (await locate(client, app, result, before, AbortSignal.timeout(10_000)).catch(() => ({}))).session || null
158
+ }
159
+
160
+ // A session's log from `after`, live, without end: a dropped connection (a network error, a 5xx, the stream closing)
161
+ // reconnects after the last durable event seen. Live events (text.delta, tool.progress: "live": true, no seq) pass
162
+ // through without moving that cursor, and a durable event at or before it is a repeat, skipped. Throws on abort, on a
163
+ // refusal (4xx) and on a frame that is not JSON, which a retry cannot mend.
164
+ async function* followLog(client, id, { after = 0, signal } = {}) {
146
165
  for (;;) {
147
- let ended = false
148
- for await (const event of client.log(id, { after, follow: true, signal })) {
149
- if (event.type === "log.synced") continue
150
- after = event.seq ?? after
151
- await onEvent(event)
152
- if (event.type === "round.ended" && (event.data || {}).status !== "busy") {
153
- ended = true
154
- break
166
+ try {
167
+ for await (const event of client.log(id, { after, follow: true, signal })) {
168
+ if (event.type !== "log.synced" && event.seq != null) {
169
+ if (event.seq <= after) continue
170
+ after = event.seq
171
+ }
172
+ yield event
155
173
  }
174
+ } catch (err) {
175
+ if ((signal && signal.aborted) || (err.status && err.status < 500) || err instanceof SyntaxError) throw err
156
176
  }
177
+ await sleep(1000, undefined, { signal })
178
+ }
179
+ }
180
+
181
+ // Follow a session's log from `after` until a round of it ends and GET wait finds the session idle (an edit runs a
182
+ // plan round, then its build round, in the same session). Resolves with wait's answer.
183
+ async function untilIdle(client, id, { after = 0, signal, onEvent }) {
184
+ for await (const event of followLog(client, id, { after, signal })) {
185
+ if (event.type === "log.synced") continue
186
+ await onEvent(event)
157
187
  // ponytail: a round that starts after wait read the session idle (the gap between an edit's rounds) ends this
158
188
  // early; an "edit finished" event from the server would close that gap.
159
- if (!ended) await sleep(1000, undefined, { signal })
160
- else {
189
+ if (event.type === "round.ended" && (event.data || {}).status !== "busy") {
161
190
  const state = await client.wait(id, 1)
162
191
  if (state.done) return state
163
192
  }
164
193
  }
165
194
  }
166
195
 
167
- module.exports = { AgentClient, connect, locate, untilIdle, mintId }
196
+ module.exports = { AgentClient, connect, locate, sessionOf, followLog, untilIdle, mintId }
package/lib/cli.js CHANGED
@@ -119,6 +119,7 @@ function printHelp() {
119
119
  console.log(" --sandbox Publish a reviewable preview to a configured Palette sandbox (no Docker)")
120
120
  console.log(" --cloud Alias for --sandbox")
121
121
  console.log(" --watch With --sandbox: live-push frontend changes onto the preview (no republish)")
122
+ console.log(" --role <role> Local simulator only: ctx.org_role as owner, admin or member (default owner; or set PALETTE_DEV_ROLE)")
122
123
  console.log(" --platform Internal only: run the Docker platform-dev parity container")
123
124
  console.log("\nLogin flags:")
124
125
  console.log(" --url <url> Palette platform URL for pltt login")