@palettelab/cli 0.3.69 → 0.3.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -323,7 +323,7 @@ Backend SDK features for app-owned data:
323
323
  - `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
324
324
  - `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
325
325
  - `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
326
- - `ctx.llm` gives chat, streaming, embeddings and image generation on the PLATFORM's own provider keys when `"llm"` is declared — no `OPENAI_API_KEY` secret to ship or rotate. An app picks any model the workspace's own chat offers with `model=` — the latest Claude, GPT and Gemini models, premium ones included, no declaration — and nothing bypasses the workspace's SECURE policy. `fallback=False` runs exactly the requested model or raises `ModelUnavailable`; every reply reports the model that actually ran. Tool calls (`tools=`, `tool_calls`, `reply["message"]` for the history) are supported. Calls spend the workspace's credits under its plan, seat and member limits, and are refused (the billing `CreditError`) when the workspace could not start a chat turn either.
326
+ - `ctx.llm` gives chat, streaming, embeddings and image generation on the PLATFORM's own provider keys when `"llm"` is declared — no `OPENAI_API_KEY` secret to ship or rotate. An app picks any model the workspace's own chat offers with `model=` — Palette's own models and the latest Claude, GPT and Gemini models, premium ones included, no declaration — and nothing bypasses the workspace's SECURE policy. `fallback=False` runs exactly the requested model or raises `ModelUnavailable`; every reply reports the model that actually ran. Tool calls (`tools=`, `tool_calls`, `reply["message"]` for the history) are supported. Calls spend the workspace's credits under its plan, seat and member limits, and are refused (the billing `CreditError`) when the workspace could not start a chat turn either.
327
327
  - `ctx.llm` also takes provider passthrough (`response_format`, `top_p`, `stop`, `seed`, …) as plain keywords, and reports `ctx.llm.catalog()` (models with limits and unavailable reasons), `ctx.llm.models()` and `ctx.llm.spend()` so an app can offer a real model picker and explain a refusal.
328
328
  - `ctx.media` gives fal.ai on the PLATFORM's key when `"media"` is declared — no `FAL_KEY` secret to ship or rotate. `ctx.media.run(model, payload)` reaches ANY fal model with the payload passed through untouched (so a model fal shipped today needs no SDK release); `image`, `video`, `speech` and `transcribe` are the same call with a default model filled in, `submit`/`status`/`result`/`cancel` handle multi-minute renders through a durable handle (`MediaStillRunning.handle`), `upload` puts bytes, public URLs or the app's own `ctx.storage` files on fal's CDN, `catalog()` lists the fal models it can run, and `save` copies an output into the app's own storage — fal's URLs expire. It spends the workspace's credits like `ctx.llm`.
329
329
  - `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared.
@@ -926,6 +926,109 @@ 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
+ # A terminal in the session's build sandbox (Ctrl-] closes it; Node 22 or later)
984
+ pltt agent terminal bas_123
985
+ pltt agent terminal bas_123 --attach term_456
986
+ pltt agent terminals bas_123 [--read] [--lines 50]
987
+
988
+ # What the agent made, and what it can use
989
+ pltt agent artifacts bas_123
990
+ pltt agent artifact bas_123 art_1 -o ./mockup
991
+ pltt agent schedules bas_123
992
+ pltt agent schedule bas_123 sch_1 pause|resume|delete
993
+ pltt agent skills
994
+ pltt agent models [query]
995
+ pltt agent mcp
996
+ pltt agent config
997
+ pltt agent plugins
998
+ pltt agent api GET /bas_123/context
999
+
1000
+ pltt agent agents
1001
+ pltt agent commands
1002
+ pltt agent edit --app 42 "add a CSV export"
1003
+ pltt agent init
1004
+ ```
1005
+
1006
+ `terminal` opens an interactive shell in the session's build sandbox: the project's files and `pltt`, no network. Keys go to it as you type and its output is drawn by your terminal; resizing the window resizes it, and Ctrl-] closes it. A terminal opened while the agent works opens at its next step; on an idle session it starts an edit build that holds it. It closes after 10 minutes without typing. Files the app may not change are put back when it closes, and the agent is told what the terminal showed. `--attach` reconnects to one that is still open; `terminals --read` prints the newest one's last lines.
1007
+
1008
+ `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`.
1009
+
1010
+ `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`.
1011
+
1012
+ `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.
1013
+
1014
+ #### Use the Build Agent from an ACP editor
1015
+
1016
+ `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`:
1017
+
1018
+ ```json
1019
+ {
1020
+ "agent_servers": {
1021
+ "Palette Build Agent": {
1022
+ "type": "custom",
1023
+ "command": "pltt",
1024
+ "args": ["agent", "acp", "--app", "42", "--env", "staging"]
1025
+ }
1026
+ }
1027
+ }
1028
+ ```
1029
+
1030
+ All of this needs a platform with the build-sessions API.
1031
+
929
1032
  ### `pltt package`
930
1033
 
931
1034
  Bundle the plugin into `dist/<plugin-id>-<version>.tar.gz` without uploading.
@@ -1058,6 +1161,7 @@ pltt models --json --env staging
1058
1161
  ```text
1059
1162
  Workspace credits: 812.50 available (normal)
1060
1163
 
1164
+ ok palette-llm palette chat 4096 out tok, 4 img
1061
1165
  ok gpt-6-astra openai chat 12000 out tok, 16 img
1062
1166
  ok claude-haiku-5-5 anthropic chat 4096 out tok, 4 img
1063
1167
  -- gemini-4-argon google chat 4096 out tok, 4 img (billing_disabled)
@@ -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.18"
158
+ __version__ = "0.1.20"
@@ -117,11 +117,23 @@ class DataRoomsClient:
117
117
  *,
118
118
  folder_id: int | None = None,
119
119
  content_type: str | None = None,
120
+ public: bool = False,
120
121
  ) -> dict[str, Any]:
122
+ """Store a file in a Drive room.
123
+
124
+ Private by default: only members of the room can read it. With
125
+ ``public=True`` every member of the organisation can read it (for
126
+ example a teammate opening an attachment you uploaded), never anyone
127
+ outside the organisation.
128
+ """
129
+ # Sent only when asked for: an older platform refuses the unknown
130
+ # argument instead of storing a file meant to be shared as private.
131
+ extra = {"public": True} if public else {}
121
132
  return await self._require_service().upload_file(
122
133
  room_id,
123
134
  filename,
124
135
  content,
125
136
  folder_id=folder_id,
126
137
  content_type=content_type,
138
+ **extra,
127
139
  )
@@ -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.18"
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"
@@ -752,9 +752,14 @@ await ctx.data_rooms.upload_file(
752
752
  content,
753
753
  folder_id=None,
754
754
  content_type=None,
755
+ public=False, # True: every member of the organisation can read it
755
756
  )
756
757
  ```
757
758
 
759
+ Uploads are private to the room's members. With `public=True` every member of
760
+ the organisation can read the file (`read_file_bytes`, Drive download/preview),
761
+ whoever's room holds it; nobody outside the organisation can.
762
+
758
763
  In local unit tests outside the Palette runtime, inject a fake Data Room service
759
764
  if you need to test routes that call `ctx.data_rooms`. In hosted sandbox and
760
765
  real OS runtime, the platform injects the real service.
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 }