@palettelab/cli 0.3.73 → 0.3.74
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 +36 -7
- package/docs/python-backend-sdk.md +3 -1
- package/lib/acp.js +227 -25
- package/lib/agent-client.js +56 -27
- package/lib/commands/agent.js +145 -50
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -949,7 +949,8 @@ Drive the Palette Build Agent (the App Builder's coding agent) on the selected e
|
|
|
949
949
|
```bash
|
|
950
950
|
# Change an app and follow the change to its end (CI)
|
|
951
951
|
pltt agent run --app 42 "add a CSV export"
|
|
952
|
-
pltt agent run --app 42
|
|
952
|
+
pltt agent run --app 42 --file change.md --json --timeout 900
|
|
953
|
+
git log -1 --format=%B | pltt agent run --app 42 --auto
|
|
953
954
|
|
|
954
955
|
# Follow, steer and answer a session
|
|
955
956
|
pltt agent sessions --app 42 [--archived] [--limit 50]
|
|
@@ -961,6 +962,7 @@ pltt agent permissions bas_123
|
|
|
961
962
|
pltt agent permit bas_123 per_456 reject "keep dist, it is deployed"
|
|
962
963
|
pltt agent questions bas_123
|
|
963
964
|
pltt agent answer bas_123 que_789 "Bars"
|
|
965
|
+
pltt agent ask bas_123 "which files did the export change?"
|
|
964
966
|
|
|
965
967
|
# Control and inspect it
|
|
966
968
|
pltt agent interrupt bas_123
|
|
@@ -992,8 +994,6 @@ pltt agent schedule bas_123 sch_1 pause|resume|delete
|
|
|
992
994
|
pltt agent skills
|
|
993
995
|
pltt agent models [query]
|
|
994
996
|
pltt agent mcp
|
|
995
|
-
pltt agent config
|
|
996
|
-
pltt agent plugins
|
|
997
997
|
pltt agent api GET /bas_123/context
|
|
998
998
|
|
|
999
999
|
pltt agent agents
|
|
@@ -1002,15 +1002,44 @@ pltt agent edit --app 42 "add a CSV export"
|
|
|
1002
1002
|
pltt agent init
|
|
1003
1003
|
```
|
|
1004
1004
|
|
|
1005
|
-
`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.
|
|
1005
|
+
`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. The change comes as words, from a file (`--file change.md`), or on standard input (`-`, `--file -`, or piped in with no words). Ctrl+C (SIGINT) and SIGTERM, which CI runners send when a job is cancelled, interrupt the session (even one still being found; a change queued behind another build stays queued) and exit 130 and 143; a second Ctrl+C ends the process at once. While it runs, the agent's text prints as it is written, a line at a time, and a running command shows its newest output line; a dropped connection picks up after the last event it saw. Without `--auto`, `run` is unattended: the platform denies the agent's permission asks and lets its questions go on with the agent's own assumption. With `--auto`, for unattended runs that should not stop at an ask, `run` counts as present and answers for you: each permission ask is allowed once (never always), and each question is answered with the agent's assumption at once instead of waiting. `edit --follow` does the same as `run`.
|
|
1006
1006
|
|
|
1007
|
-
`
|
|
1007
|
+
With `--json` (or `--format json`), `run` writes one JSON object per line, each with a `type`:
|
|
1008
1008
|
|
|
1009
|
-
|
|
1009
|
+
| `type` | Fields |
|
|
1010
|
+
|---|---|
|
|
1011
|
+
| `edit.sent` | the platform's answer to the change: `status` (`started`, `steered` or `queued`) and, when steered, `session_id` |
|
|
1012
|
+
| `run.following` | `session`, the build session carrying the change out, and `after`, the seq its events follow |
|
|
1013
|
+
| a session event | as the session's log has it. Durable events `{"type", "seq", "at", "data"}` come in seq order, without gaps or repeats. Live events `{"type", "live": true, "session", "data"}` are not stored, carry no `seq` and can be missed |
|
|
1014
|
+
| `run.ended` | the last line (an error instead ends the run with exit 1 and a message on stderr): `session`, `status`, `done`, `last_stop`, `summary`, `usage`, `exit_code`, and `signal` (`SIGINT` or `SIGTERM`) when a signal stopped the run |
|
|
1015
|
+
|
|
1016
|
+
The session events a script usually reads (skip any `type` it does not know, since the platform adds kinds):
|
|
1017
|
+
|
|
1018
|
+
- `text.delta` (live): `data.step`, `data.text`, the text written since the previous delta; `reasoning.delta` (live) is the same for the model's thinking. The step's whole text still comes in its `tool.called` or `text.ended`.
|
|
1019
|
+
- `tool.progress` (live): `data.id`, `data.name` and `data.tail`, a running command's newest output (at most 2 KB).
|
|
1020
|
+
- `tool.called`: `data.step`, `data.text`, `data.calls[]` (`id`, `name`); `text.ended`: `data.step`, `data.text` for a step that called no tool.
|
|
1021
|
+
- `tool.success` and `tool.failed`: `data.id`, `data.name`, `data.output`, `data.metadata`.
|
|
1022
|
+
- `step.ended`: `data.step`, `data.files[]` (`file`, `additions`, `deletions`, `status`, `patch`), `data.usage`.
|
|
1023
|
+
- `permission.asked` (`data.id`, `data.action`, `data.resource`), `question.asked` (`data.id`, `data.question`, `data.options`, `data.assumption`, `data.questions[]`) and their `permission.replied` and `question.replied`.
|
|
1024
|
+
- `retry.scheduled`: `data.attempt`, `data.seat`, `data.wait_s`, `data.next_at`.
|
|
1025
|
+
- `round.ended`: `data.status`, `data.stop`, `data.steps`, `data.usage` (`input`, `output`, `cache_read`, `cache_write`, `calls`).
|
|
1026
|
+
|
|
1027
|
+
```json
|
|
1028
|
+
{"type":"edit.sent","status":"steered","session_id":"bas_123"}
|
|
1029
|
+
{"type":"run.following","session":"bas_123","after":41}
|
|
1030
|
+
{"type":"text.delta","live":true,"session":"bas_123","data":{"step":1,"text":"Adding the export"}}
|
|
1031
|
+
{"seq":42,"type":"tool.called","at":"2026-11-13T09:00:01+00:00","data":{"step":1,"text":"Adding the export.","calls":[{"id":"call_1","name":"edit"}]}}
|
|
1032
|
+
{"seq":47,"type":"round.ended","at":"2026-11-13T09:02:10+00:00","data":{"status":"idle","stop":"done","steps":6,"usage":{"input":81200,"output":2400,"cache_read":64000,"cache_write":9000,"calls":6}}}
|
|
1033
|
+
{"type":"run.ended","session":"bas_123","status":"idle","done":true,"last_stop":"done","summary":"Added a CSV export.","usage":{"input":81200,"output":2400,"cache_read":64000,"cache_write":9000,"calls":6},"exit_code":0}
|
|
1034
|
+
```
|
|
1035
|
+
|
|
1036
|
+
`attach` is the interactive follower: it streams the log (the agent's text as it is written), 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`.
|
|
1037
|
+
|
|
1038
|
+
`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. `ask` puts a side question to a session ("which files did you change?") and prints the answer: the platform answers from the transcript, leaves the session's history as it is, and bills the session. `log` replays the durable event log and, with `--follow`, streams it until the running round ends, across dropped connections (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.
|
|
1010
1039
|
|
|
1011
1040
|
#### Use the Build Agent from an ACP editor
|
|
1012
1041
|
|
|
1013
|
-
`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
|
|
1042
|
+
`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. A prompt can carry embedded files, links and up to 6 pictures (PNG, JPEG, GIF, WebP, HEIC, HEIF or AVIF, at most about 5 MB each) beside its text; a picture past those limits becomes a note to the agent that it was left out. The session has two modes: build (the default) and plan, in which each prompt goes to the read-only plan agent as a plan request (the same as starting it with `/plan `), gets a plan back and leaves the app unchanged. Modes switch between prompts, not while one runs, and a plan prompt is refused while the agent is already working on the app, since it stays read-only only in a round of its own. The editor sees the agent's messages and thinking as they are written, tool calls with their live output and results, each step's changed files as diffs, and its plan; after each prompt it gets the turn's token usage and how full the session's context is. 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. While a prompt runs, a second prompt is refused: a message for the running turn goes through the `_session/steering` extension and reaches the agent at its next step, as an ordinary message in either mode; a steer that arrives after the round ended starts nothing, and the editor sends it as a prompt instead. `session/list` lists the app's build sessions, and `session/load` (with a replay) or `session/resume` (without) takes one up by its id (`bas_...`). In Zed's `settings.json`:
|
|
1014
1043
|
|
|
1015
1044
|
```json
|
|
1016
1045
|
{
|
|
@@ -972,7 +972,9 @@ state = await ctx.media.status(job["request_id"], model=job["model"])
|
|
|
972
972
|
hits = await ctx.web.search("palette os changelog", limit=5)
|
|
973
973
|
text = await ctx.web.fetch("https://example.com/report.pdf")
|
|
974
974
|
# render=True loads the page in a browser first, for content its scripts build
|
|
975
|
-
# late (a shop page's size table). Tens of seconds; ignored in pltt dev.
|
|
975
|
+
# late (a shop page's size table). Tens of seconds; ignored in pltt dev. Calls
|
|
976
|
+
# that arrive together wait their turn; PlatformServiceUnavailable (retry_after
|
|
977
|
+
# seconds) means the server's queue for these reads is full: try again.
|
|
976
978
|
page = await ctx.web.fetch("https://shop.example/product/123", render=True)
|
|
977
979
|
|
|
978
980
|
# Email through the platform's provider, from its sender address under the app's name.
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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: {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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 {
|
|
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
|
-
|
|
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 {
|
package/lib/agent-client.js
CHANGED
|
@@ -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
|
|
5
|
-
// session that carries it out (locate)
|
|
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))
|
|
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
|
-
|
|
71
|
-
|
|
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
|
|
126
|
-
//
|
|
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.
|
|
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
|
-
//
|
|
144
|
-
//
|
|
145
|
-
|
|
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
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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 (
|
|
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/commands/agent.js
CHANGED
|
@@ -10,15 +10,19 @@ const fs = require("fs")
|
|
|
10
10
|
const path = require("path")
|
|
11
11
|
const readline = require("readline")
|
|
12
12
|
const { once } = require("events")
|
|
13
|
-
const
|
|
13
|
+
const consumers = require("stream/consumers")
|
|
14
14
|
const { parseFlags } = require("../environments")
|
|
15
|
-
const { connect, locate, untilIdle } = require("../agent-client")
|
|
15
|
+
const { connect, locate, sessionOf, followLog, untilIdle } = require("../agent-client")
|
|
16
16
|
const { AcpServer } = require("../acp")
|
|
17
17
|
|
|
18
18
|
const USAGE = `usage:
|
|
19
|
-
pltt agent run --app <id> "<change>" [--format json|text] [--timeout <s>]
|
|
20
|
-
change a built app and follow it to the end
|
|
21
|
-
|
|
19
|
+
pltt agent run --app <id> ["<change>" | --file <path> | -] [--auto] [--format json|text] [--timeout <s>]
|
|
20
|
+
change a built app and follow it to the end; the change comes
|
|
21
|
+
as words, from a file, or on standard input (- or piped in).
|
|
22
|
+
--auto answers for nobody watching: each permission ask is
|
|
23
|
+
allowed once, each question goes on with the agent's assumption.
|
|
24
|
+
Exit 0 done, 2 stopped short, 1 error; Ctrl+C and SIGTERM
|
|
25
|
+
interrupt the session and exit 130 and 143
|
|
22
26
|
pltt agent edit --app <id> "<change>" [--follow] start a change (steers the agent when it is working)
|
|
23
27
|
pltt agent attach <session> follow live, answer permission asks and questions,
|
|
24
28
|
type to steer, /exit to leave
|
|
@@ -45,6 +49,8 @@ const USAGE = `usage:
|
|
|
45
49
|
pltt agent permit <session> <request> once|always|reject [message]
|
|
46
50
|
pltt agent questions <session> open questions
|
|
47
51
|
pltt agent answer <session> <question> "<answer>"
|
|
52
|
+
pltt agent ask <session> "<question>" a side question, answered from the session's transcript
|
|
53
|
+
(its history stays as it is; billed to the session)
|
|
48
54
|
pltt agent fork <session> [--seq <n>] [--title <t>]
|
|
49
55
|
pltt agent export <session> [--sanitize] [-o <file>]
|
|
50
56
|
pltt agent import --app <id> <file>
|
|
@@ -60,8 +66,6 @@ const USAGE = `usage:
|
|
|
60
66
|
pltt agent skills the skills a session can load (or invoke as /<skill>)
|
|
61
67
|
pltt agent models [query] the models a subagent can run on
|
|
62
68
|
pltt agent mcp the MCP servers the agent can use, with their tools
|
|
63
|
-
pltt agent config the Build Agent's effective settings
|
|
64
|
-
pltt agent plugins hook-bus plugins (changed plugin files reload)
|
|
65
69
|
pltt agent api <METHOD> <path> [json] a raw call under /api/v1/build-sessions
|
|
66
70
|
pltt agent agents the agents a session can run
|
|
67
71
|
pltt agent commands the slash commands a message can start with
|
|
@@ -186,19 +190,48 @@ function describe(event) {
|
|
|
186
190
|
}
|
|
187
191
|
}
|
|
188
192
|
|
|
193
|
+
// What `run`, `edit --follow`, `attach` and `log` print for each event. --json: every event as one line, live ones
|
|
194
|
+
// ("live": true) included. Text: describe()'s line, plus the agent's text as it streams in (text.delta), a line at a
|
|
195
|
+
// time, and a running command's newest output line (tool.progress) when it changes; a step whose text streamed in
|
|
196
|
+
// does not print it again when its text.ended arrives.
|
|
189
197
|
function printer(json, log) {
|
|
198
|
+
let partial = null // the streamed text after its last newline; null: nothing streamed in this step yet
|
|
199
|
+
let step = null // the step whose text streamed in
|
|
200
|
+
let progress = ""
|
|
190
201
|
return (event) => {
|
|
191
|
-
|
|
202
|
+
if (json) return log(JSON.stringify(event))
|
|
203
|
+
const d = event.data || {}
|
|
204
|
+
if (event.type === "text.delta") {
|
|
205
|
+
const lines = `${partial ?? "agent: "}${d.text || ""}`.split("\n")
|
|
206
|
+
partial = lines.pop()
|
|
207
|
+
lines.forEach((line) => log(line))
|
|
208
|
+
step = d.step
|
|
209
|
+
return
|
|
210
|
+
}
|
|
211
|
+
if (event.type === "tool.progress") {
|
|
212
|
+
const line = ` … ${d.name}: ${String(d.tail || "").trimEnd().split(/[\r\n]/).pop().slice(0, 160)}`
|
|
213
|
+
if (line !== progress) log((progress = line))
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
if (event.live) return // thinking (reasoning.delta), and live kinds newer than this CLI
|
|
217
|
+
if (partial !== null && (event.type === "tool.called" || event.type === "text.ended")) {
|
|
218
|
+
if (partial) log(partial)
|
|
219
|
+
const said = step === d.step
|
|
220
|
+
partial = step = null
|
|
221
|
+
if (said && event.type === "text.ended") return
|
|
222
|
+
}
|
|
223
|
+
const line = describe(event)
|
|
192
224
|
if (line) log(line)
|
|
193
225
|
}
|
|
194
226
|
}
|
|
195
227
|
|
|
196
228
|
// `log`: replay the durable log; live, stream it until the round running now ends (a round.ended in the replay is
|
|
197
|
-
// history, not the end).
|
|
229
|
+
// history, not the end), across dropped connections.
|
|
198
230
|
async function follow(client, sessionId, { after = 0, live = true, print, signal }) {
|
|
199
231
|
let last = after
|
|
200
232
|
let synced = false
|
|
201
|
-
|
|
233
|
+
const events = live ? followLog(client, sessionId, { after, signal }) : client.log(sessionId, { after, follow: false, signal })
|
|
234
|
+
for await (const event of events) {
|
|
202
235
|
if (event.type === "log.synced") {
|
|
203
236
|
if (!live) return { last: event.seq, stop: null }
|
|
204
237
|
synced = true
|
|
@@ -222,27 +255,89 @@ function promptLine(result) {
|
|
|
222
255
|
return result.running ? "[pltt] sent — the agent picks it up between two steps" : "[pltt] waiting — the session is not running now; its next round starts with it"
|
|
223
256
|
}
|
|
224
257
|
|
|
225
|
-
//
|
|
226
|
-
//
|
|
227
|
-
async function
|
|
228
|
-
const
|
|
258
|
+
// A change's text: the words given, a file (--file <path>), or standard input (`-`, `--file -`, or piped in with no
|
|
259
|
+
// words).
|
|
260
|
+
async function changeText(words, file, { cwd, stdin }) {
|
|
261
|
+
const piped = file === "-" || (!file && (words.join(" ") === "-" || (!words.length && !(stdin || process.stdin).isTTY)))
|
|
262
|
+
const text = piped ? await consumers.text(stdin || process.stdin) : file ? fs.readFileSync(path.resolve(cwd, file), "utf8") : words.join(" ")
|
|
263
|
+
if (!text.trim()) throw new Error(`no change given: pass it as words, with --file <path>, or on standard input\n${USAGE}`)
|
|
264
|
+
return text.trim()
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// --auto: nobody is there to answer, so the run does. A permission ask is allowed for that one call (never always);
|
|
268
|
+
// a question gets the agent's own assumption back at once, instead of waiting out its timer.
|
|
269
|
+
async function autoReply(client, session, event) {
|
|
270
|
+
const d = event.data || {}
|
|
271
|
+
try {
|
|
272
|
+
if (event.type === "permission.asked") await client.permit(session, d.id, "once")
|
|
273
|
+
if (event.type === "question.asked") {
|
|
274
|
+
await client.answer(session, d.id, `Unattended run: nobody can answer, so go with your assumption${d.assumption ? ` (${d.assumption})` : ""}.`)
|
|
275
|
+
}
|
|
276
|
+
} catch (err) {
|
|
277
|
+
console.error(`[pltt] could not answer ${d.id}: ${err.message}`)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// `run` (and `edit --follow`): send the change, follow its session until it is idle, exit by how it stopped. Without
|
|
282
|
+
// --auto it never attends, so the server decides each ask unattended: a permission ask is denied, a question goes on
|
|
283
|
+
// with the agent's assumption. With --auto it attends and answers them itself (autoReply). Ctrl+C (SIGINT) and
|
|
284
|
+
// SIGTERM interrupt the session and exit 130 and 143; a second one ends the process at once.
|
|
285
|
+
async function runChange(client, { app, text, json, log, timeout, auto }) {
|
|
286
|
+
const controller = new AbortController()
|
|
287
|
+
const { signal } = controller
|
|
288
|
+
const timer = setTimeout(() => controller.abort(), Math.min(timeout * 1000, 2 ** 31 - 1)) // a timer's longest delay
|
|
289
|
+
let stopped = null // the signal that stopped the run
|
|
290
|
+
const handlers = ["SIGINT", "SIGTERM"].map((name) => [name, () => {
|
|
291
|
+
stopped = stopped || name
|
|
292
|
+
controller.abort()
|
|
293
|
+
}])
|
|
294
|
+
for (const [name, handler] of handlers) process.once(name, handler)
|
|
295
|
+
const print = printer(json, log)
|
|
296
|
+
let before = []
|
|
297
|
+
let result = null
|
|
229
298
|
let session = null
|
|
299
|
+
let attending
|
|
230
300
|
let state
|
|
231
301
|
try {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
302
|
+
;({ sessions: before } = await client.sessions(app, { limit: 100 }))
|
|
303
|
+
signal.throwIfAborted() // stopped before the change was sent: nothing to interrupt
|
|
304
|
+
result = await client.edit(app, text)
|
|
305
|
+
log(json ? JSON.stringify({ type: "edit.sent", ...result }) : `[pltt] ${editLine(result)}`)
|
|
235
306
|
const found = await locate(client, app, result, before, signal)
|
|
236
307
|
session = found.session
|
|
237
|
-
|
|
238
|
-
|
|
308
|
+
log(json ? JSON.stringify({ type: "run.following", session, after: found.after }) : `[pltt] following ${session}`)
|
|
309
|
+
if (auto) {
|
|
310
|
+
const attend = () => client.attend(session).catch((err) => console.error(`[pltt] attend failed: ${err.message}`))
|
|
311
|
+
attend()
|
|
312
|
+
attending = setInterval(attend, 30_000)
|
|
313
|
+
}
|
|
314
|
+
state = await untilIdle(client, session, {
|
|
315
|
+
after: found.after,
|
|
316
|
+
signal,
|
|
317
|
+
onEvent: async (event) => {
|
|
318
|
+
print(event)
|
|
319
|
+
if (auto) await autoReply(client, session, event)
|
|
320
|
+
},
|
|
321
|
+
})
|
|
239
322
|
} catch (err) {
|
|
240
323
|
if (!signal.aborted) throw err
|
|
324
|
+
if (stopped) {
|
|
325
|
+
session = session || (await sessionOf(client, app, result, before))
|
|
326
|
+
if (session) await client.interrupt(session).catch((error) => console.error(`[pltt] interrupt failed: ${error.message}`))
|
|
327
|
+
}
|
|
241
328
|
state = session ? await client.wait(session, 1) : { status: null, done: false, last_stop: null }
|
|
329
|
+
} finally {
|
|
330
|
+
clearTimeout(timer)
|
|
331
|
+
clearInterval(attending)
|
|
332
|
+
for (const [name, handler] of handlers) process.removeListener(name, handler)
|
|
242
333
|
}
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
334
|
+
const code = stopped ? { SIGINT: 130, SIGTERM: 143 }[stopped] : exitCode(state)
|
|
335
|
+
const outcome = stopped ? `interrupted (${stopped})`
|
|
336
|
+
: !state.done ? `still running after ${timeout}s` : state.last_stop === "done" ? "done" : `stopped: ${state.last_stop}`
|
|
337
|
+
log(json
|
|
338
|
+
? JSON.stringify({ type: "run.ended", session, ...state, exit_code: code, ...(stopped ? { signal: stopped } : {}) })
|
|
339
|
+
: `[pltt] ${outcome}${state.summary ? ` — ${state.summary}` : ""}`)
|
|
340
|
+
process.exitCode = code
|
|
246
341
|
}
|
|
247
342
|
|
|
248
343
|
// What a line typed into `attach` does, given the oldest open ask (a permission ask or a question; null when none):
|
|
@@ -273,9 +368,10 @@ function askLine(ask) {
|
|
|
273
368
|
|
|
274
369
|
// `attach`: a line-mode follower. Attends (so asks wait for the owner), prompts for each open ask, and sends any other
|
|
275
370
|
// line as a steering message. Leaves on /exit or the end of input.
|
|
276
|
-
async function attach(client, sessionId, { log }) {
|
|
371
|
+
async function attach(client, sessionId, { log, json }) {
|
|
277
372
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
278
373
|
const controller = new AbortController()
|
|
374
|
+
const print = printer(json, log)
|
|
279
375
|
const asks = [] // open permission asks and questions, oldest first
|
|
280
376
|
let synced = false
|
|
281
377
|
const promptNext = () => {
|
|
@@ -305,27 +401,21 @@ async function attach(client, sessionId, { log }) {
|
|
|
305
401
|
promptNext()
|
|
306
402
|
})
|
|
307
403
|
rl.on("close", () => controller.abort())
|
|
308
|
-
let after = 0
|
|
309
404
|
try {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
if (
|
|
321
|
-
const at = asks.findIndex((ask) => ask.id === d.id)
|
|
322
|
-
if (at >= 0) asks.splice(at, 1)
|
|
323
|
-
}
|
|
324
|
-
const line = describe(event)
|
|
325
|
-
if (line) log(line)
|
|
326
|
-
if (synced && /^(permission|question)\.(asked|replied)$/.test(event.type)) promptNext()
|
|
405
|
+
for await (const event of followLog(client, sessionId, { signal: controller.signal })) {
|
|
406
|
+
if (event.type === "log.synced") {
|
|
407
|
+
synced = true
|
|
408
|
+
promptNext()
|
|
409
|
+
continue
|
|
410
|
+
}
|
|
411
|
+
const d = event.data || {}
|
|
412
|
+
if (event.type === "permission.asked" || event.type === "question.asked") asks.push({ kind: event.type.split(".")[0], ...d })
|
|
413
|
+
if (event.type === "permission.replied" || event.type === "question.replied") {
|
|
414
|
+
const at = asks.findIndex((ask) => ask.id === d.id)
|
|
415
|
+
if (at >= 0) asks.splice(at, 1)
|
|
327
416
|
}
|
|
328
|
-
|
|
417
|
+
print(event)
|
|
418
|
+
if (synced && /^(permission|question)\.(asked|replied)$/.test(event.type)) promptNext()
|
|
329
419
|
}
|
|
330
420
|
} catch (err) {
|
|
331
421
|
if (!controller.signal.aborted) throw err
|
|
@@ -371,7 +461,7 @@ function diffStat(data, log) {
|
|
|
371
461
|
log(` ${files.length} file${files.length === 1 ? "" : "s"} changed, +${data.additions} -${data.deletions}`)
|
|
372
462
|
}
|
|
373
463
|
|
|
374
|
-
async function run(argv, { cwd = process.cwd(), log = console.log } = {}) {
|
|
464
|
+
async function run(argv, { cwd = process.cwd(), log = console.log, stdin } = {}) {
|
|
375
465
|
const [sub, ...args] = argv
|
|
376
466
|
const { flags, rest } = parseFlags(args)
|
|
377
467
|
const json = flags.json
|
|
@@ -450,15 +540,19 @@ async function run(argv, { cwd = process.cwd(), log = console.log } = {}) {
|
|
|
450
540
|
const app = option(rest, "--app")
|
|
451
541
|
const format = option(rest, "--format")
|
|
452
542
|
const timeout = option(rest, "--timeout")
|
|
543
|
+
const file = option(rest, "--file")
|
|
544
|
+
const auto = flag(rest, "--auto")
|
|
453
545
|
const followIt = flag(rest, "--follow") || sub === "run"
|
|
454
|
-
need(app
|
|
455
|
-
const text = rest
|
|
456
|
-
if (followIt)
|
|
546
|
+
need(app)
|
|
547
|
+
const text = await changeText(rest, file, { cwd, stdin })
|
|
548
|
+
if (followIt) {
|
|
549
|
+
return runChange(client, { app, text, json: json || format === "json", log, timeout: timeout ? positiveInt(timeout, "--timeout") : 1800, auto })
|
|
550
|
+
}
|
|
457
551
|
return out(await client.edit(app, text), (result) => log(`[pltt] ${editLine(result)}`))
|
|
458
552
|
}
|
|
459
553
|
case "attach":
|
|
460
554
|
need(id)
|
|
461
|
-
return attach(client, id, { log })
|
|
555
|
+
return attach(client, id, { log, json })
|
|
462
556
|
case "acp": {
|
|
463
557
|
const app = option(rest, "--app")
|
|
464
558
|
need(app)
|
|
@@ -555,6 +649,9 @@ async function run(argv, { cwd = process.cwd(), log = console.log } = {}) {
|
|
|
555
649
|
case "answer":
|
|
556
650
|
need(id, words[0], words[1])
|
|
557
651
|
return out(await client.answer(id, words[0], words.slice(1).join(" ")), () => log(`[pltt] answered ${words[0]}`))
|
|
652
|
+
case "ask":
|
|
653
|
+
need(id, words[0])
|
|
654
|
+
return out(await client.ask(id, words.join(" ")), (r) => log(r.answer))
|
|
558
655
|
case "fork": {
|
|
559
656
|
const seq = option(rest, "--seq")
|
|
560
657
|
const title = option(rest, "--title")
|
|
@@ -637,10 +734,8 @@ async function run(argv, { cwd = process.cwd(), log = console.log } = {}) {
|
|
|
637
734
|
? data.servers.forEach((m) => log(`${m.name}: ${m.error ? `unavailable (${m.error})` : `${(m.tools || []).length} tools, ${(m.resources || []).length} resources, ${(m.prompts || []).length} prompts`}`))
|
|
638
735
|
: log("[pltt] no MCP servers are configured"))
|
|
639
736
|
case "config":
|
|
640
|
-
return out(await client.config(), (data) => Object.entries(data.config).forEach(([k, v]) => log(`${k.padEnd(20)} ${JSON.stringify(v)}`)))
|
|
641
737
|
case "plugins":
|
|
642
|
-
|
|
643
|
-
data.plugins.forEach((p) => log(`${p.name.padEnd(20)} ${(p.points || []).join(", ") || "-"}${p.error ? ` ERROR ${p.error}` : ""}`)))
|
|
738
|
+
throw new Error(`the Build Agent's ${sub === "config" ? "settings" : "plugins"} are for platform operators (the superadmin console's Build Agent tab)`)
|
|
644
739
|
case "api": {
|
|
645
740
|
const [method, route, body] = rest
|
|
646
741
|
need(method, route)
|