@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.
package/README.md CHANGED
@@ -926,6 +926,102 @@ pltt test --publish-type preview
926
926
 
927
927
  Checks include manifest validity, SDK/platform compatibility, release semver bump detection, forbidden platform imports, frontend bundling and size limits, sandbox bridge smoke, backend dependency installation/import, route permission gates, route permission declarations, migration linting, frontend sandbox policy, and dependency policy for `package.json` / `pyproject.toml`. The semver bump check is skipped for `--publish-type preview` because hosted previews may reuse the current app version. The default frontend and backend bundle limits are 50 MiB; set `PALETTE_MAX_FRONTEND_BUNDLE_BYTES` or `PALETTE_MAX_BACKEND_BUNDLE_BYTES` for reviewed exceptions.
928
928
 
929
+ ### `pltt check`
930
+
931
+ The checks of `pltt test`, reported as one diagnostic per problem for coding agents and editors.
932
+
933
+ ```bash
934
+ pltt check
935
+ pltt check --json
936
+ pltt check --json --files frontend/src/index.tsx backend/api/main.py
937
+ ```
938
+
939
+ Each diagnostic has a stable `id` (`bundle.syntax`, `py.import`, `route.ungated`, `permission.unknown`, `migration.<code>`, ...), a `severity`, the `file`, `line` and `column` where the check knows them, the `message` and the `fix`. Each esbuild error becomes its own diagnostic, and a backend import failure points at the innermost frame inside the project. `--files` keeps the diagnostics about those files plus the project-wide ones. The command exits 1 on any error.
940
+
941
+ ### `pltt agent`
942
+
943
+ Drive the Palette Build Agent (the App Builder's coding agent) on the selected environment, with the publish token: change an app from CI, follow and steer a session from a terminal, or work with it from an ACP editor. `pltt agent help` lists every subcommand.
944
+
945
+ ```bash
946
+ # Change an app and follow the change to its end (CI)
947
+ pltt agent run --app 42 "add a CSV export"
948
+ pltt agent run --app 42 "add a CSV export" --format json --timeout 900
949
+
950
+ # Follow, steer and answer a session
951
+ pltt agent sessions --app 42 [--archived] [--limit 50]
952
+ pltt agent attach bas_123
953
+ pltt agent log bas_123 --follow
954
+ pltt agent prompt bas_123 "make the header blue"
955
+ pltt agent wait bas_123 --timeout 600
956
+ pltt agent permissions bas_123
957
+ pltt agent permit bas_123 per_456 reject "keep dist, it is deployed"
958
+ pltt agent questions bas_123
959
+ pltt agent answer bas_123 que_789 "Bars"
960
+
961
+ # Control and inspect it
962
+ pltt agent interrupt bas_123
963
+ pltt agent revert bas_123 4
964
+ pltt agent unrevert bas_123
965
+ pltt agent compact bas_123
966
+ pltt agent diff bas_123 --stat
967
+ pltt agent context bas_123
968
+ pltt agent children bas_123
969
+ pltt agent inbox bas_123
970
+ pltt agent deliver bas_123 inb_1 queue
971
+ pltt agent cancel bas_123 inb_1
972
+
973
+ # Keep, copy and move sessions
974
+ pltt agent fork bas_123 --seq 120 --title "Try tabs instead"
975
+ pltt agent export bas_123 --sanitize -o session.json
976
+ pltt agent import --app 42 session.json
977
+ pltt agent rename bas_123 "CSV export"
978
+ pltt agent archive bas_123 [--undo]
979
+
980
+ pltt agent move bas_123 --app 43
981
+ pltt agent delete bas_123
982
+
983
+ # What the agent made, and what it can use
984
+ pltt agent artifacts bas_123
985
+ pltt agent artifact bas_123 art_1 -o ./mockup
986
+ pltt agent schedules bas_123
987
+ pltt agent schedule bas_123 sch_1 pause|resume|delete
988
+ pltt agent skills
989
+ pltt agent models [query]
990
+ pltt agent mcp
991
+ pltt agent config
992
+ pltt agent plugins
993
+ pltt agent api GET /bas_123/context
994
+
995
+ pltt agent agents
996
+ pltt agent commands
997
+ pltt agent edit --app 42 "add a CSV export"
998
+ pltt agent init
999
+ ```
1000
+
1001
+ `run` sends the change (it steers the agent when it is already working on the app), follows the session that carries it out until the session is idle again, and exits 0 when the agent finished (`done`), 2 when it stopped short (`blocked`, `declined`, `stalled`, `gate_rounds`, `steps`, `timeout`, `tokens`, `output_limit`, or still running at `--timeout`, default 1800 s), and 1 on errors. With `--format json` (or `--json`) it writes the edit response, then one event per line, then the final state. `run` is unattended: the agent's permission asks are denied by the platform. `edit --follow` does the same as `run`.
1002
+
1003
+ `attach` is the interactive follower: it streams the log, keeps the owner present (the agent's permission asks and questions wait for you instead of being decided unattended), prompts `Allow <action> on <resource>? [o]nce/[a]lways/[r]eject:` for each ask (a reject may carry a message after the letter), lists each question's options to answer by number or in your own words, sends any other line you type as a steering message, and leaves on `/exit`.
1004
+
1005
+ `prompt` reaches a running session at its next step (`--queue` waits until the round ends) and wakes an idle one, as an edit of its app that continues the same transcript; each prompt carries a client-minted id, so a retried request is admitted once. `log` replays the durable event log and, with `--follow`, streams it until the running round ends (exit 1 when that round did not finish, 130 on Ctrl-C). `wait` returns when the session stops, with the same exit codes as `run`. `diff` prints every file's patches, step by step (`--stat`: a table of additions and deletions). `export --sanitize` drops file contents and tool outputs. Every command takes `--json` to print the raw response as one JSON line. `init` writes the platform's AGENTS.md, the Palette app contract the hosted agent follows, into a project for any coding agent.
1006
+
1007
+ #### Use the Build Agent from an ACP editor
1008
+
1009
+ `pltt agent acp --app <id>` is an [Agent Client Protocol](https://agentclientprotocol.com) server on stdin/stdout, so Zed and other ACP editors can drive the hosted Build Agent. A session's first prompt starts an edit of that app; later prompts go to the same build session. The editor sees the agent's messages, tool calls with their results, and its plan; the agent's permission asks come up as the editor's permission prompts (the owner counts as present while a prompt runs), and a question with choices comes up the same way, with "Let the agent decide" beside the choices; cancelling interrupts the round. `session/load` with a build session id (`bas_...`) replays that session. In Zed's `settings.json`:
1010
+
1011
+ ```json
1012
+ {
1013
+ "agent_servers": {
1014
+ "Palette Build Agent": {
1015
+ "type": "custom",
1016
+ "command": "pltt",
1017
+ "args": ["agent", "acp", "--app", "42", "--env", "staging"]
1018
+ }
1019
+ }
1020
+ }
1021
+ ```
1022
+
1023
+ All of this needs a platform with the build-sessions API.
1024
+
929
1025
  ### `pltt package`
930
1026
 
931
1027
  Bundle the plugin into `dist/<plugin-id>-<version>.tar.gz` without uploading.
@@ -1205,6 +1301,27 @@ Subcommands:
1205
1301
  `pltt test` verifies every agent capability has a stable `capability_id` and a
1206
1302
  matching `@capability(...)` / `service(..., agent_exposable=True)` handler.
1207
1303
 
1304
+ ## App CSS Isolation
1305
+
1306
+ The bundler scopes every stylesheet your frontend imports to your app's root
1307
+ element, `[data-palette-plugin-root="<id>"]`, so app CSS never restyles Palette
1308
+ or another app.
1309
+
1310
+ - `:root`, `html` and `body` all mean that one root element. Chains such as
1311
+ `html body .x` or `:root[data-theme=dark] body` collapse onto it, so
1312
+ `:root[data-theme=dark] { --bg: #000 }` needs `data-theme` on the root
1313
+ element itself (`el.closest("[data-palette-plugin-root]")`), not on
1314
+ `document.documentElement`. For an in-app theme, font-size, contrast or
1315
+ motion toggle you can also put the attribute on your own top-level wrapper
1316
+ and write `.app[data-theme=dark] …`.
1317
+ - Nested CSS is supported: it is flattened before scoping, with the same
1318
+ matching as in a normal page.
1319
+ - Palette's dark mode is a `dark` class on `<html>`. `.dark .your-root { … }`
1320
+ and `.dark { … }` follow it; a `.dark` class your app sets on its own
1321
+ elements does not.
1322
+ - An unclosed `{`, `(` or `[`, a stray `}`, or a `//` comment fails the build
1323
+ with its file and line. The browser would silently drop the rules after it.
1324
+
1208
1325
  ## Global Flags
1209
1326
 
1210
1327
  - `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, `version`, `login`, `dev --sandbox`, `platform list`, `services list`, and `capabilities`.
@@ -25,7 +25,7 @@ from palette_sdk.platform_services import (
25
25
  )
26
26
  from palette_sdk.repository import OrgRepository
27
27
  from palette_sdk.lifecycle import LifecycleHooks
28
- from palette_sdk.jobs import JobCancelledError, JobExecution, JobHandle, JobsClient, job
28
+ from palette_sdk.jobs import JobCancelledError, JobExecution, JobFailedError, JobHandle, JobsClient, job
29
29
  from palette_sdk.tool_definition import ToolDefinition
30
30
  from palette_sdk.capabilities import (
31
31
  ApprovalRequired,
@@ -105,6 +105,7 @@ __all__ = [
105
105
  "LifecycleHooks",
106
106
  "JobCancelledError",
107
107
  "JobExecution",
108
+ "JobFailedError",
108
109
  "JobHandle",
109
110
  "JobsClient",
110
111
  "job",
@@ -154,4 +155,4 @@ __all__ = [
154
155
  "LocalStorageService",
155
156
  ]
156
157
 
157
- __version__ = "0.1.19"
158
+ __version__ = "0.1.20"
@@ -166,8 +166,26 @@ class JobCancelledError(Exception):
166
166
  """Cooperative cancellation raised by ``JobExecution.check_cancelled``."""
167
167
 
168
168
 
169
+ class JobFailedError(Exception):
170
+ """End the job as ``failed`` now: no retry, no dead letter.
171
+
172
+ Raise it for expected outcomes (the record is gone, the user lost access,
173
+ the input is invalid). ``message`` is shown to the user, so never put a
174
+ traceback or SQL in it. The platform matches the ``retryable = False``
175
+ attribute, not this class; an exception with a ``retry_after`` attribute
176
+ (seconds) is retried after that delay while attempts remain.
177
+ """
178
+
179
+ retryable = False
180
+
181
+ def __init__(self, message: str, code: str = "app_error") -> None:
182
+ super().__init__(message)
183
+ self.code = code
184
+
185
+
169
186
  __all__ = [
170
187
  "JobCancelledError",
188
+ "JobFailedError",
171
189
  "JobDecl",
172
190
  "JobExecution",
173
191
  "JobHandle",
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "palette-sdk"
3
- version = "0.1.19"
3
+ version = "0.1.20"
4
4
  description = "Palette Platform SDK for building backend plugins"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
package/lib/acp.js ADDED
@@ -0,0 +1,267 @@
1
+ "use strict"
2
+
3
+ // `pltt agent acp`: an Agent Client Protocol server (JSON-RPC 2.0, one JSON message per line on stdin/stdout), so ACP
4
+ // editors (Zed and others) drive the hosted Build Agent. A session's first prompt starts an edit of the app given by
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.
7
+
8
+ const crypto = require("crypto")
9
+ const { locate, untilIdle } = require("./agent-client")
10
+
11
+ const KINDS = {
12
+ read: "read", glob: "read", grep: "read",
13
+ write: "edit", edit: "edit", apply_patch: "edit",
14
+ bash: "execute", check: "execute", pltt_test: "execute",
15
+ webfetch: "fetch", websearch: "fetch",
16
+ }
17
+ const STOP_REASONS = {
18
+ done: "end_turn",
19
+ steps: "max_turn_requests", tokens: "max_turn_requests", timeout: "max_turn_requests",
20
+ declined: "refusal", blocked: "refusal",
21
+ }
22
+ const PERMISSION_OPTIONS = [
23
+ { optionId: "once", name: "Allow once", kind: "allow_once" },
24
+ { optionId: "always", name: "Always allow", kind: "allow_always" },
25
+ { optionId: "reject", name: "Reject", kind: "reject_once" },
26
+ ]
27
+
28
+ const text = (value) => ({ type: "text", text: String(value) })
29
+
30
+ function rpcError(code, message) {
31
+ return Object.assign(new Error(message), { code })
32
+ }
33
+
34
+ // The session/update payloads one Build Agent event becomes (the owner's own messages are only replayed by load).
35
+ function updates(event) {
36
+ const d = event.data || {}
37
+ switch (event.type) {
38
+ case "tool.called":
39
+ case "text.ended":
40
+ return [
41
+ ...(d.text ? [{ sessionUpdate: "agent_message_chunk", content: text(d.text) }] : []),
42
+ ...(d.calls || []).map((call) => ({
43
+ sessionUpdate: "tool_call", toolCallId: call.id, title: call.name, kind: KINDS[call.name] || "other", status: "in_progress",
44
+ })),
45
+ ]
46
+ case "tool.success":
47
+ case "tool.failed": {
48
+ const status = event.type === "tool.success" ? "completed" : "failed"
49
+ const content = d.output ? [{ type: "content", content: text(String(d.output).slice(0, 4000)) }] : undefined
50
+ const out = (d.reconciled || [d.id]).map((toolCallId) => ({ sessionUpdate: "tool_call_update", toolCallId, status, content }))
51
+ const todos = event.type === "tool.success" && d.name === "todowrite" && (d.metadata || {}).todos
52
+ if (todos) {
53
+ out.push({
54
+ sessionUpdate: "plan",
55
+ entries: todos.filter((t) => t.status !== "cancelled").map((t) => ({ content: t.content, priority: "medium", status: t.status })),
56
+ })
57
+ }
58
+ return out
59
+ }
60
+ default:
61
+ return []
62
+ }
63
+ }
64
+
65
+ class AcpServer {
66
+ // client: an AgentClient; write(message): sends one JSON-RPC message to the editor; log(line): stderr.
67
+ constructor({ client, app, write, log = () => {}, attendMs = 30_000 }) {
68
+ 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 }
70
+ this.replies = new Map() // id of a request we sent the editor → its resolve
71
+ this.nextId = 1
72
+ }
73
+
74
+ // One line from stdin.
75
+ receive(line) {
76
+ if (!line.trim()) return undefined
77
+ let message
78
+ try {
79
+ message = JSON.parse(line)
80
+ } catch {
81
+ return this.write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } })
82
+ }
83
+ return this.handle(message)
84
+ }
85
+
86
+ async handle(message) {
87
+ if (!message || typeof message !== "object") return this.write({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request" } })
88
+ if (!message.method) {
89
+ // The editor's answer to a request of ours (session/request_permission).
90
+ const resolve = this.replies.get(message.id)
91
+ this.replies.delete(message.id)
92
+ if (resolve) resolve(message.result || null)
93
+ return undefined
94
+ }
95
+ const methods = {
96
+ initialize: (params) => (this.capabilities = (params && params.clientCapabilities) || {}, {
97
+ protocolVersion: 1,
98
+ agentCapabilities: { loadSession: true, promptCapabilities: { image: false, audio: false, embeddedContext: false } },
99
+ authMethods: [],
100
+ }),
101
+ "session/new": () => this.newSession(),
102
+ "session/load": (params) => this.load(params),
103
+ "session/prompt": (params) => this.prompt(params),
104
+ "session/cancel": (params) => this.cancel(params),
105
+ }
106
+ const method = methods[message.method]
107
+ const notification = message.id === undefined // no answer to it, whatever happens
108
+ if (!method) {
109
+ if (!notification) this.write({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: `Method not found: ${message.method}` } })
110
+ return undefined
111
+ }
112
+ try {
113
+ const result = await method(message.params || {})
114
+ if (!notification) this.write({ jsonrpc: "2.0", id: message.id, result: result === undefined ? null : result })
115
+ } catch (err) {
116
+ if (notification) this.log(`${message.method}: ${err.message}`)
117
+ else this.write({ jsonrpc: "2.0", id: message.id, error: { code: err.code || -32603, message: err.message } })
118
+ }
119
+ return undefined
120
+ }
121
+
122
+ // A request to the editor; resolves with its result.
123
+ request(method, params) {
124
+ const id = this.nextId++
125
+ const reply = new Promise((resolve) => this.replies.set(id, resolve))
126
+ this.write({ jsonrpc: "2.0", id, method, params })
127
+ return reply
128
+ }
129
+
130
+ notify(sessionId, update) {
131
+ this.write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update } })
132
+ }
133
+
134
+ newSession() {
135
+ const sessionId = `acp_${crypto.randomBytes(8).toString("hex")}`
136
+ this.sessions.set(sessionId, { build: null, turn: null })
137
+ return { sessionId }
138
+ }
139
+
140
+ // sessionId is a build session id: its log so far, replayed as session/update notifications.
141
+ async load({ sessionId }) {
142
+ if (!sessionId) throw rpcError(-32602, "sessionId is required")
143
+ this.sessions.set(sessionId, { build: sessionId, turn: null })
144
+ for await (const event of this.client.log(sessionId, { after: 0, follow: false })) {
145
+ if (event.type === "log.synced") break
146
+ if (event.type === "message.user" && (event.data || {}).text) {
147
+ this.notify(sessionId, { sessionUpdate: "user_message_chunk", content: text(event.data.text) })
148
+ }
149
+ for (const update of updates(event)) this.notify(sessionId, update)
150
+ }
151
+ return null
152
+ }
153
+
154
+ async prompt({ sessionId, prompt = [] }) {
155
+ const session = this.sessions.get(sessionId)
156
+ 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 }
160
+ session.turn = turn
161
+ let timer
162
+ 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)
166
+ session.build = build
167
+ const attend = () => this.client.attend(build).catch((err) => this.log(`attend: ${err.message}`))
168
+ attend()
169
+ timer = setInterval(attend, this.attendMs)
170
+ const state = await untilIdle(this.client, build, {
171
+ after,
172
+ signal: turn.controller.signal,
173
+ onEvent: (event) => {
174
+ for (const update of updates(event)) this.notify(sessionId, update)
175
+ if (event.type === "permission.asked") this.permission(sessionId, build, event.data || {})
176
+ if (event.type === "question.asked") this.question(sessionId, build, event.data || {})
177
+ },
178
+ })
179
+ return { stopReason: turn.cancelled ? "cancelled" : STOP_REASONS[state.last_stop] || "end_turn" }
180
+ } catch (err) {
181
+ if (!turn.cancelled) throw err
182
+ // session/cancel aborted the follow: the round stops at its next step.
183
+ if (session.build) await this.client.interrupt(session.build).catch((error) => this.log(`interrupt: ${error.message}`))
184
+ return { stopReason: "cancelled" }
185
+ } finally {
186
+ clearInterval(timer)
187
+ if (session.turn === turn) session.turn = null
188
+ }
189
+ }
190
+
191
+ // Ask the editor, then reply to the build session (a cancelled ask is a reject). Not awaited: the log goes on.
192
+ async permission(sessionId, build, ask) {
193
+ try {
194
+ const { outcome } = (await this.request("session/request_permission", {
195
+ sessionId,
196
+ toolCall: { toolCallId: ask.id, title: `${ask.action} ${ask.resource}` },
197
+ options: PERMISSION_OPTIONS,
198
+ })) || {}
199
+ const reply = outcome && outcome.outcome === "selected" && ["once", "always"].includes(outcome.optionId) ? outcome.optionId : "reject"
200
+ await this.client.permit(build, ask.id, reply)
201
+ } catch (err) {
202
+ this.log(`permission ${ask.id}: ${err.message}`)
203
+ }
204
+ }
205
+
206
+ // A question goes to the editor as a form (elicitation/create) when the editor supports forms: its choices as a
207
+ // select, and a free answer beside them. Otherwise it goes as a choice prompt (session/request_permission): each
208
+ // choice an option (or, without choices, "Go with: <the agent's assumption>"), plus "Let the agent decide".
209
+ // Not awaited, like a permission.
210
+ async question(sessionId, build, ask) {
211
+ const choices = Array.isArray(ask.options) ? ask.options.slice(0, 6).map(String) : []
212
+ if (this.capabilities && this.capabilities.elicitation && this.capabilities.elicitation.form) {
213
+ try {
214
+ const answer = (await this.request("elicitation/create", {
215
+ mode: "form",
216
+ sessionId,
217
+ message: String(ask.question || "The agent has a question"),
218
+ requestedSchema: {
219
+ type: "object",
220
+ properties: {
221
+ ...(choices.length ? { answer: { type: "string", title: "Answer", oneOf: choices.map((c) => ({ const: c, title: c })) } } : {}),
222
+ other: { type: "string", title: choices.length ? "Or type your own answer" : "Your answer" },
223
+ },
224
+ required: [],
225
+ },
226
+ })) || {}
227
+ const content = answer.action === "accept" ? answer.content || {} : {}
228
+ const text = String(content.other || content.answer || "").trim()
229
+ if (text) await this.client.answer(build, ask.id, text)
230
+ } catch (err) {
231
+ this.log(`question ${ask.id}: ${err.message}`)
232
+ }
233
+ return
234
+ }
235
+ const assumption = String(ask.assumption || "").trim()
236
+ if (!choices.length && !assumption) return
237
+ if (!choices.length) choices.push(`Go with: ${assumption}`)
238
+ try {
239
+ const { outcome } = (await this.request("session/request_permission", {
240
+ sessionId,
241
+ toolCall: { toolCallId: ask.id, title: String(ask.question || "The agent has a question") },
242
+ options: [
243
+ ...choices.map((name, index) => ({ optionId: `choice-${index}`, name, kind: "allow_once" })),
244
+ { optionId: "decide", name: "Let the agent decide", kind: "reject_once" },
245
+ ],
246
+ })) || {}
247
+ const picked = outcome && outcome.outcome === "selected" && /^choice-(\d+)$/.exec(outcome.optionId || "")
248
+ if (picked) await this.client.answer(build, ask.id, choices[Number(picked[1])].replace(/^Go with: /, ""))
249
+ } catch (err) {
250
+ this.log(`question ${ask.id}: ${err.message}`)
251
+ }
252
+ }
253
+
254
+ cancel({ sessionId }) {
255
+ const turn = (this.sessions.get(sessionId) || {}).turn
256
+ if (!turn) return
257
+ turn.cancelled = true
258
+ turn.controller.abort()
259
+ }
260
+
261
+ // stdin closed: stop following every running prompt.
262
+ close() {
263
+ for (const session of this.sessions.values()) if (session.turn) session.turn.controller.abort()
264
+ }
265
+ }
266
+
267
+ module.exports = { AcpServer, updates }
@@ -0,0 +1,167 @@
1
+ "use strict"
2
+
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).
6
+
7
+ const crypto = require("crypto")
8
+ const { setTimeout: sleep } = require("timers/promises")
9
+ const { resolveEnvironment } = require("./environments")
10
+
11
+ const q = encodeURIComponent
12
+
13
+ // A prompt's client-minted id: a retried request admits the message once.
14
+ function mintId() {
15
+ return `cli_${crypto.randomBytes(12).toString("hex")}`
16
+ }
17
+
18
+ class AgentClient {
19
+ constructor(env) {
20
+ this.env = env
21
+ this.base = `${env.url}/api/v1/build-sessions`
22
+ }
23
+
24
+ // JSON over fetch. `retries` resends a request that failed in transit or with a 5xx: only for idempotent requests.
25
+ async request(method, route, body, { retries = 0 } = {}) {
26
+ const url = this.base + route
27
+ const init = {
28
+ method,
29
+ headers: { Authorization: `Bearer ${this.env.token}`, ...(body ? { "Content-Type": "application/json" } : {}) },
30
+ body: body ? JSON.stringify(body) : undefined,
31
+ }
32
+ for (let attempt = 0; ; attempt++) {
33
+ const res = await fetch(url, init).catch((err) => {
34
+ if (attempt >= retries) throw err
35
+ return null
36
+ })
37
+ 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
+ await sleep(300 * (attempt + 1))
40
+ }
41
+ }
42
+
43
+ // Server-sent events over fetch: data-only frames, comment lines are heartbeats.
44
+ async *events(route, { signal } = {}) {
45
+ const url = this.base + route
46
+ 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()}`)
48
+ const decoder = new TextDecoder()
49
+ let buffer = ""
50
+ for await (const chunk of res.body) {
51
+ buffer += decoder.decode(chunk, { stream: true })
52
+ let end
53
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
54
+ const frame = buffer.slice(0, end)
55
+ buffer = buffer.slice(end + 2)
56
+ const data = frame.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n")
57
+ if (data) yield JSON.parse(data)
58
+ }
59
+ }
60
+ }
61
+
62
+ sessions(app, { limit, archived } = {}) {
63
+ return this.request("GET", `?app_id=${q(app)}${limit ? `&limit=${limit}` : ""}${archived ? "&archived=true" : ""}`)
64
+ }
65
+ agents() { return this.request("GET", "/agents") }
66
+ commands() { return this.request("GET", "/commands") }
67
+ contract() { return this.request("GET", "/contract/agents-md") }
68
+ 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
+ }
73
+ edit(app, text) { return this.request("POST", `/apps/${q(app)}/edit`, { text }) }
74
+ wait(id, timeout = 60) { return this.request("GET", `/${q(id)}/wait?timeout=${timeout}`) }
75
+ interrupt(id) { return this.request("POST", `/${q(id)}/interrupt`) }
76
+ compact(id) { return this.request("POST", `/${q(id)}/compact`) }
77
+ revert(id, step) { return this.request("POST", `/${q(id)}/revert`, { step }) }
78
+ unrevert(id) { return this.request("POST", `/${q(id)}/unrevert`) }
79
+ diff(id) { return this.request("GET", `/${q(id)}/diff`) }
80
+ context(id) { return this.request("GET", `/${q(id)}/context`) }
81
+ children(id) { return this.request("GET", `/${q(id)}/children`) }
82
+ inbox(id) { return this.request("GET", `/${q(id)}/inbox`) }
83
+ deliver(id, item, delivery) { return this.request("PATCH", `/${q(id)}/inbox/${q(item)}`, { delivery }) }
84
+ cancel(id, item) { return this.request("DELETE", `/${q(id)}/inbox/${q(item)}`) }
85
+ fork(id, { seq, title } = {}) { return this.request("POST", `/${q(id)}/fork`, { seq, title }) }
86
+ exportSession(id, { sanitize = false } = {}) { return this.request("GET", `/${q(id)}/export?sanitize=${sanitize}`) }
87
+ importSession(app, document) { return this.request("POST", "/import", { app_id: Number(app), document }) }
88
+ update(id, fields) { return this.request("PATCH", `/${q(id)}`, fields) }
89
+ remove(id) { return this.request("DELETE", `/${q(id)}`) }
90
+ attend(id) { return this.request("POST", `/${q(id)}/attend`) }
91
+ permissions(id) { return this.request("GET", `/${q(id)}/permissions`) }
92
+ permit(id, request, reply, message) {
93
+ return this.request("POST", `/${q(id)}/permissions/${q(request)}`, { reply, ...(message ? { message } : {}) })
94
+ }
95
+ questions(id) { return this.request("GET", `/${q(id)}/questions`) }
96
+ artifacts(id) { return this.request("GET", `/${q(id)}/artifacts`) }
97
+ artifact(id, artifact) { return this.request("GET", `/${q(id)}/artifacts/${q(artifact)}`) }
98
+ schedules(id) { return this.request("GET", `/${q(id)}/schedules`) }
99
+ schedule(id, schedule, action) {
100
+ return action === "delete"
101
+ ? this.request("DELETE", `/${q(id)}/schedules/${q(schedule)}`)
102
+ : this.request("POST", `/${q(id)}/schedules/${q(schedule)}`, { action })
103
+ }
104
+ move(id, app) { return this.request("POST", `/${q(id)}/move`, { app_id: Number(app) }) }
105
+ skills() { return this.request("GET", "/skills") }
106
+ mcp() { return this.request("GET", "/mcp") }
107
+ 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
+ // A raw call under /build-sessions, for scripting what has no subcommand.
111
+ raw(method, route, body) { return this.request(method.toUpperCase(), route.startsWith("/") || route.startsWith("?") ? route : `/${route}`, body) }
112
+ answer(id, question, answer) { return this.request("POST", `/${q(id)}/questions/${q(question)}`, { answer }) }
113
+ log(id, { after = 0, follow = true, signal } = {}) {
114
+ return this.events(`/${q(id)}/log?after=${after}&follow=${follow}`, { signal })
115
+ }
116
+ }
117
+
118
+ function connect(cwd, flags) {
119
+ const env = resolveEnvironment({ cwd, flags })
120
+ if (!env.token) throw new Error(`no token for "${env.name}" — run pltt login or set $${env.token_env}`)
121
+ return new AgentClient(env)
122
+ }
123
+
124
+ // 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.
127
+ async function locate(client, app, result, before, signal) {
128
+ const seq = (id) => (before.find((s) => s.id === id) || {}).last_seq || 0
129
+ const target = result.status !== "queued" && result.session_id
130
+ if (target) {
131
+ const root = (before.find((s) => s.id === target) || {}).parent_id || target
132
+ return { session: root, after: seq(root) }
133
+ }
134
+ const seen = new Set(before.map((s) => s.id))
135
+ for (;;) {
136
+ const { sessions } = await client.sessions(app, { limit: 20 })
137
+ const found = sessions.find((s) => !s.parent_id && (result.status === "steered" || !seen.has(s.id)))
138
+ if (found) return { session: found.id, after: seq(found.id) }
139
+ await sleep(2000, undefined, { signal })
140
+ }
141
+ }
142
+
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 }) {
146
+ 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
155
+ }
156
+ }
157
+ // ponytail: a round that starts after wait read the session idle (the gap between an edit's rounds) ends this
158
+ // early; an "edit finished" event from the server would close that gap.
159
+ if (!ended) await sleep(1000, undefined, { signal })
160
+ else {
161
+ const state = await client.wait(id, 1)
162
+ if (state.done) return state
163
+ }
164
+ }
165
+ }
166
+
167
+ module.exports = { AgentClient, connect, locate, untilIdle, mintId }
package/lib/bundler.js CHANGED
@@ -369,12 +369,43 @@ export function Link({ href, replace, onClick, children, ...props }) {
369
369
  }
370
370
  }
371
371
 
372
+ // esbuild "repairs" broken CSS: an unclosed "{" or "(" swallows every later rule, and a
373
+ // stray "}" or a "//" comment eats the next selector. The browser then drops those rules
374
+ // with no error, so fail the build on these and print the remaining CSS warnings.
375
+ function isBrokenCss(warning) {
376
+ return (
377
+ warning.id === "js-comment-in-css" ||
378
+ (warning.id === "css-syntax-error" && /^(Expected "[)\]}]" to go with "[([{]"|Unexpected "}")$/.test(warning.text))
379
+ )
380
+ }
381
+
382
+ const cssGuardPlugin = {
383
+ name: "palette-css-guard",
384
+ setup(build) {
385
+ build.onEnd((result) => {
386
+ const css = result.warnings.filter((w) => /\.css$/i.test(w.location?.file || ""))
387
+ for (const w of css) {
388
+ if (!isBrokenCss(w)) console.warn(`[pltt] CSS warning: ${w.location.file}:${w.location.line}: ${w.text}`)
389
+ }
390
+ const broken = css.filter(isBrokenCss)
391
+ if (!broken.length) return undefined
392
+ return {
393
+ errors: broken.map((w) => ({
394
+ text: `${w.text}${w.notes?.[0]?.location ? ` (opened on line ${w.notes[0].location.line})` : ""}. The browser would silently drop the rules this breaks; fix the CSS.`,
395
+ location: w.location,
396
+ notes: w.notes,
397
+ })),
398
+ }
399
+ })
400
+ },
401
+ }
402
+
372
403
  function frontendBuildConfig(pluginDir, frontend = {}) {
373
404
  const framework = frontendFramework(frontend)
374
405
  const define = {
375
406
  "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "production"),
376
407
  }
377
- const plugins = []
408
+ const plugins = [cssGuardPlugin]
378
409
  const tsconfigPaths = framework === "next" || framework === "palette-app" ? makeTsconfigPathsPlugin(pluginDir, frontend) : null
379
410
  if (tsconfigPaths) plugins.push(tsconfigPaths)
380
411
  if (framework === "palette-app") plugins.push(makePaletteAppNextCompatPlugin(pluginDir))