@penguinharness/agent-development 0.2.13 → 0.2.16

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.
@@ -0,0 +1,192 @@
1
+ ---
2
+ name: penguin-plugin
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.14.2
5
+ ---
6
+
7
+ # Agent Workbench with Penguin Plugins
8
+
9
+ Inside PenguinHarness an Agent can hold *workbenches*: small plugin packages in its own directory, written in TypeScript, that the server boots as module trees, shows as tabs beside the chat, reloads on every file change, and versions so any edit can be undone. This is the same module mechanism the server itself is built from — manifests as data, everything checked before any code runs — so a workbench that does not type-check, that was written against an interface version this server no longer fits, or whose manifests do not hold together fails to load with the problem named, while the previous version keeps serving.
10
+
11
+ A workbench is a plugin of the server's own kind, which is where this skill's name comes from. It is not a program that reaches an agent from outside, so it takes neither of the penguin-sdk skill's two ways, and that skill's question does not apply to it.
12
+
13
+ ## Before you start
14
+
15
+ If the user's message only invokes this skill (e.g. "use penguin-plugin skill") without saying what the workbench is for, ask the user what they want it to do. Once the request is concrete, do **not** ask follow-up questions: build it end to end and list the assumptions you made in your final reply. A request to undo, revert or remove the UI is the exception: work out which of the four in *Undoing, reverting, removing* is meant first.
16
+
17
+ ## Build a new Agent and its workbench
18
+
19
+ For an app inside PenguinHarness, use this skill with `agent-initialization`. The Plugin host already runs the Agent; do not ask the user to choose SDK/API architecture or enable Agent API keys. If the request says **new Agent**, create that target first and put all workbench files in **its** directory, not the Builder's. Keep the resolved target path for the whole task.
20
+
21
+ 1. Read the Environment's App Data Dir and Agent ID; use `agent-initialization` to create the requested target. List existing agent ids, choose an unused id (letters, digits and underscores), and write its role. Give a contract reviewer domain instructions, not app-building skills. Inherit the current runtime unless the user specified another.
22
+ 2. Under `<App Data Dir>/agents/<target_agent_id>/workbenches/<workbench_id>/`, write the three-file scaffold below. Every visible app needs a `WebModule.sessionTabs` contribution.
23
+ 3. **Activate and check the target**, including a new Agent nobody has opened yet:
24
+ ```bash
25
+ node "<this skill directory>/scripts/check.mjs" <target_agent_id> <workbench_id>
26
+ ```
27
+ The helper uses only this Session's injected server URL/token/Project and registers Agents created through file tools, then starts the target watcher. It bypasses shell HTTP proxies. Never print tokens, scan ports, read project credentials, or use another running Penguin instance. If the injected variables are unavailable, ask the user to open the target Agent's new conversation once.
28
+ 4. Read the target's `.harness/plugin.d.ts` for exact host types and `.build/status.json` for compiler feedback. `.harness/README.md` is the running server's contract. Fix named diagnostics; re-run the helper after edits. Success means `error: null`, your contributed tab present and no hints, not merely an HTML file on disk.
29
+ 5. Exercise a real request through your handler, wait for a terminal result, and inspect the returned answer or downloaded report. For HTTP tests use the injected URL with `curl --noproxy '*'`, bearer token only in the header. Check malformed input and empty/loading/failed states too. A compiler pass is not an end-to-end test. If browser automation is unavailable, report that limitation; finish the HTTP and script-syntax checks and state that the visual check remains unverified. Do not launch a separate system browser or install a DOM/browser test environment for a one-off workbench.
30
+ 6. Hand off through **Agents → target Agent → New chat → the named workbench tab**. The workbench works in a new conversation before the user sends a chat message. Include the target Agent's link (`/agents/<target_agent_id>`) and tab name. Full-page mode is optional.
31
+
32
+ ## Background jobs: launch, poll, persist
33
+
34
+ `await host.run(...)` resolves when a turn **starts**. `await host.sessionResult(id)` is also a **snapshot**, never a wait. Its `status` is `running`, `completed` or `failed`; `text` is the final assistant answer only on success, and `error` explains failure. `sessionStatus() === "idle"` alone does not prove success.
35
+
36
+ Use this pattern for uploads, research and support tickets:
37
+
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
+ - 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.
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
+ - `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
+ - 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
+
45
+ ## Layout
46
+
47
+ Layout, under `<root>/<project_id>/agents/<agent_id>/workbenches/<workbench_id>/` (beside `agent_state/`):
48
+
49
+ ```
50
+ package.json "type": "module" and "penguin": { "modules": [ …manifests ] } — no dependency to install
51
+ index.ts default export { modules: { <Name>: { create(ctx) } } } satisfies WorkbenchPackage — TypeScript only
52
+ ui/ the workbench's pages and their assets; which of them are tabs is what the manifest contributes
53
+ state.json the workbench's own document, kept by the server across reloads and rollbacks
54
+ .harness/ the server's: the types this workbench was written against (plugin.d.ts) and their interface table — read plugin.d.ts, never edit it
55
+ .build/ the server's: emitted JavaScript per revision, and status.json — the result of the last load; read it, never edit it
56
+ ```
57
+
58
+ ## The manifest and the handler
59
+
60
+ The root manifest is named `Workbench`; it requires the host, provides the handler, and contributes its tabs:
61
+
62
+ ```json
63
+ {
64
+ "name": "demo",
65
+ "version": "0.1.0",
66
+ "type": "module",
67
+ "penguin": {
68
+ "modules": [
69
+ {
70
+ "name": "Workbench",
71
+ "requires": { "host": { "iface": "@prismshadow/penguin-server#WorkbenchHost", "from": "Host" } },
72
+ "provides": { "main": "@prismshadow/penguin-server#WorkbenchMain" },
73
+ "contributes": {
74
+ "WebModule.sessionTabs": [
75
+ { "id": "demo.main", "key": "main", "title": "Demo", "titleZh": "演示", "renderer": { "iframe": { "src": "ui/index.html" } } }
76
+ ]
77
+ }
78
+ }
79
+ ]
80
+ }
81
+ }
82
+ ```
83
+
84
+ ```ts
85
+ import type { WorkbenchPackage, WorkbenchResponse } from "@prismshadow/penguin-server/plugin";
86
+
87
+ export default {
88
+ modules: {
89
+ Workbench: {
90
+ create({ use }) {
91
+ const host = use.host;
92
+ return {
93
+ api: {
94
+ main: {
95
+ async handle(req): Promise<WorkbenchResponse> {
96
+ // req = { method, path, query, body }; path is below the workbench's api/ mount
97
+ if (req.path === "/ask" && req.method === "POST") {
98
+ const { question } = req.body as { question: string };
99
+ // The SDK's two verbs: open a Session, run a turn in it.
100
+ const { sessionId } = await host.createSession();
101
+ await host.run(sessionId, [{ text: question }]);
102
+ return { body: { sessionId } };
103
+ }
104
+ return { status: 404, body: { error: "no such route" } };
105
+ },
106
+ },
107
+ },
108
+ };
109
+ },
110
+ },
111
+ },
112
+ } satisfies WorkbenchPackage;
113
+ ```
114
+
115
+ ## Design the interaction before writing the UI
116
+
117
+ Treat the workbench as an application people return to. Before coding, choose its main list,
118
+ its item detail, and how a person creates and revisits an item. Use that structure even when the
119
+ request only says “build a Q&A app”. Do not turn independent conversations into one ever-growing
120
+ page of complete answers.
121
+
122
+ - For questions, requests and jobs, start with a compact, centered list of titles, statuses and
123
+ update times. Open one item's conversation in a dialog or detail panel. Keep follow-up messages
124
+ within that item's Session. Add search or pagination when a growing list needs it; long replies
125
+ scroll inside the detail view instead of stretching the main page.
126
+ - A new-question dialog asks for the question only. Derive its title from
127
+ `host.sessionTitle(sessionId)` once available, with a short question preview while waiting.
128
+ Do not ask people to type both a title and the same question. Keep drafts when they dismiss and
129
+ reopen the dialog. Persist the list and its Session IDs with `host.setState`.
130
+ - Dialogs need an obvious close button, Escape, and dismissal by clicking the surrounding blank
131
+ backdrop. Only dismiss when the pointer starts and ends outside the dialog; dragging selected
132
+ text out of it must not close it. Trap focus while open and restore focus to the opener on close.
133
+ Native `<dialog>.showModal()` provides the keyboard and focus foundation, but implement and test
134
+ backdrop dismissal yourself.
135
+ - Show submission and generation progress immediately, prevent duplicate submits, and keep a
136
+ retry path for failures. For a long task, show elapsed time and optionally a clearly approximate
137
+ remaining-time estimate; if the estimate runs out, say it is still processing instead of claiming
138
+ completion. Preserve the question on failure. Do not hide useful actions behind an indefinite
139
+ loading screen.
140
+ - Keep the code small: separate UI, styles and handler logic, reuse the host's theme variables,
141
+ and prefer native controls before adding dependencies. Use real empty, loading and error states;
142
+ never leave blank alert boxes or display internal errors as a successful answer.
143
+
144
+ Verify the interaction, not just compilation: create **two independent items**, follow up in one,
145
+ close it by the backdrop and Escape, reopen each, and reload the page. Confirm the items remain
146
+ separate, saved answers return, drafts survive dismissal, and a long answer does not push the list
147
+ far down the page. Also check a narrow viewport, dark mode, keyboard focus and the way back from
148
+ full-app mode. Use a real browser when available; report any interaction you could not run. A
149
+ successful TypeScript load alone is not UI/UX validation.
150
+
151
+ ## TypeScript, checked by the server
152
+
153
+ There is no build step to run, no `tsconfig.json` to write and nothing to `npm install`: the server builds one program from `index.ts` (and the `.ts` files it imports, with `.js` in the import specifier as NodeNext asks) under options it fixes itself — `strict` among them — refuses the load on any diagnostic, reporting file, line and reason, and otherwise emits into `.build/<revision>/` and imports that. `satisfies WorkbenchPackage` is what types `use.host` and `req`; without it `strict` refuses the untyped parameters. A folder holding `index.js` or `index.mjs` instead is refused outright.
154
+
155
+ ## Types come from the harness that runs you
156
+
157
+ One machine can run several harnesses — a release, a checkout, a platform someone pushed with interfaces of its own — and none of them is a version on npm, so `@prismshadow/penguin-server/plugin` is not a package here: the first time the server loads the folder it writes `.harness/plugin.d.ts`, rendered from ITS OWN interface table, and that is what the import resolves to. Create `package.json` and a minimal `index.ts`, let the server load it once, then read `.harness/plugin.d.ts` for the exact `WorkbenchHost` this harness offers. The server then leaves `.harness/` alone: it is the record of what the workbench was written against, and a later generation of the platform is COMPARED with it, by the TypeScript compiler, both for what the workbench requires and what it provides — a host method you rely on that has since gone is a load error naming it, not a failure on the first call. To move a workbench onto the harness that runs it now, delete `.harness/` and fix what the compiler then reports.
158
+
159
+ ## Tabs are contributions
160
+
161
+ Each entry under `WebModule.sessionTabs` is one tab beside the chat: `key` (unique in the workbench, part of the full-page URL), `title` / `titleZh`, and a `renderer` whose `iframe.src` is a file under `ui/`. Several entries make several tabs; none makes a server-only workbench. It is the same slot, written the same way, a plugin contributes to — the host opens it to workbenches and scopes the tab to this Agent. A slot the host has not opened (`WebModule.pages`, say) is refused by name.
162
+
163
+ ## The host
164
+
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.
166
+
167
+ ## HTTP
168
+
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.
170
+
171
+ ## Undoing, reverting, removing (撤销 / 还原 / 清掉界面)
172
+
173
+ When the user asks to undo the UI, revert it, clean it up or get the chat page back the way it was, they are asking you to TAKE SOMETHING AWAY — never to build something. Do not answer such a request by adding a feature (a reset button, an undo stack, a new route). Work out which of the four below they mean; if it is not obvious from what they said, ask in one line before touching anything. Everything about a workbench is files in your own Agent directory, so each of these is a file operation you make yourself — list `workbenches/` first to see what exists. The server notices within a moment and the user's tabs follow without a refresh.
174
+
175
+ 1. *"Get rid of it" / "back to before there was any custom UI" / 回到没定义 UI 的状态* — remove the workbench entirely: delete the folder `workbenches/<id>/` **and** its recorded versions `workbenches-history/<id>/`. That is everything there is; the tabs disappear and nothing else of the Agent is touched. It cannot be undone, so say so in one line first, and never delete a workbench you were not asked to remove. (The user can do the same from the tab's bar: *Remove*, two clicks.)
176
+ 2. *"Undo your last change" / "it was better before"* — go back to an earlier version of the CODE: the recorded versions are full copies under `workbenches-history/<id>/<revision>/` (`versions.json` lists them, newest first); copy that version's files over the folder and the server reloads it. The tab's bar offers the same as *History → Restore*.
177
+ 3. *"Remove that tab" / "I only want the first page"* — delete its entry under `WebModule.sessionTabs` in `package.json` (and its page under `ui/` if nothing else uses it). With `"contributes": {}` the workbench keeps its server code and has no UI at all.
178
+ 4. *"Bring back the data"* — you cannot: `state.json` is never part of a version (restoring code leaves the data as it is) and it has no history of its own. Say so plainly rather than inventing a recovery.
179
+
180
+ One constraint follows from 4, and it is a constraint on you, not a task to go and do: the workbench's data is only ever changed through `host.setState` from its handler. Never edit or delete `state.json` by hand — not to reset a board, not to fix a record — because what you overwrite is gone for good.
181
+
182
+ Your handler's responses are served from the app's own origin, so anything you echo back from a request is executed there: escape what you put into HTML, and treat a value that came in over `/api/*` as untrusted even though only Project members can reach it.
183
+
184
+ ## Theme
185
+
186
+ A workbench page is a separate document, so it inherits nothing from the app's stylesheet by itself. The Web App stamps `light`/`dark` on the page's root, copies its resolved palette (the gray scale, the accent pair, the font stack, the root font size) onto it, and 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-fg`, `--wb-muted`, `--wb-border`, `--wb-surface`, `--wb-accent`, `--wb-accent-fg`, plus the classes `wb-primary` (a button), `wb-card`, `wb-rows`, `wb-row`, `wb-muted`. Write plain markup, take every colour and font from those variables, and the page follows the user through a theme or accent change; hardcode them and it clashes in one theme or the other. The page's own rules always win, and linking `/workbench-ui.css` yourself makes it look right when opened outside the app too.
187
+
188
+ 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
+
190
+ ## Filling the app
191
+
192
+ A page can be shown as the whole app — no sidebar, no chat, no tab strip — at `/app/<project>/<agent>/<workbench>[/<tab key>]` (the workbench's first tab when no key is given): the tab's *Fill the app* button goes there, `penguin web --app <project>/<agent>/<workbench>[/<tab key>]` opens the browser straight onto it, and the page itself can ask with `parent.postMessage({ type: "penguin:fill-app" }, "*")`. The floating *Exit full screen* button returns to the same Agent and workbench tab. The command palette also offers *Exit full page*. Its chord is Ctrl+Alt+P (⌥⌘P on macOS) unless the user rebound it under Settings › Keyboard shortcuts. A key pressed inside the page reaches the app only when the page has not handled it, so a page must not intercept that chord.
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ // Activate the target Agent's watcher and report this server's actual load result.
3
+ import http from "node:http";
4
+ import https from "node:https";
5
+
6
+ const [agentId, workbenchId] = process.argv.slice(2);
7
+ const {
8
+ PENGUIN_API_URL: base,
9
+ PENGUIN_API_TOKEN: token,
10
+ PENGUIN_PROJECT_ID: project,
11
+ } = process.env;
12
+ if (!base || !token || !project || !agentId || !workbenchId) {
13
+ console.error(
14
+ "Usage: node check.mjs <agent_id> <workbench_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
+ );
16
+ process.exit(1);
17
+ }
18
+ async function readJson(route) {
19
+ const url = new URL(route, base);
20
+ // Direct to the injected server; shell proxies must not redirect loopback requests.
21
+ return new Promise((resolve, reject) => {
22
+ const req = (url.protocol === "https:" ? https : http).get(
23
+ url,
24
+ {
25
+ headers: { authorization: `Bearer ${token}` },
26
+ timeout: 30000,
27
+ },
28
+ (res) => {
29
+ let text = "";
30
+ res.setEncoding("utf8");
31
+ res.on("data", (chunk) => {
32
+ text += chunk;
33
+ });
34
+ res.on("end", () => {
35
+ if (res.statusCode !== 200)
36
+ reject(
37
+ new Error(
38
+ `Server returned HTTP ${res.statusCode} for ${url.pathname}. Check this Session's Project access.`,
39
+ ),
40
+ );
41
+ else {
42
+ try {
43
+ resolve(JSON.parse(text));
44
+ } catch {
45
+ reject(new Error("Server returned invalid JSON"));
46
+ }
47
+ }
48
+ });
49
+ },
50
+ );
51
+ req.on("timeout", () => req.destroy(new Error("Workbench check timed out after 30 seconds")));
52
+ req.on("error", reject);
53
+ });
54
+ }
55
+ try {
56
+ const agentsRoute = `/api/projects/${encodeURIComponent(project)}/agents`;
57
+ // Listing reconciles Agents created through file tools with the server's Session index.
58
+ const discovered = await readJson(agentsRoute);
59
+ if (!discovered.agents?.some((agent) => agent.agentId === agentId)) {
60
+ throw new Error(
61
+ `Agent ${agentId} is not initialized. Check its agent_state/system_config.yaml before loading its workbench.`,
62
+ );
63
+ }
64
+ const body = await readJson(`${agentsRoute}/${encodeURIComponent(agentId)}/workbenches`);
65
+ const workbench = body.workbenches?.find((item) => item.id === workbenchId);
66
+ if (!workbench)
67
+ throw new Error(
68
+ `No workbench ${workbenchId} under Agent ${agentId}. Check the target folder and package.json.`,
69
+ );
70
+ console.log(JSON.stringify(workbench, null, 2));
71
+ if (workbench.error || !workbench.tabs?.length || workbench.hints?.length) process.exitCode = 1;
72
+ } catch (e) {
73
+ console.error(
74
+ e instanceof Error ? e.message.replaceAll(token, "[redacted]") : "Workbench check failed",
75
+ );
76
+ process.exitCode = 1;
77
+ }
@@ -1,23 +1,88 @@
1
1
  ---
2
2
  name: penguin-sdk
3
- description: Use whenever the user wants to build an agent application — their own program with an embedded agent, such as an AI app, an agentic app or a RAG app. This is writing application code on the Penguin Harness SDK, 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, and a complete RAG recipe that ingests documents into a knowledge base and answers with citations behind a web UI.
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.14.2
4
5
  ---
5
6
 
6
- # Penguin Harness SDK
7
+ # Penguin Harness SDK and Agent API
7
8
 
8
- `@prismshadow/penguin-core` is the TypeScript SDK this agent itself runs on. Use it to build your own AI apps:
9
+ This skill builds programs that use a Penguin agent. A program reaches one in either of two ways, embedded with the SDK or through the Penguin server's Agent API, and the user picks which. Workbenches — pages and server code an Agent keeps inside PenguinHarness — are a third thing, and the penguin-plugin skill's.
9
10
 
10
- - 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.
11
- - A **Session** is one conversation of an Agent inside a **Workspace** directory.
12
- - `session.run()` executes one task and streams every step (thinking, text, tool calls) as OmniMessages.
11
+ To have an agent perform a task for you, use the `run_subagent` tool: both ways are for programs, not for handing off your own work.
12
+
13
+ ## Two ways to reach an agent
14
+
15
+ **The SDK: `@prismshadow/penguin-core`, embedded in the program.**
16
+
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 OmniMessages 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
+ - *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
+ - *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
+
22
+ **The API: Penguin's Agent API, over AMSP.**
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 as AMSP events, 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
+ - *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
+ - *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
+ - *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.
28
+
29
+ ### Ask which way first
30
+
31
+ Whenever the user asks to connect a program to an agent, or to build a program with an agent in it (an AI, agentic or RAG app, a bot, a service, a script), ask which way before you write anything, even when the request is otherwise concrete. It is the only question a concrete request gets: it overrides the no-follow-up-questions default of *Before you start* for this one question.
32
+
33
+ Do not ask when the way is already chosen:
34
+
35
+ - in the user's message: "use the SDK", "standalone", "without the Penguin server" or "embed the agent" chooses the SDK; "call it over the API", "through the Agent API", "with AMSP", "with `@prismshadow/amsp`" or "with curl" chooses the API;
36
+ - earlier in this conversation, for the same program.
37
+
38
+ Naming this skill does not choose a way. Workbenches (the penguin-plugin skill) take neither way and need no question; neither does connecting a Feishu, Telegram, QQ or WeChat bot to a conversation, which is the Web App's Remote control.
39
+
40
+ Ask with one sentence and this choice block, in the user's language, as the end of your reply. Mark one option `"recommended": true` only when the request leans that way: an Agent the user already has in PenguinHarness leans to the API, an app to ship to others leans to the SDK.
41
+
42
+ ````markdown
43
+ Your program can reach the agent in two ways: embedded with the SDK, or through the Penguin server's Agent API.
13
44
 
14
- To have an agent perform a task, use the `run_subagent` tool — the SDK is for building applications, not for invoking agents.
45
+ ```a2ui
46
+ {
47
+ "type": "choice",
48
+ "id": "agent-access",
49
+ "question": "How should the program reach the agent?",
50
+ "options": [
51
+ {
52
+ "label": "SDK: embed the agent",
53
+ "value": "Use the SDK: embed the agent in the program",
54
+ "description": "Runs inside the program on its own model key. No Penguin server; nothing appears in the Web App."
55
+ },
56
+ {
57
+ "label": "API: call a Penguin Agent",
58
+ "value": "Use the Agent API: call a Penguin Agent over AMSP",
59
+ "description": "Calls an Agent on your Penguin server. You turn on its API access and create a key; its conversations appear in the Web App."
60
+ }
61
+ ]
62
+ }
63
+ ```
64
+ ````
65
+
66
+ The Web App shows the block as two buttons; the CLI and the messaging channels show it as a numbered list. The answer arrives as the user's next message, in plain text: read it like any other message and build on the way it names.
15
67
 
16
68
  ## Before you start
17
69
 
18
- If the user's message only invokes this skill (e.g. "use penguin-sdk skill") without a concrete app to build, ask the user what they want to build. But when the request names a concrete goal — even a single sentence like "build a RAG app that answers questions about these docs" — do **not** ask follow-up questions: build it end to end with the defaults in this skill (self-contained workspace project, project default model, BM25 retrieval, web UI styled per the web-design skill) and list the assumptions you made in your final reply.
70
+ If the user's message only invokes this skill (e.g. "use penguin-sdk skill") without a concrete app to build, ask the user what they want to build. Once the request is concrete, settle the way first (see *Ask which way first*). Then do **not** ask follow-up questions: build it end to end with that way's defaults and list the assumptions you made in your final reply.
71
+
72
+ - SDK path: a self-contained workspace project, the project default model, BM25 retrieval, a web UI styled per the web-design skill.
73
+ - API path: a self-contained workspace project in TypeScript on `@prismshadow/amsp` (plain HTTP when the user's program is in another language), calling the Agent the user named ("you" means this Agent) or, with none named, a new Agent created for the purpose with the agent-initialization skill.
74
+
75
+ Each path also needs one thing only the user can provide: a model credential on the SDK path (see *Keys and the data root*), and on the API path the Agent's API access and key (see *The API path*).
76
+
77
+ ## The SDK path
78
+
79
+ `@prismshadow/penguin-core` is the TypeScript SDK this agent itself runs on. Use it to build your own AI apps:
80
+
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
+ - 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 OmniMessages.
19
84
 
20
- ## Project location
85
+ ### Project location
21
86
 
22
87
  Create the app in the current workspace directory by default (the `CWD` value from your Environment section), as a self-contained project — do not place it under `<app_data_dir>` (PenguinHarness's app data root) or depend on any path outside the project folder. When creating the app's agent, the data root defaults **under the working directory (CWD)** too: point `createAgent({ root })` at a directory inside the project, resolved from the source file so it stays relative:
23
88
 
@@ -27,7 +92,7 @@ const agent = await createAgent({ root: path.join(import.meta.dirname, "penguin_
27
92
 
28
93
  With every reference relative to the project, the user can move or copy the folder anywhere and it still runs.
29
94
 
30
- ## Keys and the data root — check before you build
95
+ ### Keys and the data root — check before you build
31
96
 
32
97
  **The app's Penguin data root must live inside the CWD workspace — never `~/.penguin`.** Point `createAgent({ root })` and every `penguin config ... --root <dir>` at a directory under the current working directory (e.g. `./penguin_data`); the global `~/.penguin` belongs to the person running Penguin and must never hold — or lend — the app's config or keys.
33
98
 
@@ -39,9 +104,9 @@ env | grep -oE "(DEEPSEEK|OPENAI|ANTHROPIC|GEMINI)_API_KEY" || echo none
39
104
 
40
105
  **Only two sources count as a usable credential**: a vault-injected environment variable (the check above; vault keys also appear in your Vault Keys section), or a key already configured in the app's own data root (`penguin config model list --root <data_dir>`). Keys in the global `~/.penguin` or any other `.penguin` directory do **not** count — a bare `penguin config model list` (no `--root`) reads the global store, because the CLI defaults to the global root unless `--root` is given, so a key showing up there proves nothing for the app and must never be used or copied.
41
106
 
42
- If neither counted source yields a key, **stop immediately and ask the user to configure one — do not start building, and do not burn turns re-checking in a loop**: have them open this agent's settings via the **gear icon** on its card (left side, Agents page) and add a model API key (e.g. `DEEPSEEK_API_KEY`) in the **key vault** tab — vault values reach your shell environment on the next task. One clear check, then hand back to the user. Build only after a credential is confirmed, or after clearly agreeing with the user to build now and verify later. Model ids to offer the user come from the penguin CLI catalog (`penguin config model add --help`) and the agenthub-models skill's id table.
107
+ If neither counted source yields a key, **stop immediately and ask the user to configure one — do not start building, and do not burn turns re-checking in a loop**: have them open this agent's settings via the **gear icon** on its card (left side, Agents page) and add a model API key (e.g. `DEEPSEEK_API_KEY`) in the **key vault** tab — vault values reach your shell environment on the next task. One clear check, then hand back to the user. Build only after a credential is confirmed, or after clearly agreeing with the user to build now and verify later. Model ids to offer the user come from the penguin CLI catalog (`penguin config model add --help`) and the unified-llm-api skill's id table.
43
108
 
44
- ## Setup
109
+ ### Setup
45
110
 
46
111
  ```bash
47
112
  npm install @prismshadow/penguin-core tsx
@@ -51,8 +116,8 @@ If the package is not on your npm registry (it is developed in the PenguinHarnes
51
116
 
52
117
  Configure a model for the app's data root, in this order — stop at the first that works:
53
118
 
54
- 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 agenthub-models 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).
55
- 2. Environment variables cover the **credential only** (`DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …) — model selection still comes from the project config, whose preset default is `deepseek-flash`. Env-only setup therefore works out of the box only with `DEEPSEEK_API_KEY`; for another vendor either run the CLI command above or pass a configured `{ provider, modelId }` pair to `createSession`.
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 an entry whose requests go to the **vendor's own endpoint** (no `--base-url`, or the vendor's official one) — an entry with a `--base-url` of its own (a gateway, a self-hosted server) needs `--api-key`, or `createSession` refuses it. Model selection still comes from the project config, whose preset default is `deepseek-flash`. Env-only setup therefore works out of the box only with `DEEPSEEK_API_KEY`; for another vendor either run the CLI command above or pass a configured `{ provider, modelId }` pair to `createSession`.
56
121
 
57
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.
58
123
 
@@ -60,7 +125,7 @@ Model config lives in one hidden file under the data root's project directory: `
60
125
 
61
126
  If the user agreed to build before a credential exists, do not fake the verification: finish the build, report it as **unverified**, and point them at the key vault flow above — once a key is added, vault values reach your environment on the next task and you can run the self-test to completion.
62
127
 
63
- ## Streaming loop
128
+ ### Streaming loop
64
129
 
65
130
  The raw `run()` stream mixes model, event and session-meta payloads — always narrow with the exported guards (`isModelMessage`, `isCompleteModelMessage`, `isEventMessage`) before touching `payload.type`; accessing `msg.payload.type` directly does not typecheck.
66
131
 
@@ -99,7 +164,7 @@ session.dispose();
99
164
  - Session lifetime is the app's memory model: reuse one Session for a stateful chat (context accumulates, as above), create one per request for stateless QA (the RAG recipe below); either way call `session.dispose()` when done to release background processes.
100
165
  - An Agent's behavior is edited in its `agent_state/` files (system_config.yaml, AGENTS.md, skills/), not in code.
101
166
 
102
- ## Thinking and image messages
167
+ ### Thinking and image messages
103
168
 
104
169
  Modern models think before answering and accept images; the stream and the input protocol carry both — use them instead of flattening everything to text.
105
170
 
@@ -116,15 +181,15 @@ Browser flow: `<input type="file" accept="image/*">` plus paste/drag-drop → `F
116
181
 
117
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; `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.
118
183
 
119
- ## Wiring in the user's tools
184
+ ### Wiring in the user's tools
120
185
 
121
186
  When the app's agent must call the user's existing tools (scripts, internal CLIs, anything with an entry point), integrate them as **CLI commands** first: wrap each one as a small executable inside the project (a script under `tools/`, or the user's own binary), and describe it in the embedded agent's persona / `AGENTS.md` — name, what it does, one usage line. The agent invokes it through the built-in `exec_command` tool, so there is nothing to register: no schema to declare, arguments are flags, stdout is the result, the `approve` callback still gates every invocation, and the same command stays testable by hand.
122
187
 
123
188
  Add an MCP server (`tools.mcpServers` in `system_config.yaml`) only when a CLI wrapper cannot express the integration — a long-lived authenticated connection, or tool schemas the model must see typed. Otherwise the CLI form is the cheaper default and keeps the project self-contained.
124
189
 
125
- ## RAG knowledge app
190
+ ### RAG knowledge app
126
191
 
127
- The default recipe when the user wants an app that answers questions over a document set ("docs QA", "knowledge base", "chat with our docs", "become an expert on X"). The core contributes the agent loop only — retrieval is app code. Default to **lexical BM25**: no extra dependencies, no embedding credential, works offline. (Semantic upgrade: embed chunks via `@prismshadow/agenthub` — see the agenthub-models skill — and rank by cosine; only when an embedding-capable key is configured.)
192
+ The default recipe when the user wants an app that answers questions over a document set ("docs QA", "knowledge base", "chat with our docs", "become an expert on X"). The core contributes the agent loop only — retrieval is app code. Default to **lexical BM25**: no extra dependencies, no embedding credential, works offline. (Semantic upgrade: embed chunks via `@prismshadow/mmsp` — see the unified-llm-api skill — and rank by cosine; only when an embedding-capable key is configured.)
128
193
 
129
194
  ```
130
195
  my-app/
@@ -344,7 +409,7 @@ http.createServer(async (req, res) => {
344
409
 
345
410
  **Persona** (`persona.md`) — the embedded agent's role, written per the agent-initialization skill. Shape: one role sentence ("You are an expert on X; you answer strictly from the provided context blocks"), citation and refusal rules, plain-text output (no Markdown — the output contract above), answer language follows the question.
346
411
 
347
- ## Verify before you hand over
412
+ ### Verify before you hand over
348
413
 
349
414
  Never declare the app done without running it:
350
415
 
@@ -357,3 +422,12 @@ Never declare the app done without running it:
357
422
  5. Open the UI (or screenshot it) to confirm the layout renders.
358
423
 
359
424
  Fix any failure and re-verify; when the app accepts image input, one verification question must include a real image. Report with backtick-wrapped relative paths (`server.ts`, `public/index.html`, …), how to start the app, and the assumptions you made.
425
+
426
+ ## The API path
427
+
428
+ The program calls an Agent that lives in PenguinHarness. You write the program; the Project's owner opens the Agent to it. Read [`reference/agent-api.md`](reference/agent-api.md) before you write any code: it has the steps to hand the owner, the client code, curl, the errors and the checks. These rules hold throughout:
429
+
430
+ - **Never open an Agent yourself.** Whether an Agent is open to programs is the owner's decision, and so is everything around it: API access, keys, keyless access, the API approval mode and the server-wide switch. An Agent must not be able to expose itself. The server refuses `penguin agent api enable`, `disable`, `set`, `keys create`, `keys rm` and `server` to the token in your shell with `403 human_required`, because they take a person's sign-in. Never run them, and never sign in or mint a session to get past that refusal. Ask the user to make the change on the Agent's **API** tab, or with those commands in their own terminal after `penguin auth login`, and give them the steps. `penguin agent api status` and `keys ls` only read; use them to check.
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
+ - **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
+ - **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`.