@penguinharness/agent-development 0.2.16 → 0.2.18
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/package.json +8 -1
- package/skills/penguin-orchestration/SKILL.md +2 -2
- package/skills/penguin-plugin/SKILL.md +84 -7
- package/skills/penguin-plugin/scripts/check.mjs +112 -6
- package/skills/penguin-sdk/SKILL.md +7 -6
- package/skills/penguin-sdk/reference/agent-api.md +33 -24
- package/skills/unified-llm-api/SKILL.md +5 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@penguinharness/agent-development",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.18",
|
|
4
4
|
"description": "Agent development on PenguinHarness: initialize agents from a requirement, build agent apps on the SDK or connect them to an agent over the Agent API, build workbenches (the pages beside the chat an agent keeps for itself), call any model through one unified LLM API, manage models and secrets, and orchestrate agents, sessions, costs and schedules.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"penguin-plugin",
|
|
@@ -37,5 +37,12 @@
|
|
|
37
37
|
},
|
|
38
38
|
"title": "Agent Development",
|
|
39
39
|
"title_zh": "智能体开发"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"vitest": "^4.1.12",
|
|
43
|
+
"@prismshadow/skills": "0.2.18"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"test": "vitest run"
|
|
40
47
|
}
|
|
41
48
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: penguin-orchestration
|
|
3
3
|
description: Drive PenguinHarness itself from a shell — list and create agents and sessions, send and steer messages mid-flight, and query costs and scheduled tasks via the penguin CLI over the local server.
|
|
4
|
-
version: 2026.10.
|
|
4
|
+
version: 2026.10.15.1
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Penguin Orchestration
|
|
@@ -130,7 +130,7 @@ penguin schedule update daily-report --period 12h # adjust; --enable/--disabl
|
|
|
130
130
|
penguin schedule rm daily-report # remove — no confirmation prompt
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
-
- `--agent-id` defaults to yourself from the caller env, so this schedules the current agent. `--start-at` takes ISO 8601 or `now`; `--period` is at least 5m (`30m`/`12h`/`1d`/`7d`), omit it for a one-shot; `--end-at` bounds recurrence. Target the session you are in — `--session-id "$PENGUIN_SESSION_ID"` — unless the user asked for somewhere else: the prompt then arrives in this conversation, with its context. Leave the target off when the user wants a separate session, or when the task is better off starting clean (a nightly report that should not inherit this conversation); each firing then opens a new session, which `--workspace <path>` and the `--model-id` + `--provider` pair configure.
|
|
133
|
+
- `--agent-id` defaults to yourself from the caller env, so this schedules the current agent. `--start-at` takes ISO 8601 or `now`; `--period` is at least 5m (`30m`/`12h`/`1d`/`7d`), omit it for a one-shot, which needs a future `--start-at` (`now` is refused there); `--end-at` bounds recurrence. Target the session you are in — `--session-id "$PENGUIN_SESSION_ID"` — unless the user asked for somewhere else: the prompt then arrives in this conversation, with its context. Leave the target off when the user wants a separate session, or when the task is better off starting clean (a nightly report that should not inherit this conversation); each firing then opens a new session, which `--workspace <path>` and the `--model-id` + `--provider` pair configure.
|
|
134
134
|
- `add` creates the schedule **enabled** (`--disabled` stages it off) — deliberately diverging from the raw file, where `enabled` defaults to false. `update` is read-modify-write: unspecified fields keep their stored values, and switching the target form clears the other one.
|
|
135
135
|
- In `schedule ls`, read: the AGENT column (without `--agent-id` the listing spans agents), `enabled` (a disabled entry never fires), `startAt` (first firing), `period` (absent means one-shot), the target — an existing session versus a new session per firing — and `lastFiredAt`.
|
|
136
136
|
- The CLI writes through the schedules API, so mistakes are rejected synchronously. The TOML file stays the single source of truth — `<app_data_dir>/agents/<agent_id>/agent_state/schedule/<name>.toml`, fields mirroring the flags (`prompt`, `enabled` — false by default in the file, `start_at`, `period`, `end_at`, `session_id` / `workspace`+`provider`+`model_id`) — and remains editable with file tools; your system prompt's schedule roster lists yours. A hand edit is only validated by the periodic reconcile (roughly every 30s), with errors landing in error records rather than your terminal — prefer the CLI.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: penguin-plugin
|
|
3
3
|
description: Use for workbenches — the tabs and pages beside the chat, with server code behind them, that an Agent keeps in its own `workbenches/` folder inside PenguinHarness — building one, changing it, showing it as the whole app, restoring an earlier version, and removing a tab or a whole workbench when the user wants the custom UI gone.
|
|
4
|
-
version: 2026.10.
|
|
4
|
+
version: 2026.10.26.1
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Agent Workbench with Penguin Plugins
|
|
@@ -37,11 +37,87 @@ Use this pattern for uploads, research and support tickets:
|
|
|
37
37
|
|
|
38
38
|
- On POST, validate input, create a Session and persist a job containing its `sessionId` and `status: "running"` with `host.setState`. Start the turn and return the job immediately. Catch launch failures and persist `failed`.
|
|
39
39
|
- On GET, for each running job call `host.sessionResult(sessionId)`. Leave `running` jobs alone. Persist `completed` plus the returned text, or `failed` plus the error. Never mark a running snapshot failed because its text is empty.
|
|
40
|
-
- Let the page poll GET every few seconds while visible. Reopening the tab or reloading code resumes from persisted session ids. Do not keep the only job state in a detached promise or a timer that disappears on reload.
|
|
40
|
+
- Let the page poll GET every few seconds while visible; to show the answer as it is written, follow the Session too (*Follow the Agent live*). Reopening the tab or reloading code resumes from persisted session ids. Do not keep the only job state in a detached promise or a timer that disappears on reload.
|
|
41
41
|
- For text reports, ask the Agent to put the complete report in its **final answer**; store that returned text and serve it with a download content type and `Content-Disposition: attachment`. Link directly to the same-origin report route with an `<a download>`; avoid fetching a Blob and clicking an object URL, which did not download in the embedded browser. Verify the saved file, not a toast saying it started. No Trace parsing or cross-workspace report-file probe is needed.
|
|
42
42
|
- `host.getState()` is synchronous, `unknown`, initially `null`. Clone before editing; serialize read/modify/write handlers to avoid lost updates. Await `host.setState` before returning success.
|
|
43
43
|
- Store large upload bytes outside the watched source folder, e.g. the target Agent's `scratchpad/<workbench_id>/uploads/`. Keep metadata in host state. Source changes trigger reloads; runtime files in `workbenches/<id>/` trigger needless rebuilds and enter version history. `import.meta.url` points into `.build/<revision>/`, not the source root.
|
|
44
44
|
|
|
45
|
+
## Follow the Agent live (AMSP)
|
|
46
|
+
|
|
47
|
+
Polling shows a job only once it is done. To show the answer while the Agent writes it, and to learn the moment a turn ends, follow the job's Session over AMSP: the records its Trace holds plus the streamed fragments, the same ones the chat view reads. AMSP carries the Agent's conversation and nothing else. Starting a turn, follow-ups, saving results and every other side effect stay in your handler.
|
|
48
|
+
|
|
49
|
+
**The page** imports the page SDK the server serves beside your workbench, relative to the page just like `../api/…`: `../sdk/workbench.js` from a page directly under `ui/`, one more `../` for each folder deeper:
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
let reader = null;
|
|
53
|
+
|
|
54
|
+
async function openItem(item) {
|
|
55
|
+
if (item.status !== "running") return;
|
|
56
|
+
let sdk;
|
|
57
|
+
try {
|
|
58
|
+
sdk = await import("../sdk/workbench.js");
|
|
59
|
+
} catch {
|
|
60
|
+
return startPolling(); // an older server has no page SDK: keep polling GET
|
|
61
|
+
}
|
|
62
|
+
let draft = "";
|
|
63
|
+
reader = sdk.followSession(item.sessionId, { tailLimit: 1 });
|
|
64
|
+
reader.on("event", ({ record }) => {
|
|
65
|
+
if (record.origin) return; // a subagent's record, not the main conversation
|
|
66
|
+
const p = record.payload;
|
|
67
|
+
if (p.type === "request_begin") draft = "";
|
|
68
|
+
if (p.type === "partial_text") showDraft((draft += p.text));
|
|
69
|
+
if (p.type === "tool_call") showActivity(p.name);
|
|
70
|
+
if (p.type === "task_end") refresh(); // the saved answer replaces the draft
|
|
71
|
+
});
|
|
72
|
+
reader.on("reset", () => showDraft((draft = "")));
|
|
73
|
+
stopButton.onclick = () => sdk.abortSession(item.sessionId);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function closeItem() {
|
|
77
|
+
reader?.close();
|
|
78
|
+
reader = null;
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- Open one reader for the item on screen (its dialog or detail view), never one per list row: each reader holds a connection, and a browser allows only a few per origin. Close it when the dialog closes and when the page is hidden (`visibilitychange`).
|
|
83
|
+
- `followSession(sessionId, options?)` returns the SDK's `SessionReader` on the Session's stream, taking `tailLimit` and the reader's other options: it reads the latest Tasks of the history (events with `source: "history"`), then the live tail, and reconnects on its own. On `reset`, drop what you drew; the history follows again. Records of subagents come through with an `origin`; skip them yourself.
|
|
84
|
+
- `task_end` is a hint, not the result: on it, refresh from your handler, whose saved answer is what stays. Keep the polling path from *Background jobs* as the fallback for a failed import, and keep the list itself on (slower) polling.
|
|
85
|
+
- `abortSession(sessionId)` stops the running task, for a Stop button, and resolves `true` when there was one to stop, `false` when nothing was running.
|
|
86
|
+
- `workbench.js` re-exports everything `@prismshadow/amsp` does, plus `apiBase` and `transport` for other reads of the signed-in user's door. Never write an absolute `/api/…` path into a page: a workbench on a machine is served under `/server/<machine>/api/…`, a reverse proxy may add a prefix of its own, and `apiBase` already says which.
|
|
87
|
+
|
|
88
|
+
**The handler** gets the same records from `host.subscribe(sessionId, listener)`, which returns the function that stops them. It is live only: nothing from before the call, no history, so subscribe before `host.run`. A record is a `WorkbenchRecord` (`{ timestamp, type, payload: { type?, … }, origin? }`, from `@prismshadow/penguin-server/plugin`). Treat it as a trigger and keep `await host.sessionResult(sessionId)` as the authoritative snapshot:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
create({ use }) {
|
|
92
|
+
const host = use.host;
|
|
93
|
+
const watching = new Map<string, () => void>();
|
|
94
|
+
const watch = (sessionId: string) => {
|
|
95
|
+
if (watching.has(sessionId)) return;
|
|
96
|
+
const stop = host.subscribe(sessionId, (record) => {
|
|
97
|
+
if (record.origin || record.payload.type !== "task_end") return;
|
|
98
|
+
void settleWhenIdle(sessionId).then((done) => {
|
|
99
|
+
if (!done) return; // a queued follow-up started: wait for its task_end
|
|
100
|
+
stop();
|
|
101
|
+
watching.delete(sessionId);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
watching.set(sessionId, stop);
|
|
105
|
+
};
|
|
106
|
+
// create runs again whenever the workbench loads, and a reload ends every subscription.
|
|
107
|
+
for (const job of runningJobs(host.getState())) watch(job.sessionId);
|
|
108
|
+
// …and call watch(sessionId) before host.run, when a job starts and on every follow-up.
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
- The main `task_end` arrives a moment before the Session reads idle, and until then `sessionResult` still says `running`. So `settleWhenIdle` waits a little for `host.sessionStatus(sessionId)` to read `idle`, then reads `sessionResult` and saves `completed` or `failed` with `host.setState` under the same read/modify/write lock as your routes. If the Session stays busy, a queued follow-up has started: return `false` and keep watching.
|
|
113
|
+
- Keep the GET-time reconcile from *Background jobs*. Nothing is replayed: subscriptions end with a reload, a rollback, removal or a server restart (and `create` runs again only when the workbench next loads), and on their own once the Session has sat idle with nothing published for a while.
|
|
114
|
+
- A listener that throws is logged once and keeps receiving. A Session outside this Project throws at `subscribe`.
|
|
115
|
+
- If `.harness/plugin.d.ts` has no `subscribe`, the workbench was written against an older harness: delete `.harness/` and let the server write it again, then fix what the compiler reports.
|
|
116
|
+
|
|
117
|
+
Never reach the Agent from a workbench through the Agent API: not `/api/amsp/v1`, not an Agent key, not the Agent's API switch or the key door. That door needs the owner to open the Agent, refuses the Sessions a workbench creates, and a key in a page is readable by everyone who opens it. The page SDK reads the signed-in user's own door, which needs nothing.
|
|
118
|
+
|
|
119
|
+
To see what a page will see, start a turn through your handler and run `node "<this skill directory>/scripts/check.mjs" --follow <sessionId>`: it prints the Session's records as they arrive, one JSON line each, until the main conversation's `task_end` or for a minute at most.
|
|
120
|
+
|
|
45
121
|
## Layout
|
|
46
122
|
|
|
47
123
|
Layout, under `<root>/<project_id>/agents/<agent_id>/workbenches/<workbench_id>/` (beside `agent_state/`):
|
|
@@ -135,8 +211,9 @@ page of complete answers.
|
|
|
135
211
|
- Show submission and generation progress immediately, prevent duplicate submits, and keep a
|
|
136
212
|
retry path for failures. For a long task, show elapsed time and optionally a clearly approximate
|
|
137
213
|
remaining-time estimate; if the estimate runs out, say it is still processing instead of claiming
|
|
138
|
-
completion.
|
|
139
|
-
|
|
214
|
+
completion. Better still, show the answer as the Agent writes it and what it is doing
|
|
215
|
+
(*Follow the Agent live*), with a Stop button. Preserve the question on failure. Do not hide
|
|
216
|
+
useful actions behind an indefinite loading screen.
|
|
140
217
|
- Keep the code small: separate UI, styles and handler logic, reuse the host's theme variables,
|
|
141
218
|
and prefer native controls before adding dependencies. Use real empty, loading and error states;
|
|
142
219
|
never leave blank alert boxes or display internal errors as a successful answer.
|
|
@@ -162,11 +239,11 @@ Each entry under `WebModule.sessionTabs` is one tab beside the chat: `key` (uniq
|
|
|
162
239
|
|
|
163
240
|
## The host
|
|
164
241
|
|
|
165
|
-
`WorkbenchHost` (published as module `Host`) speaks the SDK's verbs, scoped to the workbench's Project: `listAgents()` returns the Project's Agents as `{ agentId }[]`; `createSession({ agentId? })` opens a Session of this Agent — or of another Agent of the same Project — and returns `{ sessionId }`. These Sessions carry source `workbench` and are automatically archived from the main chat sidebar; your list still reads and runs them through the host. `sessionTitle(sessionId)` returns the current generated title (or `null` before one exists); `run(sessionId, [{ text: "…" }])` — the SDK's `session.run`, its input items spelled out because a workbench has no package to import `userText` from — runs one turn in a Session, new or existing, and returns `{ sessionId, queued }` once it has started (a busy Session queues it as a follow-up; the Agent hears it as a message from the server, not from a person); `sessionStatus(sessionId)` says `idle` / `running` / …; `await sessionResult(sessionId)` returns a snapshot of the latest task (see *Background jobs*); `getState()` / `setState(doc)` over `state.json` (`getState()` is `unknown`: narrow it); `log(text)`. More modules may be listed in `penguin.modules` and named as `children` of `Workbench`, with their own `requires` between them — the tree is checked as a whole.
|
|
242
|
+
`WorkbenchHost` (published as module `Host`) speaks the SDK's verbs, scoped to the workbench's Project: `listAgents()` returns the Project's Agents as `{ agentId }[]`; `createSession({ agentId? })` opens a Session of this Agent — or of another Agent of the same Project — and returns `{ sessionId }`. These Sessions carry source `workbench` and are automatically archived from the main chat sidebar; your list still reads and runs them through the host. `sessionTitle(sessionId)` returns the current generated title (or `null` before one exists); `run(sessionId, [{ text: "…" }])` — the SDK's `session.run`, its input items spelled out because a workbench has no package to import `userText` from — runs one turn in a Session, new or existing, and returns `{ sessionId, queued }` once it has started (a busy Session queues it as a follow-up; the Agent hears it as a message from the server, not from a person); `sessionStatus(sessionId)` says `idle` / `running` / …; `await sessionResult(sessionId)` returns a snapshot of the latest task (see *Background jobs*); `subscribe(sessionId, listener)` hands the listener the Session's AMSP records as they are written, live only, and returns the function that stops it (see *Follow the Agent live*); `getState()` / `setState(doc)` over `state.json` (`getState()` is `unknown`: narrow it); `log(text)`. More modules may be listed in `penguin.modules` and named as `children` of `Workbench`, with their own `requires` between them — the tree is checked as a whole.
|
|
166
243
|
|
|
167
244
|
## HTTP
|
|
168
245
|
|
|
169
|
-
HTTP, all under `/api/projects/:projectId/agents/:agentId/workbenches` (Project members only): `GET /` lists the workbenches with their `revision`, `uiRev`, `tabs` (each page's URL resolved) and current load `error`; `GET /:id/ui/*` serves a file of `ui/` (there is no default document — a tab names its page); any method on `/:id/api/*` reaches `handle` — JSON by default in both directions (`req.body` parsed, `{ status?, body? }` answered as JSON), and anything else when you say so: a non-JSON request body arrives as `req.bytes` (a `Uint8Array`; `req.headers` has its `content-type`, never the app's cookie), and a response that names a `content-type` in `headers` sends `body` as the string you wrote, or `bytes` for binary, or `stream` — an async iterable (an `async function*`) of strings or `Uint8Array`s, each chunk written to the client as you yield it, which is how server-sent events and a model's token-by-token answer get through without waiting for the end (relay an upstream stream by yielding its chunks; a `finally` in the generator runs when the client goes away — though a generator parked inside an `await` only gets there once that await settles, so give a relay its own timeout rather than trusting the disconnect) — with `location` + a 3xx status for a redirect. That is how a handler serves a page it renders, an upload, a download, or the pages of a program it runs on this machine: fetch `http://127.0.0.1:<port>/…` from the HANDLER and return what came back — never put `127.0.0.1` in a page, because the page runs in the user's browser, which may be on another machine than you are; `POST /:id/reload`; `GET /:id/history` lists recorded versions; `POST /:id/rollback { revision }` restores one (code only — `state.json` stays) and reloads. `DELETE /:id` removes the workbench together with its recorded versions. From a page directly under `ui/`, call your handler with a relative `fetch("../api/…")`; the Web App shows each page in its tab and reloads it when `uiRev` changes.
|
|
246
|
+
HTTP, all under `/api/projects/:projectId/agents/:agentId/workbenches` (Project members only): `GET /` lists the workbenches with their `revision`, `uiRev`, `tabs` (each page's URL resolved) and current load `error`; `GET /:id/ui/*` serves a file of `ui/` (there is no default document — a tab names its page); any method on `/:id/api/*` reaches `handle` — JSON by default in both directions (`req.body` parsed, `{ status?, body? }` answered as JSON), and anything else when you say so: a non-JSON request body arrives as `req.bytes` (a `Uint8Array`; `req.headers` has its `content-type`, never the app's cookie), and a response that names a `content-type` in `headers` sends `body` as the string you wrote, or `bytes` for binary, or `stream` — an async iterable (an `async function*`) of strings or `Uint8Array`s, each chunk written to the client as you yield it, which is how server-sent events and a model's token-by-token answer get through without waiting for the end (relay an upstream stream by yielding its chunks; a `finally` in the generator runs when the client goes away — though a generator parked inside an `await` only gets there once that await settles, so give a relay its own timeout rather than trusting the disconnect) — with `location` + a 3xx status for a redirect. That is how a handler serves a page it renders, an upload, a download, or the pages of a program it runs on this machine: fetch `http://127.0.0.1:<port>/…` from the HANDLER and return what came back — never put `127.0.0.1` in a page, because the page runs in the user's browser, which may be on another machine than you are; `GET /:id/sdk/workbench.js` and `GET /:id/sdk/amsp.js` serve the page SDK (the `@prismshadow/amsp` browser build of the server answering, see *Follow the Agent live*); `POST /:id/reload`; `GET /:id/history` lists recorded versions; `POST /:id/rollback { revision }` restores one (code only — `state.json` stays) and reloads. `DELETE /:id` removes the workbench together with its recorded versions. From a page directly under `ui/`, call your handler with a relative `fetch("../api/…")` and import the page SDK with `import("../sdk/workbench.js")`; the Web App shows each page in its tab and reloads it when `uiRev` changes.
|
|
170
247
|
|
|
171
248
|
## Undoing, reverting, removing (撤销 / 还原 / 清掉界面)
|
|
172
249
|
|
|
@@ -183,7 +260,7 @@ Your handler's responses are served from the app's own origin, so anything you e
|
|
|
183
260
|
|
|
184
261
|
## Theme
|
|
185
262
|
|
|
186
|
-
A workbench page is a separate document, so it inherits nothing from the app's stylesheet by itself. The Web App stamps
|
|
263
|
+
A workbench page is a separate document, so it inherits nothing from the app's stylesheet by itself. The Web App stamps the app's look onto the page's root on every load and every appearance change: `light`/`dark`, `data-theme` (`modern`, `geek` or `github`), `data-accent` (only when the theme paints that accent), `data-font-latin` and `data-font-cjk`, the root font size, every `--ui-*` token of the app's token contract resolved as an inline style, and the app's bundled fonts. It injects `/workbench-ui.css` first in the head: a base stylesheet that styles plain HTML (headings, lists, forms, tables, code) to match the app and exposes `--wb-bg`, `--wb-surface`, `--wb-fg`, `--wb-muted`, `--wb-border`, `--wb-hover`, `--wb-accent`, `--wb-accent-fg`, `--wb-radius` (a box radius, not a pill), `--wb-font`, `--wb-mono`, the tone colours `--wb-tone-<tone>-fg`, `-bg` and `-line`, plus the classes `wb-primary` (a button), `wb-card`, `wb-rows`, `wb-row`, `wb-muted` and `wb-badge`, a status pill coloured by `data-tone` (`neutral` without one). Pick the tone the way the app does: there is no busy tone, so a running item is `success` with the word "Running", waiting or queued is `attention`, failed is `danger`, and finished is `done` or `neutral`, e.g. `<span class="wb-badge" data-tone="done">Resolved</span>`. Write plain markup, take every colour and font from those variables, and the page follows the user through every theme, accent, font and light/dark change; hardcode them and it clashes in one theme or another. The `--wb-*` names are only ever added to, never renamed. The `--ui-*` tokens underneath are readable too, but they follow the app's token contract and can be renamed with it, and as inline styles on the root no stylesheet of yours overrides them: to restyle, redeclare `--wb-*` on `:root`. The page's own rules always win over `/workbench-ui.css`, and linking `/workbench-ui.css` yourself makes it look right when opened outside the app too.
|
|
187
264
|
|
|
188
265
|
Keep empty alerts hidden. A component rule such as `.notice { display: flex }` overrides the browser's default `[hidden]` styling; the shared stylesheet preserves `[hidden]`, and standalone custom CSS should do the same. Check both empty and populated states.
|
|
189
266
|
|
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Activate the target Agent's watcher and report this server's actual load result
|
|
2
|
+
// Activate the target Agent's watcher and report this server's actual load result, or, with
|
|
3
|
+
// --follow, print a Session's records as a workbench page would receive them.
|
|
3
4
|
import http from "node:http";
|
|
4
5
|
import https from "node:https";
|
|
5
6
|
|
|
6
|
-
const
|
|
7
|
+
const args = process.argv.slice(2);
|
|
8
|
+
const following = args[0] === "--follow";
|
|
9
|
+
const [agentId, workbenchId] = following ? [] : args;
|
|
10
|
+
const sessionId = following ? args[1] : undefined;
|
|
7
11
|
const {
|
|
8
12
|
PENGUIN_API_URL: base,
|
|
9
13
|
PENGUIN_API_TOKEN: token,
|
|
10
14
|
PENGUIN_PROJECT_ID: project,
|
|
11
15
|
} = process.env;
|
|
12
|
-
if (!base || !token || !project || !agentId || !workbenchId) {
|
|
16
|
+
if (!base || !token || (following ? !sessionId : !project || !agentId || !workbenchId)) {
|
|
13
17
|
console.error(
|
|
14
|
-
"Usage: node check.mjs <agent_id> <workbench_id
|
|
18
|
+
"Usage: node check.mjs <agent_id> <workbench_id>, or node check.mjs --follow <session_id>, inside a PenguinHarness Session. Requires its injected PENGUIN_API_URL, PENGUIN_API_TOKEN and PENGUIN_PROJECT_ID. Do not search for another server or credentials.",
|
|
15
19
|
);
|
|
16
20
|
process.exit(1);
|
|
17
21
|
}
|
|
22
|
+
/** How long --follow waits for the main conversation's task_end. */
|
|
23
|
+
const FOLLOW_LIMIT_MS = 60_000;
|
|
18
24
|
async function readJson(route) {
|
|
19
25
|
const url = new URL(route, base);
|
|
20
26
|
// Direct to the injected server; shell proxies must not redirect loopback requests.
|
|
@@ -52,7 +58,104 @@ async function readJson(route) {
|
|
|
52
58
|
req.on("error", reject);
|
|
53
59
|
});
|
|
54
60
|
}
|
|
55
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Reads the Session's AMSP stream through the signed-in user's door, the one a workbench page
|
|
63
|
+
* reads, and prints each record as one JSON line. Live only: it shows what is written from now.
|
|
64
|
+
* Resolves the exit code: 0 at the main conversation's task_end, or at the time limit once
|
|
65
|
+
* records came; 1 when none came or the stream ended first.
|
|
66
|
+
*/
|
|
67
|
+
function follow(id) {
|
|
68
|
+
const url = new URL(`/api/sessions/${encodeURIComponent(id)}/amsp`, base);
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
let records = 0;
|
|
71
|
+
let announced = false;
|
|
72
|
+
let pending = "";
|
|
73
|
+
let settled = false;
|
|
74
|
+
const finish = (code, note) => {
|
|
75
|
+
if (settled) return;
|
|
76
|
+
settled = true;
|
|
77
|
+
clearTimeout(limit);
|
|
78
|
+
if (note) console.error(note);
|
|
79
|
+
req.destroy();
|
|
80
|
+
resolve(code);
|
|
81
|
+
};
|
|
82
|
+
// finish() destroys the request, and the response then reports an "aborted" error: ignored.
|
|
83
|
+
const fail = (e) => {
|
|
84
|
+
if (settled) return;
|
|
85
|
+
settled = true;
|
|
86
|
+
clearTimeout(limit);
|
|
87
|
+
reject(e);
|
|
88
|
+
};
|
|
89
|
+
const frame = (text) => {
|
|
90
|
+
const lines = text.split("\n");
|
|
91
|
+
const event = lines
|
|
92
|
+
.find((l) => l.startsWith("event:"))
|
|
93
|
+
?.slice(6)
|
|
94
|
+
.trim();
|
|
95
|
+
const data = lines
|
|
96
|
+
.filter((l) => l.startsWith("data:"))
|
|
97
|
+
.map((l) => l.slice(5).replace(/^ /, ""))
|
|
98
|
+
.join("\n");
|
|
99
|
+
if (event === "ping" && !announced) {
|
|
100
|
+
announced = true;
|
|
101
|
+
console.error(
|
|
102
|
+
`Following ${id}. Records print as they are written; start a turn if none come.`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
// A named event is a control frame; only records carry no name.
|
|
106
|
+
if (event !== undefined || data === "") return;
|
|
107
|
+
records++;
|
|
108
|
+
console.log(data);
|
|
109
|
+
let record;
|
|
110
|
+
try {
|
|
111
|
+
record = JSON.parse(data);
|
|
112
|
+
} catch {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (record.type === "event_msg" && record.payload?.type === "task_end" && !record.origin)
|
|
116
|
+
finish(0);
|
|
117
|
+
};
|
|
118
|
+
const req = (url.protocol === "https:" ? https : http).get(
|
|
119
|
+
url,
|
|
120
|
+
{ headers: { authorization: `Bearer ${token}`, accept: "text/event-stream" } },
|
|
121
|
+
(res) => {
|
|
122
|
+
res.on("error", fail);
|
|
123
|
+
if (res.statusCode !== 200) {
|
|
124
|
+
res.resume();
|
|
125
|
+
fail(
|
|
126
|
+
new Error(
|
|
127
|
+
`Server returned HTTP ${res.statusCode} for ${url.pathname}. Check the Session id and this Session's Project access.`,
|
|
128
|
+
),
|
|
129
|
+
);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
res.setEncoding("utf8");
|
|
133
|
+
res.on("data", (chunk) => {
|
|
134
|
+
pending += chunk.replaceAll("\r\n", "\n");
|
|
135
|
+
let end;
|
|
136
|
+
while (!settled && (end = pending.indexOf("\n\n")) !== -1) {
|
|
137
|
+
frame(pending.slice(0, end));
|
|
138
|
+
pending = pending.slice(end + 2);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
res.on("end", () => finish(1, "The stream ended before the main conversation's task_end."));
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
const limit = setTimeout(
|
|
145
|
+
() =>
|
|
146
|
+
finish(
|
|
147
|
+
records > 0 ? 0 : 1,
|
|
148
|
+
records > 0
|
|
149
|
+
? `Stopped after ${FOLLOW_LIMIT_MS / 1000} seconds without the main conversation's task_end; the turn is still running.`
|
|
150
|
+
: `No record in ${FOLLOW_LIMIT_MS / 1000} seconds. The stream is live only: start a turn, then follow it.`,
|
|
151
|
+
),
|
|
152
|
+
FOLLOW_LIMIT_MS,
|
|
153
|
+
);
|
|
154
|
+
req.on("error", fail);
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
/** Lists the target's workbenches, which loads them, and prints this one's load result. */
|
|
158
|
+
async function check() {
|
|
56
159
|
const agentsRoute = `/api/projects/${encodeURIComponent(project)}/agents`;
|
|
57
160
|
// Listing reconciles Agents created through file tools with the server's Session index.
|
|
58
161
|
const discovered = await readJson(agentsRoute);
|
|
@@ -68,7 +171,10 @@ try {
|
|
|
68
171
|
`No workbench ${workbenchId} under Agent ${agentId}. Check the target folder and package.json.`,
|
|
69
172
|
);
|
|
70
173
|
console.log(JSON.stringify(workbench, null, 2));
|
|
71
|
-
|
|
174
|
+
return workbench.error || !workbench.tabs?.length || workbench.hints?.length ? 1 : 0;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
process.exitCode = following ? await follow(sessionId) : await check();
|
|
72
178
|
} catch (e) {
|
|
73
179
|
console.error(
|
|
74
180
|
e instanceof Error ? e.message.replaceAll(token, "[redacted]") : "Workbench check failed",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: penguin-sdk
|
|
3
3
|
description: Use to build a standalone external program with an agent in it, or connect an external program to a Penguin agent. For an app inside PenguinHarness with its own Agent and workbench tab, use agent-initialization and penguin-plugin directly; no SDK/API question applies. A program reaches an agent in one of two ways, and the skill asks the user which before building — embedded with the Penguin Harness SDK (`@prismshadow/penguin-core`, no server), or over the Penguin server's Agent API (AMSP, with the `@prismshadow/amsp` client or curl). This is writing application code, not configuring an Agent State inside PenguinHarness. Covers self-contained projects, the createSession/run streaming loop with thinking and image messages, wiring the user's existing tools in as CLI commands, a complete RAG recipe that ingests documents into a knowledge base and answers with citations behind a web UI, and the Agent API client. Workbenches — the tabs and pages beside the chat that an Agent keeps for itself inside PenguinHarness — are the penguin-plugin skill's.
|
|
4
|
-
version: 2026.10.
|
|
4
|
+
version: 2026.10.26.1
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Penguin Harness SDK and Agent API
|
|
@@ -15,13 +15,13 @@ To have an agent perform a task for you, use the `run_subagent` tool: both ways
|
|
|
15
15
|
**The SDK: `@prismshadow/penguin-core`, embedded in the program.**
|
|
16
16
|
|
|
17
17
|
- *What it is.* The agent loop as a TypeScript library. The program creates its own Agent from a data directory inside the project and runs its Sessions in-process. No Penguin server is involved, at build time or at run time.
|
|
18
|
-
- *What you get.* The basic agent loop: the Agent State files (`AGENTS.md`, Skills, tools), the streamed
|
|
18
|
+
- *What you get.* The basic agent loop: the Agent State files (`AGENTS.md`, Skills, tools), the streamed AMSP records and an `approve` callback for every tool call, in a self-contained folder that runs wherever Node 24 does, on the program's own model key.
|
|
19
19
|
- *What you don't get.* No server-managed Sessions (the program keeps its own), no visibility in the Web App, no approvals UI (the program answers in code) and no cost center. The embedded agent belongs to the program: changes to an Agent inside PenguinHarness never reach it.
|
|
20
20
|
- *Choose it when* the program must stand alone: shipped to other machines or people, run where no Penguin server is, or with the agent built into the product.
|
|
21
21
|
|
|
22
22
|
**The API: Penguin's Agent API, over AMSP.**
|
|
23
23
|
|
|
24
|
-
- *What it is.* The program calls an Agent that lives in PenguinHarness, over HTTP. The Penguin server runs each turn and streams it back
|
|
24
|
+
- *What it is.* The program calls an Agent that lives in PenguinHarness, over HTTP. The Penguin server runs each turn and streams it back over AMSP as the Session's records, the ones its Trace holds, and the program continues a conversation by its Session id. TypeScript uses the `@prismshadow/amsp` client (`AgentClient`); any other language, or curl, speaks HTTP and SSE directly.
|
|
25
25
|
- *What you get.* The Agent as PenguinHarness runs it: its `AGENTS.md`, Skills and memory, on the Project's models and credentials, so the program holds no model key. The server keeps the conversations as archived chats (**Settings › Archived chats** in the Web App), where a person finds one and unarchives it to read it and answer its approvals, and their usage lands in the cost center.
|
|
26
26
|
- *What it requires.* A running Penguin server that the program can reach over the network; API access turned on for that Agent by the Project's owner, on the Agent's **API** tab; and a key created there, shown once. You never turn these on yourself (see *The API path*).
|
|
27
27
|
- *Choose it when* the Agent already exists in PenguinHarness or should be managed there, people need to see its conversations or costs, or the program is not written in TypeScript.
|
|
@@ -80,7 +80,7 @@ Each path also needs one thing only the user can provide: a model credential on
|
|
|
80
80
|
|
|
81
81
|
- An **Agent** loads its state (prompts, tools, skills) from `<root>/<project_id>/agents/<agent_id>/`. Creating an Agent whose directory is empty initializes it with defaults.
|
|
82
82
|
- A **Session** is one conversation of an Agent inside a **Workspace** directory.
|
|
83
|
-
- `session.run()` executes one task and streams every step (thinking, text, tool calls) as
|
|
83
|
+
- `session.run()` executes one task and streams every step (thinking, text, tool calls) as AMSP records.
|
|
84
84
|
|
|
85
85
|
### Project location
|
|
86
86
|
|
|
@@ -117,7 +117,7 @@ If the package is not on your npm registry (it is developed in the PenguinHarnes
|
|
|
117
117
|
Configure a model for the app's data root, in this order — stop at the first that works:
|
|
118
118
|
|
|
119
119
|
1. `penguin config model add --root <data_dir> --provider <group> --model-id <id> --api-key <key> [--base-url <url>] [--client-type openai-chat] --set-default` — prefer `--client-type openai-chat --base-url <endpoint>` (works with any OpenAI Chat Completions compatible endpoint; exact ids in the unified-llm-api skill). `--provider` is required: a model is always the `(provider, model_id)` pair and the group is never inferred from the id (`custom` for an endpoint outside the built-in groups).
|
|
120
|
-
2. Environment variables cover the **credential only** (`DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …), and only for
|
|
120
|
+
2. Environment variables cover the **credential only** (`DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …), and only for a model with **no base URL** on itself or its group, or the vendor's own default endpoint — a model with any other base URL (a gateway, a self-hosted server) needs `--api-key`, or `createSession` refuses it. The SDK carries no model catalog: a data root only the SDK and the CLI touch starts with **no models and no default**, so model selection always comes from what step 1 or your code writes. For env-only setup, add the model in code before `createAgent` — `addModel(root, "default_project", { provider: "deepseek", model_id: "deepseek-flash" }, { setDefault: true })`, exported by `@prismshadow/penguin-core` — and leave its group's base URL empty.
|
|
121
121
|
|
|
122
122
|
Keep model API keys **project-local**: configure them with the penguin CLI into the app's own data root under the working directory, so the project stays self-contained and movable. When building an AI app, **always pass `--root <data_dir>` pointing at the app's data directory inside the current working directory** (the same path you give `createAgent({ root })`, e.g. `./penguin_data`) — never run `penguin config ...` without `--root`, or it writes to the global `~/.penguin/data` instead of the project. Never read, copy or fall back to model keys stored in the user's global `~/.penguin` directory — that config belongs to the person running Penguin, not to the app you are building.
|
|
123
123
|
|
|
@@ -179,7 +179,7 @@ session.run([userText(question), ...images.map(imageUrlMessage)], { ... });
|
|
|
179
179
|
|
|
180
180
|
Browser flow: `<input type="file" accept="image/*">` plus paste/drag-drop → `FileReader.readAsDataURL` → POST `{ question, images: [dataUrl] }` → the server maps each entry to `imageUrlMessage`. Reject non-image MIME types and cap size (a data URL rides the context window; a few MB is plenty). Whether the session model actually sees pixels is the model config's `vision` flag (`penguin config model list` prints `vision=Y/-`; set via `--vision/--no-vision` on `model add`, default supported): with `vision=false` the core folds the image into an `[attached image: <path>]` line and the built-in `read_file` tool reads it through the project's configured `vision_model` (`penguin config model vision --provider <group> --model-id <id> --root <data_dir>`) — the app still works, through a description instead of direct sight.
|
|
181
181
|
|
|
182
|
-
**Other payloads worth handling** (always narrow with the guards first): `partial_tool_call` / `partial_tool_call_output` — surface as an activity line ("running `search`…") in apps that grant tools; `request_end` (event) — a non-`completed` `status` is the error signal (`auth` → ask for a key; `
|
|
182
|
+
**Other payloads worth handling** (always narrow with the guards first): `partial_tool_call` / `partial_tool_call_output` — surface as an activity line ("running `search`…") in apps that grant tools; `request_end` (event) — a non-`completed` `status` is the error signal (`error_code` `auth` → ask for a key; `error_message` carries the failure detail; `retry_in_ms` announces a planned in-run retry, renderable as a countdown); `token_usage` (event) — session-cumulative and last-request counts, if the app shows cost; `compaction_begin` / `compaction_end` (events) — long-lived chats only, show a brief "context being compacted" notice. Everything else is safe to ignore.
|
|
183
183
|
|
|
184
184
|
### Wiring in the user's tools
|
|
185
185
|
|
|
@@ -431,3 +431,4 @@ The program calls an Agent that lives in PenguinHarness. You write the program;
|
|
|
431
431
|
- **Keep the key out of the code.** The program reads it from the `PENGUIN_AGENT_KEY` environment variable. Never write a key into source, a committed file, a log or a reply, and never ask the user to paste one into the chat.
|
|
432
432
|
- **Connection values.** The Base URL and the Agent ID come from the API tab or `penguin agent api status --agent-id <agentId>`. A local server's Base URL is `http://localhost:7364/api/amsp/v1`: `localhost`, not `127.0.0.1`, where a local server serves previews and refuses every API request with `401`. The Agent ID is `<projectId>/<agentId>`.
|
|
433
433
|
- **No data root, no model key.** The server runs the Agent on the Project's models. An SDK recipe keeps its shape on this path: the RAG app, for instance, replaces `createAgent`, `createSession` and `session.run` with an `AgentClient` run, and its persona goes into the Agent's `AGENTS.md`.
|
|
434
|
+
- **Not for workbenches.** A workbench that shows its Agent's answer live still takes neither way: its page follows the Session through the page SDK its server serves (`../sdk/workbench.js`) and its handler through `host.subscribe`, with no key and no API switch (the penguin-plugin skill, *Follow the Agent live*).
|
|
@@ -41,7 +41,7 @@ Suggest the approval mode that fits the program, and say why in one line:
|
|
|
41
41
|
| Shows every tool call to its own user | `always-ask` | Every call waits for the program's answer |
|
|
42
42
|
| Must never run a tool | `deny-all` | Every call is denied; the agent answers without tools |
|
|
43
43
|
|
|
44
|
-
A call that waits
|
|
44
|
+
A call that waits is listed by the conversation's approvals resource, `GET <Base URL>/sessions/<session_id>/approvals`, and the run waits, with no time limit, for an answer, an abort or a disconnect. The `@prismshadow/amsp` client polls that resource and answers with `onApproval`, or with `deny` when there is none. The mode is read when an API conversation is created; a change on the tab applies to conversations created after it.
|
|
45
45
|
|
|
46
46
|
Leave **Allow keyless access** off unless the user asks for it. With it on, anything that can reach the server can run the Agent on the Project's models.
|
|
47
47
|
|
|
@@ -64,10 +64,10 @@ To run the program yourself, you need the key in your environment. Ask the user
|
|
|
64
64
|
npm install @prismshadow/amsp
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
-
The client has no dependencies and runs in Node 24 and in current browsers. If your registry does not have the package, call the API over HTTP as in section 4.
|
|
67
|
+
Use a version after 0.2.16, which reads the current stream; 0.2.16 and earlier read the old events and cannot. The package is versioned with PenguinHarness, so match it to the server: a server of 0.2.16 or earlier needs the client of the same version. The client has no dependencies and runs in Node 24 and in current browsers. If your registry does not have the package, call the API over HTTP as in section 4.
|
|
68
68
|
|
|
69
69
|
```ts
|
|
70
|
-
import { AgentClient, parseArguments } from "@prismshadow/amsp";
|
|
70
|
+
import { AgentClient, isModelMessage, parseArguments } from "@prismshadow/amsp";
|
|
71
71
|
|
|
72
72
|
const apiKey = process.env.PENGUIN_AGENT_KEY;
|
|
73
73
|
if (!apiKey) throw new Error("Set PENGUIN_AGENT_KEY to the key from the agent's API tab.");
|
|
@@ -87,25 +87,28 @@ console.log(first.text);
|
|
|
87
87
|
const run = client.stream({
|
|
88
88
|
sessionId: first.sessionId,
|
|
89
89
|
input: "Now list its headings",
|
|
90
|
-
onApproval: (
|
|
91
|
-
const args = parseArguments(
|
|
92
|
-
return
|
|
90
|
+
onApproval: (toolCall, origin) => {
|
|
91
|
+
const args = parseArguments(toolCall);
|
|
92
|
+
return !origin && toolCall.name === "exec_command" && args?.cmd === "ls" ? "allow" : "deny";
|
|
93
93
|
},
|
|
94
94
|
});
|
|
95
|
-
for await (const
|
|
96
|
-
//
|
|
97
|
-
if (
|
|
95
|
+
for await (const record of run) {
|
|
96
|
+
// A record without `origin` is the main conversation's; a subagent's carry one.
|
|
97
|
+
if (record.origin || !isModelMessage(record)) continue;
|
|
98
|
+
if (record.payload.type === "partial_text") process.stdout.write(record.payload.text);
|
|
98
99
|
}
|
|
99
100
|
const second = await run.result();
|
|
100
101
|
```
|
|
101
102
|
|
|
102
|
-
-
|
|
103
|
+
- The stream carries the conversation's records: AMSP record envelopes `{timestamp, type, payload, origin?}`, the same lines the Trace stores. The answer streams as `partial_text` records and arrives whole as an assistant `text` record.
|
|
104
|
+
- `run()` runs to the end and resolves with the result: `status`, `error`, `sessionId`, `text` (the main conversation's answer), `usage`, `sessionUsage` and `requests`. `stream()` starts the run and returns it at once: iterate it once for the records, await `run.session` for the Session id, and `run.result()` for the end.
|
|
103
105
|
- **Conversations.** Keep one `sessionId` per conversation of the program, such as one per end user or chat thread, and pass it back to continue. Omit it to start a new conversation. Only the Agent's own API conversations can be continued.
|
|
104
|
-
- **Approvals.** `onApproval` is called only when the approval mode makes a call wait. Without it, or when it throws, the client answers `deny`. A person can answer the same
|
|
105
|
-
- **Aborting.** Abort the `signal` passed to `stream()` or `run()` to drop the connection: the server aborts the run. `run.abort()` asks the server to abort and
|
|
106
|
-
- **Failures.** A refusal before the stream starts rejects with `AmspHttpError` (`status`, `code`, `message`; see section 5). After that, `result()` resolves for every run
|
|
107
|
-
- **Unknown
|
|
108
|
-
- **
|
|
106
|
+
- **Approvals.** `onApproval(toolCall, origin, { sessionId })` is called only when the approval mode makes a call wait; `origin` is set for a subagent's call. Without it, or when it throws, the client answers `deny`. A person can answer the same call in the Web App; the first answer counts.
|
|
107
|
+
- **Aborting.** Abort the `signal` passed to `stream()` or `run()` to drop the connection: the server aborts the run. `run.abort()` asks the server to abort and keeps the stream until `[DONE]`; the result's `status` is `aborted`.
|
|
108
|
+
- **Failures.** A refusal before the stream starts rejects with `AmspHttpError` (`status`, `code`, `message`; see section 5). After that, `result()` resolves for every run that reached `[DONE]`: check `status` (`completed`, `aborted`, `retryable` or `fatal`) and `error`. A stream that breaks before `[DONE]` rejects with `AmspStreamError`.
|
|
109
|
+
- **Unknown records** are passed through. Switch on `payload.type` with a default branch.
|
|
110
|
+
- **Following a conversation** that runs elsewhere, or across many runs: `SessionReader` reads its history and then its live records, and reconnects on its own.
|
|
111
|
+
- **A web app** keeps the key on its own server. The page posts to the app's server, which runs the Agent and relays the answer's `partial_text` to the page over SSE, aborting through `signal` when the page disconnects: the shape of the RAG recipe's `server.ts`. A key inside a page is readable by everyone who loads the page.
|
|
109
112
|
|
|
110
113
|
## 4. Any language: HTTP and curl
|
|
111
114
|
|
|
@@ -117,12 +120,16 @@ curl -N "$BASE/agents/demo/coder/runs" \
|
|
|
117
120
|
-H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
|
|
118
121
|
-d '{"input":"Summarize README.md"}'
|
|
119
122
|
|
|
120
|
-
# Continue it with the session_id that
|
|
123
|
+
# Continue it with the session_id that its first record, the session_meta, carried.
|
|
121
124
|
curl -N "$BASE/agents/demo/coder/runs" \
|
|
122
125
|
-H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
|
|
123
126
|
-d '{"session_id":"<session_id>","input":"Now list its headings"}'
|
|
124
127
|
|
|
125
|
-
#
|
|
128
|
+
# List the calls waiting for an answer, holding the request up to 30 seconds.
|
|
129
|
+
curl "$BASE/sessions/<session_id>/approvals?wait=30" \
|
|
130
|
+
-H "Authorization: Bearer $PENGUIN_AGENT_KEY"
|
|
131
|
+
|
|
132
|
+
# Answer one while its run is still streaming.
|
|
126
133
|
curl -X POST "$BASE/sessions/<session_id>/approvals/<tool_call_id>" \
|
|
127
134
|
-H "Authorization: Bearer $PENGUIN_AGENT_KEY" -H "Content-Type: application/json" \
|
|
128
135
|
-d '{"decision":"allow"}'
|
|
@@ -130,14 +137,15 @@ curl -X POST "$BASE/sessions/<session_id>/approvals/<tool_call_id>" \
|
|
|
130
137
|
|
|
131
138
|
To read the stream in your own code:
|
|
132
139
|
|
|
133
|
-
-
|
|
134
|
-
- The
|
|
135
|
-
-
|
|
136
|
-
- `POST <Base URL>/sessions/<session_id>/abort` aborts a run and keeps its stream open until `
|
|
140
|
+
- It is SSE. An event without an `event:` name is a record: its `id:` is `<epoch>-<seq>` and its `data:` one JSON envelope `{timestamp, type, payload, origin?}`. A named event is a control frame: `ping`, first and every 20 seconds. The run ends with `data: [DONE]`. Skip every event name and `payload.type` you do not know.
|
|
141
|
+
- The run's records go from `task_begin` to `task_end`. A new conversation's first run opens with its `session_meta`, whose `session_id` is the id to continue it with; a run that continues a conversation carries none. The answer is the assistant `text` records without an `origin`, or their `partial_text` fragments as they arrive.
|
|
142
|
+
- How the run went is in the records: an `abort` record means it was aborted; a `request_end` that is not `completed` and has no `retry_in_ms` gives its failure in `error_code` and `error_message`; a last `task_begin` with no `task_end` before `[DONE]` means the server failed. A body that ends without `[DONE]` means the connection broke.
|
|
143
|
+
- `POST <Base URL>/sessions/<session_id>/abort` aborts a run and keeps its stream open until `[DONE]`.
|
|
144
|
+
- `GET <Base URL>/sessions/<session_id>/stream` follows a conversation across runs; `POST <Base URL>/sessions/<session_id>/tasks` with `{"input": …}` starts a run on it without holding a connection, and its records arrive on that stream.
|
|
137
145
|
|
|
138
146
|
## 5. Errors
|
|
139
147
|
|
|
140
|
-
A request refused before the stream gets an HTTP status and `{"error": {"code": "…", "message": "…"}}`. Once the stream has started,
|
|
148
|
+
A request refused before the stream gets an HTTP status and `{"error": {"code": "…", "message": "…"}}`. Once the stream has started, the records carry the error instead.
|
|
141
149
|
|
|
142
150
|
| Status | `code` | Usually | What to do |
|
|
143
151
|
| --- | --- | --- | --- |
|
|
@@ -146,8 +154,9 @@ A request refused before the stream gets an HTTP status and `{"error": {"code":
|
|
|
146
154
|
| 403 | `agent_api_disabled` | The administrator turned the Agent API off | Ask the user to have an administrator turn it on |
|
|
147
155
|
| 404 | `agent_not_found` | API access is off, the Agent ID is wrong, or the key belongs to another Agent | Check with `penguin agent api status`, then ask the owner |
|
|
148
156
|
| 404 | `session_not_found` | The `session_id` is not one of this Agent's API conversations | Start a new conversation |
|
|
149
|
-
| 409 | `task_in_progress`, `compacting` | The conversation is still busy | Wait for its `
|
|
150
|
-
|
|
|
157
|
+
| 409 | `task_in_progress`, `compacting` | The conversation is still busy | Wait for its `[DONE]`: one run per conversation at a time |
|
|
158
|
+
| 409 | `resync_required` | A Session stream reopened with a `Last-Event-ID` the server no longer holds (it restarted, or moved past it) | Read the history again and reopen the stream without `Last-Event-ID`; `SessionReader` does this itself |
|
|
159
|
+
| 429 | `too_many_runs` | The Agent already has as many conversations running as its limit allows (4 by default), Web App ones included | Retry after `Retry-After` seconds |
|
|
151
160
|
|
|
152
161
|
## 6. Verify before you hand over
|
|
153
162
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: unified-llm-api
|
|
3
3
|
description: Call model APIs through @prismshadow/mmsp (MMSP) — streaming text generation, image generation, speech synthesis, embeddings and the supported-model registry with one client.
|
|
4
|
-
version: 2026.10.
|
|
4
|
+
version: 2026.10.24.1
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Unified LLM API (MMSP)
|
|
@@ -59,7 +59,7 @@ Use exact model ids. If an id is not in the table below and the user has not giv
|
|
|
59
59
|
| GPT-5.5 / 5.4 | `gpt-5.5`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.4-nano` | OpenRouter `openai/gpt-5.5`, `openai/gpt-5.5-pro`, `openai/gpt-5.4`, `openai/gpt-5.4-mini`, `openai/gpt-5.4-nano`, `openai/gpt-5.4-pro` |
|
|
60
60
|
| OpenAI embedding | `text-embedding-3-small`, `text-embedding-3-large` | — |
|
|
61
61
|
| MiniMax M3 | `MiniMax-M3` | OpenRouter `minimax/minimax-m3` |
|
|
62
|
-
| Kimi K3 / K2.6
|
|
62
|
+
| Kimi K3.1 / K3 / K2.6 | `kimi-k3.1-pro`, `kimi-k3.1-pro-highspeed`, `kimi-k3`, `kimi-k2.6` | OpenRouter `moonshotai/kimi-k3.1-pro`, `moonshotai/kimi-k3`, `moonshotai/kimi-k2.6`; SiliconFlow `Pro/moonshotai/Kimi-K2.6` |
|
|
63
63
|
| Kimi K2.7 Code | — | SiliconFlow `moonshotai/Kimi-K2.7-Code`; Fireworks AI `accounts/fireworks/models/kimi-k2p7-code` |
|
|
64
64
|
| DeepSeek V4 | `deepseek-flash`, `deepseek-v4-pro` | OpenRouter `deepseek/deepseek-v4.1-flash`, `deepseek/deepseek-v4-pro-0813`, `deepseek/deepseek-v4-pro`, `deepseek/deepseek-v4-flash`, `deepseek/deepseek-v4-flash-0731`, `deepseek/deepseek-v4-flash-vision-exp`; Fireworks AI `accounts/fireworks/models/deepseek-v4p1-flash`, `accounts/fireworks/models/deepseek-v4-pro-0813`, `accounts/fireworks/models/deepseek-v4-flash-0731`; SiliconFlow `deepseek-ai/DeepSeek-V4-Pro`, `deepseek-ai/DeepSeek-V4-Flash` |
|
|
65
65
|
| GLM 5.3 / 5.2 / 5.1 | `glm-5.3`, `glm-5.3-flash`, `glm-5.2`, `glm-5.1` | OpenRouter `z-ai/glm-5.3`, `z-ai/glm-5.3-flash`, `z-ai/glm-5.2`; SiliconFlow `zai-org/GLM-5.2` |
|
|
@@ -195,10 +195,10 @@ try {
|
|
|
195
195
|
}
|
|
196
196
|
```
|
|
197
197
|
|
|
198
|
-
- `thinking_level` never throws: every client maps each level onto the closest one the model supports. `MAX` falls back silently where the vendor has no such tier, and a model that always reasons (
|
|
198
|
+
- `thinking_level` never throws: every client maps each level onto the closest one the model supports. `MAX` falls back silently where the vendor has no such tier, and a model that always reasons (GLM-5.3, Claude Opus 5.5 / Fable 5.1) turns `NONE` into its lowest effort, and so does Claude Haiku 5.5. On the Kimi K3 series (`kimi-k3`, `kimi-k3.1-pro`, `kimi-k3.1-pro-highspeed`), `moonshot-official` sends `NONE` as `reasoning_effort: "none"`, which turns reasoning off.
|
|
199
199
|
- `temperature`: both Gemini clients reject any value; `openai-official`, `anthropic-official`, `moonshot-official` and `deepseek-official` accept only `1.0`; `minimax-official` accepts 0 to 1; `zai-official` and the compatible clients pass it through.
|
|
200
|
-
- `tool_choice`: `"auto"` works everywhere. `zai-official` accepts nothing else; `deepseek-official` and `minimax-official` add `"none"`; `moonshot-official` adds `"required"` for Kimi K3 but never a named tool; `anthropic-official` takes `"required"` or one tool name, except on Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1, which cannot be forced.
|
|
201
|
-
- `prompt_caching`: `ENABLE` (the default) works everywhere
|
|
200
|
+
- `tool_choice`: `"auto"` works everywhere. `zai-official` accepts nothing else; `deepseek-official` and `minimax-official` add `"none"`; `moonshot-official` adds `"required"` for the Kimi K3 series but never a named tool; `anthropic-official` takes `"required"` or one tool name, except on Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1, which cannot be forced.
|
|
201
|
+
- `prompt_caching`: `ENABLE` (the default) works everywhere. `anthropic-official` also takes `DISABLE` and `ENHANCE` (a one-hour cache); `moonshot-official` takes `ENHANCE` on the Kimi K3 series, sent as `prompt_cache_options` with a one-hour TTL; Moonshot bills those cache writes at twice the input price.
|
|
202
202
|
- `fast_mode`: fast processing at premium pricing, decided by the client the model routes to:
|
|
203
203
|
- sent as `service_tier: "priority"` by `openai-official`, `openai-responses`, `openai-chat`, `openai-chat-vllm-adapter`, `google-official` and `minimax-official`;
|
|
204
204
|
- sent as `speed: "fast"` with the fast-mode beta header by `ant-messages` and `anthropic-official` — except on Bedrock and on Claude 4.6, Sonnet 5.5, Haiku 5.5 and Fable 5.1, which reject it. Anthropic's fast mode is a research preview: organizations without access get a 429;
|