@penguinharness/agent-development 0.2.15 → 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@penguinharness/agent-development",
3
- "version": "0.2.15",
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 workflows (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.",
3
+ "version": "0.2.16",
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",
7
7
  "penguinharness",
@@ -23,9 +23,9 @@
23
23
  "access": "public"
24
24
  },
25
25
  "penguin": {
26
- "description_zh": "基于 PenguinHarness 的智能体开发:依据需求初始化智能体、用 SDK 构建应用或经 Agent API 接入智能体、搭建 Workflow(智能体自己维护的、对话旁的页面)、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。",
27
- "short_description": "Agent setup, SDK, Agent API, workflows, LLM API, config and orchestration.",
28
- "short_description_zh": "智能体初始化、SDK、Agent API、Workflow、LLM API、配置与编排。",
26
+ "description_zh": "基于 PenguinHarness 的智能体开发:依据需求初始化智能体、用 SDK 构建应用或经 Agent API 接入智能体、搭建 Workbench(智能体自己维护的、对话旁的页面)、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。",
27
+ "short_description": "Agent setup, SDK, Agent API, workbenches, LLM API, config and orchestration.",
28
+ "short_description_zh": "智能体初始化、SDK、Agent API、Workbench、LLM API、配置与编排。",
29
29
  "category": "ai-app-development",
30
30
  "icon": "icon.svg",
31
31
  "quick_start": {
@@ -34,6 +34,8 @@
34
34
  "skills": [
35
35
  "penguin-orchestration"
36
36
  ]
37
- }
37
+ },
38
+ "title": "Agent Development",
39
+ "title_zh": "智能体开发"
38
40
  }
39
41
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: agent-initialization
3
- description: Initialize or extend an Agent from a user requirement - write AGENTS.md, set identity metadata, and create, install or import Skills and hook packages (scripts the harness runs on every prompt, before tool calls, or after a task). For an agent that a program will use, the penguin-sdk skill first settles how the program reaches it.
4
- version: 2026.10.12.1
3
+ description: Initialize or extend an Agent from a user requirement - write AGENTS.md, set identity metadata, and create, install or import Skills and hook packages (scripts the harness runs on every prompt, before tool calls, or after a task). For an Agent with an in-app workbench, pair with penguin-plugin; for a standalone external program, use penguin-sdk.
4
+ version: 2026.10.14.1
5
5
  ---
6
6
 
7
7
  # Agent Initialization
@@ -12,11 +12,11 @@ This skill initializes an agent's settings from a user requirement — plain fil
12
12
 
13
13
  If the user's message only invokes this skill (e.g. "use agent-initialization skill") without a concrete requirement, ask the user what agent they want and what it should do. But when the requirement is already concrete — even a single sentence like "an expert that answers questions about X" — do **not** ask follow-up questions: derive the role and rules from that sentence, apply the defaults below, and list your assumptions in the final reply.
14
14
 
15
- One question comes first even then: when the agent is for a program to use, how the program reaches it is settled before you create anything (see *An agent for a program*).
15
+ An Agent Workbench inside PenguinHarness already has its runtime: create the new Agent and follow `penguin-plugin` for its tab. No SDK/API question is needed. Only an external program without a chosen architecture needs the question below.
16
16
 
17
17
  ## An agent for a program
18
18
 
19
- A program — an app, a service, a bot, a script — reaches a Penguin agent either embedded with the SDK or through the Penguin server's Agent API, and the two put the agent in different places. That choice is the penguin-sdk skill's, in this same plugin: whenever the requested agent is for a program, follow its *Ask which way first* before you create anything. An agent that people talk to, in the Web App, the CLI or a Remote-control bot, is not for a program and needs no question. Then:
19
+ An external program — an app, a service, a bot, a script outside PenguinHarness — reaches a Penguin agent either embedded with the SDK or through the Penguin server's Agent API, and the two put the agent in different places. That choice is the penguin-sdk skill's, in this same plugin: whenever the requested agent is for a program, follow its *Ask which way first* before you create anything. An agent that people talk to, in the Web App, the CLI or a Remote-control bot, is not for a program and needs no question. Then:
20
20
 
21
21
  - **SDK:** no Agent is created in this Project. Build the program with the penguin-sdk skill, and apply this skill to the program's embedded agent (see *The embedded agent of an SDK app*).
22
22
  - **API:** create or configure the Agent here with the rest of this skill. Its API access and keys are the owner's to turn on, never yours; the penguin-sdk skill's *The API path* and its `reference/agent-api.md` have the rules and the steps to hand the user.
@@ -79,8 +79,9 @@ Do not register Skills in AGENTS.md; the frontmatter is injected automatically.
79
79
 
80
80
  Common library bundles, so you don't under-equip the target:
81
81
 
82
- - **App builder** (builds apps or web frontends): `penguin-sdk`, `web-design`, `unified-llm-api`.
83
- - **Knowledge expert** (answers questions over a document set): usually a RAG app built with the penguin-sdk skill rather than a harness agent alone (see *An agent for a program*).
82
+ - **Workbench builder**: `agent-initialization`, `penguin-plugin`, `web-design`. The domain Agent it creates needs domain capabilities, not the builder bundle.
83
+ - **Standalone app builder**: `penguin-sdk`, `web-design`, `unified-llm-api`.
84
+ - **Knowledge expert**: document retrieval and citation instructions. For an in-app knowledge workspace, use `penguin-plugin`; use `penguin-sdk` only for a standalone external app.
84
85
  - **Evaluation loop**: `benchmark-design` and `agent-evaluation` (the `agent-evaluation` plugin), `agent-optimization` (the `default-rsi-toolkit` plugin).
85
86
 
86
87
  When creating a Test Agent, install only the capabilities it needs to solve ordinary tasks.
@@ -154,16 +155,16 @@ In the target's `agent_state/system_config.yaml`, set the top-level `name:` and
154
155
 
155
156
  ## Creating a brand-new agent
156
157
 
157
- Prefer configuring an agent the user already created. If the user requires a new Agent, confirm that `TARGET` does not exist. If it already exists, stop and tell the user; never silently overwrite, reinitialize, or reuse an existing Agent under the same id.
158
+ Prefer configuring an agent the user already created. If the user requires a new Agent, confirm that `TARGET` does not exist. If your chosen id already exists, choose an unused suffixed id for the requested new Agent; never overwrite, reinitialize, or silently reuse it. If the user required that exact id, explain the conflict.
158
159
 
159
- After confirming that the target is absent, pick a short id using letters, digits, `_`, or `-`, copy the default Agent's `system_config.yaml` as the base, and create the layout described above:
160
+ After confirming that the target is absent, pick a short id using letters, digits or `_` (not hyphens), copy the default Agent's `system_config.yaml` as the base, and create the layout described above:
160
161
 
161
162
  ```bash
162
163
  mkdir -p "$TARGET/agent_state/skills" "$TARGET/agent_state/hooks" "$TARGET/agent_state/memory" "$TARGET/agent_state/tools" "$TARGET/scratchpad"
163
164
  cp "$APP_DATA_DIR/agents/default_agent/agent_state/system_config.yaml" "$TARGET/agent_state/"
164
165
  ```
165
166
 
166
- Then set the top-level `name`, `description`, and `version: 1`, set `model.thinking_level` to the resolved value, write `agent_state/AGENTS.md` (it lives under `agent_state/`, not at the agent directory root), and install only the Skills and hook packages required by the user's requirement. Do not persist the resolved provider/model pair in the Agent State.
167
+ Then set the top-level `name`, `description`, and `version: 1`, set `model.thinking_level` to the resolved value, write `agent_state/AGENTS.md` (it lives under `agent_state/`, not at the agent directory root), and install only the Skills and hook packages required by the user's requirement. Do not persist the resolved provider/model pair in the Agent State. For a new Agent with a workbench, run the `penguin-plugin` check helper after writing its files: it first refreshes the Project's Agent index, so `host.createSession()` can find a file-created Agent before anybody opens the Agents page.
167
168
 
168
169
  ## Validate and report
169
170
 
@@ -1,46 +1,63 @@
1
1
  ---
2
2
  name: penguin-plugin
3
- description: Use for workflows — the tabs and pages beside the chat, with server code behind them, that an Agent keeps in its own `workflows/` folder inside PenguinHarness — building one, changing it, showing it as the whole app, restoring an earlier version, and removing a tab or a whole workflow when the user wants the custom UI gone.
4
- version: 2026.10.12.2
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
5
  ---
6
6
 
7
- # Penguin plugins: workflows
7
+ # Agent Workbench with Penguin Plugins
8
8
 
9
- Inside PenguinHarness an Agent can hold *workflows*: 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 workflow 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.
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
10
 
11
- A workflow 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.
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
12
 
13
13
  ## Before you start
14
14
 
15
- If the user's message only invokes this skill (e.g. "use penguin-plugin skill") without saying what the workflow 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.
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
16
 
17
- ## Start here — the whole loop is files
17
+ ## Build a new Agent and its workbench
18
18
 
19
- You need nothing but your file tools: no HTTP API, no port, no login, no server source. Do not go looking for the running server, its bundle or a checkout of the repository, and do not probe its API — everything you need to know is written into the workflow folder by the server itself.
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
20
 
21
- 1. *Where:* your Agent directory is `<App Data Dir>/agents/<Agent ID>/` — both values are in the Environment section of your system prompt. Workflows live in its `workflows/` folder (create it if it is missing); `ls` it to see what already exists before you add or change anything.
22
- 2. *Scaffold:* write the three files below — `package.json`, a minimal `index.ts`, one page under `ui/`. The server notices the folder within a second or two.
23
- 3. *Read what the server wrote back:* `.build/status.json` is the result of the last load — `{ ok, revision, checkedAt, error, tabs, hints }`. `ok: false` carries the compiler's or the checker's message with file, line and reason; fix that and look again. `ok: true` with an empty `tabs` means NOTHING shows in the user's chat page, however finished the page under `ui/` is: a page is only a file until `package.json` contributes a tab for it (see *Tabs are contributions* below), and `hints` spells out the entry to add. `.harness/README.md` is this same contract in the harness's own words — trust it over this skill if the two ever differ. `.harness/plugin.d.ts` is the exact `WorkflowHost` and `WorkflowMain` THIS harness offers — read it once instead of guessing at an interface.
24
- 4. *Iterate:* edit, wait a moment, read `.build/status.json` again. `checkedAt` changing tells you the server saw your edit. When it says `ok: true`, lists your tab under `tabs` and has no `hints`, the tab is already in the user's chat page — and not before. If `status.json` never appears, ask the user to open this Agent's chat page once (that is what starts the server watching the folder) rather than hunting for another way in.
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.
25
31
 
26
- What you do not need to find out by experiment: `host.run` resolves as soon as the turn has STARTED (not when it ends) with `{ sessionId, queued }`; `host.sessionStatus(id)` returns `"idle"`, `"running"` or `"compacting"`, so a run is finished when its Session is back to `"idle"`; `host.getState()` is synchronous and returns whatever was last passed to `setState` (`null` before the first one).
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.
27
44
 
28
45
  ## Layout
29
46
 
30
- Layout, under `<root>/<project_id>/agents/<agent_id>/workflows/<workflow_id>/` (beside `agent_state/`):
47
+ Layout, under `<root>/<project_id>/agents/<agent_id>/workbenches/<workbench_id>/` (beside `agent_state/`):
31
48
 
32
49
  ```
33
50
  package.json "type": "module" and "penguin": { "modules": [ …manifests ] } — no dependency to install
34
- index.ts default export { modules: { <Name>: { create(ctx) } } } satisfies WorkflowPackage — TypeScript only
35
- ui/ the workflow's pages and their assets; which of them are tabs is what the manifest contributes
36
- state.json the workflow's own document, kept by the server across reloads and rollbacks
37
- .harness/ the server's: the types this workflow was written against (plugin.d.ts) and their interface table — read plugin.d.ts, never edit it
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
38
55
  .build/ the server's: emitted JavaScript per revision, and status.json — the result of the last load; read it, never edit it
39
56
  ```
40
57
 
41
58
  ## The manifest and the handler
42
59
 
43
- The root manifest is named `Workflow`; it requires the host, provides the handler, and contributes its tabs:
60
+ The root manifest is named `Workbench`; it requires the host, provides the handler, and contributes its tabs:
44
61
 
45
62
  ```json
46
63
  {
@@ -50,9 +67,9 @@ The root manifest is named `Workflow`; it requires the host, provides the handle
50
67
  "penguin": {
51
68
  "modules": [
52
69
  {
53
- "name": "Workflow",
54
- "requires": { "host": { "iface": "@prismshadow/penguin-server#WorkflowHost", "from": "Host" } },
55
- "provides": { "main": "@prismshadow/penguin-server#WorkflowMain" },
70
+ "name": "Workbench",
71
+ "requires": { "host": { "iface": "@prismshadow/penguin-server#WorkbenchHost", "from": "Host" } },
72
+ "provides": { "main": "@prismshadow/penguin-server#WorkbenchMain" },
56
73
  "contributes": {
57
74
  "WebModule.sessionTabs": [
58
75
  { "id": "demo.main", "key": "main", "title": "Demo", "titleZh": "演示", "renderer": { "iframe": { "src": "ui/index.html" } } }
@@ -65,18 +82,18 @@ The root manifest is named `Workflow`; it requires the host, provides the handle
65
82
  ```
66
83
 
67
84
  ```ts
68
- import type { WorkflowPackage } from "@prismshadow/penguin-server/plugin";
85
+ import type { WorkbenchPackage, WorkbenchResponse } from "@prismshadow/penguin-server/plugin";
69
86
 
70
87
  export default {
71
88
  modules: {
72
- Workflow: {
89
+ Workbench: {
73
90
  create({ use }) {
74
91
  const host = use.host;
75
92
  return {
76
93
  api: {
77
94
  main: {
78
- async handle(req) {
79
- // req = { method, path, query, body }; path is below the workflow's api/ mount
95
+ async handle(req): Promise<WorkbenchResponse> {
96
+ // req = { method, path, query, body }; path is below the workbench's api/ mount
80
97
  if (req.path === "/ask" && req.method === "POST") {
81
98
  const { question } = req.body as { question: string };
82
99
  // The SDK's two verbs: open a Session, run a turn in it.
@@ -92,46 +109,84 @@ export default {
92
109
  },
93
110
  },
94
111
  },
95
- } satisfies WorkflowPackage;
112
+ } satisfies WorkbenchPackage;
96
113
  ```
97
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
+
98
151
  ## TypeScript, checked by the server
99
152
 
100
- 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 WorkflowPackage` 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.
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.
101
154
 
102
155
  ## Types come from the harness that runs you
103
156
 
104
- 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 `WorkflowHost` this harness offers. The server then leaves `.harness/` alone: it is the record of what the workflow was written against, and a later generation of the platform is COMPARED with it, by the TypeScript compiler, both for what the workflow 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 workflow onto the harness that runs it now, delete `.harness/` and fix what the compiler then reports.
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.
105
158
 
106
159
  ## Tabs are contributions
107
160
 
108
- Each entry under `WebModule.sessionTabs` is one tab beside the chat: `key` (unique in the workflow, 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 workflow. It is the same slot, written the same way, a plugin contributes to — the host opens it to workflows and scopes the tab to this Agent. A slot the host has not opened (`WebModule.pages`, say) is refused by name.
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.
109
162
 
110
163
  ## The host
111
164
 
112
- `WorkflowHost` (published as module `Host`) speaks the SDK's verbs, scoped to the workflow'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 }`; `run(sessionId, [{ text: "…" }])` — the SDK's `session.run`, its input items spelled out because a workflow 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` / …; `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 `Workflow`, with their own `requires` between them — the tree is checked as a whole.
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.
113
166
 
114
167
  ## HTTP
115
168
 
116
- HTTP, all under `/api/projects/:projectId/agents/:agentId/workflows` (Project members only): `GET /` lists the workflows 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 workflow 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.
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.
117
170
 
118
171
  ## Undoing, reverting, removing (撤销 / 还原 / 清掉界面)
119
172
 
120
- 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 workflow is files in your own Agent directory, so each of these is a file operation you make yourself — list `workflows/` first to see what exists. The server notices within a moment and the user's tabs follow without a refresh.
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.
121
174
 
122
- 1. *"Get rid of it" / "back to before there was any custom UI" / 回到没定义 UI 的状态* — remove the workflow entirely: delete the folder `workflows/<id>/` **and** its recorded versions `workflows-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 workflow you were not asked to remove. (The user can do the same from the tab's bar: *Remove*, two clicks.)
123
- 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 `workflows-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*.
124
- 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 workflow keeps its server code and has no UI at all.
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.
125
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.
126
179
 
127
- One constraint follows from 4, and it is a constraint on you, not a task to go and do: the workflow'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.
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.
128
181
 
129
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.
130
183
 
131
184
  ## Theme
132
185
 
133
- A workflow 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 `/workflow-ui.css` first in the head — a base stylesheet that styles plain HTML (headings, lists, forms, tables, code) to match the app and exposes `--wf-bg`, `--wf-fg`, `--wf-muted`, `--wf-border`, `--wf-surface`, `--wf-accent`, `--wf-accent-fg`, plus the classes `wf-primary` (a button), `wf-card`, `wf-rows`, `wf-row`, `wf-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 `/workflow-ui.css` yourself makes it look right when opened outside the app too.
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.
134
189
 
135
190
  ## Filling the app
136
191
 
137
- A page can be shown as the whole app — no sidebar, no chat, no tab strip — at `/app/<project>/<agent>/<workflow>[/<tab key>]` (the workflow's first tab when no key is given): the tab's *Fill the app* button goes there, `penguin web --app <project>/<agent>/<workflow>[/<tab key>]` opens the browser straight onto it, and the page itself can ask with `parent.postMessage({ type: "penguin:fill-app" }, "*")`. The way back is the command palette, whose *Exit full page* lands on that Agent's chat. 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 never `preventDefault` that chord: on this route it is the only way out.
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,12 +1,12 @@
1
1
  ---
2
2
  name: penguin-sdk
3
- description: Use whenever the user wants to build an agent application — their own program with an agent in it, such as an AI app, an agentic app, a RAG app or a bot — or to connect a program to a Penguin agent. 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. Workflows — 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.12.2
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
5
5
  ---
6
6
 
7
7
  # Penguin Harness SDK and Agent API
8
8
 
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. Workflows — pages and server code an Agent keeps inside PenguinHarness — are a third thing, and the penguin-plugin skill's.
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.
10
10
 
11
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
12
 
@@ -35,7 +35,7 @@ Do not ask when the way is already chosen:
35
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
36
  - earlier in this conversation, for the same program.
37
37
 
38
- Naming this skill does not choose a way. Workflows (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.
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
39
 
40
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
41
 
@@ -79,12 +79,12 @@ const client = new AgentClient({
79
79
  });
80
80
 
81
81
  // One question, the whole answer.
82
- const first = await client.ask({ input: "Summarize README.md" });
82
+ const first = await client.run({ input: "Summarize README.md" });
83
83
  if (first.status !== "completed") throw new Error(`${first.status}: ${first.error?.message ?? ""}`);
84
84
  console.log(first.text);
85
85
 
86
86
  // The same conversation, streamed: pass its Session id back.
87
- const run = client.run({
87
+ const run = client.stream({
88
88
  sessionId: first.sessionId,
89
89
  input: "Now list its headings",
90
90
  onApproval: (request) => {
@@ -99,10 +99,10 @@ for await (const event of run) {
99
99
  const second = await run.result();
100
100
  ```
101
101
 
102
- - `ask()` runs to the end and resolves with the result: `status`, `error`, `sessionId`, `text` (the main conversation's answer), `items`, `usage`, `sessionUsage` and `requests`. `run()` starts the run and returns it at once: iterate it once for the events, await `run.session` for the Session id, and `run.result()` for the end.
102
+ - `run()` runs to the end and resolves with the result: `status`, `error`, `sessionId`, `text` (the main conversation's answer), `items`, `usage`, `sessionUsage` and `requests`. `stream()` starts the run and returns it at once: iterate it once for the events, await `run.session` for the Session id, and `run.result()` for the end.
103
103
  - **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
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 request in the Web App; the first answer counts.
105
- - **Aborting.** Abort the `signal` passed to `run()` or `ask()` to drop the connection: the server aborts the run. `run.abort()` asks the server to abort and still delivers the final `run.done`, with `status: "aborted"`.
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 still delivers the final `run.done`, with `status: "aborted"`.
106
106
  - **Failures.** A refusal before the stream starts rejects with `AmspHttpError` (`status`, `code`, `message`; see section 5). After that, `result()` resolves for every run: check `status` (`completed`, `aborted`, `retryable` or `fatal`) and `error`. A stream that breaks before `run.done` rejects with `AmspStreamError`.
107
107
  - **Unknown events** are passed through. Switch on `event.type` with a default branch.
108
108
  - **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 `text.delta` events 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.