@palettelab/cli 0.3.70 → 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 +103 -0
- package/backend-sdk/palette_sdk/__init__.py +3 -2
- package/backend-sdk/palette_sdk/jobs.py +18 -0
- package/backend-sdk/pyproject.toml +1 -1
- package/lib/acp.js +267 -0
- package/lib/agent-client.js +176 -0
- package/lib/cli.js +8 -1
- package/lib/commands/agent.js +763 -0
- package/lib/commands/check.js +106 -0
- package/package.json +1 -1
- package/template-fallback/package.json +1 -1
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/provider-app/package.json +1 -1
package/README.md
CHANGED
|
@@ -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.
|
|
@@ -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.
|
|
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",
|
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,176 @@
|
|
|
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
|
+
terminals(id) { return this.request("GET", `/${q(id)}/terminals`) }
|
|
111
|
+
openTerminal(id, { cols, rows, title } = {}) { return this.request("POST", `/${q(id)}/terminals`, { cols, rows, title }) }
|
|
112
|
+
readTerminal(id, lines = 100) { return this.request("GET", `/${q(id)}/terminals/read?lines=${lines}`) }
|
|
113
|
+
closeTerminal(id, terminal) { return this.request("DELETE", `/${q(id)}/terminals/${q(terminal)}`) }
|
|
114
|
+
terminalTicket(id, terminal) { return this.request("POST", `/${q(id)}/terminals/${q(terminal)}/ticket`) }
|
|
115
|
+
// The terminal's WebSocket, authorised by a one-use ticket (a WebSocket cannot carry the token header).
|
|
116
|
+
terminalUrl(id, terminal, ticket, after = "0") {
|
|
117
|
+
return `${this.base.replace(/^http/, "ws")}/${q(id)}/terminals/${q(terminal)}/connect?ticket=${q(ticket)}&after=${q(after)}`
|
|
118
|
+
}
|
|
119
|
+
// A raw call under /build-sessions, for scripting what has no subcommand.
|
|
120
|
+
raw(method, route, body) { return this.request(method.toUpperCase(), route.startsWith("/") || route.startsWith("?") ? route : `/${route}`, body) }
|
|
121
|
+
answer(id, question, answer) { return this.request("POST", `/${q(id)}/questions/${q(question)}`, { answer }) }
|
|
122
|
+
log(id, { after = 0, follow = true, signal } = {}) {
|
|
123
|
+
return this.events(`/${q(id)}/log?after=${after}&follow=${follow}`, { signal })
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function connect(cwd, flags) {
|
|
128
|
+
const env = resolveEnvironment({ cwd, flags })
|
|
129
|
+
if (!env.token) throw new Error(`no token for "${env.name}" — run pltt login or set $${env.token_env}`)
|
|
130
|
+
return new AgentClient(env)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// The root session that carries out a change just sent (`result` of an edit or a prompt) and the seq its new events
|
|
134
|
+
// start after. `before` lists the app's sessions from just before it was sent: a queued change, and an edit that
|
|
135
|
+
// started a build, run in a session that is not among them yet.
|
|
136
|
+
async function locate(client, app, result, before, signal) {
|
|
137
|
+
const seq = (id) => (before.find((s) => s.id === id) || {}).last_seq || 0
|
|
138
|
+
const target = result.status !== "queued" && result.session_id
|
|
139
|
+
if (target) {
|
|
140
|
+
const root = (before.find((s) => s.id === target) || {}).parent_id || target
|
|
141
|
+
return { session: root, after: seq(root) }
|
|
142
|
+
}
|
|
143
|
+
const seen = new Set(before.map((s) => s.id))
|
|
144
|
+
for (;;) {
|
|
145
|
+
const { sessions } = await client.sessions(app, { limit: 20 })
|
|
146
|
+
const found = sessions.find((s) => !s.parent_id && (result.status === "steered" || !seen.has(s.id)))
|
|
147
|
+
if (found) return { session: found.id, after: seq(found.id) }
|
|
148
|
+
await sleep(2000, undefined, { signal })
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Follow a session's log from `after` until a round of it ends and GET wait finds the session idle (an edit runs a
|
|
153
|
+
// plan round, then its build round, in the same session); a dropped stream reconnects. Resolves with wait's answer.
|
|
154
|
+
async function untilIdle(client, id, { after = 0, signal, onEvent }) {
|
|
155
|
+
for (;;) {
|
|
156
|
+
let ended = false
|
|
157
|
+
for await (const event of client.log(id, { after, follow: true, signal })) {
|
|
158
|
+
if (event.type === "log.synced") continue
|
|
159
|
+
after = event.seq ?? after
|
|
160
|
+
await onEvent(event)
|
|
161
|
+
if (event.type === "round.ended" && (event.data || {}).status !== "busy") {
|
|
162
|
+
ended = true
|
|
163
|
+
break
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// ponytail: a round that starts after wait read the session idle (the gap between an edit's rounds) ends this
|
|
167
|
+
// early; an "edit finished" event from the server would close that gap.
|
|
168
|
+
if (!ended) await sleep(1000, undefined, { signal })
|
|
169
|
+
else {
|
|
170
|
+
const state = await client.wait(id, 1)
|
|
171
|
+
if (state.done) return state
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
module.exports = { AgentClient, connect, locate, untilIdle, mintId }
|
package/lib/cli.js
CHANGED
|
@@ -19,6 +19,8 @@ const capabilities = require("./commands/capabilities")
|
|
|
19
19
|
const connections = require("./commands/connections")
|
|
20
20
|
const platform = require("./commands/platform")
|
|
21
21
|
const models = require("./commands/models")
|
|
22
|
+
const agent = require("./commands/agent")
|
|
23
|
+
const check = require("./commands/check")
|
|
22
24
|
|
|
23
25
|
const COMMANDS = {
|
|
24
26
|
init: { run: init, help: "Scaffold a new plugin directory from the template" },
|
|
@@ -41,6 +43,7 @@ const COMMANDS = {
|
|
|
41
43
|
},
|
|
42
44
|
build: { run: build, help: "Validate palette-plugin.json and check entry points exist" },
|
|
43
45
|
test: { run: test, help: "Run local plugin contract checks before publishing" },
|
|
46
|
+
check: { run: check, help: "The checks of pltt test as diagnostics (id, file, line, fix) for agents and editors" },
|
|
44
47
|
package: { run: pkg, help: "Bundle the plugin into a tar.gz under dist/ (no upload)" },
|
|
45
48
|
publish: {
|
|
46
49
|
run: publish,
|
|
@@ -86,6 +89,10 @@ const COMMANDS = {
|
|
|
86
89
|
run: capabilities,
|
|
87
90
|
help: "Add, list, or inspect agent-callable app capabilities",
|
|
88
91
|
},
|
|
92
|
+
agent: {
|
|
93
|
+
run: agent,
|
|
94
|
+
help: "Drive the hosted Build Agent: run a change to its end, attach, steer, diff, fork, export, ACP server (pltt agent help)",
|
|
95
|
+
},
|
|
89
96
|
version: { run: version, help: "Show the installed pltt CLI version" },
|
|
90
97
|
update: { run: update, help: "Update the globally installed pltt CLI" },
|
|
91
98
|
}
|
|
@@ -98,7 +105,7 @@ function printHelp() {
|
|
|
98
105
|
console.log(` ${name.padEnd(12)} ${help}`)
|
|
99
106
|
}
|
|
100
107
|
console.log("\nGlobal flags:")
|
|
101
|
-
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, update, version, login, dev --sandbox, platform, models, services, capabilities)")
|
|
108
|
+
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, check, update, version, login, dev --sandbox, platform, models, services, capabilities)")
|
|
102
109
|
console.log(" -v, --version Show the installed pltt CLI version")
|
|
103
110
|
console.log("\nPublish flags:")
|
|
104
111
|
console.log(" --env <name> Target environment from ~/.palette/config.json (default: local)")
|