A local-first multi-agent app development platform, built on PenguinHarness
feat: allow agents to register its owned modules, a.k.a. workflow (#718)
Myriad-Dreamin9537a2840aaa
diff --git a/changelog/unreleased/2026-08-30-command-palette.md b/changelog/unreleased/2026-08-30-command-palette.mdindex 588d2cee..c9dc82fa 100644--- a/changelog/unreleased/2026-08-30-command-palette.md+++ b/changelog/unreleased/2026-08-30-command-palette.md@@ -6,7 +6,7 @@[中文版](2026-08-30-command-palette.zh.md)-Ctrl+P (⌘P on macOS) opens a VS Code-style command palette: an input that filters a list of commands, ↑↓ to select, Enter to run, Escape to close. The palette is the mechanism; commands register with it instead of claiming shortcuts of their own.+Ctrl+P or Ctrl+Shift+P (⌘P / ⌘⇧P on macOS) opens a VS Code-style command palette: an input that filters a list of commands, ↑↓ to select, Enter to run, Escape to close. The palette is the mechanism; commands register with it instead of claiming shortcuts of their own.## Harness historydiff --git a/changelog/unreleased/2026-08-30-command-palette.zh.md b/changelog/unreleased/2026-08-30-command-palette.zh.mdindex 9721369e..3e9e926b 100644--- a/changelog/unreleased/2026-08-30-command-palette.zh.md+++ b/changelog/unreleased/2026-08-30-command-palette.zh.md@@ -6,7 +6,7 @@[English](2026-08-30-command-palette.md)-Ctrl+P(macOS 上为 ⌘P)打开一个 VS Code 风格的命令面板:一个输入框筛选命令列表,↑↓ 选择,Enter 执行,Escape 关闭。面板是机制;命令向它注册,而不是各自占用快捷键。+Ctrl+P 或 Ctrl+Shift+P(macOS 上为 ⌘P / ⌘⇧P)打开一个 VS Code 风格的命令面板:一个输入框筛选命令列表,↑↓ 选择,Enter 执行,Escape 关闭。面板是机制;命令向它注册,而不是各自占用快捷键。## Harness 历史diff --git a/changelog/unreleased/2026-08-30-workflows.md b/changelog/unreleased/2026-08-30-workflows.mdnew file mode 100644index 00000000..b801c8d8--- /dev/null+++ b/changelog/unreleased/2026-08-30-workflows.md@@ -0,0 +1,48 @@+# Workflows: an Agent's own page and server code, hot-reloaded and versioned++- **Date:** 2026-08-30+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `cli`, `skills`+- **PR:** [#718](https://github.com/Prism-Shadow/penguin-harness/pull/718)++[中文版](2026-08-30-workflows.zh.md)++An Agent can now keep *workflows* in its own directory: `workflows/<id>/` holds a plugin package — `package.json#penguin.modules` manifests, an `index.ts` whose default export pairs them with code, its pages under `ui/` — that the server boots as a module tree of its own. It is the same mechanism the server is built from and that plugins use, and everything is checked before any of the workflow's code runs: 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, and the previous version keeps serving.++## Contract++The root module `Workflow` requires `WorkflowHost` (published by the server as module `Host`: the SDK's verbs scoped to the Project — `listAgents()`, `createSession({ agentId? })` for this Agent or another of the same Project, `run(sessionId, [{ text: "…" }])` for a turn in a new or existing Session, queued as a follow-up when it is busy — plus `sessionStatus`, `getState` / `setState` over the workflow's `state.json`, `log`) and provides `WorkflowMain` — a handler `handle({ method, path, query, headers, body, bytes? })` the server mounts at `/api/projects/:p/agents/:a/workflows/:id/api/*`. JSON is the default in both directions; a request body of any other content type reaches the handler as `bytes` (50 MB at most; the app's `cookie` and `authorization` headers are withheld), and a response that names a `content-type` in `headers` is sent as written — `body` as a string, `bytes` as binary, `stream` (an async iterable of strings or bytes) chunk by chunk as it is produced, so server-sent events and a relayed streaming answer are not held back until the end; `location` with a 3xx for a redirect (`set-cookie` is dropped). So a handler can take an upload, answer a page or a download, or relay a program it runs on its own machine, which a page cannot reach when the browser is elsewhere. The workflow's `ui/` is served at `…/workflows/:id/ui/*`. Nothing is added to any Agent's system prompt: the `penguin-sdk` skill carries the layout and the contract, loaded when an Agent is asked for a workflow.++## TypeScript, checked by the server++A workflow is TypeScript — `index.ts`; a folder with `index.js` or `index.mjs` is refused. The server builds one compiler program from the entry under options it fixes itself (`strict`; a `tsconfig.json` in the folder is not consulted), and also assigns the default export to `WorkflowPackage`, so the shape is checked whether or not the author wrote `satisfies WorkflowPackage`. Any diagnostic fails the load, reported as file, line, column and reason; a clean program is emitted into `<workflow>/.build/<revision>/`, a dot-directory that is no part of the revision, the recorded versions or what the watcher reacts to, and that is what gets imported. The compiler is the one the plugin interface check made a runtime dependency and ships with a hot push ([#808](https://github.com/Prism-Shadow/penguin-harness/pull/808)); an installation without it loads no workflow and says so.++## Types from the harness, compared across generations++A workflow installs nothing: one machine can run several harnesses — a release, a checkout, a pushed platform with interfaces of its own — and none of them is a version on npm. The first load writes `<workflow>/.harness/`, rendered from THIS platform's interface table: `plugin.d.ts`, which `@prismshadow/penguin-server/plugin` resolves to for that workflow, and `ifaces.json`, the slice of the table it was rendered from. It is then left alone — the record of what the workflow was written against — until someone deletes it. That record is what makes the interface comparison real: looking a required interface up in the platform's own table compares a declaration with itself, which can never fail, so each side brings its own — the workflow's `.harness/ifaces.json`, the platform's table — each is rendered as a self-contained `.d.ts`, and the TypeScript compiler decides, in both directions: the platform's interface must be assignable to what the workflow requires, and what the workflow provides must be assignable to what the platform asks for. A host method the workflow was written against that has since gone is a load error naming it; an addition on the platform's side breaks nothing. A table that cannot be read is a problem and never a pass; an expression the renderer cannot write as TypeScript is refused by name rather than widened. It is the comparison a plugin package gets at load ([#808](https://github.com/Prism-Shadow/penguin-harness/pull/808)), with one difference: a workflow's table is written by the harness and is complete, so an interface it holds no copy of is a load error rather than a line in the log.++## Tabs are contributions++A workflow's manifest contributes its tabs to `WebModule.sessionTabs` — the slot a plugin contributes to, written the same way, which the host publishes into the workflow's tree and scopes to the Agent: `key`, `title` / `titleZh`, and a `renderer` whose `iframe.src` is a file under `ui/`. Several entries are several tabs; none is a server-only workflow; a slot the host has not opened is refused by name. The list returns them as `tabs`, each page's URL resolved, and keeps the serving instance's tabs while a broken edit is reported. The slot's shape gains `title` / `titleZh` and its renderer drops the unused `namespace`. `ui/` no longer has a default document: a tab names its page.++## Reload and rollback++The server watches the Agent's `workflows/` folder and reloads a workflow when its files change (also `POST …/:id/reload`); the emitted code lives under the folder's content hash, so an edited module is a new import URL and never served from the module cache. Loads of one workflow run one at a time, since each now takes a compiler run. Every load writes its result to `<workflow>/.build/status.json` (`ok`, `revision`, `checkedAt`, `error`, `tabs`, `hints`), so the Agent that wrote the workflow — which has its files and no session with the HTTP API — reads whether its edit loaded, and the compiler's message if it did not; `hints` (also on the workflow in the API) names what loaded but is probably not what was meant, with the edit that settles it — today, pages under `ui/` that no tab shows, with the `WebModule.sessionTabs` entry to add. The harness also writes `.harness/README.md`, its own contract in brief (files, the manifest, tabs, the status file), because an Agent's installed SDK skill is a copy a push does not refresh; and an Agent's first `workflows/` folder is noticed when it appears, not only when somebody lists the workflows again. Every successful load is recorded under `workflows-history/<id>/<revision>/` (twenty kept, `GET …/:id/history`), and `POST …/:id/rollback { revision }` restores that version's files — `state.json` untouched — and reloads. `DELETE …/:id` removes the workflow together with its versions. Users of the Project hear `workflow_updated` and `workflow_removed` on their event stream, so a tab appears, refreshes or disappears without a reload.++## Web App++Each contributed tab sits beside *Chat* at the top of the chat page, titled in the user's language; the tab shows its page in an iframe (reloaded when the UI's revision changes, the chat staying mounted underneath), with the workflow's version and revision, its load error when the current files do not boot, a *Reload* button, a *History* fold with a *Restore* button per recorded version, and a two-click *Remove*.++## Filling the app++A page can be the whole app: `/app/:projectId/:agentId/:workflowId[/:tabKey]` shows one workflow page — the tab that key names, or the workflow's first — with no sidebar, chat or tab strip. The tab's *Fill the app* button navigates there, the page itself can ask with `parent.postMessage({ type: "penguin:fill-app" }, "*")`, and `penguin web --app <project>/<agent>/<workflow>[/<tab>]` opens the browser straight onto it (`Invalid --app` before anything starts when the spec is not three or four segments). The route has no chrome to leave by on purpose; the command palette is the way out — it now answers **Ctrl+Shift+P as well as Ctrl+P** (⌘ on macOS), so a page that takes one chord for itself cannot trap the user — and on that route carries *Exit full page (back to chat)*, which remembers the Project and Agent and lands on their chat.++## Theme++A workflow page is its own document, so the app's stylesheet reaches none of it. The frame now stamps `light` / `dark` on the page's root, copies the app's *resolved* tokens onto it — the gray scale, the accent pair, the font stack, the root font size — and injects `/workflow-ui.css` first in its 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`, `wf-card`, `wf-rows`, `wf-row`, `wf-muted`. The page's own rules still win, and the palette keeps one definition: the app copies what it already resolved instead of the stylesheet restating it. Switching theme or accent re-themes an open page without reloading it. The skill asks for markup written against those variables, so a workflow an Agent writes matches the user's theme in both directions.++The `penguin-sdk` skill documents the layout and the contract. The new-chat page's *Build and optimize agents* examples gain **Build a custom workflow UI: mission control** — a workflow that dispatches one task to several of the Project's Agents in parallel and shows every Session's live status, with a second tab of statistics and a fill-the-app view — in place of the Claude Code docs RAG example.++## Interface checks parse once per process++Every module-tree boot — a workflow's, a plugin's, the platform's own — checks each wire and contribution against its interface, and each leaf comparison and slot schema was parsed by arktype afresh. arktype files every parse in a registry that lives as long as the process and never shrinks, so each boot added thousands of entries: a long-running server grew with every hot push, plugin load and workflow reload, and a test worker booting hundreds of apps stalled outright. A leaf comparison is now decided once per process and remembered, and a slot's schema is parsed once per definition; both come from interface tables, so there are only so many.diff --git a/changelog/unreleased/2026-08-30-workflows.zh.md b/changelog/unreleased/2026-08-30-workflows.zh.mdnew file mode 100644index 00000000..3a48aa80--- /dev/null+++ b/changelog/unreleased/2026-08-30-workflows.zh.md@@ -0,0 +1,48 @@+# 工作流:Agent 自己的页面与服务端代码,热重载并可回滚++- **Date:** 2026-08-30+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `cli`, `skills`+- **PR:** [#718](https://github.com/Prism-Shadow/penguin-harness/pull/718)++[English](2026-08-30-workflows.md)++Agent 现在可以在自己的目录里保存*工作流*:`workflows/<id>/` 是一个插件包——`package.json#penguin.modules` 里的清单、默认导出把清单与代码按名配对的 `index.ts`、放在 `ui/` 下的页面——服务器把它作为一棵独立的模块树启动。这与服务器自身以及插件所用的是同一套机制,并且一切检查都在工作流的任何代码运行之前完成:类型检查不过、它所依据的接口版本已与本服务器不合、或清单自身不成立的工作流,都会带着具名的问题加载失败,而上一个版本继续服务。++## 契约++根模块 `Workflow` 要求 `WorkflowHost`(服务器以 `Host` 模块发布:限定在本 Project 之内的 SDK 动词——`listAgents()`、`createSession({ agentId? })` 为本 Agent 或同一 Project 的另一个 Agent 开一个 Session,`run(sessionId, [{ text: "…" }])` 在新的或已有的 Session 里跑一轮,Session 正忙时作为后续消息排队——以及 `sessionStatus`、基于工作流 `state.json` 的 `getState` / `setState`、`log`),并提供 `WorkflowMain`——处理器 `handle({ method, path, query, headers, body, bytes? })`,服务器把它挂在 `/api/projects/:p/agents/:a/workflows/:id/api/*`。收发两个方向都以 JSON 为默认;其他内容类型的请求体以 `bytes` 交给处理器(上限 50 MB;应用自己的 `cookie` 与 `authorization` 请求头不会传入),而在 `headers` 里写明 `content-type` 的响应按原样发出——`body` 为字符串,`bytes` 为二进制,`stream`(字符串或字节的异步可迭代对象)则随产生逐块发出,server-sent events 与被转发的流式应答因此不必等到结束;`location` 加 3xx 状态即重定向(`set-cookie` 会被丢弃)。处理器因此可以接收上传、返回页面或下载,也可以转发它在本机上运行的程序——浏览器在另一台机器上时,页面自己是够不到那个程序的。工作流的 `ui/` 从 `…/workflows/:id/ui/*` 提供。不向任何 Agent 的系统提示词添加内容:目录布局与契约由 `penguin-sdk` 技能承载,Agent 被要求做工作流时才加载。++## TypeScript,由服务器检查++工作流以 TypeScript 编写——`index.ts`;只有 `index.js` 或 `index.mjs` 的目录会被拒绝。服务器以入口文件构建一个编译器程序,编译选项由服务器固定(`strict`;目录里的 `tsconfig.json` 不被采用);同时把默认导出赋给 `WorkflowPackage`,因此无论作者是否写了 `satisfies WorkflowPackage`,形状都会被检查。任何诊断都使加载失败,并以文件、行、列与原因报出;通过的程序被输出到 `<workflow>/.build/<revision>/`——一个点目录,不计入修订、不进版本记录、也不触发监视器——被导入的正是它。所用的编译器就是插件接口检查引入的那一个——它成为运行时依赖,并随热推送一起送达([#808](https://github.com/Prism-Shadow/penguin-harness/pull/808));没有它的安装不加载任何工作流,并说明原因。++## 类型来自 harness,跨代比较++工作流不安装任何东西:一台机器上可以有多个 harness——发行版、某个检出、别人推送的带着自己接口的平台——它们都不是 npm 上的某个版本。第一次加载时服务器写下 `<workflow>/.harness/`,内容由**这个**平台自己的接口表渲染:`plugin.d.ts`(该工作流里 `@prismshadow/penguin-server/plugin` 解析到的就是它)与 `ifaces.json`(渲染它所用的那一部分表)。此后服务器不再动它——它是「这个工作流写下时依据什么」的记录——直到有人删除。接口比较靠的正是这份记录:在平台自己的表里查一个被依赖的接口,是拿一条声明与它自己比较,永远不会失败;现在两侧各带自己的那一份——工作流的 `.harness/ifaces.json` 与平台的表——各渲染为一份自包含的 `.d.ts`,由 TypeScript 编译器在两个方向上判定:平台的接口须可赋值给工作流所依赖的,工作流所提供的须可赋值给平台所要求的。工作流写下时依据、此后已被删除的宿主方法,是一条点名它的加载错误;平台一侧的新增不影响任何工作流。读不出来的表是问题而绝不算通过;渲染器无法如实写成 TypeScript 的表达式按名拒绝,而不是放宽。这正是插件包在加载时得到的那种比较([#808](https://github.com/Prism-Shadow/penguin-harness/pull/808)),只有一点不同:工作流的表由 harness 写下、是完整的,所以表里没有副本的接口对工作流而言是加载错误,而不是日志里的一行。++## 标签页是贡献++工作流在清单里向 `WebModule.sessionTabs` 投稿它的标签页——与插件投稿的是同一个槽、同一种写法,由宿主发布进工作流的树并限定于该 Agent:`key`、`title` / `titleZh`,以及 `iframe.src` 指向 `ui/` 下某个文件的 `renderer`。几条投稿即几张标签页;没有投稿即纯服务端的工作流;宿主未开放的槽按名拒绝。列表以 `tabs` 返回它们,各页面的 URL 已解析;报告一次失败的编辑时,保留的是服务着的那个实例的标签页。该槽的形状增加 `title` / `titleZh`,其 renderer 去掉了无人使用的 `namespace`。`ui/` 不再有缺省文档:标签页自己点名页面。++## 重载与回滚++服务器监视 Agent 的 `workflows/` 目录,文件变化时重新加载对应工作流(也可 `POST …/:id/reload`);输出的代码放在以目录内容哈希命名的位置,改过的模块是一个新的导入 URL,不会从模块缓存里被拿出来。同一个工作流的加载逐次进行,因为每次加载现在都要跑一遍编译器。每次加载的结果写入 `<workflow>/.build/status.json`(`ok`、`revision`、`checkedAt`、`error`、`tabs`、`hints`):写工作流的 Agent 手里只有文件、没有 HTTP API 的会话,它由此得知刚才的修改是否加载成功、失败时编译器说了什么;`hints`(API 返回的工作流上也有)指出「加载成功但多半不是本意」的情形并给出对应的修改——目前是 `ui/` 下有页面却没有任何标签页展示它,并附上应添加的 `WebModule.sessionTabs` 条目。Harness 还会写入 `.harness/README.md`,用自己的话简述这份约定(文件、清单、标签页、状态文件),因为 Agent 已安装的 SDK Skill 只是副本,推送不会刷新它;Agent 的第一个 `workflows/` 目录在出现时即被发现,而不必等有人再次列出工作流。每次成功加载都记录在 `workflows-history/<id>/<revision>/`(保留二十个,`GET …/:id/history`),`POST …/:id/rollback { revision }` 恢复该版本的文件——`state.json` 不动——并重新加载。`DELETE …/:id` 连同版本一起删除工作流。Project 的用户会在事件流上收到 `workflow_updated` 与 `workflow_removed`,标签页因此无需刷新即可出现、更新或消失。++## Web App++每一条投稿的标签页都在聊天页顶部、*聊天* 旁边,标题随用户的语言显示;标签页以 iframe 展示其页面(UI 版本变化时重新加载,聊天在其下保持挂载),并显示工作流的版本与修订、当前文件启动失败时的加载错误、*重新加载* 按钮、每个已记录版本带 *恢复* 按钮的 *历史* 折叠面板,以及需点击两次的 *移除*。++## 占满应用++页面可以成为整个应用:`/app/:projectId/:agentId/:workflowId[/:tabKey]` 只显示某个 workflow 的一张页面——该 key 所指的标签页,缺省为第一张——没有侧栏、聊天和标签条。标签页上的 *占满应用* 按钮会跳到这里,页面自己也可以用 `parent.postMessage({ type: "penguin:fill-app" }, "*")` 请求,`penguin web --app <project>/<agent>/<workflow>[/<tab>]` 则让浏览器直接打开到这个页面(spec 不是三段或四段时在启动任何东西之前就报 `Invalid --app`)。这个路由刻意没有任何可点的退出入口;出口是命令面板——它现在同时响应 **Ctrl+Shift+P 与 Ctrl+P**(macOS 为 ⌘),页面拿走其中一个也困不住用户——并在该路由上多出 *退出全页模式(回到聊天)*,会记住 Project 与 Agent 并落到它们的聊天页。++## 主题++工作流页面是独立文档,应用的样式表照不进去。现在框架会在页面根节点打上 `light` / `dark`,把应用*已解析*的令牌复制过去——灰阶、强调色对、字体栈、根字号——并把 `/workflow-ui.css` 注入到 head 最前面:这份基础样式表按应用的观感为纯 HTML(标题、列表、表单、表格、代码)定样,并暴露 `--wf-bg`、`--wf-fg`、`--wf-muted`、`--wf-border`、`--wf-surface`、`--wf-accent`、`--wf-accent-fg`,以及 `wf-primary`、`wf-card`、`wf-rows`、`wf-row`、`wf-muted` 等类。页面自己的规则依然优先;调色板只有一份定义——应用复制它已经解析出来的值,样式表不再重述一遍。切换主题或强调色会直接给已打开的页面换装,无需重新加载。技能要求用这些变量书写标记,因此 Agent 写出的工作流在明暗两种主题下都与用户的主题一致。++`penguin-sdk` 技能记录了目录布局与契约。新建对话页的「搭建和优化智能体」示例新增 **搭建自定义工作流界面:Agent 指挥台**——一个把同一任务并行派给本 Project 多个 Agent、实时显示每个 Session 状态的工作流,另有一张统计标签页与占满应用的大屏视图——取代了原来的 Claude Code 文档 RAG 示例。++## 接口检查每个进程只解析一次++每次启动模块树——工作流的、插件的、平台自身的——都要把每条连线和每个 contribution 与其接口比对,而每次叶子比较和每个 slot 的 schema 都由 arktype 重新解析一遍。arktype 会把每次解析登记到一张与进程同寿、从不收缩的注册表里,于是每次启动都要往里添上数千条:长期运行的服务器随每次热推送、插件加载和工作流重载不断增长,启动数百个 App 的测试 worker 更是直接卡死。现在叶子比较在每个进程里只判定一次并记住结果,slot 的 schema 按定义只解析一次;二者都来自接口表,数量有限。diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.tsindex 674b8cf8..839ad16d 100644--- a/packages/cli/src/commands/serve.ts+++ b/packages/cli/src/commands/serve.ts@@ -3,7 +3,7 @@** penguin server [--port <port>] [--host <host>]* penguin server reset-admin-password (subcommand, see reset-password.ts)- * penguin web [--port <port>] [--host <host>] [--no-open]+ * penguin web [--port <port>] [--host <host>] [--no-open] [--app <project>/<agent>/<workflow>[/<tab>]]** Both are entry points into the same service process: after setting PORT / HOST, it* dynamically imports `@prismshadow/penguin-server` (whose entry point handles dotenv@@ -86,6 +86,23 @@ export function browserUrl(host: string, port: number): string {return `http://${target}:${port}/`;}+/**+ * `--app <project>/<agent>/<workflow>[/<tab>]` → the path of that workflow page as the whole+ * app (the Web App's /app route: no sidebar, no chat; the command palette is the way out).+ * A workflow contributes its tabs, so a fourth segment names one by its key; without it the+ * workflow's first tab opens. Three or four non-empty segments; anything else is a usage+ * error. Exported for unit tests.+ */+export function appPagePath(spec: string): string {+ const parts = spec.split("/");+ if ((parts.length !== 3 && parts.length !== 4) || parts.some((p) => p === "")) {+ throw new Error(+ `Invalid --app "${spec}". Expected <project>/<agent>/<workflow>[/<tab>], e.g. default_project/default_agent/todo.`,+ );+ }+ return `app/${parts.map(encodeURIComponent).join("/")}`;+}+/*** The CLI entry script advertised to the server for the admin self-update endpoint* (POST /api/version/update re-runs it as `node <entry> update --yes`), or null when it@@ -355,7 +372,10 @@ export function registerServeCommands(program: Command, t: Messages): void {.option("--port <port>", t.serve.port).option("--host <host>", t.serve.host).option("--no-open", t.serve.noOpen)- .action(async (opts: { port?: string; host?: string; open: boolean }) => {+ .option("--app <spec>", t.serve.app)+ .action(async (opts: { port?: string; host?: string; open: boolean; app?: string }) => {+ // Resolved first so a malformed spec fails before anything starts.+ const page = opts.app === undefined ? "" : appPagePath(opts.app);const existing = await existingInstanceUrl();if (existing !== null) {process.stdout.write(t.webAlreadyRunning(existing) + "\n");@@ -363,7 +383,7 @@ export function registerServeCommands(program: Command, t: Messages): void {// no admin password yet prints a first-login LINK, and that link's token lives only// in the running server's memory — this terminal cannot reproduce it, and should// not. Its own console has it; restarting reissues it.- if (opts.open) openBrowser(existing);+ if (opts.open) openBrowser(existing + page);return;}const { host, port } = await startServer(opts, t);@@ -375,7 +395,7 @@ export function registerServeCommands(program: Command, t: Messages): void {);return;}- process.stdout.write(`${t.webReady(url)}\n`);- if (opts.open) openBrowser(url);+ process.stdout.write(`${t.webReady(url + page)}\n`);+ if (opts.open) openBrowser(url + page);});}diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex 7126377e..b178a3ec 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -565,6 +565,7 @@ export interface Messages {noOpen: string;/** Printed by the supervising process as it relaunches the service on a restart request (the web UI's "restart to update"). */restarting: string;+ app: string;};/** `penguin server reset-admin-password`: help text and every line the command can print. */auth: {@@ -1353,6 +1354,7 @@ const en: Messages = {host: "Listen address (falls back to the HOST env var, default 127.0.0.1)",noOpen: "Do not open a browser automatically",restarting: "Restarting the service to apply the update…",+ app: "Open one workflow page as the whole app: <project>/<agent>/<workflow>[/<tab>] (Ctrl+P or Ctrl+Shift+P in the page opens the command palette to leave)",},auth: {desc: "Sign in to a PenguinHarness server from the terminal",@@ -2103,6 +2105,7 @@ const zh: Messages = {host: "监听地址(其次取环境变量 HOST,缺省 127.0.0.1)",noOpen: "不自动打开浏览器",restarting: "正在重启服务以应用更新…",+ app: "以某个 workflow 页面占满整个应用打开:<project>/<agent>/<workflow>[/<tab>](页面内按 Ctrl+P 或 Ctrl+Shift+P 打开命令面板可退出)",},auth: {desc: "在终端里登录 PenguinHarness 服务",diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.tsindex dd3f8785..c0df6d17 100644--- a/packages/cli/test/serve.test.ts+++ b/packages/cli/test/serve.test.ts@@ -6,6 +6,7 @@ import {DEFAULT_HOST,DEFAULT_PORT,browserCommand,+ appPagePath,browserUrl,cliEntryFor,describeReadinessFailure,@@ -222,3 +223,19 @@ describe("readiness probe diagnostics", () => {}});});++describe("appPagePath (--app <project>/<agent>/<workflow>[/<tab>])", () => {+ it("maps the spec to the Web App's full-page route, segments encoded", () => {+ expect(appPagePath("default_project/default_agent/todo")).toBe(+ "app/default_project/default_agent/todo",+ );+ expect(appPagePath("p 1/a/w")).toBe("app/p%201/a/w");+ // A workflow contributes its tabs; a fourth segment names one by its key.+ expect(appPagePath("p/a/todo/stats")).toBe("app/p/a/todo/stats");+ });+ it("refuses anything but three or four non-empty segments", () => {+ for (const bad of ["todo", "p/a", "p/a/w/x/y", "p//w", "/a/w", "p/a/w/"]) {+ expect(() => appPagePath(bad)).toThrow(/Invalid --app/);+ }+ });+});diff --git a/packages/core/src/kernel/check.ts b/packages/core/src/kernel/check.tsindex 65d1acd3..6fff13e2 100644--- a/packages/core/src/kernel/check.ts+++ b/packages/core/src/kernel/check.ts@@ -211,7 +211,7 @@ export function checkTree(}let schema: ((v: unknown) => unknown) | null = null;try {- schema = type.raw(inlineRefs(slot.data, tableOf(table).types)).onUndeclaredKey("reject");+ schema = slotSchema(inlineRefs(slot.data, tableOf(table).types));} catch (err) {problems.push({path: m.path,@@ -246,6 +246,23 @@ export function checkTree(return { problems, provides };}+/**+ * A slot's contribution schema, parsed once per definition. arktype files every parse in a+ * registry that lives as long as the process and never shrinks, and every boot checks every+ * contribution: parsed afresh, each boot grew it (see leafExtends in ./data.ts).+ */+const slotSchemas = new Map<string, (v: unknown) => unknown>();++function slotSchema(def: Json): (v: unknown) => unknown {+ const key = JSON.stringify(def);+ let schema = slotSchemas.get(key);+ if (schema === undefined) {+ schema = type.raw(def).onUndeclaredKey("reject");+ slotSchemas.set(key, schema);+ }+ return schema;+}+/** A definition with its `$ref`s substituted, for arktype (which knows no references); a cycle stays a reference and parses as `unknown`. */export function inlineRefs(def: Json, types: Record<string, Json>, stack: string[] = []): Json {if (Array.isArray(def)) return def.map((d) => inlineRefs(d, types, stack));diff --git a/packages/core/src/kernel/data.ts b/packages/core/src/kernel/data.tsindex 46fcc1eb..ab230dab 100644--- a/packages/core/src/kernel/data.ts+++ b/packages/core/src/kernel/data.ts@@ -47,12 +47,28 @@ function arrayElem(s: string): string | null {return splitUnion(inner) === null ? inner : null;}+/**+ * Leaf decisions, once per process. arktype files every node a parse builds in a registry+ * that lives as long as the process and never shrinks (`$ark.nodesByRegisteredId`) — a+ * definition it has parsed before still adds entries — and every boot's interface check asks+ * thousands of these. A long-lived server boots a tree on every hot push and plugin load,+ * and a test worker boots hundreds of apps: the registry grew until each insert took longer+ * than a boot should. The pairs come from interface tables, so there are only so many.+ */+const leafDecisions = new Map<string, boolean>();+function leafExtends(a: string, b: string): boolean {+ const key = `${a}\u0000${b}`;+ const known = leafDecisions.get(key);+ if (known !== undefined) return known;+ let fits: boolean;try {- return type.raw(a).extends(type.raw(b));+ fits = type.raw(a).extends(type.raw(b));} catch {- return a === b;+ fits = a === b;}+ leafDecisions.set(key, fits);+ return fits;}/**diff --git a/packages/desktop/scripts/build-assets.mjs b/packages/desktop/scripts/build-assets.mjsindex b38af256..22bd1433 100644--- a/packages/desktop/scripts/build-assets.mjs+++ b/packages/desktop/scripts/build-assets.mjs@@ -113,7 +113,7 @@ if (hostBinding(ptyFiles) === undefined) {process.exit(1);}-// The compiler a plugin's interfaces are checked with, beside the server bundle for the same reason+// The compiler plugin interfaces and workflows are checked with, beside the server bundle for the same reason// node-pty is: the bundle has no node_modules of its own, and the server resolves// `typescript` from the program that is running.const { typescriptPayload } = await import(diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 1601d837..fdcdaffd 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -26,6 +26,7 @@ import type {// Build/harness identity is not an interface contract — it ships from the barrel (core's version-info.ts).import type { HarnessInfo, VersionReport, HarnessHistory } from "@prismshadow/penguin-core";import type { IfacesDiff } from "@prismshadow/penguin-hmr";+import type { WorkflowInfo } from "../mechanisms/workflows.js";// ---------------------------------------------------------------------------// General@@ -2609,7 +2610,11 @@ export type ScheduleServerEvent =agentId: string;name: string;sessionId: string;- };+ }+ /** A workflow of the Agent was (re)loaded — its folder changed, a reload was requested, or a version was restored. */+ | { type: "workflow_updated"; projectId: string; agentId: string; workflow: WorkflowInfo }+ /** A workflow's folder is gone — removed from the Web App or deleted on disk. */+ | { type: "workflow_removed"; projectId: string; agentId: string; workflowId: string };// ---------------------------------------------------------------------------// Trace browsing and performance analysis@@ -3727,6 +3732,12 @@ export interface PluginReadmeResponse {export type VersionResponse = VersionReport;export type { HarnessHistoryEntry, IfacesSummary } from "@prismshadow/penguin-core";+export type {+ WorkflowInfo,+ WorkflowVersion,+ WorkflowRequest,+ WorkflowResponse,+} from "../mechanisms/workflows.js";/** GET /api/version/history: the harness versions this data root has committed, newest first. */export type VersionHistoryResponse = HarnessHistory;diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.tsindex f662ea83..f6be096b 100644--- a/packages/server/src/auth/middleware.ts+++ b/packages/server/src/auth/middleware.ts@@ -116,10 +116,52 @@ const ALLOWED_WRITE_CONTENT_TYPES = ["application/octet-stream",];+/**+ * A workflow's own handler (`…/workflows/:id/api/*`) takes any body — an upload, a form of a+ * program it relays — so there the content type cannot be the defense. What stands in for it+ * is the browser's own account of where the request came from, which a page cannot forge:+ * `Sec-Fetch-Site`, and `Origin` against `Host` for a browser that sends no fetch metadata.+ * A request with neither is not a browser's, and carries no ambient cookie to ride on.+ */+const WORKFLOW_API = /^\/api\/projects\/[^/]+\/agents\/[^/]+\/workflows\/[^/]+\/api(\/|$)/;++function fromThisOrigin(header: (name: string) => string | undefined): boolean {+ const site = header("sec-fetch-site");+ if (site !== undefined) return site === "same-origin";+ const origin = header("origin");+ if (origin === undefined) return true;+ try {+ return new URL(origin).host === header("host");+ } catch {+ return false;+ }+}++const crossOrigin = () =>+ new HttpError(+ 403,+ "cross_origin_write",+ "A request to a workflow's handler must come from this app's own pages.",+ );+export const jsonOnlyWrites: MiddlewareHandler = async (c, next) => {+ // A workflow's handler answers every method, so its GET is whatever the workflow made it+ // — not the read every other route's GET is. A `SameSite=Lax` cookie rides along on a+ // cross-site top-level navigation, so `window.open` on another site would otherwise run+ // that handler as the signed-in user; the browser's own account of where the request came+ // from is what settles it, on every method rather than only on writes.+ if (!WRITE_METHODS.has(c.req.method) && WORKFLOW_API.test(c.req.path)) {+ if (!fromThisOrigin((name) => c.req.header(name))) throw crossOrigin();+ }if (WRITE_METHODS.has(c.req.method)) {const contentType = c.req.header("content-type")?.toLowerCase();- if (contentType && !ALLOWED_WRITE_CONTENT_TYPES.some((t) => contentType.startsWith(t))) {+ const forgeable =+ contentType !== undefined &&+ contentType !== "" &&+ !ALLOWED_WRITE_CONTENT_TYPES.some((t) => contentType.startsWith(t));+ if (forgeable && WORKFLOW_API.test(c.req.path)) {+ if (!fromThisOrigin((name) => c.req.header(name))) throw crossOrigin();+ } else if (forgeable) {throw new HttpError(415,"unsupported_media_type",diff --git a/packages/server/src/http/routes/contributions.ts b/packages/server/src/http/routes/contributions.tsindex 66405dd2..3e672128 100644--- a/packages/server/src/http/routes/contributions.ts+++ b/packages/server/src/http/routes/contributions.ts@@ -37,8 +37,16 @@ export interface WebShellSlots {pages: { key: string; path: string; nav: "main" | "none"; admin: boolean; renderer: RendererRef };/** A tab on the Agent settings page. */agentTabs: { key: string; order: number; renderer: RendererRef };- /** A tab beside a Session's chat (a workflow UI lives here). */- sessionTabs: { key: string; renderer: RendererRef };+ /**+ * A tab beside a Session's chat. A workflow contributes here too, from its own tree, where+ * the host publishes this slot under this module's name and scopes the tab to its Agent.+ */+ sessionTabs: {+ key: string;+ title: string;+ titleZh?: string;+ renderer: { builtin: string } | { iframe: { src: string } };+ };}@Module({diff --git a/packages/server/src/mechanisms/workflows.ts b/packages/server/src/mechanisms/workflows.tsnew file mode 100644index 00000000..947ee2b3--- /dev/null+++ b/packages/server/src/mechanisms/workflows.ts@@ -0,0 +1,179 @@+/**+ * Workflows: code an Agent keeps in its own directory and the server boots as a module+ * tree of its own — the same manifests and the same tree check the platform's plugins go+ * through (`package.json#penguin.modules` + the default export of `index.ts`). Two+ * interfaces cross the boundary:+ *+ * - `WorkflowHost` is what the server PUBLISHES into every workflow tree (the workflow's+ * manifest requires it `from: "Host"`): Sessions of the Project's Agents, opened and run+ * the way the SDK does it, a small state document, a log line.+ * - `WorkflowMain` is what a workflow PROVIDES: a JSON request handler the server mounts+ * under `/api/projects/:p/agents/:a/workflows/:id/api/*`, which the workflow's own UI+ * (served from its `ui/` folder) calls.+ *+ * `Workflows` is the platform-side mechanism the routes drive: list, reload, dispatch,+ * serve a UI file, and the version history every successful load appends to — which is+ * what makes an Agent's own edits to its workflow reversible.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";++/** A request the workflow's handler receives (the HTTP shape, minus the transport). */+export interface WorkflowRequest {+ method: string;+ /** Path below the workflow's `api/` mount, always starting with `/`. */+ path: string;+ query: Record<string, string>;+ /** Request headers, names lower-cased. The app's own credentials (`cookie`, `authorization`) are withheld. */+ headers: Record<string, string>;+ /** The parsed body of a JSON request; `null` otherwise (GET/HEAD, no body, another content type). */+ body: unknown;+ /** The body as sent, when there is one and it is not JSON: a form, an upload, plain text. */+ bytes?: Uint8Array;+}++export interface WorkflowResponse {+ /** HTTP status; 200 when absent. */+ status?: number;+ /**+ * Response headers. Naming a `content-type` is what makes the response something other than+ * JSON; `location` with a 3xx status redirects. `set-cookie` is dropped — a workflow does not+ * write the app's cookies.+ */+ headers?: Record<string, string>;+ /** JSON by default (`null` when absent); with a `content-type` header, a string sent as written. */+ body?: unknown;+ /** A binary body (an image, a font, a download); wins over `body`. */+ bytes?: Uint8Array;+ /**+ * A body sent as it is produced — server-sent events, a model's answer token by token, a+ * large download — each chunk written to the client when the iterator yields it; wins over+ * `bytes` and `body`. A client that goes away ends the iteration: `return()` is called, so+ * a `finally` in the generator is where an upstream request is aborted — but a generator+ * suspended inside an `await` receives it only once that await settles, so a relay whose+ * upstream can hang should carry its own deadline rather than rely on the disconnect.+ */+ stream?: AsyncIterable<Uint8Array | string>;+}++/**+ * One item of what `WorkflowHost.run` sends: the SDK builds these with `userText("…")`, but a+ * workflow has no package to import that from — its types come from the harness, and so does+ * nothing at run time. An object, so an image or a file is a new optional member later.+ */+export interface WorkflowInput {+ text: string;+}++/** What a workflow provides (its manifest: `provides: { main: "@prismshadow/penguin-server#WorkflowMain" }`). */+@Interface()+export abstract class WorkflowMain {+ abstract handle(request: WorkflowRequest): Promise<WorkflowResponse>;+}++/** What the server publishes into a workflow tree as module `Host`. */+@Interface()+export abstract class WorkflowHost {+ /** The Agents of this Project — who `createSession` can be asked to open a Session of. */+ abstract listAgents(): { agentId: string }[];+ /**+ * Opens a Session of an Agent of this Project — the workflow's own Agent when `agentId`+ * is absent. The SDK's `agent.createSession`.+ */+ abstract createSession(opts?: { agentId?: string }): Promise<{ sessionId: string }>;+ /**+ * Runs one turn in a Session of this Project, new or existing — the SDK's `session.run`.+ * `input` is a list of items like the SDK's, each one `{ text }` today; it reaches the+ * Agent as a message from the server, not from a person. A Session that is busy takes it as a queued follow-up+ * (`queued: true`) instead of refusing it. Resolves once the turn has started; watch it+ * with `sessionStatus`.+ */+ abstract run(+ sessionId: string,+ input: WorkflowInput[],+ ): Promise<{ sessionId: string; queued: boolean }>;+ /** `idle` / `running` / … of a Session of this Project. */+ abstract sessionStatus(sessionId: string): string;+ /** The workflow's own document (`state.json`, kept by the server across reloads and rollbacks). */+ abstract getState(): unknown;+ abstract setState(state: unknown): Promise<void>;+ abstract log(message: string): void;+}++/** How the Web App draws a contributed tab: a page of the workflow, or a renderer it carries. */+export type WorkflowTabRenderer = { iframe: { src: string } } | { builtin: string };++/**+ * One tab beside Chat, as the workflow contributed it (`WebModule.sessionTabs`). In a+ * manifest `renderer.iframe.src` is a path inside the workflow folder, under `ui/`; in a+ * `WorkflowInfo` it is the URL that file is served from.+ */+export interface WorkflowTab {+ id: string;+ /** Unique within the workflow; the tab's stable name (it appears in the full-page URL). */+ key: string;+ title: string;+ titleZh?: string;+ renderer: WorkflowTabRenderer;+}++export interface WorkflowInfo {+ id: string;+ name: string;+ version: string | null;+ /** Content revision of the whole folder (what history records). */+ revision: string;+ /** Content revision of `ui/`: the cache key of the workflow's pages. Null when it has no `ui/`. */+ uiRev: string | null;+ /** The tabs of the instance that is SERVING — the previous one's while `error` is set. */+ tabs: WorkflowTab[];+ loadedAt: string;+ /** The boot error when the current files do not load (the previous instance, if any, keeps serving). */+ error: string | null;+ /**+ * What loaded but is probably not what its author meant, each with the edit that settles it+ * — pages under `ui/` that no tab shows, say. Never a failure: `error` is that.+ */+ hints: string[];+}++export interface WorkflowVersion {+ revision: string;+ savedAt: string;+ name: string;+ version: string | null;+ uiRev: string | null;+ /** The files of that version (relative paths), for display. */+ files: string[];+}++@Interface()+export abstract class Workflows {+ abstract list(projectId: string, agentId: string): Promise<WorkflowInfo[]>;+ abstract reload(projectId: string, agentId: string, workflowId: string): Promise<WorkflowInfo>;+ abstract dispatch(+ projectId: string,+ agentId: string,+ workflowId: string,+ request: WorkflowRequest,+ ): Promise<WorkflowResponse>;+ /** Absolute path of a file under the workflow's `ui/`, or null when absent/unsafe. */+ abstract uiFile(+ projectId: string,+ agentId: string,+ workflowId: string,+ rel: string,+ ): Promise<string | null>;+ abstract history(+ projectId: string,+ agentId: string,+ workflowId: string,+ ): Promise<WorkflowVersion[]>;+ abstract rollback(+ projectId: string,+ agentId: string,+ workflowId: string,+ revision: string,+ ): Promise<WorkflowInfo>;+ /** Deletes the folder and its recorded versions; the instance goes with them. */+ abstract remove(projectId: string, agentId: string, workflowId: string): Promise<void>;+}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 0c9868a9..096f862a 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -140,6 +140,9 @@ import {Projects,} from "./mechanisms/projects.js";import { Schedules, Scheduling, SessionIndex, SessionOrigins } from "./mechanisms/sessions.js";+import { Workflows } from "./mechanisms/workflows.js";+import { WorkflowService } from "./workflows/service.js";+import { WorkflowRoutes } from "./workflows/routes.js";import {ErrorLog,Errors,@@ -433,6 +436,12 @@ export class CompanyModule {}})export class ApiModule {}+@Module({+ children: [WorkflowService, WorkflowRoutes],+ exports: [Workflows],+})+export class WorkflowsModule {}+/** The root: provides nothing and requires nothing; it exists so the groups have a scope to see each other in. */@Module({children: [@@ -453,6 +462,7 @@ export class ApiModule {}SandboxSettingsModule,TerminalModule,MachinesModule,+ WorkflowsModule,Startup,],})diff --git a/packages/server/src/plugin/iface-check.ts b/packages/server/src/plugin/iface-check.tsindex 5488103d..e2a0a53c 100644--- a/packages/server/src/plugin/iface-check.ts+++ b/packages/server/src/plugin/iface-check.ts@@ -3,8 +3,9 @@** A comparison needs two declarations. Looking both sides up in the platform's own table* compares a declaration with itself and can never fail, so here each side brings its own:- * the CONSUMER's is the table the package carries — a plugin's generated `ifaces.json` —- * and the PLATFORM's is this generation's. Nothing in+ * the CONSUMER's is the table the package carries — a plugin's generated `ifaces.json`; for+ * a workflow, the slice of the harness's table it was written against, kept in its folder+ * (../workflows/harness-types.ts) — and the PLATFORM's is this generation's. Nothing in* this module judges assignability itself: each table is rendered as a self-contained* `.d.ts`, the questions become assignments in a third file, and the TypeScript compiler* answers them —@@ -85,8 +86,8 @@ class Renderer {constructor(private readonly table: IfaceTable) {}/**- * The identifier a table key is declared under: its export name (`…#SessionIndex` →- * `SessionIndex`), numbered on a clash — so the text reads as a declaration file an author+ * The identifier a table key is declared under: its export name (`…#WorkflowHost` →+ * `WorkflowHost`), numbered on a clash — so the text reads as a declaration file an author* can write against, and a diagnostic names the type the way its source does.*/ident(key: string): string {diff --git a/packages/server/src/plugin/typescript.ts b/packages/server/src/plugin/typescript.tsindex 04a6e13c..af20de01 100644--- a/packages/server/src/plugin/typescript.ts+++ b/packages/server/src/plugin/typescript.ts@@ -2,7 +2,9 @@* The TypeScript compiler, loaded when something first needs it.** The compiler decides whether the interfaces a package was written against still fit this- * platform (./iface-check.ts). It is a dependency of this package, but the platform also runs as a single pushed bundle that sits outside any+ * platform (./iface-check.ts) — for plugins and for workflows alike — and type-checks and+ * transpiles a workflow's source (../workflows/compile.ts). It is a dependency of this+ * package, but the platform also runs as a single pushed bundle that sits outside any* `node_modules`, on machines whose program may predate that dependency — so the specifier* is kept out of the bundler's sight and resolved at run time, in three places: beside this* module, beside the program that is running, and in the assets the push carried it indiff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.tsindex 4c96bc7b..43267f9f 100644--- a/packages/server/src/runtime/scheduler.ts+++ b/packages/server/src/runtime/scheduler.ts@@ -47,7 +47,8 @@ export interface ScheduleTaskRunnerShape {startTask(sessionId: string,input: ReturnType<typeof userText>[],- ): Promise<{ sessionId: string }>;+ opts?: { queueIfBusy?: boolean },+ ): Promise<{ sessionId: string; queued: boolean }>;}/** Minimal dependency the scheduler needs from SessionService: new-Session mode (model ref passed through as a pair). */diff --git a/packages/server/src/workflows/compile.ts b/packages/server/src/workflows/compile.tsnew file mode 100644index 00000000..05d5ac11--- /dev/null+++ b/packages/server/src/workflows/compile.ts@@ -0,0 +1,193 @@+/**+ * A workflow's source, checked and transpiled by the server.+ *+ * A workflow is TypeScript — `index.ts`, never JavaScript: what its handler returns and+ * which host members it calls are then questions the compiler answers before any of it+ * runs, not ones the first request answers. The server builds one program from the entry+ * (and whatever it imports), under options the HOST fixes — `strict`, NodeNext; a+ * `tsconfig.json` in the folder is not consulted, so a workflow cannot switch strictness+ * off for itself. `@prismshadow/penguin-server/plugin` resolves to the types the harness+ * wrote into the folder (./harness-types.ts), never to a package: what the workflow was+ * written against. Whether that still fits this platform is ../plugin/iface-check.ts.+ *+ * A second, virtual root file assigns the default export to `WorkflowPackage`, so the+ * shape is checked even when the author left `satisfies WorkflowPackage` out (in which+ * case `strict` has already refused the untyped parameters).+ *+ * Any diagnostic fails the load. A clean program is emitted into+ * `<workflow>/.build/<revision>/` — inside the folder, so the emitted code resolves the+ * workflow's own dependencies the way its source does; a dot-directory, so it is no part+ * of the revision, the recorded versions or what the watcher reacts to.+ */+import fs from "node:fs";+import path from "node:path";+import type { TypeScript } from "../plugin/typescript.js";+import { harnessTypesFile } from "./harness-types.js";++export const ENTRY = "index.ts";+export const BUILD_DIR = ".build";+/** The module a workflow imports its types from. */+export const TYPES_MODULE = "@prismshadow/penguin-server/plugin";+const CHECK_FILE = "__workflow_check__.ts";+const CHECK_SOURCE = `import type { WorkflowPackage } from ${JSON.stringify(TYPES_MODULE)};+import pkg from "./index.js";+const check: WorkflowPackage = pkg;+void check;+`;+/** Diagnostics reported per load; a broken import alone can produce hundreds. */+const MAX_DIAGNOSTICS = 12;++export class WorkflowCompileError extends Error {}++/** Type-checks the workflow in `dir` and emits it; resolves to the emitted entry file. */+export function compileWorkflow(ts: TypeScript, dir: string, revision: string): string {+ const entry = path.join(dir, ENTRY);+ if (!fs.existsSync(entry)) {+ const js = ["index.mjs", "index.js"].find((f) => fs.existsSync(path.join(dir, f)));+ throw new WorkflowCompileError(+ js === undefined+ ? `no ${ENTRY} next to package.json`+ : `a workflow is written in TypeScript: rename ${js} to ${ENTRY} and type its default export (\`satisfies WorkflowPackage\`)`,+ );+ }+ const outDir = path.join(dir, BUILD_DIR, revision);+ const options: import("typescript").CompilerOptions = {+ strict: true,+ noEmitOnError: true,+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.NodeNext,+ moduleResolution: ts.ModuleResolutionKind.NodeNext,+ esModuleInterop: true,+ forceConsistentCasingInFileNames: true,+ skipLibCheck: true,+ rootDir: dir,+ outDir,+ };+ const checkFile = path.join(dir, CHECK_FILE);+ const same = (file: string) => path.resolve(file) === checkFile;+ const host = ts.createCompilerHost(options);+ const { fileExists, readFile, getSourceFile } = host;+ host.fileExists = (file) => same(file) || fileExists.call(host, file);+ host.readFile = (file) => (same(file) ? CHECK_SOURCE : readFile.call(host, file));+ host.getSourceFile = (file, languageVersion, ...rest) =>+ same(file)+ ? ts.createSourceFile(file, CHECK_SOURCE, languageVersion, true)+ : getSourceFile.call(host, file, languageVersion, ...rest);+ const types = {+ resolvedFileName: harnessTypesFile(dir),+ extension: ts.Extension.Dts,+ isExternalLibraryImport: false,+ };+ host.resolveModuleNameLiterals = (literals, containingFile, redirected, opts, source) =>+ literals.map((literal) =>+ literal.text === TYPES_MODULE+ ? { resolvedModule: types }+ : ts.resolveModuleName(+ literal.text,+ containingFile,+ opts,+ host,+ undefined,+ redirected,+ ts.getModeForUsageLocation(source, literal, opts),+ ),+ );++ const program = ts.createProgram([entry, checkFile], options, host);+ const all = ts.getPreEmitDiagnostics(program);+ // The virtual root asks what `satisfies WorkflowPackage` already asks; when the author's+ // own files have something to say, its copy of the same complaint is left out.+ const authored = all.filter((d) => d.file === undefined || !same(d.file.fileName));+ const diagnostics = authored.length > 0 ? authored : all;+ if (diagnostics.length > 0) throw new WorkflowCompileError(describe(ts, dir, diagnostics));++ fs.rmSync(outDir, { recursive: true, force: true });+ for (const source of program.getSourceFiles()) {+ if (source.isDeclarationFile || same(source.fileName)) continue;+ if (program.isSourceFileFromExternalLibrary(source)) continue;+ const result = program.emit(source);+ if (result.emitSkipped) {+ throw new WorkflowCompileError(describe(ts, dir, result.diagnostics));+ }+ }+ return path.join(outDir, "index.js");+}++/** What the last load came to, beside the emitted code: see {@link writeLoadStatus}. */+export const STATUS_FILE = "status.json";++/**+ * Writes `.build/status.json` after every load, good or bad. The Agent that wrote the+ * workflow has its files and nothing else — no session with the HTTP API — so this is how+ * it learns whether the edit it just made loaded, and what the compiler said if it did not:+ * edit, wait a moment, read this file.+ */+export function writeLoadStatus(+ dir: string,+ status: {+ revision: string;+ checkedAt: string;+ error: string | null;+ tabs: string[];+ hints: string[];+ },+): void {+ try {+ fs.mkdirSync(path.join(dir, BUILD_DIR), { recursive: true });+ const file = path.join(dir, BUILD_DIR, STATUS_FILE);+ fs.writeFileSync(+ `${file}.tmp`,+ `${JSON.stringify({ ok: status.error === null, ...status }, null, 1)}\n`,+ );+ fs.renameSync(`${file}.tmp`, file);+ } catch {+ // The folder may have just been removed; the status of a workflow that is gone is moot.+ }+}++/** Drops the emitted code of every revision but `keep` (the one now serving). */+export function pruneBuilds(dir: string, keep: string): void {+ const base = path.join(dir, BUILD_DIR);+ let entries: string[];+ try {+ entries = fs.readdirSync(base);+ } catch {+ return;+ }+ for (const name of entries) {+ if (name === keep || name === STATUS_FILE) continue;+ fs.rmSync(path.join(base, name), { recursive: true, force: true });+ }+}++/**+ * An assignability failure arrives as a chain from the outermost type down to the member+ * that does not fit, each level restating the whole shape. The first line says what was+ * being assigned and the last two say what is wrong; the levels between are dropped.+ */+function briefly(chain: string): string {+ const lines = chain.split("\n").map((line) => line.trim());+ const kept = lines.length <= 4 ? lines : [lines[0]!, "…", ...lines.slice(-2)];+ return kept.join("\n ");+}++function describe(+ ts: TypeScript,+ dir: string,+ diagnostics: readonly import("typescript").Diagnostic[],+): string {+ const lines = diagnostics.slice(0, MAX_DIAGNOSTICS).map((d) => {+ const text = briefly(ts.flattenDiagnosticMessageText(d.messageText, "\n"));+ if (d.file === undefined || d.start === undefined) return `TS${d.code} ${text}`;+ const at = d.file.getLineAndCharacterOfPosition(d.start);+ const file = path.relative(dir, d.file.fileName).split(path.sep).join("/");+ // The virtual root file is the server's question, not a file the author can open.+ const where =+ file === CHECK_FILE ? "default export" : `${file}:${at.line + 1}:${at.character + 1}`;+ return `${where} TS${d.code} ${text}`;+ });+ if (diagnostics.length > MAX_DIAGNOSTICS) {+ lines.push(`… and ${diagnostics.length - MAX_DIAGNOSTICS} more`);+ }+ return lines.join("\n");+}diff --git a/packages/server/src/workflows/harness-types.ts b/packages/server/src/workflows/harness-types.tsnew file mode 100644index 00000000..c05537c7--- /dev/null+++ b/packages/server/src/workflows/harness-types.ts@@ -0,0 +1,165 @@+/**+ * The types a workflow is written against come from the harness that is running it.+ *+ * One machine can run several harnesses — a release, a checkout, a platform someone pushed+ * with interfaces of their own — and none of them is a version on npm. So a workflow does+ * not install its types: the first load writes them into `<workflow>/.harness/`, rendered+ * from THIS platform's interface table —+ *+ * plugin.d.ts what `@prismshadow/penguin-server/plugin` resolves to for this workflow+ * (./compile.ts): `WorkflowHost`, `WorkflowMain` and what they reach, plus+ * the shape of the default export+ * ifaces.json the slice of the table those declarations were rendered from — the+ * workflow's side of the interface comparison (../plugin/iface-check.ts)+ * harness.json which table wrote them, and when+ *+ * and then leaves them alone. (`README.md` beside them is not part of that record: it is this+ * harness describing its own contract, rewritten whenever it differs — see {@link README}.) They are the record of what the workflow was written against:+ * a later generation of the platform, or another harness on the same machine, is compared+ * WITH them rather than overwriting them, which is what lets a removed host method be named+ * before the first call instead of failing at it. Deleting the directory is how a workflow+ * is moved onto the harness that runs it now. A dot-directory: no part of the revision or+ * the recorded versions, nothing the watcher reacts to, nothing `npm install` prunes.+ */+import fs from "node:fs";+import path from "node:path";+import type { IfaceTable } from "@prismshadow/penguin-core/kernel";+import { renderDts } from "../plugin/iface-check.js";++export const HARNESS_DIR = ".harness";+const TYPES_FILE = "plugin.d.ts";+const TABLE_FILE = "ifaces.json";++/**+ * The default export's shape, in terms of the two rendered interfaces. The root module's+ * manifest requires the host under the alias `host` and provides the handler under `main`.+ */+const PACKAGE_TYPES = `+export interface WorkflowModuleCtx<Use> {+ use: Use;+ /** Runs when the tree is disposed (a reload, a removal, the platform going away). */+ effect(dispose: () => void): void;+}+export interface WorkflowRootModule {+ create(ctx: WorkflowModuleCtx<{ host: WorkflowHost }>): {+ api: { main: WorkflowMain } & Record<string, unknown>;+ };+}+/** Any other module of the package: what it uses is whatever its own manifest requires. */+export interface WorkflowModule {+ create(ctx: WorkflowModuleCtx<Record<string, unknown>>): { api?: Record<string, unknown> };+}+/** The default export of index.ts: \`export default { … } satisfies WorkflowPackage\`. */+export interface WorkflowPackage {+ modules: { Workflow: WorkflowRootModule; [name: string]: WorkflowRootModule | WorkflowModule };+}+`;++/**+ * The contract in the words of the harness that enforces it. The Agent writing a workflow may+ * carry an old copy of the SDK skill, or none — installed skills are copies, and a platform+ * can be pushed without them — but it always has this folder. What it most often gets wrong+ * without being told is the last step: a page under `ui/` is only a file until the manifest+ * contributes a tab for it, and a workflow with no tab loads clean and shows nothing.+ */+const README = `# This workflow, as the harness running it sees it++Written by the harness; edits here are overwritten. \`plugin.d.ts\` and \`ifaces.json\` in this+folder are the types this workflow was written against — delete \`.harness/\` to take the+running harness's types afresh.++## Files++- \`package.json\` — \`"type": "module"\`, and the manifest under \`penguin.modules\`: a module named+ \`Workflow\` that requires \`host\` (\`@prismshadow/penguin-server#WorkflowHost\`, from \`Host\`),+ provides \`main\` (\`@prismshadow/penguin-server#WorkflowMain\`) and contributes its tabs.+- \`index.ts\` — TypeScript, never JavaScript. \`export default { modules: { Workflow: { create(ctx) {+ … } } } } satisfies WorkflowPackage\`, types imported from \`@prismshadow/penguin-server/plugin\`+ (it resolves to \`.harness/plugin.d.ts\`; nothing to install).+- \`ui/\` — pages and their assets. A page calls the workflow's handler at \`../api/<path>\`.++The handler speaks JSON by default. A request body of another content type arrives as+\`req.bytes\`; a response that names a \`content-type\` in \`headers\` is sent as written (\`body\` a+string, or \`bytes\`, or \`stream\` — an \`async function*\` whose chunks go out as they are yielded:+server-sent events, a relayed streaming answer). A page runs in the user's browser, which may be on another machine: to+show a program running on THIS machine, fetch \`http://127.0.0.1:<port>\` from the handler and+return the answer — never from the page. When branches of \`handle\` answer with different+headers, declare its return type (\`Promise<WorkflowResponse>\`) so they are not inferred apart.++## A page shows only if a tab is contributed for it++\`\`\`json+"contributes": {+ "WebModule.sessionTabs": [+ { "key": "main", "title": "Board", "titleZh": "看板",+ "renderer": { "iframe": { "src": "ui/index.html" } } }+ ]+}+\`\`\`++One entry per tab, beside the chat of this Agent; \`key\` is unique in the workflow; \`src\` is a+file under \`ui/\`. \`"contributes": {}\` is a server-only workflow with no UI — also how a UI is+taken away again.++## Did it load++Every save reloads the workflow. \`.build/status.json\` says what came of it: \`ok\`, the compiler's+\`error\` when it did not load (the previous version keeps serving), the \`tabs\` now showing, and+\`hints\` — things that loaded but are probably not what you meant, each with the edit that+settles it. Read it after every edit before telling anyone the work is done.+`;++/** Keeps `.harness/README.md` at this harness's text; best effort, it is documentation. */+function writeReadme(target: string): void {+ try {+ const file = path.join(target, "README.md");+ if (fs.existsSync(file) && fs.readFileSync(file, "utf8") === README) return;+ fs.writeFileSync(`${file}.tmp`, README);+ fs.renameSync(`${file}.tmp`, file);+ } catch {+ // The folder may have just been removed.+ }+}++export function harnessTypesFile(dir: string): string {+ return path.join(dir, HARNESS_DIR, TYPES_FILE);+}++/** Writes this harness's types into the workflow folder, unless it already holds some. */+export function installHarnessTypes(+ dir: string,+ platform: IfaceTable & { hash?: string },+ keys: readonly string[],+ now: Date,+): void {+ const target = path.join(dir, HARNESS_DIR);+ if (fs.existsSync(target)) {+ writeReadme(target);+ return;+ }+ const { text, slice } = renderDts(platform, keys);+ // Built aside and moved into place: a half-written directory must never read as installed.+ const staging = `${target}.${process.pid}.tmp`;+ fs.rmSync(staging, { recursive: true, force: true });+ fs.mkdirSync(staging, { recursive: true });+ fs.writeFileSync(path.join(staging, TYPES_FILE), `${text}\n${PACKAGE_TYPES}`);+ fs.writeFileSync(path.join(staging, TABLE_FILE), `${JSON.stringify(slice, null, 1)}\n`);+ fs.writeFileSync(+ path.join(staging, "harness.json"),+ `${JSON.stringify({ ifaces: platform.hash ?? null, installedAt: now.toISOString() }, null, 1)}\n`,+ );+ fs.renameSync(staging, target);+ writeReadme(target);+}++/** The table the workflow was written against, or why it cannot be read. */+export function readHarnessTable(dir: string): IfaceTable | string {+ const file = path.join(dir, HARNESS_DIR, TABLE_FILE);+ try {+ const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as Partial<IfaceTable>;+ if (typeof parsed.ifaces !== "object" || parsed.ifaces === null) throw new Error("no ifaces");+ return { ifaces: parsed.ifaces, types: parsed.types ?? {} };+ } catch (err) {+ return `${HARNESS_DIR}/${TABLE_FILE} cannot be read (${err instanceof Error ? err.message : String(err)}) — delete ${HARNESS_DIR}/ to take this harness's types afresh`;+ }+}diff --git a/packages/server/src/workflows/routes.ts b/packages/server/src/workflows/routes.tsnew file mode 100644index 00000000..02b1bd0f--- /dev/null+++ b/packages/server/src/workflows/routes.ts@@ -0,0 +1,314 @@+/**+ * Agent-scoped workflow routes, mounted at /api/projects/:projectId/agents/:agentId/workflows:+ *+ * GET / the Agent's workflows (loads any that changed on disk)+ * POST /:id/reload re-import the folder now (the watcher does this on change too)+ * GET /:id/history recorded versions, newest first+ * POST /:id/rollback {revision} restore that version's files and reload+ * DELETE /:id remove the folder and its recorded versions+ * GET /:id/ui/* a file of the workflow's `ui/` (the pages its tabs name)+ * * /:id/api/* handed to the workflow's WorkflowMain.handle: JSON by default, any+ * content type when the handler names one (see respond)+ *+ * Every route requires access to the Project; the UI and api routes are what the+ * workflow's own page (an iframe in the Web App, same-origin cookie auth) talks to.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { Hono } from "hono";+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";+import type { AppEnv } from "../auth/middleware.js";+import { HttpError } from "../http/errors.js";+import { requireValidId } from "../http/validate.js";+import type { Access } from "../mechanisms/projects.js";+import type { WorkflowRequest, WorkflowResponse, Workflows } from "../mechanisms/workflows.js";+import { WorkflowNotFound } from "./service.js";++const MIME: Record<string, string> = {+ ".html": "text/html; charset=utf-8",+ ".htm": "text/html; charset=utf-8",+ ".js": "text/javascript; charset=utf-8",+ ".mjs": "text/javascript; charset=utf-8",+ ".css": "text/css; charset=utf-8",+ ".json": "application/json; charset=utf-8",+ ".svg": "image/svg+xml",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".ico": "image/x-icon",+ ".txt": "text/plain; charset=utf-8",+ ".map": "application/json; charset=utf-8",+ ".woff": "font/woff",+ ".woff2": "font/woff2",+};++/** The largest request body a workflow's handler is handed. */+const MAX_BODY_BYTES = 50 * 1024 * 1024;+/** Never shown to a workflow: they are the app's credentials, not the workflow's. */+const WITHHELD_REQUEST_HEADERS = new Set(["cookie", "authorization", "proxy-authorization"]);+/** Never taken from a workflow: the app's cookies, and what the transport decides for itself. */+const DROPPED_RESPONSE_HEADERS = new Set([+ "set-cookie",+ "connection",+ "keep-alive",+ "transfer-encoding",+ "content-length",+]);++const tooLarge = () =>+ new HttpError(+ 413,+ "payload_too_large",+ `A workflow request body is at most ${MAX_BODY_BYTES} bytes`,+ );++const isJson = (contentType: string | undefined): boolean =>+ contentType === undefined || /^application\/([\w.-]+\+)?json\b/i.test(contentType.trim());++function parseJson(bytes: Uint8Array): unknown {+ try {+ return JSON.parse(new TextDecoder().decode(bytes)) as unknown;+ } catch {+ return null;+ }+}++function forwardedHeaders(headers: Headers): Record<string, string> {+ const out: Record<string, string> = {};+ headers.forEach((value, name) => {+ if (!WITHHELD_REQUEST_HEADERS.has(name.toLowerCase())) out[name.toLowerCase()] = value;+ });+ return out;+}++/**+ * JSON unless the handler says otherwise: a `content-type` header (or `bytes`) makes the+ * response the handler's own — a page it proxies from a program it runs, an image, a+ * download, a redirect — and `stream` sends it as it is produced. The same origin already serves the workflow's `ui/` files as+ * written, so a handler that answers HTML is no wider than a file that is HTML.+ */+/**+ * The body, refused the moment it goes past the cap rather than after it is in memory. A+ * declared `content-length` is only a claim — a chunked request carries none at all — so the+ * count that decides is the one taken while reading. Nothing larger than the cap is ever+ * held, and the reader is cancelled so the sender is not left writing into a socket no one+ * reads.+ */+async function readCapped(body: ReadableStream<Uint8Array> | null): Promise<Uint8Array> {+ if (body === null) return new Uint8Array(0);+ const reader = body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > MAX_BODY_BYTES) throw tooLarge();+ chunks.push(value);+ }+ } finally {+ await reader.cancel().catch(() => undefined);+ }+ const out = new Uint8Array(size);+ let at = 0;+ for (const chunk of chunks) {+ out.set(chunk, at);+ at += chunk.byteLength;+ }+ return out;+}++function respond(response: WorkflowResponse): Response {+ const status = response.status ?? 200;+ const headers = new Headers();+ for (const [name, value] of Object.entries(response.headers ?? {})) {+ if (DROPPED_RESPONSE_HEADERS.has(name.toLowerCase())) continue;+ // An illegal value (a CR/LF among them, which is why this throws) loses the header, not+ // the whole answer: the handler still gets to reply.+ try {+ headers.set(name, value);+ } catch {+ continue;+ }+ }+ // The statuses fetch forbids a body on: constructing a Response with one throws, which+ // would reach the client as a bare 500 instead of the answer the handler meant.+ const bodiless =+ status === 101 ||+ status === 103 ||+ status === 204 ||+ status === 205 ||+ status === 304 ||+ (status >= 300 && status < 400);+ if (response.stream !== undefined && bodiless) {+ // Nothing will read it, so whatever it holds open is released now.+ const it = response.stream[Symbol.asyncIterator]();+ void it.return?.(undefined);+ }+ if (response.stream !== undefined && !bodiless) {+ if (!headers.has("content-type")) headers.set("content-type", "application/octet-stream");+ return new Response(streamOf(response.stream), { status, headers });+ }+ if (response.bytes !== undefined) {+ if (!headers.has("content-type")) headers.set("content-type", "application/octet-stream");+ return new Response(bodiless ? null : response.bytes, { status, headers });+ }+ if (headers.has("content-type")) {+ const text = typeof response.body === "string" ? response.body : "";+ return new Response(bodiless ? null : text, { status, headers });+ }+ if (bodiless) return new Response(null, { status, headers });+ headers.set("content-type", "application/json; charset=utf-8");+ return new Response(JSON.stringify(response.body ?? null), { status, headers });+}++/**+ * The handler's iterator as a response body: one chunk out per chunk yielded, pulled only as+ * fast as the client reads. A client that disconnects cancels the stream, which ends the+ * iteration — the generator's `finally` runs, and whatever it was relaying is let go.+ */+function streamOf(chunks: AsyncIterable<Uint8Array | string>): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ let iterator: AsyncIterator<Uint8Array | string> | null = null;+ return new ReadableStream<Uint8Array>({+ async pull(controller) {+ iterator ??= chunks[Symbol.asyncIterator]();+ try {+ const next = await iterator.next();+ if (next.done) controller.close();+ else+ controller.enqueue(+ typeof next.value === "string" ? encoder.encode(next.value) : next.value,+ );+ } catch (err) {+ controller.error(err);+ }+ },+ async cancel() {+ await iterator?.return?.();+ },+ });+}++export interface WorkflowRouteDeps {+ access: Access;+ workflows: Workflows;+}++export function workflowRoutes(deps: WorkflowRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ const scope = (c: {+ req: { param(name: string): string | undefined };+ var: AppEnv["Variables"];+ }) => {+ const projectId = requireValidId(c as never, "projectId");+ const agentId = requireValidId(c as never, "agentId");+ deps.access.requireProjectAccess(c.var.user.userId, projectId);+ return { projectId, agentId };+ };+ const notFound = (err: unknown): never => {+ if (err instanceof WorkflowNotFound) throw new HttpError(404, "not_found", err.message);+ throw err;+ };++ app.get("/", async (c) => {+ const { projectId, agentId } = scope(c);+ return c.json({ workflows: await deps.workflows.list(projectId, agentId) });+ });++ app.post("/:id/reload", async (c) => {+ const { projectId, agentId } = scope(c);+ const workflow = await deps.workflows+ .reload(projectId, agentId, c.req.param("id"))+ .catch(notFound);+ return c.json({ workflow });+ });++ app.get("/:id/history", async (c) => {+ const { projectId, agentId } = scope(c);+ return c.json({+ versions: await deps.workflows.history(projectId, agentId, c.req.param("id")),+ });+ });++ app.post("/:id/rollback", async (c) => {+ const { projectId, agentId } = scope(c);+ const body = (await c.req.json().catch(() => ({}))) as { revision?: unknown };+ if (typeof body.revision !== "string")+ throw new HttpError(400, "bad_request", "revision is required");+ const workflow = await deps.workflows+ .rollback(projectId, agentId, c.req.param("id"), body.revision)+ .catch(notFound);+ return c.json({ workflow });+ });++ app.delete("/:id", async (c) => {+ const { projectId, agentId } = scope(c);+ await deps.workflows.remove(projectId, agentId, c.req.param("id")).catch(notFound);+ return c.body(null, 204);+ });++ app.get("/:id/ui/*", async (c) => {+ const { projectId, agentId } = scope(c);+ const id = c.req.param("id");+ const rel = c.req.path.split(`/workflows/${id}/ui/`)[1] ?? "";+ const file = await deps.workflows.uiFile(projectId, agentId, id, decodeURIComponent(rel));+ if (file === null) throw new HttpError(404, "not_found", "No such file in the workflow's ui/.");+ const body = await fs.readFile(file);+ return c.body(body, 200, {+ "content-type": MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream",+ "cache-control": "no-cache",+ });+ });++ app.all("/:id/api/*", async (c) => {+ const { projectId, agentId } = scope(c);+ const id = c.req.param("id");+ const sub = c.req.path.split(`/workflows/${id}/api`)[1] ?? "/";+ const request: WorkflowRequest = {+ method: c.req.method,+ path: sub === "" ? "/" : sub,+ query: c.req.query(),+ headers: forwardedHeaders(c.req.raw.headers),+ body: null,+ };+ if (c.req.method !== "GET" && c.req.method !== "HEAD") {+ const declared = Number(c.req.header("content-length"));+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) throw tooLarge();+ const bytes = await readCapped(c.req.raw.body);+ // JSON stays what it always was — parsed, and `null` when it does not parse. Anything+ // else reaches the handler as the bytes that were sent.+ if (isJson(c.req.header("content-type"))) request.body = parseJson(bytes);+ else if (bytes.byteLength > 0) request.bytes = bytes;+ }+ const response = await deps.workflows.dispatch(projectId, agentId, id, request).catch(notFound);+ return respond(response);+ });++ return app;+}++@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "WorkflowsModule.routes",+ prefix: "/api/projects/:projectId/agents/:agentId/workflows",+ auth: "user",+ order: 20,+ },+ ],+ },+})+export class WorkflowRoutes {+ @Use() private readonly access!: Access;+ @Use() private readonly workflows!: Workflows;+ @Bind("WorkflowsModule.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = workflowRoutes({ access: this.access, workflows: this.workflows });+ }+}diff --git a/packages/server/src/workflows/service.ts b/packages/server/src/workflows/service.tsnew file mode 100644index 00000000..80ec3bad--- /dev/null+++ b/packages/server/src/workflows/service.ts@@ -0,0 +1,771 @@+/**+ * WorkflowService: boots every workflow folder of an Agent as a module tree of its own.+ *+ * A workflow is a plugin package: hand-written manifests in `package.json#penguin.modules`+ * and an `index.ts` whose default export pairs them with code. Its root module must be+ * named `Workflow` and provide `WorkflowMain`; the server publishes `WorkflowHost` to the+ * tree as module `Host`, and the slots it opens to workflows under the platform's own+ * module names (today `WebModule.sessionTabs`), so a workflow contributes a tab the way a+ * plugin does and the host scopes it to the Agent.+ *+ * Three checks run before any create(), and a failure of any keeps the previous instance+ * serving with the problem named: the source is type-checked under `strict` against the+ * types the harness wrote into the folder when the workflow was new (./harness-types.ts,+ * ./compile.ts); those are compared with this platform's, both ways, by the compiler+ * (../plugin/iface-check.ts); and the tree is checked like any other — wiring, slots,+ * contribution shapes.+ *+ * Loading is by content: the folder's revision (store.ts) names the directory the source+ * is emitted into, so an edited workflow is a new import URL rather than a hit in the ESM+ * cache, and every successful load records the folder as a version the Agent (or the+ * user) can roll back to. A watcher on the `workflows/` folder reloads on change, debounced, and the users of+ * the Project hear `workflow_updated` on their event stream.+ */+import fs from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { bootModules, Component, parseManifest, Use } from "@prismshadow/penguin-core/kernel";+import type {+ ClassCtx,+ IfaceDecl,+ IfaceTable,+ Manifest,+ ModuleDef,+ ModuleTree,+} from "@prismshadow/penguin-core/kernel";+import { userText } from "@prismshadow/penguin-core";+import table from "../ifaces.json" with { type: "json" };+import type { ServerEvent } from "../api/types.js";+import type { Channels, Clock, Hmr, Log, Paths } from "../hmr/capabilities.js";+import { userChannelKey } from "../http/routes/events.js";+import type { AgentIndex, Members, Projects } from "../mechanisms/projects.js";+import type { SessionIndex } from "../mechanisms/sessions.js";+import type {+ WorkflowInfo,+ WorkflowInput,+ WorkflowRequest,+ WorkflowResponse,+ WorkflowTab,+ WorkflowVersion,+ Workflows,+} from "../mechanisms/workflows.js";+import { ScheduleSessionCreator, ScheduleTaskRunner } from "../runtime/scheduler.js";+import { compileWorkflow, pruneBuilds, writeLoadStatus } from "./compile.js";+import { installHarnessTypes, readHarnessTable } from "./harness-types.js";+import { checkIfaces, ifaceQuestions } from "../plugin/iface-check.js";+import { loadTypeScript } from "../plugin/typescript.js";+import {+ historyDir,+ isSafeRelPath,+ isTempName,+ isWorkflowId,+ listFolders,+ listVersions,+ readFolder,+ readState,+ recordVersion,+ restoreVersion,+ STATE_FILE,+ UI_DIR,+ workflowsDir,+ writeState,+ type WorkflowFolder,+} from "./store.js";++const PKG = "@prismshadow/penguin-server";+export const HOST_MODULE = "Host";+export const ROOT_MODULE = "Workflow";+export const HOST_IFACE = `${PKG}#WorkflowHost`;+export const MAIN_IFACE = `${PKG}#WorkflowMain`;+/** The platform module whose slots the host opens to workflows, and the slots it opens. */+export const WEB_MODULE = "WebModule";+export const WEB_IFACE = `${PKG}#WebShell`;+export const TABS_SLOT = "sessionTabs";+const OPEN_WEB_SLOTS = [TABS_SLOT] as const;+/** A burst of file writes (an editor, a git checkout, a rollback) becomes one reload. */+const WATCH_SETTLE_MS = 300;++interface Loaded {+ folder: WorkflowFolder;+ tree: ModuleTree | null;+ main: { handle(request: WorkflowRequest): Promise<WorkflowResponse> } | null;+ tabs: WorkflowTab[];+ loadedAt: string;+ error: string | null;+}++function key(projectId: string, agentId: string, workflowId: string): string {+ return `${projectId}/${agentId}/${workflowId}`;+}++function messageOf(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/** Reads `package.json`: the manifests, and that the package is an ES module. */+async function readManifests(folder: WorkflowFolder): Promise<Manifest[]> {+ const raw = JSON.parse(+ await fs.promises.readFile(path.join(folder.dir, "package.json"), "utf8"),+ ) as {+ type?: unknown;+ penguin?: { modules?: unknown };+ };+ if (raw.type !== "module") {+ throw new Error('package.json must set "type": "module" (a workflow is an ES module)');+ }+ const list = raw.penguin?.modules;+ if (!Array.isArray(list) || list.length === 0) {+ throw new Error("package.json#penguin.modules must list at least the `Workflow` module");+ }+ return list.map((doc, i) => {+ try {+ return parseManifest(doc);+ } catch (err) {+ throw new Error(`package.json#penguin.modules[${i}]: ${messageOf(err)}`);+ }+ });+}++/**+ * A workflow that loads and shows nothing is the quietest way to get this wrong: the pages are+ * written, the load is green, and no tab appears, because a page is only a file until the+ * manifest contributes a tab for it. The author is usually an Agent with nothing but these+ * files and the load status, so the status says it, with the entry to add.+ */+export function loadHints(+ uiRev: string | null,+ tabs: readonly WorkflowTab[],+ error: string | null,+): string[] {+ if (error !== null || uiRev === null || tabs.length > 0) return [];+ const entry = {+ key: "main",+ title: "<tab title>",+ renderer: { iframe: { src: `${UI_DIR}/index.html` } },+ };+ return [+ `${UI_DIR}/ has pages but the manifest contributes no tab, so nothing shows beside the chat. ` ++ `In package.json, under penguin.modules[0] (the module named Workflow), set ` ++ `"contributes": ${JSON.stringify({ [`${WEB_MODULE}.${TABS_SLOT}`]: [entry] })} — ` ++ `one entry per tab, src a file under ${UI_DIR}/.`,+ ];+}++/**+ * The tabs the manifests contribute to `WebModule.sessionTabs`, with each page's path (in+ * the folder, under `ui/`) turned into the URL it is served from. The slot's shape was+ * checked with the tree; where a page may live is this host's rule.+ */+function contributedTabs(manifests: readonly Manifest[], uiBase: string): WorkflowTab[] {+ const tabs: WorkflowTab[] = [];+ const keys = new Set<string>();+ for (const m of manifests) {+ for (const entry of m.contributes[`${WEB_MODULE}.${TABS_SLOT}`] ?? []) {+ const tab = entry as unknown as WorkflowTab;+ if (keys.has(tab.key)) {+ throw new Error(+ `contribution '${tab.id}': another tab of this workflow already has the key '${tab.key}'`,+ );+ }+ keys.add(tab.key);+ if (!("iframe" in tab.renderer)) {+ tabs.push(tab);+ continue;+ }+ const src = tab.renderer.iframe.src;+ if (!isSafeRelPath(src) || !src.startsWith(`${UI_DIR}/`)) {+ throw new Error(+ `contribution '${tab.id}': renderer.iframe.src must be a file under ${UI_DIR}/ (got '${src}')`,+ );+ }+ const rest = src+ .slice(UI_DIR.length + 1)+ .split("/")+ .map(encodeURIComponent)+ .join("/");+ tabs.push({ ...tab, renderer: { iframe: { src: `${uiBase}/${rest}` } } });+ }+ }+ return tabs;+}++/** Pairs the manifests with the emitted default export, by name. */+async function loadDefs(manifests: readonly Manifest[], entry: string): Promise<ModuleDef> {+ const mod = (await import(pathToFileURL(entry).href)) as {+ default?: { modules?: Record<string, ModuleDef["create"] | { create: ModuleDef["create"] }> };+ };+ const code = mod.default?.modules;+ if (code === null || typeof code !== "object") {+ throw new Error("the default export must be { modules: { <name>: { create } } }");+ }+ const defs = new Map<string, ModuleDef>();+ for (const manifest of manifests) {+ const found = code[manifest.name];+ const create = typeof found === "function" ? found : found?.create;+ if (typeof create !== "function") {+ throw new Error(+ `package.json names module '${manifest.name}' but the default export has no create() for it`,+ );+ }+ defs.set(manifest.name, { manifest, create });+ }+ for (const def of defs.values()) {+ def.children = def.manifest.children.map((ref) => {+ const name = typeof ref === "string" ? ref : ref.keyed;+ const child = defs.get(name);+ if (!child)+ throw new Error(+ `module '${def.manifest.name}' lists child '${name}', which package.json does not declare`,+ );+ return child;+ });+ }+ const root = defs.get(ROOT_MODULE);+ if (!root)+ throw new Error(`package.json#penguin.modules must include a module named '${ROOT_MODULE}'`);+ if (!Object.values(root.manifest.provides).some((ref) => ref === MAIN_IFACE)) {+ throw new Error(`module '${ROOT_MODULE}' must provide "${MAIN_IFACE}"`);+ }+ return root;+}++@Component()+export class WorkflowService implements Workflows {+ @Use() private readonly paths!: Paths;+ @Use() private readonly clock!: Clock;+ @Use() private readonly log!: Log;+ @Use() private readonly channels!: Channels;+ @Use() private readonly members!: Members;+ @Use() private readonly projects!: Projects;+ @Use() private readonly hmr!: Hmr;+ @Use() private readonly agents!: AgentIndex;+ @Use() private readonly sessionIndex!: SessionIndex;+ @Use() private readonly runner!: ScheduleTaskRunner;+ @Use() private readonly sessions!: ScheduleSessionCreator;++ private readonly loaded = new Map<string, Loaded>();+ private readonly watchers = new Map<string, fs.FSWatcher>();+ private readonly pending = new Map<string, NodeJS.Timeout>();+ /** The load in flight per workflow: a load takes a compiler run, so two can overlap. */+ private readonly loading = new Map<string, Promise<Loaded>>();+ /** The revision the newest queued load will load, while one is queued (see reloadIfChanged). */+ private readonly loadingRevision = new Map<string, string>();+ /** Workflows whose folder is being deleted: the watcher schedules no reload for them. */+ private readonly removing = new Set<string>();+ private resources: ClassCtx["resources"] | null = null;+ private disposed = false;++ setup(ctx: ClassCtx) {+ this.resources = ctx.resources;+ ctx.effect(() => {+ this.disposed = true;+ for (const t of this.pending.values()) clearTimeout(t);+ for (const w of this.watchers.values()) w.close();+ for (const l of this.loaded.values()) l.tree?.dispose();+ this.loaded.clear();+ });+ }++ async list(projectId: string, agentId: string): Promise<WorkflowInfo[]> {+ this.watch(projectId, agentId);+ const folders = await listFolders(workflowsDir(this.paths.root, projectId, agentId));+ const out: WorkflowInfo[] = [];+ for (const folder of folders) {+ const current = this.loaded.get(key(projectId, agentId, folder.id));+ const fresh =+ current && current.folder.revision === folder.revision+ ? current+ : await this.load(projectId, agentId, folder);+ out.push(this.info(folder.id, fresh));+ }+ // Folders that went away drop their instances.+ const alive = new Set(folders.map((f) => key(projectId, agentId, f.id)));+ for (const [k, l] of this.loaded) {+ if (k.startsWith(`${projectId}/${agentId}/`) && !alive.has(k)) {+ this.forget(projectId, agentId, l.folder.id);+ }+ }+ return out;+ }++ async reload(projectId: string, agentId: string, workflowId: string): Promise<WorkflowInfo> {+ const folder = await this.folder(projectId, agentId, workflowId);+ return this.info(workflowId, await this.load(projectId, agentId, folder));+ }++ /**+ * The watcher's reload: only when the content differs from what is loaded, or from what the+ * load in flight is loading. An event is a hint, not an edit — Windows reports a `change` on+ * a directory when a file in it is read or written (the workflow's own state, `.build/`, and+ * a load's own reads of the folder), and reloading on those tore the tree down under the+ * request that had just written its state, or loaded the same folder twice over. The+ * revision is the content hash, so an edit always differs.+ */+ private async reloadIfChanged(+ projectId: string,+ agentId: string,+ workflowId: string,+ ): Promise<void> {+ const folder = await this.folder(projectId, agentId, workflowId);+ const k = key(projectId, agentId, workflowId);+ const current = this.loading.has(k)+ ? this.loadingRevision.get(k)+ : this.loaded.get(k)?.folder.revision;+ if (current === folder.revision) return;+ await this.load(projectId, agentId, folder);+ }++ async dispatch(+ projectId: string,+ agentId: string,+ workflowId: string,+ request: WorkflowRequest,+ ): Promise<WorkflowResponse> {+ const loaded = await this.current(projectId, agentId, workflowId);+ if (loaded.main === null) {+ return { status: 503, body: { error: loaded.error ?? "workflow is not loaded" } };+ }+ return loaded.main.handle(request);+ }++ async uiFile(+ projectId: string,+ agentId: string,+ workflowId: string,+ rel: string,+ ): Promise<string | null> {+ if (!isWorkflowId(workflowId)) return null;+ // No default document: which page a tab shows is what its contribution says.+ const file = rel;+ if (!isSafeRelPath(file)) return null;+ const abs = path.join(+ workflowsDir(this.paths.root, projectId, agentId),+ workflowId,+ UI_DIR,+ file,+ );+ try {+ return (await fs.promises.stat(abs)).isFile() ? abs : null;+ } catch {+ return null;+ }+ }++ history(projectId: string, agentId: string, workflowId: string): Promise<WorkflowVersion[]> {+ if (!isWorkflowId(workflowId)) return Promise.resolve([]);+ return listVersions(historyDir(this.paths.root, projectId, agentId), workflowId);+ }++ async rollback(+ projectId: string,+ agentId: string,+ workflowId: string,+ revision: string,+ ): Promise<WorkflowInfo> {+ const folder = await this.folder(projectId, agentId, workflowId);+ if (!/^[0-9a-f]{12}$/.test(revision)) throw new WorkflowNotFound("no such version");+ const restored = await restoreVersion(+ historyDir(this.paths.root, projectId, agentId),+ folder,+ revision,+ );+ if (!restored) throw new WorkflowNotFound("no such version");+ return this.reload(projectId, agentId, workflowId);+ }++ async remove(projectId: string, agentId: string, workflowId: string): Promise<void> {+ const folder = await this.folder(projectId, agentId, workflowId);+ const k = key(projectId, agentId, workflowId);+ // Nothing may write into the folder while it is deleted: a load writes `.build/`, and a+ // file recreated there mid-delete fails the rm on Windows (ENOTEMPTY). Pending reloads are+ // dropped, none is scheduled until the folder is gone, and one already running finishes.+ this.removing.add(k);+ try {+ const t = this.pending.get(k);+ if (t) clearTimeout(t);+ this.pending.delete(k);+ await this.loading.get(k)?.catch(() => undefined);+ await fs.promises.rm(folder.dir, {+ recursive: true,+ force: true,+ maxRetries: 5,+ retryDelay: 100,+ });+ } finally {+ this.removing.delete(k);+ }+ await fs.promises.rm(path.join(historyDir(this.paths.root, projectId, agentId), workflowId), {+ recursive: true,+ force: true,+ });+ this.forget(projectId, agentId, workflowId);+ }++ // ---- internals ------------------------------------------------------------------++ private async folder(+ projectId: string,+ agentId: string,+ workflowId: string,+ ): Promise<WorkflowFolder> {+ if (!isWorkflowId(workflowId)) throw new WorkflowNotFound("no such workflow");+ const dir = path.join(workflowsDir(this.paths.root, projectId, agentId), workflowId);+ const folder = await readFolder(dir, workflowId);+ if (!folder) throw new WorkflowNotFound("no such workflow");+ return folder;+ }++ private async current(projectId: string, agentId: string, workflowId: string): Promise<Loaded> {+ const folder = await this.folder(projectId, agentId, workflowId);+ const k = key(projectId, agentId, workflowId);+ const existing = this.loaded.get(k);+ if (existing && existing.folder.revision === folder.revision) return existing;+ return this.load(projectId, agentId, folder);+ }++ private info(id: string, l: Loaded): WorkflowInfo {+ return {+ id,+ name: l.folder.pkg.name,+ version: l.folder.pkg.version,+ revision: l.folder.revision,+ uiRev: l.folder.uiRev,+ tabs: l.tabs,+ loadedAt: l.loadedAt,+ error: l.error,+ hints: loadHints(l.folder.uiRev, l.tabs, l.error),+ };+ }++ /**+ * One load at a time per workflow. The watcher and a request can both ask while the+ * compiler is still running for the last edit; the later one waits and then loads what+ * is on disk by then, so versions are recorded in order and never concurrently.+ */+ private load(projectId: string, agentId: string, folder: WorkflowFolder): Promise<Loaded> {+ const k = key(projectId, agentId, folder.id);+ const after = this.loading.get(k) ?? Promise.resolve();+ const run = after+ .catch(() => undefined)+ .then(async () => {+ const current = (await readFolder(folder.dir, folder.id)) ?? folder;+ if (this.loading.get(k) === run) this.loadingRevision.set(k, current.revision);+ return this.loadNow(projectId, agentId, current);+ });+ this.loading.set(k, run);+ this.loadingRevision.set(k, folder.revision);+ void run+ .finally(() => {+ if (this.loading.get(k) === run) {+ this.loading.delete(k);+ this.loadingRevision.delete(k);+ }+ })+ .catch(() => undefined);+ return run;+ }++ /** Boots the folder; on failure keeps the previous instance and reports the error. */+ private async loadNow(+ projectId: string,+ agentId: string,+ folder: WorkflowFolder,+ ): Promise<Loaded> {+ const k = key(projectId, agentId, folder.id);+ const previous = this.loaded.get(k);+ const loadedAt = this.clock.now().toISOString();+ let next: Loaded;+ /** The tree this attempt booted, so a later throw can let it go instead of leaking it. */+ let booted: { dispose: () => void } | null = null;+ try {+ const manifests = await readManifests(folder);+ const tabs = contributedTabs(manifests, uiBase(projectId, agentId, folder.id));+ const ts = await loadTypeScript(this.hmr.assetsDir());+ // A new workflow takes its types from THIS harness; one that has them keeps them, and+ // they are its side of the comparison below.+ installHarnessTypes(+ folder.dir,+ table as unknown as IfaceTable,+ [HOST_IFACE, MAIN_IFACE],+ this.clock.now(),+ );+ const entry = compileWorkflow(ts, folder.dir, folder.revision);+ const written = readHarnessTable(folder.dir);+ if (typeof written === "string") throw new Error(written);+ const fit = checkIfaces(+ ts,+ table as unknown as IfaceTable,+ written,+ ifaceQuestions(manifests),+ );+ // An interface the workflow names but holds no types for cannot be compared, and for a+ // workflow that is a problem, not a pass.+ const misfits = [+ ...fit.uncompared.map((q) => `${q}: not among the types this workflow was written against`),+ ...fit.problems,+ ];+ if (misfits.length > 0) throw new Error(misfits.join("\n"));+ const root = await loadDefs(manifests, entry);+ const host = this.host(projectId, agentId, folder);+ const tree = await bootModules(root, {+ ifaces: table as unknown as IfaceTable,+ resources: this.resources!,+ published: {+ ifaces: { [HOST_MODULE]: { host: hostDecl() }, [WEB_MODULE]: { web: webSlotsDecl() } },+ values: { [HOST_MODULE]: { host }, [WEB_MODULE]: { web: {} } },+ },+ });+ const alias = Object.entries(root.manifest.provides).find(+ ([, ref]) => ref === MAIN_IFACE,+ )![0];+ const main = tree.api<Loaded["main"]>(ROOT_MODULE, alias);+ next = { folder, tree, main, tabs, loadedAt, error: null };+ booted = tree;+ // Recording the version is bookkeeping around a load that has already succeeded, so it+ // cannot be inside the try that decides whether the load failed: a copy that ENOENTs on+ // a file rewritten since it was hashed would hand the caller back the tree disposed+ // just above, and leak the one that is actually serving.+ previous?.tree?.dispose();+ pruneBuilds(folder.dir, folder.revision);+ try {+ await recordVersion(+ historyDir(this.paths.root, projectId, agentId),+ folder,+ this.clock.now(),+ );+ } catch (err) {+ this.log.line(+ `[workflows] ${k}@${folder.revision}: version not recorded: ${messageOf(err)}`,+ );+ }+ } catch (err) {+ const error = messageOf(err);+ this.log.line(`[workflows] ${k}@${folder.revision}: ${error}`);+ // A tree booted before the throw serves nobody: nothing holds it, so it is let go here+ // rather than left behind. The previous instance keeps answering — it was never+ // disposed, because that only happens once the new one is in place.+ booted?.dispose();+ next = {+ folder,+ tree: previous?.tree ?? null,+ main: previous?.main ?? null,+ tabs: previous?.tabs ?? [],+ loadedAt: previous?.loadedAt ?? loadedAt,+ error,+ };+ }+ if (this.disposed) {+ next.tree?.dispose();+ return next;+ }+ writeLoadStatus(folder.dir, {+ revision: folder.revision,+ checkedAt: loadedAt,+ error: next.error,+ tabs: next.tabs.map((tab) => tab.key),+ hints: loadHints(folder.uiRev, next.tabs, next.error),+ });+ this.loaded.set(k, next);+ this.notify(projectId, agentId, this.info(folder.id, next));+ return next;+ }++ private host(projectId: string, agentId: string, folder: WorkflowFolder) {+ const service = this;+ let state: unknown = null;+ let stateRead: Promise<void> | null = null;+ const ensureState = () => (stateRead ??= readState(folder.dir).then((s) => void (state = s)));+ void ensureState();+ return {+ listAgents: () => service.agents.list(projectId).map((row) => ({ agentId: row.agentId })),+ async createSession(opts?: { agentId?: string }) {+ const target = opts?.agentId ?? agentId;+ if (!service.agents.exists(projectId, target)) {+ throw new Error(`createSession: this Project has no Agent '${target}'`);+ }+ return service.sessions.createSession({ projectId, agentId: target });+ },+ async run(sessionId: string, input: WorkflowInput[]) {+ service.ownSession(projectId, sessionId, "run");+ const texts = (Array.isArray(input) ? input : []).map((item) => item?.text);+ if (texts.length === 0 || texts.some((t) => typeof t !== "string" || t === "")) {+ throw new Error('run: input is a non-empty list of { text: "…" } items');+ }+ // Whatever the workflow stamped, the Agent hears the server, never a person.+ return service.runner.startTask(+ sessionId,+ texts.map((text) => userText(text, "server")),+ { queueIfBusy: true },+ );+ },+ sessionStatus: (sessionId: string) => {+ service.ownSession(projectId, sessionId, "sessionStatus");+ return service.runner.statusOf(sessionId);+ },+ getState: () => state,+ async setState(next: unknown) {+ await ensureState();+ state = next ?? null;+ await writeState(folder.dir, state);+ },+ log: (message: string) => service.log.line(`[workflow ${folder.id}] ${message}`),+ };+ }++ /** A workflow reaches the Sessions of its own Project and no others. */+ private ownSession(projectId: string, sessionId: string, call: string): void {+ if (this.sessionIndex.findById(sessionId)?.projectId !== projectId) {+ throw new Error(`${call}: this Project has no Session '${sessionId}'`);+ }+ }++ /** Drops a workflow's instance and tells the Project's users it is gone. */+ private forget(projectId: string, agentId: string, workflowId: string): void {+ const k = key(projectId, agentId, workflowId);+ const t = this.pending.get(k);+ if (t) clearTimeout(t);+ this.pending.delete(k);+ this.loaded.get(k)?.tree?.dispose();+ this.loaded.delete(k);+ this.publish(projectId, { type: "workflow_removed", projectId, agentId, workflowId });+ }++ private notify(projectId: string, agentId: string, workflow: WorkflowInfo): void {+ this.publish(projectId, { type: "workflow_updated", projectId, agentId, workflow });+ }++ /** Users of the Project (owner + members) hear about the change. */+ private publish(projectId: string, event: ServerEvent): void {+ const users = new Set(this.members.list(projectId).map((m) => m.userId));+ const owner = this.projects.findById(projectId)?.ownerUserId;+ if (owner) users.add(owner);+ for (const userId of users) {+ this.channels.peek(userChannelKey(userId))?.publish(event, "server_event");+ }+ }++ private watch(projectId: string, agentId: string): void {+ const k = `${projectId}/${agentId}`;+ if (this.watchers.has(k) || this.disposed) return;+ const declared = workflowsDir(this.paths.root, projectId, agentId);+ if (!fs.existsSync(declared)) {+ this.awaitFirstWorkflow(projectId, agentId, declared);+ return;+ }+ // Watch the REAL path: libuv compares each event's filename against the string it was+ // given, and a Windows short name (`RUNNER~1\…`, which is what os.tmpdir() hands back+ // on a CI runner) never matches the long name the events carry — the mismatch trips an+ // assertion inside fs-event.c and aborts the whole process, which no `try` can catch.+ let dir: string;+ try {+ dir = fs.realpathSync.native(declared);+ } catch {+ dir = declared;+ }+ let watcher: fs.FSWatcher;+ try {+ watcher = fs.watch(dir, { recursive: true }, (_event, filename) => {+ const segments = typeof filename === "string" ? filename.split(/[\\/]/) : [];+ const id = segments[0];+ // The workflow's own document is not code, and neither is the staging file a write+ // of it goes through: `state.json` used to be the only name skipped, so every+ // `setState` recompiled the workflow and tore down the tree that had just written it.+ if (id === undefined || !isWorkflowId(id)) return;+ if (filename?.endsWith(STATE_FILE) || (filename !== null && isTempName(filename))) return;+ // The server's own emit (`.build/`), and any other dot-directory, is not an edit.+ if (segments[1]?.startsWith(".")) return;+ this.schedule(projectId, agentId, id);+ });+ } catch {+ return;+ }+ watcher.on("error", () => {+ watcher.close();+ this.watchers.delete(k);+ });+ this.watchers.set(k, watcher);+ }++ /**+ * An Agent with no `workflows/` folder yet: watch its own directory for that folder to+ * appear. The Agent makes its first workflow with its file tools and nothing else — without+ * this, nothing noticed until somebody listed the workflows again, and the Agent sat+ * waiting for a load that was never going to happen.+ */+ private awaitFirstWorkflow(projectId: string, agentId: string, declared: string): void {+ const k = `${projectId}/${agentId}`;+ const parent = path.dirname(declared);+ let watcher: fs.FSWatcher;+ try {+ watcher = fs.watch(fs.realpathSync.native(parent), (_event, filename) => {+ if (filename !== path.basename(declared) || !fs.existsSync(declared)) return;+ watcher.close();+ this.watchers.delete(k);+ // The folder exists now: watch it properly, and load whatever is already inside.+ void this.list(projectId, agentId).catch((err) =>+ this.log.line(`[workflows] ${k}: ${messageOf(err)}`),+ );+ });+ } catch {+ return;+ }+ watcher.on("error", () => {+ watcher.close();+ this.watchers.delete(k);+ });+ this.watchers.set(k, watcher);+ }++ private schedule(projectId: string, agentId: string, workflowId: string): void {+ const k = key(projectId, agentId, workflowId);+ if (this.removing.has(k)) return;+ const t = this.pending.get(k);+ if (t) clearTimeout(t);+ this.pending.set(+ k,+ setTimeout(() => {+ this.pending.delete(k);+ void this.reloadIfChanged(projectId, agentId, workflowId).catch((err) => {+ if (err instanceof WorkflowNotFound) {+ this.forget(projectId, agentId, workflowId);+ return;+ }+ this.log.line(`[workflows] ${k}: ${messageOf(err)}`);+ });+ }, WATCH_SETTLE_MS),+ );+ }+}++export class WorkflowNotFound extends Error {}++/** Where a workflow's `ui/` is served from (./routes.ts). */+function uiBase(projectId: string, agentId: string, workflowId: string): string {+ const [p, a, w] = [projectId, agentId, workflowId].map(encodeURIComponent);+ return `/api/projects/${p}/agents/${a}/workflows/${w}/${UI_DIR}`;+}++/**+ * The slots the host opens to a workflow tree, published under the platform module's own+ * name: the slot declarations come from the platform's table (so a workflow's contribution+ * has the shape a plugin's has), and only the opened ones are there — contributing to any+ * other is `no-such-slot`. No members: there is nothing to require from it.+ */+function webSlotsDecl(): IfaceDecl {+ const decl = (table as unknown as { ifaces: Record<string, IfaceDecl> }).ifaces[WEB_IFACE];+ if (!decl) throw new Error(`${WEB_IFACE} is not in ifaces.json (regenerate it)`);+ const slots: IfaceDecl["slots"] = {};+ for (const name of OPEN_WEB_SLOTS) {+ const slot = decl.slots[name];+ if (!slot) throw new Error(`${WEB_IFACE} declares no slot '${name}' (regenerate ifaces.json)`);+ slots[name] = slot;+ }+ return { name: "WorkflowWebSlots", methods: {}, slots };+}++/** The published `WorkflowHost` declaration, straight from the platform's interface table. */+function hostDecl(): IfaceDecl {+ const decl = (table as unknown as { ifaces: Record<string, IfaceDecl> }).ifaces[HOST_IFACE];+ if (!decl) throw new Error(`${HOST_IFACE} is not in ifaces.json (regenerate it)`);+ return decl;+}diff --git a/packages/server/src/workflows/store.ts b/packages/server/src/workflows/store.tsnew file mode 100644index 00000000..f76b12b9--- /dev/null+++ b/packages/server/src/workflows/store.ts@@ -0,0 +1,248 @@+/**+ * Where an Agent's workflows live and how their versions are kept.+ *+ * <agentDir>/workflows/<id>/package.json `penguin.modules` manifests (a plugin package)+ * <agentDir>/workflows/<id>/index.ts default export `{ modules: { <Name>: { create } } }`+ * <agentDir>/workflows/<id>/ui/ the pages its contributed tabs name+ * <agentDir>/workflows/<id>/state.json the workflow's own document (WorkflowHost.getState)+ * <agentDir>/workflows/<id>/.harness/ the types it was written against (harness-types.ts)+ * <agentDir>/workflows/<id>/.build/ its emitted code, per revision (compile.ts)+ * <agentDir>/workflows-history/<id>/<revision>/ a full copy of the folder at each successful load+ * <agentDir>/workflows-history/<id>/versions.json the list, newest first+ *+ * The revision is the content hash of every file except `state.json` (the state is the+ * workflow's data, not its code, and survives a rollback untouched), `node_modules` and the+ * dot-directories, which are the server's. Reading is tolerant:+ * a folder without a package.json is not a workflow, a broken versions.json is an empty list.+ */+import { createHash, randomBytes } from "node:crypto";+import fs from "node:fs/promises";+import path from "node:path";+import { agentDir } from "@prismshadow/penguin-core";+import type { WorkflowVersion } from "../mechanisms/workflows.js";++export const STATE_FILE = "state.json";+export const UI_DIR = "ui";+/** Versions kept per workflow; older copies are removed with their folders. */+export const KEEP_VERSIONS = 20;++export interface WorkflowFolder {+ id: string;+ dir: string;+ /** Relative paths, sorted, excluding state.json. */+ files: string[];+ revision: string;+ uiRev: string | null;+ pkg: { name: string; version: string | null };+}++export function workflowsDir(root: string, projectId: string, agentId: string): string {+ return path.join(agentDir(root, projectId, agentId), "workflows");+}++export function historyDir(root: string, projectId: string, agentId: string): string {+ return path.join(agentDir(root, projectId, agentId), "workflows-history");+}++/** A workflow id is one path segment of the folder's own name; nothing else is accepted. */+export function isWorkflowId(id: string): boolean {+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(id) && id !== "." && id !== "..";+}++export function isSafeRelPath(rel: string): boolean {+ if (rel === "" || rel.startsWith("/") || rel.includes("\\")) return false;+ return rel.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");+}++async function walk(dir: string, prefix = ""): Promise<string[]> {+ let entries: import("node:fs").Dirent[];+ try {+ entries = await fs.readdir(dir, { withFileTypes: true });+ } catch {+ return [];+ }+ const out: string[] = [];+ for (const e of entries) {+ if (e.name === "node_modules" || e.name.startsWith(".") || isTempName(e.name)) continue;+ const rel = prefix === "" ? e.name : `${prefix}/${e.name}`;+ if (e.isDirectory()) out.push(...(await walk(path.join(dir, e.name), rel)));+ else if (e.isFile()) out.push(rel);+ }+ return out.sort();+}++async function hashFiles(dir: string, files: string[]): Promise<string> {+ const h = createHash("sha256");+ for (const rel of files) {+ // A file listed a moment ago can be gone by now — an editor's own scratch file, the+ // Agent deleting one mid-write. That is a folder that has changed, not a broken read:+ // the hash covers what is still there, and the watcher brings the next one round.+ // Reading whatever is there is also what every other read in this module does.+ let body: Buffer;+ try {+ body = await fs.readFile(path.join(dir, rel));+ } catch {+ continue;+ }+ h.update(rel).update("\0");+ h.update(body).update("\0");+ }+ return h.digest("hex").slice(0, 12);+}++/** Reads one workflow folder; null when it is not a workflow (no package.json). */+export async function readFolder(dir: string, id: string): Promise<WorkflowFolder | null> {+ let raw: string;+ try {+ raw = await fs.readFile(path.join(dir, "package.json"), "utf8");+ } catch {+ return null;+ }+ let pkg: { name?: unknown; version?: unknown } = {};+ try {+ pkg = JSON.parse(raw) as typeof pkg;+ } catch {+ // A broken package.json is still a workflow folder: the loader reports the error.+ }+ const files = (await walk(dir)).filter((f) => f !== STATE_FILE);+ const ui = files.filter((f) => f.startsWith(`${UI_DIR}/`));+ return {+ id,+ dir,+ files,+ revision: await hashFiles(dir, files),+ uiRev: ui.length === 0 ? null : await hashFiles(dir, ui),+ pkg: {+ name: typeof pkg.name === "string" && pkg.name !== "" ? pkg.name : id,+ version: typeof pkg.version === "string" ? pkg.version : null,+ },+ };+}++export async function listFolders(base: string): Promise<WorkflowFolder[]> {+ let entries: import("node:fs").Dirent[];+ try {+ entries = await fs.readdir(base, { withFileTypes: true });+ } catch {+ return [];+ }+ const out: WorkflowFolder[] = [];+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {+ if (!e.isDirectory() || !isWorkflowId(e.name)) continue;+ const folder = await readFolder(path.join(base, e.name), e.name);+ if (folder) out.push(folder);+ }+ return out;+}++export async function readState(dir: string): Promise<unknown> {+ try {+ return JSON.parse(await fs.readFile(path.join(dir, STATE_FILE), "utf8")) as unknown;+ } catch {+ return null;+ }+}++/**+ * The suffix every staged write of ours carries. It is what tells the watcher and the+ * revision hash that a file is the server's own scratch and not an edit: a fixed+ * `state.json.tmp` was neither — it reloaded the workflow on every `setState`, and entered+ * the hash it was supposed to be outside of. The random middle keeps two concurrent writes+ * from truncating each other's staging file and renaming a half-written document into place.+ */+export const TMP_SUFFIX = ".penguin-tmp";+export const isTempName = (name: string): boolean => name.includes(TMP_SUFFIX);+const tempPath = (file: string) => `${file}${TMP_SUFFIX}${randomBytes(6).toString("hex")}`;++export async function writeState(dir: string, state: unknown): Promise<void> {+ const file = path.join(dir, STATE_FILE);+ const staged = tempPath(file);+ try {+ await fs.writeFile(staged, JSON.stringify(state ?? null, null, 2));+ await fs.rename(staged, file);+ } catch (err) {+ await fs.rm(staged, { force: true }).catch(() => undefined);+ throw err;+ }+}++async function readVersions(dir: string): Promise<WorkflowVersion[]> {+ try {+ const parsed = JSON.parse(await fs.readFile(path.join(dir, "versions.json"), "utf8"));+ return Array.isArray(parsed) ? (parsed as WorkflowVersion[]) : [];+ } catch {+ return [];+ }+}++async function writeVersions(dir: string, versions: WorkflowVersion[]): Promise<void> {+ await fs.mkdir(dir, { recursive: true });+ const file = path.join(dir, "versions.json");+ const staged = tempPath(file);+ await fs.writeFile(staged, JSON.stringify(versions, null, 2));+ await fs.rename(staged, file);+}++/**+ * Records the folder's current content as a version (no-op when that revision is already+ * the newest), copying the files and trimming to KEEP_VERSIONS.+ */+export async function recordVersion(+ history: string,+ folder: WorkflowFolder,+ now: Date,+): Promise<WorkflowVersion[]> {+ const dir = path.join(history, folder.id);+ const versions = await readVersions(dir);+ if (versions[0]?.revision === folder.revision) return versions;+ const target = path.join(dir, folder.revision);+ await fs.rm(target, { recursive: true, force: true });+ for (const rel of folder.files) {+ await fs.mkdir(path.dirname(path.join(target, rel)), { recursive: true });+ await fs.copyFile(path.join(folder.dir, rel), path.join(target, rel));+ }+ const entry: WorkflowVersion = {+ revision: folder.revision,+ savedAt: now.toISOString(),+ name: folder.pkg.name,+ version: folder.pkg.version,+ uiRev: folder.uiRev,+ files: folder.files,+ };+ // A revision seen before moves to the front rather than duplicating (a rollback IS such a load).+ const next = [entry, ...versions.filter((v) => v.revision !== folder.revision)];+ for (const old of next.splice(KEEP_VERSIONS)) {+ await fs.rm(path.join(dir, old.revision), { recursive: true, force: true });+ }+ await writeVersions(dir, next);+ return next;+}++export function listVersions(history: string, id: string): Promise<WorkflowVersion[]> {+ return readVersions(path.join(history, id));+}++/**+ * Replaces the folder's code files with a recorded version's, keeping state.json. Files+ * the current folder has and the version lacks are removed, so the result is exactly that+ * version. Returns false when the version is not recorded.+ */+export async function restoreVersion(+ history: string,+ folder: WorkflowFolder,+ revision: string,+): Promise<boolean> {+ const versions = await readVersions(path.join(history, folder.id));+ const version = versions.find((v) => v.revision === revision);+ if (!version) return false;+ const source = path.join(history, folder.id, revision);+ const keep = new Set(version.files);+ for (const rel of folder.files) {+ if (!keep.has(rel)) await fs.rm(path.join(folder.dir, rel), { force: true });+ }+ for (const rel of version.files) {+ await fs.mkdir(path.dirname(path.join(folder.dir, rel)), { recursive: true });+ await fs.copyFile(path.join(source, rel), path.join(folder.dir, rel));+ }+ return true;+}diff --git a/packages/server/test/iface-check.test.ts b/packages/server/test/iface-check.test.tsindex 26b6ff04..bd9e336a 100644--- a/packages/server/test/iface-check.test.ts+++ b/packages/server/test/iface-check.test.ts@@ -1,5 +1,5 @@/**- * The interface comparison a plugin package gets at load: its OWN table against this+ * The interface comparison plugins and workflows share: a package's OWN table against this* platform's, decided by the TypeScript compiler, both for what it requires and for what* it provides.*/@@ -12,7 +12,7 @@ import { checkIfaces, ifaceQuestions, renderDts } from "../src/plugin/iface-checconst platform = platformTable as unknown as IfaceTable;const LOG = "@prismshadow/penguin-server#Log";-const MAIN = "@prismshadow/penguin-server#AgentConfigService";+const MAIN = "@prismshadow/penguin-server#WorkflowMain";const manifest = parseManifest({name: "Demo",@@ -45,7 +45,7 @@ describe("interface check", () => {it("names a required interface that no longer fits, and a provided one", () => {const own = compiledAgainst((t) => {t.ifaces[LOG]!.methods["line"]!.params = [{ data: "number" }];- t.ifaces[MAIN]!.methods["exists"]!.returns = { promise: { data: "string" } };+ t.ifaces[MAIN]!.methods["handle"]!.returns = { promise: { data: "string" } };});const { problems } = checkIfaces(ts, platform, own, ifaceQuestions([manifest]));expect(problems).toHaveLength(2);@@ -66,7 +66,7 @@ describe("interface check", () => {delete t.ifaces[LOG];});// It is reported as uncompared; whether that fails the load is the caller's rule (a- // plugin's — whose table the generator does not fill yet — does not).+ // workflow's does, a plugin's — whose table the generator does not fill yet — does not).expect(checkIfaces(ts, platform, own, ifaceQuestions([manifest]))).toEqual({problems: [],uncompared: [`Demo: requires.log '${LOG}'`],diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.tsindex 47143662..c7c5e49a 100644--- a/packages/server/test/scheduler.test.ts+++ b/packages/server/test/scheduler.test.ts@@ -95,7 +95,7 @@ describe("scheduler", () => {statusOf: (id: string) => (busy.has(id) ? "running" : "idle"),startTask: async (sessionId: string, input: OmniMessage[]) => {started.push({ sessionId, text: JSON.stringify(input[0]?.payload ?? "") });- return { sessionId };+ return { sessionId, queued: false };},} satisfies ScheduleTaskRunner,sessionCreator: {diff --git a/packages/server/test/workflows.test.ts b/packages/server/test/workflows.test.tsnew file mode 100644index 00000000..b65f3ab1--- /dev/null+++ b/packages/server/test/workflows.test.ts@@ -0,0 +1,588 @@+/**+ * Workflows: an Agent's own plugin package booted as a module tree — TypeScript the server+ * checks and transpiles, interfaces compared with the version the workflow installed,+ * tabs it contributes, loaded by content, versioned on every successful load, restorable,+ * and never taken down by a broken edit.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import fs from "node:fs/promises";+import path from "node:path";+import { agentDir } from "@prismshadow/penguin-core";+import type { IfaceTable } from "@prismshadow/penguin-core/kernel";+import type { WorkflowInfo, WorkflowVersion } from "../src/api/types.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const PROJECT = "owner-wf";+const AGENT = "default_agent";+const BASE = `/api/projects/${PROJECT}/agents/${AGENT}/workflows`;+const HOST_KEY = "@prismshadow/penguin-server#WorkflowHost";+const MAIN_KEY = "@prismshadow/penguin-server#WorkflowMain";++const TAB = {+ id: "demo.board",+ key: "board",+ title: "Board",+ titleZh: "看板",+ renderer: { iframe: { src: "ui/index.html" } },+};++const MANIFEST = {+ name: "Workflow",+ requires: { host: { iface: HOST_KEY, from: "Host" } },+ provides: { main: MAIN_KEY },+ contributes: { "WebModule.sessionTabs": [TAB] },+ children: [],+};++function packageJson(modules: unknown[] = [MANIFEST], extra: Record<string, unknown> = {}) {+ return JSON.stringify({+ name: "Demo",+ version: "1.0.0",+ type: "module",+ penguin: { modules },+ ...extra,+ });+}++function indexSource(greeting: string): string {+ return `import type { WorkflowPackage } from "@prismshadow/penguin-server/plugin";++export default {+ modules: {+ Workflow: {+ create({ use }) {+ const host = use.host;+ return {+ api: {+ main: {+ async handle(req) {+ if (req.path === "/open") {+ // The SDK's verbs, scoped to this Project: another of its Agents, never a stranger's Session.+ const agent = req.query["agent"];+ // No argument at all is this Agent: the rendered types keep the parameter optional.+ const opened = await (agent ? host.createSession({ agentId: agent }) : host.createSession()).catch((e: Error) => e.message);+ const ran = await host.run(req.query["session"] ?? "", [{ text: "hi" }]).catch((e: Error) => e.message);+ return { body: { opened, ran, agents: host.listAgents().map((a) => a.agentId) } };+ }+ if (req.path === "/page") {+ const headers: Record<string, string> = { "content-type": "text/html; charset=utf-8", "set-cookie": "x=1" };+ return { headers, body: "<h1>proxied</h1>" };+ }+ if (req.path === "/upload") {+ // Whatever was sent comes back as sent, with what the handler saw of the request.+ const headers: Record<string, string> = {+ "content-type": req.headers["content-type"] ?? "application/octet-stream",+ "x-saw-cookie": String("cookie" in req.headers),+ "x-json-body": JSON.stringify(req.body),+ };+ return { status: 201, headers, bytes: req.bytes ?? new Uint8Array() };+ }+ if (req.path === "/events") {+ const headers: Record<string, string> = { "content-type": "text/event-stream" };+ async function* events() {+ yield "data: one\\n\\n";+ await new Promise((r) => setTimeout(r, 400));+ yield new TextEncoder().encode("data: two\\n\\n");+ }+ return { headers, stream: events() };+ }+ if (req.path === "/moved") {+ const headers: Record<string, string> = { location: "page" };+ return { status: 302, headers };+ }+ if (req.path === "/count" && req.method === "POST") {+ const n = (((host.getState() ?? {}) as { count?: number }).count ?? 0) + 1;+ await host.setState({ count: n });+ return { body: { count: n } };+ }+ return { status: 200, body: { greeting: ${JSON.stringify(greeting)}, path: req.path, q: req.query } };+ },+ },+ },+ };+ },+ },+ },+} satisfies WorkflowPackage;+`;+}++/** Rewrites the table the harness wrote into the folder: the workflow was written against an OLDER one. */+async function writtenAgainst(dir: string, edit: (table: IfaceTable) => void): Promise<void> {+ const file = path.join(dir, ".harness", "ifaces.json");+ const table = JSON.parse(await fs.readFile(file, "utf8")) as IfaceTable;+ edit(table);+ await fs.writeFile(file, JSON.stringify(table));+}++// Most of these run the TypeScript compiler, several times each: on a CI runner a single test+// can pass 5s, the default POSIX limit, without anything being wrong.+describe("workflows", { timeout: 30_000 }, () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let ownerCookie: string;+ let dir: string;++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner");+ owner = apiClient(t.app, a.cookie);+ ownerCookie = a.cookie;+ const created = await owner.post("/api/projects", { projectId: PROJECT, name: "wf" });+ expect(created.status, await created.text()).toBe(201);+ dir = path.join(agentDir(t.root, PROJECT, AGENT), "workflows", "demo");+ await fs.mkdir(path.join(dir, "ui"), { recursive: true });+ await fs.writeFile(path.join(dir, "package.json"), packageJson());+ await fs.writeFile(path.join(dir, "index.ts"), indexSource("hello"));+ await fs.writeFile(path.join(dir, "ui", "index.html"), "<h1>demo v1</h1>");+ });++ afterEach(async () => {+ await t.cleanup();+ });++ async function list(): Promise<WorkflowInfo[]> {+ const res = await owner.get(BASE);+ expect(res.status).toBe(200);+ return ((await res.json()) as { workflows: WorkflowInfo[] }).workflows;+ }++ it("checks and transpiles the TypeScript, boots the tree, serves its UI and dispatches to its handler", async () => {+ const [wf] = await list();+ expect(wf).toMatchObject({ id: "demo", name: "Demo", version: "1.0.0", error: null });+ expect(wf!.uiRev).toMatch(/^[0-9a-f]{12}$/);+ // The tab is the contribution, its page path turned into the URL it is served from.+ expect(wf!.tabs).toEqual([+ { ...TAB, renderer: { iframe: { src: `${BASE}/demo/ui/index.html` } } },+ ]);+ // The emitted code lives in a dot-directory: no part of the revision or the versions.+ // Beside it, what the load came to — the Agent's only view of it is its own files.+ expect((await fs.readdir(path.join(dir, ".build"))).sort()).toEqual(+ [wf!.revision, "status.json"].sort(),+ );+ expect(JSON.parse(await fs.readFile(path.join(dir, ".build", "status.json"), "utf8"))).toEqual({+ ok: true,+ revision: wf!.revision,+ checkedAt: wf!.loadedAt,+ error: null,+ tabs: ["board"],+ hints: [],+ });+ // Its types came from this harness, not from a package: written once, then left alone.+ expect((await fs.readdir(path.join(dir, ".harness"))).sort()).toEqual([+ "README.md",+ "harness.json",+ "ifaces.json",+ "plugin.d.ts",+ ]);+ const types = await fs.readFile(path.join(dir, ".harness", "plugin.d.ts"), "utf8");+ expect(types).toContain("export interface WorkflowHost {");+ expect(types).toContain("export interface WorkflowPackage {");+ await expect(fs.stat(path.join(dir, "node_modules"))).rejects.toThrow();++ const ui = await owner.get(`${BASE}/demo/ui/index.html`);+ expect(ui.status).toBe(200);+ // No default document: a tab names its page.+ expect((await owner.get(`${BASE}/demo/ui/`)).status).toBe(404);+ expect(ui.headers.get("content-type")).toContain("text/html");+ expect(await ui.text()).toBe("<h1>demo v1</h1>");+ expect((await owner.get(`${BASE}/demo/ui/../package.json`)).status).toBe(404);+ expect((await owner.get(`${BASE}/demo/ui/nope.js`)).status).toBe(404);++ const res = await owner.get(`${BASE}/demo/api/greet?x=1`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ greeting: "hello", path: "/greet", q: { x: "1" } });++ // Host state persists on disk across a reload.+ expect(await (await owner.post(`${BASE}/demo/api/count`, {})).json()).toEqual({ count: 1 });+ expect((await owner.post(`${BASE}/demo/reload`)).status).toBe(200);+ expect(await (await owner.post(`${BASE}/demo/api/count`, {})).json()).toEqual({ count: 2 });+ expect(JSON.parse(await fs.readFile(path.join(dir, "state.json"), "utf8"))).toEqual({+ count: 2,+ });+ });++ it("does not treat its own state write as an edit: the revision holds and nothing is staged", async () => {+ const [before] = await list();+ // Writing state used to leave a `state.json.tmp` behind, which the watcher read as an+ // edit (recompiling the workflow and tearing down the tree that had just written it) and+ // the revision hash read as content.+ expect(await (await owner.post(`${BASE}/demo/api/count`, {})).json()).toEqual({ count: 1 });+ const [after] = await list();+ expect(after!.revision).toBe(before!.revision);+ expect(after!.loadedAt).toBe(before!.loadedAt);+ const left = (await fs.readdir(dir)).filter((n) => n.includes("tmp"));+ expect(left).toEqual([]);+ });++ it("a folder file that disappears mid-read is a change, not a failed request", async () => {+ // `walk` lists the files, then each is read: one that goes away in between (an editor's+ // scratch file, the Agent deleting one) used to reject the read and answer 500 although+ // the loaded instance was fine.+ await fs.writeFile(path.join(dir, "notes.md"), "gone in a moment");+ const [listed] = await list();+ expect(listed!.error).toBe(null);+ await fs.rm(path.join(dir, "notes.md"));+ const res = await owner.get(`${BASE}/demo/api/greet`);+ expect(res.status, await res.text()).toBe(200);+ });++ it("re-imports an edited folder, records every version and rolls back to any of them", async () => {+ const [v1] = await list();+ await fs.writeFile(path.join(dir, "index.ts"), indexSource("bonjour"));+ await fs.writeFile(path.join(dir, "ui", "index.html"), "<h1>demo v2</h1>");+ const reload = await owner.post(`${BASE}/demo/reload`);+ const v2 = ((await reload.json()) as { workflow: WorkflowInfo }).workflow;+ expect(v2.revision).not.toBe(v1!.revision);+ expect(v2.uiRev).not.toBe(v1!.uiRev);+ expect(+ (await (await owner.get(`${BASE}/demo/api/`)).json()) as { greeting: string },+ ).toMatchObject({+ greeting: "bonjour",+ });++ const history = (await (await owner.get(`${BASE}/demo/history`)).json()) as {+ versions: WorkflowVersion[];+ };+ expect(history.versions.map((v) => v.revision)).toEqual([v2.revision, v1!.revision]);+ expect(history.versions[1]!.files).toContain("ui/index.html");++ const back = await owner.post(`${BASE}/demo/rollback`, { revision: v1!.revision });+ expect(back.status).toBe(200);+ expect(((await back.json()) as { workflow: WorkflowInfo }).workflow.revision).toBe(+ v1!.revision,+ );+ expect(await (await owner.get(`${BASE}/demo/ui/index.html`)).text()).toBe("<h1>demo v1</h1>");+ // Only the serving revision keeps its emitted code.+ expect((await fs.readdir(path.join(dir, ".build"))).sort()).toEqual(+ [v1!.revision, "status.json"].sort(),+ );+ expect(+ (await (await owner.get(`${BASE}/demo/api/`)).json()) as { greeting: string },+ ).toMatchObject({+ greeting: "hello",+ });+ // The rolled-back revision is now the newest entry, once.+ const after = (await (await owner.get(`${BASE}/demo/history`)).json()) as {+ versions: WorkflowVersion[];+ };+ expect(after.versions.map((v) => v.revision)).toEqual([v1!.revision, v2.revision]);+ expect((await owner.post(`${BASE}/demo/rollback`, { revision: "000000000000" })).status).toBe(+ 404,+ );+ });++ it("keeps the previous instance serving when an edit does not load, and names the problem", async () => {+ await list();+ await fs.writeFile(+ path.join(dir, "package.json"),+ packageJson([+ {+ ...MANIFEST,+ requires: { host: { iface: "@prismshadow/penguin-server#Workflows", from: "Host" } },+ },+ ]),+ );+ const res = await owner.post(`${BASE}/demo/reload`);+ const broken = ((await res.json()) as { workflow: WorkflowInfo }).workflow;+ // Named before anything runs: the host gave this workflow no types for that interface.+ expect(broken.error).toContain(+ "requires.host '@prismshadow/penguin-server#Workflows': not among the types this workflow was written against",+ );+ expect(await (await owner.get(`${BASE}/demo/api/`)).json()).toMatchObject({+ greeting: "hello",+ });+ expect(await (await owner.get(`${BASE}/demo/history`)).json()).toMatchObject({+ versions: [{ name: "Demo" }],+ });+ });++ async function reload(): Promise<WorkflowInfo> {+ const res = await owner.post(`${BASE}/demo/reload`);+ expect(res.status).toBe(200);+ return ((await res.json()) as { workflow: WorkflowInfo }).workflow;+ }++ async function reloadError(): Promise<string> {+ const workflow = await reload();+ // Whatever went wrong, the instance that loaded keeps answering, with its tabs.+ expect(workflow.tabs).toHaveLength(1);+ expect(await (await owner.get(`${BASE}/demo/api/`)).json()).toMatchObject({+ greeting: "hello",+ });+ return workflow.error ?? "";+ }++ it("refuses source that does not type-check, with the compiler's file, line and reason", async () => {+ await list();+ await fs.writeFile(+ path.join(dir, "index.ts"),+ indexSource("hello")+ .replace("await host.setState({ count: n });", "await host.setStat({ count: n });")+ .replace("return { body: { count: n } };", 'return "text";'),+ );+ const error = await reloadError();+ expect(error).toMatch(+ /index\.ts:\d+:\d+ TS2551 Property 'setStat' does not exist on type 'WorkflowHost'/,+ );+ expect(error).toContain("TS2322");+ // The same words reach the Agent through its files.+ expect(+ JSON.parse(await fs.readFile(path.join(dir, ".build", "status.json"), "utf8")),+ ).toMatchObject({ ok: false, error });+ // Said once, by the author's own file; the server's copy of the same question is left out.+ expect(error).not.toContain("default export");+ expect(error.match(/TS2322/g)).toHaveLength(1);++ // A JSON body may be null: an optional `unknown` member stays `unknown` in the table.+ await fs.writeFile(+ path.join(dir, "index.ts"),+ indexSource("hello").replace("return { body: { count: n } };", "return { body: null };"),+ );+ expect((await reload()).error).toBeNull();++ // Untyped is refused too: `strict` leaves no implicit any to slip through.+ await fs.writeFile(+ path.join(dir, "index.ts"),+ indexSource("hello").replace(" satisfies WorkflowPackage", ""),+ );+ expect(await reloadError()).toContain("TS7031");+ });++ it("opens and runs Sessions the SDK's way, inside its own Project only", async () => {+ await list();+ const res = await owner.get(`${BASE}/demo/api/open?agent=nobody&session=not-a-session`);+ expect(await res.json()).toEqual({+ opened: "createSession: this Project has no Agent 'nobody'",+ ran: "run: this Project has no Session 'not-a-session'",+ agents: [AGENT],+ });+ const own = await (await owner.get(`${BASE}/demo/api/open`)).json();+ // Its own Agent passes the Project check and reaches the session runtime, which in this+ // fixture has no model key to open a Session with.+ expect(own).toMatchObject({ opened: expect.stringContaining("API key") });+ });++ it("notices an Agent's FIRST workflow, made with nothing but its file tools", async () => {+ // Another Agent of the Project, with no workflows/ folder when its list is first read.+ const made = await owner.post(`/api/projects/${PROJECT}/agents`, { agentId: "builder" });+ expect(made.status, await made.text()).toBe(201);+ const base = `/api/projects/${PROJECT}/agents/builder/workflows`;+ expect(((await (await owner.get(base)).json()) as { workflows: unknown[] }).workflows).toEqual(+ [],+ );++ const first = path.join(agentDir(t.root, PROJECT, "builder"), "workflows", "first");+ await fs.mkdir(path.join(first, "ui"), { recursive: true });+ await fs.writeFile(path.join(first, "package.json"), packageJson());+ await fs.writeFile(path.join(first, "index.ts"), indexSource("first"));+ await fs.writeFile(path.join(first, "ui", "index.html"), "<h1>first</h1>");++ // Nobody lists again: the server has to see the folder appear and load it on its own.+ const statusFile = path.join(first, ".build", "status.json");+ let status: { ok?: boolean } = {};+ for (let i = 0; i < 100 && status.ok === undefined; i++) {+ await new Promise((r) => setTimeout(r, 100));+ status = await fs.readFile(statusFile, "utf8").then(+ (text) => JSON.parse(text) as { ok: boolean },+ () => ({}),+ );+ }+ expect(status).toMatchObject({ ok: true, error: null, tabs: ["board"] });+ });++ it("refuses JavaScript", async () => {+ await list();+ await fs.rename(path.join(dir, "index.ts"), path.join(dir, "index.mjs"));+ expect(await reloadError()).toContain(+ "a workflow is written in TypeScript: rename index.mjs to index.ts",+ );+ });++ it("compares the types the workflow was written against with this platform's, both ways", async () => {+ await list();+ // requires: it was written when the host had a method this platform lacks.+ await writtenAgainst(dir, (t) => {+ t.ifaces[HOST_KEY]!.methods["removedSince"] = { params: [], returns: { void: true } };+ });+ let error = await reloadError();+ expect(error).toContain(`Workflow: requires.host '${HOST_KEY}'`);+ expect(error).toContain("removedSince");++ // provides: the handler it was written against answers with something else.+ await writtenAgainst(dir, (t) => {+ delete t.ifaces[HOST_KEY]!.methods["removedSince"];+ t.ifaces[MAIN_KEY]!.methods["handle"]!.returns = { promise: { data: "string" } };+ });+ error = await reloadError();+ expect(error).toContain(`Workflow: provides.main '${MAIN_KEY}'`);+ expect(error).toContain("TS2322");++ // An addition on the platform's side breaks nothing.+ await fs.rm(path.join(dir, ".harness"), { recursive: true });+ expect((await reload()).error).toBeNull();+ await writtenAgainst(dir, (t) => {+ delete t.ifaces[HOST_KEY]!.methods["log"];+ });+ expect((await reload()).error).toBeNull();++ // A table that cannot be read is a problem, never a pass against the platform's own;+ // deleting the directory is how a workflow takes this harness's types afresh.+ await fs.writeFile(path.join(dir, ".harness", "ifaces.json"), "{");+ expect(await reloadError()).toContain(".harness/ifaces.json cannot be read");+ await fs.rm(path.join(dir, ".harness"), { recursive: true });+ expect((await reload()).error).toBeNull();+ });++ it("takes tabs from contributions: several per workflow, pages under ui/, open slots only", async () => {+ await list();+ const stats = {+ ...TAB,+ id: "demo.stats",+ key: "stats",+ title: "Stats",+ renderer: { iframe: { src: "ui/stats.html" } },+ };+ const write = (contributes: Record<string, unknown[]>) =>+ fs.writeFile(path.join(dir, "package.json"), packageJson([{ ...MANIFEST, contributes }]));++ await write({ "WebModule.sessionTabs": [TAB, stats] });+ const two = await reload();+ expect(two.error).toBeNull();+ expect(two.tabs.map((tab) => tab.key)).toEqual(["board", "stats"]);++ await write({+ "WebModule.sessionTabs": [{ ...TAB, renderer: { iframe: { src: "index.ts" } } }],+ });+ expect((await reload()).error).toContain("renderer.iframe.src must be a file under ui/");+ await write({+ "WebModule.pages": [+ {+ id: "demo.page",+ key: "p",+ path: "/p",+ nav: "main",+ admin: false,+ renderer: { builtin: "x" },+ },+ ],+ });+ expect((await reload()).error).toContain("WebModule.pages");+ await write({ "WebModule.sessionTabs": [{ ...TAB, title: 7 }] });+ expect((await reload()).error).toContain("module tree rejected");+ // A workflow with no contribution is server-side only — and since this one has pages, the+ // load says that nothing shows them, with the entry to add, in the API and in the status+ // file alike (the Agent that wrote it may have only the file).+ await write({});+ const bare = (await reload()) as { error: string | null; tabs: unknown[]; hints: string[] };+ expect(bare).toMatchObject({ error: null, tabs: [] });+ expect(bare.hints).toHaveLength(1);+ expect(bare.hints[0]).toContain('"WebModule.sessionTabs"');+ expect(bare.hints[0]).toContain("ui/index.html");+ const status = JSON.parse(await fs.readFile(path.join(dir, ".build", "status.json"), "utf8"));+ expect(status).toMatchObject({ ok: true, tabs: [], hints: bare.hints });+ // The harness describes its own contract beside the types it wrote.+ expect(await fs.readFile(path.join(dir, ".harness", "README.md"), "utf8")).toContain(+ "A page shows only if a tab is contributed for it",+ );+ // With the tab back there is nothing to hint at.+ await write({ "WebModule.sessionTabs": [TAB] });+ expect(((await reload()) as { hints: string[] }).hints).toEqual([]);+ });++ it("hands a handler any body and sends back any content type; JSON stays the default", async () => {+ await list();+ // An upload: not JSON, so the handler gets the bytes as sent — and never the app's cookie.+ const sent = new Uint8Array([0, 1, 2, 250, 251, 255]);+ const upload = await t.app.request(`${BASE}/demo/api/upload`, {+ method: "POST",+ headers: { cookie: ownerCookie, "content-type": "application/x-demo" },+ body: sent,+ });+ expect(upload.status).toBe(201);+ expect(upload.headers.get("content-type")).toBe("application/x-demo");+ expect(upload.headers.get("x-saw-cookie")).toBe("false");+ expect(upload.headers.get("x-json-body")).toBe("null");+ expect(new Uint8Array(await upload.arrayBuffer())).toEqual(sent);+ // A form is what another site can make a browser send with the cookie attached, so on this+ // mount the browser's own account of the request's origin is the defense: a form from one+ // of the app's pages passes, the same form from anywhere else does not.+ const form = (site: string) =>+ t.app.request(`${BASE}/demo/api/upload`, {+ method: "POST",+ headers: {+ cookie: ownerCookie,+ "content-type": "application/x-www-form-urlencoded",+ "sec-fetch-site": site,+ },+ body: "a=1",+ });+ expect((await form("same-origin")).status).toBe(201);+ const forged = await form("cross-site");+ expect(forged.status).toBe(403);+ expect(((await forged.json()) as { error: { code: string } }).error.code).toBe(+ "cross_origin_write",+ );+ // Everywhere else a form is still refused outright.+ const elsewhere = await t.app.request(`${BASE}/demo/reload`, {+ method: "POST",+ headers: {+ cookie: ownerCookie,+ "content-type": "text/plain",+ "sec-fetch-site": "same-origin",+ },+ body: "x",+ });+ expect(elsewhere.status).toBe(415);+ // A page: the handler names the content type, the string goes out as written, and a+ // workflow does not get to set the app's cookies.+ const page = await owner.get(`${BASE}/demo/api/page`);+ expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");+ expect(page.headers.get("set-cookie")).toBeNull();+ expect(await page.text()).toBe("<h1>proxied</h1>");+ // A stream: the first chunk is in the client's hands while the handler is still producing+ // the second — nothing is held back until the end.+ const events = await owner.get(`${BASE}/demo/api/events`);+ expect(events.headers.get("content-type")).toBe("text/event-stream");+ const reader = events.body!.getReader();+ const startedAt = Date.now();+ const first = await reader.read();+ expect(new TextDecoder().decode(first.value)).toBe("data: one\n\n");+ expect(Date.now() - startedAt).toBeLessThan(300);+ const second = await reader.read();+ expect(new TextDecoder().decode(second.value)).toBe("data: two\n\n");+ expect((await reader.read()).done).toBe(true);+ // A redirect, relative to the api mount.+ const moved = await owner.get(`${BASE}/demo/api/moved`);+ expect(moved.status).toBe(302);+ expect(moved.headers.get("location")).toBe("page");+ // And what every existing workflow does is unchanged: JSON in, JSON out.+ const json = await owner.post(`${BASE}/demo/api/count`, {});+ expect(json.headers.get("content-type")).toContain("application/json");+ expect(await json.json()).toEqual({ count: 1 });+ });++ it("removes the folder and its recorded versions on request", async () => {+ await list();+ expect((await owner.delete(`${BASE}/demo`)).status).toBe(204);+ expect(await list()).toEqual([]);+ await expect(fs.stat(dir)).rejects.toThrow();+ expect((await owner.get(`${BASE}/demo/api/`)).status).toBe(404);+ expect((await owner.delete(`${BASE}/demo`)).status).toBe(404);+ const history = (await (await owner.get(`${BASE}/demo/history`)).json()) as {+ versions: WorkflowVersion[];+ };+ expect(history.versions).toEqual([]);+ });++ it("is scoped to the Project's users", async () => {+ const other = apiClient(t.app, (await provisionUser(t.app, "other")).cookie);+ expect((await other.get(BASE)).status).toBe(404);+ expect((await other.get(`${BASE}/demo/ui/index.html`)).status).toBe(404);+ expect((await other.delete(`${BASE}/demo`)).status).toBe(404);+ expect((await owner.get(`${BASE}/demo/ui/index.html`)).status).toBe(200);+ expect((await owner.get(`${BASE}/nope/ui/index.html`)).status).toBe(404);+ expect((await owner.get(`${BASE}/nope/api/`)).status).toBe(404);+ });+});diff --git a/packages/web/public/workflow-ui.css b/packages/web/public/workflow-ui.cssnew file mode 100644index 00000000..a2c615c6--- /dev/null+++ b/packages/web/public/workflow-ui.css@@ -0,0 +1,261 @@+/**+ * Base stylesheet for a workflow's own page (features/workflows/workflow-tabs.tsx injects it+ * into the frame, and a page may link it itself for standalone viewing).+ *+ * A workflow page is a separate document: Tailwind never sees it, and the app's `html.dark`+ * class and accent variables stop at the frame boundary. So the app copies its RESOLVED+ * tokens — the gray scale, the accent pair, the font stack, the root font size — onto this+ * document's root (lib/workflow-theme.ts), and everything here is expressed in those+ * variables. The literal fallbacks are only for a page opened outside the app; the palette+ * has exactly one source of truth, styles.css.+ *+ * This is a floor, not a framework: it styles the plain HTML an agent writes (headings,+ * lists, forms, tables, code) and gets out of the way. It is injected FIRST in the head, so+ * a page's own rules always win.+ */++:root {+ color-scheme: light;+ --wf-bg: #ffffff;+ --wf-surface: var(--color-gray-50, #f9fafb);+ --wf-fg: var(--color-gray-900, #111827);+ --wf-muted: var(--color-gray-500, #6b7280);+ --wf-border: var(--color-gray-200, #e5e7eb);+ --wf-hover: var(--color-gray-100, #f3f4f6);+ --wf-accent: var(--accent-bg, #111827);+ --wf-accent-fg: var(--accent-fg, #ffffff);+ --wf-radius: 6px;+ --wf-font: var(+ --font-app-sans,+ ui-sans-serif,+ system-ui,+ -apple-system,+ "Segoe UI",+ Roboto,+ "PingFang SC",+ "Microsoft YaHei",+ sans-serif+ );+ --wf-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+}++/* The app stamps `dark` or `light` on the root; `prefers-color-scheme` only decides for a+ page opened on its own, where no class is stamped at all. */+@media (prefers-color-scheme: dark) {+ :root:not(.light) {+ color-scheme: dark;+ --wf-bg: var(--color-gray-950, #000000);+ --wf-surface: var(--color-gray-900, #0d0d0d);+ --wf-fg: var(--color-gray-100, #f3f4f6);+ --wf-muted: var(--color-gray-400, #9ca3af);+ --wf-border: var(--color-gray-700, #303030);+ --wf-hover: var(--color-gray-800, #1f1f1f);+ }+}++:root.dark {+ color-scheme: dark;+ --wf-bg: var(--color-gray-950, #000000);+ --wf-surface: var(--color-gray-900, #0d0d0d);+ --wf-fg: var(--color-gray-100, #f3f4f6);+ --wf-muted: var(--color-gray-400, #9ca3af);+ --wf-border: var(--color-gray-700, #303030);+ --wf-hover: var(--color-gray-800, #1f1f1f);+}++body {+ margin: 0;+ padding: 16px;+ background: var(--wf-bg);+ color: var(--wf-fg);+ font-family: var(--wf-font);+ font-size: 0.875rem;+ line-height: 1.6;+}++h1,+h2,+h3,+h4 {+ margin: 0 0 12px;+ font-weight: 600;+ line-height: 1.3;+ text-wrap: balance;+}+h1 {+ font-size: 1.375rem;+}+h2 {+ font-size: 1.125rem;+}+h3 {+ font-size: 1rem;+}+h4 {+ font-size: 0.9375rem;+}++p {+ margin: 0 0 12px;+}++small,+.wf-muted {+ color: var(--wf-muted);+ font-size: 0.8125rem;+}++a {+ color: var(--wf-accent);+ text-decoration: none;+}+a:hover {+ text-decoration: underline;+}++hr {+ border: 0;+ border-top: 1px solid var(--wf-border);+ margin: 16px 0;+}++ul,+ol {+ margin: 0 0 12px;+ padding-left: 20px;+}+li {+ margin: 4px 0;+}+/* A list used as a row list rather than prose: the page opts in. */+ul.wf-rows {+ list-style: none;+ padding: 0;+ border: 1px solid var(--wf-border);+ border-radius: var(--wf-radius);+}+ul.wf-rows > li {+ margin: 0;+ padding: 8px 12px;+ display: flex;+ align-items: center;+ gap: 8px;+ border-top: 1px solid var(--wf-border);+}+ul.wf-rows > li:first-child {+ border-top: 0;+}++code,+kbd,+samp {+ font-family: var(--wf-mono);+ font-size: 0.8125rem;+}+code {+ background: var(--wf-surface);+ border: 1px solid var(--wf-border);+ border-radius: 4px;+ padding: 1px 4px;+}+pre {+ background: var(--wf-surface);+ border: 1px solid var(--wf-border);+ border-radius: var(--wf-radius);+ padding: 10px 12px;+ overflow-x: auto;+}+pre code {+ background: none;+ border: 0;+ padding: 0;+}++table {+ border-collapse: collapse;+ width: 100%;+ font-variant-numeric: tabular-nums;+}+th,+td {+ border-bottom: 1px solid var(--wf-border);+ padding: 6px 10px;+ text-align: left;+}+th {+ color: var(--wf-muted);+ font-weight: 500;+ font-size: 0.8125rem;+}++input,+select,+textarea {+ font: inherit;+ color: inherit;+ background: var(--wf-bg);+ border: 1px solid var(--wf-border);+ border-radius: var(--wf-radius);+ padding: 5px 8px;+}+input:focus-visible,+select:focus-visible,+textarea:focus-visible,+button:focus-visible {+ outline: 2px solid var(--wf-accent);+ outline-offset: 1px;+}+input[type="checkbox"],+input[type="radio"] {+ accent-color: var(--wf-accent);+ padding: 0;+}++button {+ font: inherit;+ font-weight: 500;+ color: inherit;+ background: var(--wf-bg);+ border: 1px solid var(--wf-border);+ border-radius: var(--wf-radius);+ padding: 5px 10px;+ cursor: pointer;+ transition: background-color 150ms;+}+button:hover:not(:disabled) {+ background: var(--wf-hover);+}+button:disabled {+ opacity: 0.6;+ cursor: not-allowed;+}+button.wf-primary {+ background: var(--wf-accent);+ border-color: var(--wf-accent);+ color: var(--wf-accent-fg);+}+button.wf-primary:hover:not(:disabled) {+ background: var(--wf-accent);+ opacity: 0.9;+}++.wf-card {+ background: var(--wf-surface);+ border: 1px solid var(--wf-border);+ border-radius: var(--wf-radius);+ padding: 12px;+}++.wf-row {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++@media (prefers-reduced-motion: reduce) {+ * {+ transition: none !important;+ animation: none !important;+ }+}diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex f06f73ae..c6c61a21 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -199,6 +199,8 @@ import type {InstalledPluginsResponse,VersionHistoryDiffResponse,VersionHistoryResponse,+ WorkflowInfo,+ WorkflowVersion,VersionRollbackResponse,VersionResponse,WeChatBindingPutRequest,@@ -1819,6 +1821,38 @@ export const getDesktopTray = () => apiFetch<DesktopTrayStatusResponse>("/api/deexport const setDesktopTray = (patch: DesktopTrayPatch) =>apiFetch<void>("/api/desktop/tray", { method: "PUT", body: patch });+// ---- Workflows (an Agent's own extension packages, served as tabs beside the chat) ----+const workflowsBase = (projectId: string, agentId: string) =>+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/workflows`;+export const getWorkflows = (projectId: string, agentId: string) =>+ apiFetch<{ workflows: WorkflowInfo[] }>(workflowsBase(projectId, agentId));+/** Re-import the folder now (the server also does this whenever a file changes). */+export const reloadWorkflow = (projectId: string, agentId: string, workflowId: string) =>+ apiFetch<{ workflow: WorkflowInfo }>(+ `${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}/reload`,+ { method: "POST", body: {} },+ );+export const getWorkflowHistory = (projectId: string, agentId: string, workflowId: string) =>+ apiFetch<{ versions: WorkflowVersion[] }>(+ `${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}/history`,+ );+/** Restore a recorded version's files (state.json is kept) and reload. */+export const rollbackWorkflow = (+ projectId: string,+ agentId: string,+ workflowId: string,+ revision: string,+) =>+ apiFetch<{ workflow: WorkflowInfo }>(+ `${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}/rollback`,+ { method: "POST", body: { revision } },+ );+/** Delete the folder and the versions recorded for it; nothing of the workflow is kept. */+export const removeWorkflow = (projectId: string, agentId: string, workflowId: string) =>+ apiFetch<void>(`${workflowsBase(projectId, agentId)}/${encodeURIComponent(workflowId)}`, {+ method: "DELETE",+ });+// ---- The plugins a Project asks for, and the confinement agent commands run under ----/*** A Project's plugin list. Project-scoped because machines are lent to Projects, so this isdiff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 3e908354..cfdd3253 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -35,6 +35,7 @@ import type {import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";import { S } from "../../lib/strings";+import { useWorkflowTabs, WorkflowFrame, WorkflowTabStrip } from "../workflows/workflow-tabs";import { apiErrorText } from "../../lib/api-error";import { configuredCompactionLimit } from "../../lib/context";import { useDocumentTitle } from "../../lib/use-document-title";@@ -302,6 +303,7 @@ export function ChatPage() {const { currentProject, currentAgent, setCurrentAgentId, reloadAgents, agents } = useProject();const projectId = currentProject?.projectId ?? null;const agentId = currentAgent?.agentId ?? null;+ const workflowTabs = useWorkflowTabs(projectId, agentId);const {sessions,loading: sessionsLoading,@@ -1896,7 +1898,33 @@ export function ChatPage() {return (// data-dock-host: the docks' edge bands, drop preview and the bottom dock's height// ratio all measure this column (dock-drag.tsx / dock-panel.tsx).- <div data-dock-host className="flex h-full flex-col bg-white dark:bg-gray-950">+ <div data-dock-host className="relative flex h-full flex-col bg-white dark:bg-gray-950">+ {/* Workflow tabs: the Agent's own pages beside the chat. A workflow tab covers the+ chat (which stays mounted, so its state survives a look at the page) below the+ strip; the strip is absent when the Agent has no workflow with a UI. */}+ <WorkflowTabStrip+ tabs={workflowTabs.tabs}+ notices={workflowTabs.notices}+ active={workflowTabs.active}+ onSelect={workflowTabs.setActive}+ />+ {workflowTabs.activeTab !== null && projectId !== null && agentId !== null && (+ <div className="absolute inset-x-0 bottom-0 top-9 z-10">+ <WorkflowFrame+ // Per tab: the frame keeps this workflow's history fold, its error and its+ // armed Remove, and none of that belongs to the next tab.+ key={workflowTabs.activeTab.tabId}+ projectId={projectId}+ agentId={agentId}+ tab={workflowTabs.activeTab}+ onChanged={() => void workflowTabs.refresh()}+ onRemoved={() => {+ workflowTabs.setActive(null);+ void workflowTabs.refresh();+ }}+ />+ </div>+ )}{/* Thin top toolbar */}{selected && (<div className="flex shrink-0 items-center gap-2.5 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800">diff --git a/packages/web/src/features/chat/example-tasks.ts b/packages/web/src/features/chat/example-tasks.tsindex 89228ef1..2fdfa42a 100644--- a/packages/web/src/features/chat/example-tasks.ts+++ b/packages/web/src/features/chat/example-tasks.ts@@ -32,7 +32,7 @@ export const EXAMPLE_FOLDERS = [id: "agents",tasks: [{ id: "investmentCopilot", skills: ["penguin-sdk", "web-design"] },- { id: "rag", skills: ["penguin-sdk", "web-design"] },+ { id: "missionControl", skills: ["penguin-sdk", "web-design"] },{ id: "agentBenchmarkBuild", skills: [] },{ id: "agentOptimization", skills: [] },],diff --git a/packages/web/src/features/palette/app-palette.tsx b/packages/web/src/features/palette/app-palette.tsxindex 1baf4807..8782c667 100644--- a/packages/web/src/features/palette/app-palette.tsx+++ b/packages/web/src/features/palette/app-palette.tsx@@ -10,10 +10,15 @@ import { S } from "../../lib/strings";import { HarnessHistoryOverlay } from "../harness/harness-history-overlay";import { CommandPalette } from "./command-palette";-export function AppPalette() {+/**+ * `extra` is what the mount point adds ahead of the standing actions — the full-page+ * workflow route registers its way out here, which is why it exists at all on that route.+ */+export function AppPalette({ extra = [] }: { extra?: readonly PaletteAction[] }) {const [historyOpen, setHistoryOpen] = useState(false);const actions = useMemo<PaletteAction[]>(() => [+ ...extra,{id: "harness-history",label: S.commandPalette.harnessHistory,@@ -21,7 +26,7 @@ export function AppPalette() {run: () => setHistoryOpen(true),},],- [],+ [extra],);return (<>diff --git a/packages/web/src/features/workflows/workflow-app-page.tsx b/packages/web/src/features/workflows/workflow-app-page.tsxnew file mode 100644index 00000000..6e7a0e76--- /dev/null+++ b/packages/web/src/features/workflows/workflow-app-page.tsx@@ -0,0 +1,123 @@+/**+ * One workflow page as the whole app: /app/:projectId/:agentId/:workflowId[/:tabKey] — the+ * tab that key names, or the workflow's first tab without one.+ *+ * No sidebar, no chat, no tab strip — the page fills the window, which is what+ * `penguin web --app …` opens and what a tab's "fill the app" action navigates to. There is+ * deliberately no chrome to leave by: the command palette (Ctrl+P / Ctrl+Shift+P, both, in+ * case the page takes one) carries the way out, "Exit full page", which lands on the chat of+ * that same Agent. The route sits outside the app shell (no ProjectProvider), so the exit+ * remembers the Project and Agent the way the shell does — its localStorage keys — before+ * navigating.+ */+import { useEffect, useMemo, useState } from "react";+import { useNavigate, useParams } from "react-router";+import * as api from "../../api/endpoints";+import type { PaletteAction } from "../../lib/command-palette";+import { S } from "../../lib/strings";+import {+ appPageTab,+ WORKFLOW_UPDATED_EVENT,+ workflowTabsOf,+ type WorkflowTab,+} from "../../lib/workflow-tabs";+import { rememberSelection } from "../../state/project";+import { AppPalette } from "../palette/app-palette";+import { openUserEvents } from "../../api/sse";+import { WorkflowFrame } from "./workflow-tabs";++export function WorkflowAppPage() {+ const params = useParams();+ const projectId = params["projectId"] ?? "";+ const agentId = params["agentId"] ?? "";+ const workflowId = params["workflowId"] ?? "";+ const tabKey = params["tabKey"];+ const navigate = useNavigate();+ const [tab, setTab] = useState<WorkflowTab | null | undefined>(undefined);+ const [failure, setFailure] = useState<string | null>(null);++ useEffect(() => {+ let alive = true;+ const load = async () => {+ try {+ const res = await api.getWorkflows(projectId, agentId);+ if (!alive) return;+ setTab(appPageTab(workflowTabsOf(res.workflows), workflowId, tabKey));+ setFailure(null);+ } catch (err) {+ if (alive) setFailure(err instanceof Error ? err.message : String(err));+ }+ };+ void load();+ const onUpdated = (e: Event) => {+ const d = (e as CustomEvent<{ projectId: string; agentId: string }>).detail;+ if (d.projectId === projectId && d.agentId === agentId) void load();+ };+ window.addEventListener(WORKFLOW_UPDATED_EVENT, onUpdated);+ // This route is outside the app shell, so the provider that usually holds the event+ // stream open (and raises the event above) is not mounted: without a stream of its own,+ // a page shown as the whole app would never notice its workflow being edited or removed.+ const conn = openUserEvents({+ onOmniMessage: () => undefined,+ onServerEvent: (ev) => {+ if (ev.type !== "workflow_updated" && ev.type !== "workflow_removed") return;+ if (ev.projectId === projectId && ev.agentId === agentId) void load();+ },+ });+ return () => {+ alive = false;+ window.removeEventListener(WORKFLOW_UPDATED_EVENT, onUpdated);+ conn.close();+ };+ }, [projectId, agentId, workflowId, tabKey]);++ const exit = useMemo<PaletteAction[]>(+ () => [+ {+ id: "exit-full-page",+ label: S.workflows.exitFullPage,+ keywords: ["exit", "leave", "chat", "full page", "app"],+ run: () => {+ rememberSelection(projectId, agentId);+ void navigate("/chat");+ },+ },+ ],+ [projectId, agentId, navigate],+ );++ return (+ <div className="relative h-full w-full bg-white dark:bg-gray-950">+ {/* A list request that fails after the page is up says so over it, rather than leaving+ a frame that quietly stopped following the workflow. */}+ {tab && failure !== null && (+ <div+ className="absolute inset-x-0 top-0 z-10 bg-amber-50 px-3 py-1 text-center text-xs text-amber-900 dark:bg-amber-950 dark:text-amber-200"+ role="status"+ >+ {failure}+ </div>+ )}+ {tab ? (+ <WorkflowFrame+ projectId={projectId}+ agentId={agentId}+ tab={tab}+ bare+ onChanged={() => undefined}+ onRemoved={() => exit[0]!.run()}+ />+ ) : (+ <div className="flex h-full flex-col items-center justify-center gap-1 px-6 text-center text-sm text-gray-500 dark:text-gray-400">+ <span>+ {tab === undefined && failure === null+ ? S.workflows.loadingPage+ : (failure ?? S.workflows.noSuchPage)}+ </span>+ <span>{S.workflows.exitHint}</span>+ </div>+ )}+ <AppPalette extra={exit} />+ </div>+ );+}diff --git a/packages/web/src/features/workflows/workflow-tabs.tsx b/packages/web/src/features/workflows/workflow-tabs.tsxnew file mode 100644index 00000000..33dc1bb0--- /dev/null+++ b/packages/web/src/features/workflows/workflow-tabs.tsx@@ -0,0 +1,415 @@+/**+ * Workflow tabs beside Chat, and the page a workflow tab shows.+ *+ * The strip lists the Agent's workflows that ship a UI (lib/workflow-tabs.ts); the frame+ * is that UI in an iframe served from the workflow's own `ui/` folder, plus a thin bar+ * with the workflow's version, its load error when the current files do not boot, a+ * reload, and a history fold with one restore button per recorded version. The list+ * refetches when the server announces `workflow_updated` for this Agent, so an Agent+ * editing its own workflow sees the tab update (the iframe keys on `uiRev`).+ */+import { useCallback, useEffect, useRef, useState } from "react";+import { useNavigate } from "react-router";+import type { WorkflowInfo, WorkflowVersion } from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { Button } from "../../components/ui/button";+import { formatDateTime } from "../../lib/format";+import { S } from "../../lib/strings";+import { toneInk, toneStrip } from "../../lib/tone";+import { forwardFrameKeys, readDocumentTheme, themeWorkflowFrame } from "../../lib/workflow-theme";+import {+ FILL_APP_MESSAGE,+ settleActiveTab,+ WORKFLOW_UPDATED_EVENT,+ workflowAppPath,+ workflowNoticesOf,+ workflowTabsOf,+ workflowUiUrl,+ type WorkflowNotice,+ type WorkflowTab,+ type WorkflowUpdatedDetail,+} from "../../lib/workflow-tabs";+import { useLocale } from "../../state/locale";+import { useTheme } from "../../state/theme";+import { localizedText } from "../chat/skill-use";++/** The Agent's workflow tabs, kept fresh by the server's `workflow_updated` events. */+export function useWorkflowTabs(projectId: string | null, agentId: string | null) {+ const [tabs, setTabs] = useState<WorkflowTab[]>([]);+ const [notices, setNotices] = useState<WorkflowNotice[]>([]);+ const [active, setActiveRaw] = useState<string | null>(null);++ // Which Agent the newest request was for. A slow answer for the Agent just left must not+ // land on the one now open: the strip would show its tabs beside another Agent's chat, and+ // a Remove from there would address the wrong Agent's workflow.+ const asked = useRef(0);+ const refresh = useCallback(async () => {+ const mine = ++asked.current;+ if (projectId === null || agentId === null) {+ setTabs([]);+ setNotices([]);+ return;+ }+ try {+ const res = await api.getWorkflows(projectId, agentId);+ if (asked.current !== mine) return;+ setTabs(workflowTabsOf(res.workflows));+ setNotices(workflowNoticesOf(res.workflows));+ } catch {+ // The strip is a convenience over the chat: a failed list leaves it as it was.+ }+ }, [projectId, agentId]);++ useEffect(() => {+ setActiveRaw(null);+ void refresh();+ }, [refresh]);++ useEffect(() => {+ const onUpdated = (e: Event) => {+ const d = (e as CustomEvent<WorkflowUpdatedDetail>).detail;+ if (d.projectId === projectId && d.agentId === agentId) void refresh();+ };+ window.addEventListener(WORKFLOW_UPDATED_EVENT, onUpdated);+ return () => window.removeEventListener(WORKFLOW_UPDATED_EVENT, onUpdated);+ }, [projectId, agentId, refresh]);++ const settled = settleActiveTab(active, tabs);+ // A tab that is gone is forgotten, not merely filtered: kept, the raw id would pull the+ // frame back over the chat the moment a workflow of the same id reappears — which is what+ // an Agent rewriting its folder (delete, then write) looks like from here.+ useEffect(() => {+ if (active !== null && settled === null) setActiveRaw(null);+ }, [active, settled]);+ const activeTab = settled === null ? null : (tabs.find((t) => t.tabId === settled) ?? null);+ return { tabs, notices, active: settled, activeTab, setActive: setActiveRaw, refresh };+}++/** How long a page that never finishes loading stays hidden before it is shown as it is. */+const FRAME_REVEAL_TIMEOUT_MS = 4000;++const TAB_BASE =+ "relative h-9 shrink-0 border-b-2 px-3 text-[13px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400";+const TAB_ACTIVE = "border-[var(--accent-bg)] font-medium text-gray-900 dark:text-gray-100";+const TAB_IDLE =+ "border-transparent text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200";++export function WorkflowTabStrip({+ tabs,+ notices = [],+ active,+ onSelect,+}: {+ tabs: readonly WorkflowTab[];+ /** Workflows with nothing to show but something to say; see workflowNoticesOf. */+ notices?: readonly WorkflowNotice[];+ active: string | null;+ onSelect: (tabId: string | null) => void;+}) {+ const { locale } = useLocale();+ if (tabs.length === 0 && notices.length === 0) return null;+ return (+ <>+ {notices.map((n) => (+ <div+ key={n.workflowId}+ role="status"+ className={`shrink-0 truncate px-3 py-1 text-xs ${+ n.error === null ? toneStrip.muted : toneStrip.attention+ }`}+ title={n.error ?? n.hints.join("\n")}+ >+ <span className="font-mono">{n.workflowId}</span>: {n.error ?? n.hints[0]}+ </div>+ ))}+ {tabs.length > 0 && (+ <div+ role="tablist"+ aria-label={S.workflows.tabsLabel}+ className="flex shrink-0 items-stretch gap-1 overflow-x-auto border-b border-gray-200 px-2 dark:border-gray-800"+ >+ <button+ type="button"+ role="tab"+ aria-selected={active === null}+ className={`${TAB_BASE} ${active === null ? TAB_ACTIVE : TAB_IDLE}`}+ onClick={() => onSelect(null)}+ >+ {S.workflows.chatTab}+ </button>+ {tabs.map((t) => (+ <button+ key={t.tabId}+ type="button"+ role="tab"+ aria-selected={active === t.tabId}+ title={t.error ?? undefined}+ className={`${TAB_BASE} ${active === t.tabId ? TAB_ACTIVE : TAB_IDLE}`}+ onClick={() => onSelect(t.tabId)}+ >+ {localizedText(locale, t.title, t.titleZh)}+ {t.error !== null && (+ <span className={`ml-1.5 ${toneInk.danger}`} aria-label={S.workflows.brokenMark}>+ !+ </span>+ )}+ </button>+ ))}+ </div>+ )}+ </>+ );+}++export function WorkflowFrame({+ projectId,+ agentId,+ tab,+ bare = false,+ onChanged,+ onRemoved,+}: {+ projectId: string;+ agentId: string;+ tab: WorkflowTab;+ /** The page alone, no bar: the full-page route (its palette carries the actions). */+ bare?: boolean;+ /** The workflow was reloaded or restored; the caller refetches the list. */+ onChanged: (workflow: WorkflowInfo) => void;+ /** The workflow and its versions are gone; the caller drops the tab (the list refetch confirms). */+ onRemoved: () => void;+}) {+ const { dark, accent, fontScale } = useTheme();+ const frameRef = useRef<HTMLIFrameElement | null>(null);+ const [busy, setBusy] = useState<"reload" | "rollback" | "remove" | null>(null);+ // Removal is armed by a first click and sent by the second; the arm drops when the tab changes.+ const [removeArmed, setRemoveArmed] = useState(false);+ useEffect(() => setRemoveArmed(false), [tab.workflowId]);+ const [failure, setFailure] = useState<string | null>(null);+ const [historyOpen, setHistoryOpen] = useState(false);+ const [versions, setVersions] = useState<WorkflowVersion[] | null>(null);++ const loadHistory = useCallback(async () => {+ try {+ setVersions((await api.getWorkflowHistory(projectId, agentId, tab.workflowId)).versions);+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ }+ }, [projectId, agentId, tab.workflowId]);++ useEffect(() => {+ if (historyOpen) void loadHistory();+ }, [historyOpen, loadHistory, tab.revision]);++ const reload = async () => {+ setBusy("reload");+ setFailure(null);+ try {+ onChanged((await api.reloadWorkflow(projectId, agentId, tab.workflowId)).workflow);+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(null);+ }+ };++ const rollback = async (revision: string) => {+ setBusy("rollback");+ setFailure(null);+ try {+ onChanged(+ (await api.rollbackWorkflow(projectId, agentId, tab.workflowId, revision)).workflow,+ );+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(null);+ }+ };++ // The page is a separate document: the app's dark class, accent and root font size stop at+ // the frame, so they are copied in (lib/workflow-theme.ts) on load and on every appearance+ // change. Past the commit, because the provider that stamps them on the app's own document+ // is an ancestor and its effect runs after this one's.+ const applyTheme = useCallback(() => {+ themeWorkflowFrame(frameRef.current, readDocumentTheme(document));+ }, []);+ useEffect(() => {+ const id = requestAnimationFrame(applyTheme);+ return () => cancelAnimationFrame(id);+ }, [applyTheme, dark, accent, fontScale, tab.uiRev]);++ // A page is its own document: until it has loaded and been themed it paints the browser's+ // white canvas, and then its own unstyled markup — a white flash in a dark app, on every+ // tab switch and every reload. So the frame stays invisible over the app's own background+ // until the theme is on it, and fades in. The timer is for a page that never fires `load`+ // (a hung subresource): it is shown anyway rather than hidden forever.+ const frameKey = `${tab.tabId}@${tab.uiRev}`;+ const [shownKey, setShownKey] = useState<string | null>(null);+ const detachKeys = useRef<() => void>(() => undefined);+ useEffect(() => () => detachKeys.current(), []);+ const onFrameLoad = useCallback(() => {+ applyTheme();+ // The page's keys reach the app too, so the palette — the only way out of the full-page+ // route — still answers once the reader has clicked into the page.+ detachKeys.current();+ detachKeys.current = forwardFrameKeys(frameRef.current);+ setShownKey(frameKey);+ }, [applyTheme, frameKey]);+ useEffect(() => {+ const id = setTimeout(() => setShownKey(frameKey), FRAME_REVEAL_TIMEOUT_MS);+ return () => clearTimeout(id);+ }, [frameKey]);++ const remove = async () => {+ setBusy("remove");+ setFailure(null);+ try {+ await api.removeWorkflow(projectId, agentId, tab.workflowId);+ onRemoved();+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ setBusy(null);+ setRemoveArmed(false);+ }+ };++ // Filling the app: the bar's button, or the page asking for it itself+ // (`parent.postMessage({ type: "penguin:fill-app" }, "*")`) — only from our own frame.+ const navigate = useNavigate();+ const fillApp = useCallback(+ () => void navigate(workflowAppPath(projectId, agentId, tab.workflowId, tab.key)),+ [navigate, projectId, agentId, tab.workflowId, tab.key],+ );+ useEffect(() => {+ if (bare) return;+ const onMessage = (e: MessageEvent) => {+ if (e.source !== frameRef.current?.contentWindow) return;+ if ((e.data as { type?: unknown } | null)?.type === FILL_APP_MESSAGE) fillApp();+ };+ window.addEventListener("message", onMessage);+ return () => window.removeEventListener("message", onMessage);+ }, [bare, fillApp]);++ const historyId = `workflow-history-${tab.workflowId}`;+ return (+ <div className="flex h-full min-h-0 flex-col bg-white dark:bg-gray-950">+ <div+ hidden={bare}+ className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1 border-b border-gray-200 px-3 py-1.5 text-xs text-gray-500 dark:border-gray-800 dark:text-gray-400"+ >+ <span className="font-medium text-gray-800 dark:text-gray-200">{tab.name}</span>+ {tab.version !== null && <span>v{tab.version}</span>}+ <span className="font-mono">{tab.revision}</span>+ <span className="flex-1" />+ <Button variant="secondary" size="sm" title={S.workflows.fillAppHint} onClick={fillApp}>+ {S.workflows.fillApp}+ </Button>+ <Button+ variant="secondary"+ size="sm"+ disabled={busy !== null}+ onClick={() => void reload()}+ >+ {busy === "reload" ? S.workflows.reloading : S.workflows.reload}+ </Button>+ <Button+ variant="secondary"+ size="sm"+ aria-expanded={historyOpen}+ aria-controls={historyId}+ onClick={() => setHistoryOpen((v) => !v)}+ >+ {S.workflows.history}+ </Button>+ {removeArmed ? (+ <>+ <span className={toneInk.danger}>{S.workflows.removeConfirm}</span>+ <Button+ variant="danger"+ size="sm"+ disabled={busy !== null}+ onClick={() => void remove()}+ >+ {busy === "remove" ? S.workflows.removing : S.workflows.removeYes}+ </Button>+ <Button+ variant="secondary"+ size="sm"+ disabled={busy !== null}+ onClick={() => setRemoveArmed(false)}+ >+ {S.workflows.removeNo}+ </Button>+ </>+ ) : (+ <Button+ variant="secondary"+ size="sm"+ disabled={busy !== null}+ onClick={() => setRemoveArmed(true)}+ >+ {S.workflows.remove}+ </Button>+ )}+ </div>+ {tab.error !== null && !bare && (+ <div className={`shrink-0 px-3 py-1.5 text-xs ${toneStrip.danger}`}>+ {S.workflows.loadError}: {tab.error}+ </div>+ )}+ {failure !== null && (+ <div className={`shrink-0 px-3 py-1.5 text-xs ${toneStrip.danger}`}>{failure}</div>+ )}+ <div+ id={historyId}+ hidden={!historyOpen || bare}+ className="max-h-64 shrink-0 overflow-y-auto border-b border-gray-200 dark:border-gray-800"+ >+ {versions === null ? (+ <p className="px-3 py-2 text-xs text-gray-500">{S.workflows.loadingHistory}</p>+ ) : versions.length === 0 ? (+ <p className="px-3 py-2 text-xs text-gray-500">{S.workflows.noHistory}</p>+ ) : (+ <ul className="divide-y divide-gray-100 dark:divide-gray-800">+ {versions.map((v) => {+ const current = v.revision === tab.revision;+ return (+ <li key={v.revision} className="flex items-center gap-3 px-3 py-1.5 text-xs">+ <span className="font-mono">{v.revision}</span>+ <span className="text-gray-500">{formatDateTime(v.savedAt)}</span>+ {v.version !== null && <span className="text-gray-500">v{v.version}</span>}+ <span className="text-gray-400">{S.workflows.fileCount(v.files.length)}</span>+ <span className="flex-1" />+ {current ? (+ <span className={toneInk.success}>{S.workflows.current}</span>+ ) : (+ <Button+ variant="secondary"+ size="sm"+ disabled={busy !== null}+ onClick={() => void rollback(v.revision)}+ >+ {S.workflows.restore}+ </Button>+ )}+ </li>+ );+ })}+ </ul>+ )}+ </div>+ <iframe+ key={frameKey}+ ref={frameRef}+ onLoad={onFrameLoad}+ title={tab.title}+ src={workflowUiUrl(tab)}+ className={`min-h-0 flex-1 border-0 transition-opacity duration-150 motion-reduce:transition-none ${+ shownKey === frameKey ? "opacity-100" : "opacity-0"+ }`}+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"+ />+ </div>+ );+}diff --git a/packages/web/src/lib/command-palette.ts b/packages/web/src/lib/command-palette.tsindex 00c0ec7b..3e550546 100644--- a/packages/web/src/lib/command-palette.ts+++ b/packages/web/src/lib/command-palette.ts@@ -10,13 +10,15 @@ export type ShortcutKeyEvent = Pick<>;/**- * Ctrl+P on Windows/Linux, Cmd+P on macOS — the platform is a parameter (read once at- * the call site) so the matcher stays a pure function. Shift and Alt must be up: Ctrl+Shift+P- * belongs to the browser's own tooling, and a chord with Alt is never ours.+ * Ctrl+P and Ctrl+Shift+P on Windows/Linux, Cmd+P and Cmd+Shift+P on macOS — the platform+ * is a parameter (read once at the call site) so the matcher stays a pure function. Shift is+ * accepted because a workflow page that fills the app may itself take Ctrl+P (print, its+ * own shortcut); the palette is that page's only way out, so it has to answer both chords.+ * A chord with Alt is never ours.*/export function isCommandPaletteShortcut(e: ShortcutKeyEvent, isMac: boolean): boolean {if (e.key !== "p" && e.key !== "P") return false;- if (e.altKey || e.shiftKey) return false;+ if (e.altKey) return false;return isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 250722ac..8b0fd906 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -270,9 +270,36 @@ export const en: Strings = {title: "Command Palette",placeholder: "Type to filter commands…",noResults: "No matching commands",- hint: "Ctrl+P / ⌘P to toggle · ↑↓ to select · Enter to run",+ hint: "Ctrl+P / Ctrl+Shift+P (⌘P) to toggle · ↑↓ to select · Enter to run",harnessHistory: "Harness history",},+ workflows: {+ tabsLabel: "Chat and workflows",+ chatTab: "Chat",+ brokenMark: "The current files failed to load",+ reload: "Reload",+ reloading: "Reloading…",+ history: "History",+ loadError: "Load error",+ loadingHistory: "Loading history…",+ /** The full-page route while it is still finding out which page it should show. */+ loadingPage: "Opening the page…",+ noHistory: "No versions recorded yet.",+ current: "current",+ restore: "Restore",+ remove: "Remove",+ fillApp: "Fill the app",+ fillAppHint:+ "Show this page as the whole app; Ctrl+P / Ctrl+Shift+P opens the command palette to leave",+ exitFullPage: "Exit full page (back to chat)",+ exitHint: "Press Ctrl+P or Ctrl+Shift+P for the command palette to get back to the chat.",+ noSuchPage: "This workflow does not exist or has no page.",+ removeConfirm: "Delete this workflow and all its recorded versions?",+ removeYes: "Remove",+ removing: "Removing…",+ removeNo: "Keep",+ fileCount: (n: number) => `${n} files`,+ },harnessHistory: {title: "Harness history",pageDesc:@@ -2096,18 +2123,16 @@ When done, open index.html in a browser and self-test once.`,'stock for me": resolve a company name to its ticker itself, and when there is no match ' +"or the company is not listed, say so rather than inventing a quote.",},- rag: {- label: "Build a Claude Code docs RAG agent",- desc: "Collect the claude-code-docs repo into a conversational RAG knowledge app with source citations",+ missionControl: {+ label: "Build a custom workflow UI: mission control",+ desc: "A workflow tab beside the chat: dispatch a task to several agents at once and watch every Session's live status",prompt:- "Collect the docs from https://github.com/ericbuess/claude-code-docs and build a RAG knowledge app: " +- "clone the repo and prepare the corpus, then build a retrieval index; " +- "the app acts as a Claude Code configuration expert, answering Claude Code questions " +- "with retrieval-augmented replies and clickable citations that reveal the matched " +- "original text chunk and link to the real documents; " +- "give it a beautiful web chat UI following the web-design skill. " +- "When done, run the app and self-test one Chinese question and one English question, confirming both retrieve " +- "the right English documents and stream their answers, then tell me how to access it.",+ "Build yourself a workflow: a mission-control tab beside this chat. I type a task and pick " ++ "one or more of this Project's Agents; it opens a Session for each and runs them in " ++ "parallel. Every run is a card with a live, animated status (queued, running, done) and " ++ "its elapsed time, and the board survives a reload. Add a second tab with the numbers — " ++ "runs per Agent, average duration — and a button that fills the whole app, like a wall " ++ "display. Take every colour from the theme variables so it looks right in light and dark.",},agentBenchmarkBuild: {label: "Build a general-purpose decision agent and its benchmark",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 0d04b6f6..e9243007 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -285,9 +285,35 @@ export const zh = {title: "命令面板",placeholder: "输入以筛选命令…",noResults: "没有匹配的命令",- hint: "Ctrl+P / ⌘P 切换 · ↑↓ 选择 · Enter 执行",+ hint: "Ctrl+P / Ctrl+Shift+P(⌘P)切换 · ↑↓ 选择 · Enter 执行",harnessHistory: "Harness 历史",},+ workflows: {+ tabsLabel: "聊天与工作流",+ chatTab: "聊天",+ brokenMark: "当前文件加载失败",+ reload: "重新加载",+ reloading: "加载中…",+ history: "历史",+ loadError: "加载失败",+ loadingHistory: "加载历史…",+ /** The full-page route while it is still finding out which page it should show. */+ loadingPage: "正在打开页面…",+ noHistory: "还没有记录过版本。",+ current: "当前",+ restore: "恢复",+ remove: "移除",+ fillApp: "占满应用",+ fillAppHint: "让这个页面占满整个应用;Ctrl+P / Ctrl+Shift+P 打开命令面板可退出",+ exitFullPage: "退出全页模式(回到聊天)",+ exitHint: "按 Ctrl+P 或 Ctrl+Shift+P 打开命令面板可回到聊天。",+ noSuchPage: "这个 workflow 不存在或没有页面。",+ removeConfirm: "删除这个工作流及其全部已记录版本?",+ removeYes: "确认移除",+ removing: "移除中…",+ removeNo: "取消",+ fileCount: (n: number) => `${n} 个文件`,+ },harnessHistory: {title: "Harness 历史",pageDesc:@@ -2093,17 +2119,14 @@ Penguin 视觉风格(见 web-design 技能),默认深色。手机端侧边"只做分析不是投资建议。它的查股工具要能答「帮我查一下智谱的股票」这类问题:" +"按公司名(中文也行)自己对应到股票代码,查不到或没上市就直说,不要编。",},- rag: {- label: "构建 Claude Code 文档 RAG 智能体",- desc: "收集 claude-code-docs 仓库,生成可对话、带来源引用的 RAG 知识应用",+ missionControl: {+ label: "搭建自定义工作流界面:Agent 指挥台",+ desc: "聊天旁的 Workflow 标签页:把一个任务同时派给多个 Agent,实时看每个 Session 的状态",prompt:- "收集 https://github.com/ericbuess/claude-code-docs 的文档,构建一个 RAG 知识应用:" +- "克隆仓库并整理语料,建立检索索引;应用化身 Claude Code 配置专家," +- "检索增强回答 Claude Code 相关问题并标注可点击的来源引用——" +- "引用要能展示命中的原文片段,并链接到真实文档;" +- "按 web-design 技能提供美观的 Web 聊天界面。" +- "完成后运行应用,用一个中文问题和一个英文问题各自测一次," +- "确认两者都检索到了正确的英文文档、流式回答正常,并告诉我访问方式。",+ "给你自己做一个 Workflow:聊天旁边的一张「指挥台」标签页。我输入一个任务、勾选本 Project 里的一个或多个 Agent," ++ "它就为每个 Agent 开一个 Session 并行跑起来。每次运行是一张卡片,带实时的动态状态(排队、运行中、完成)和耗时," ++ "刷新页面后看板仍在。再加第二张标签页放统计——各 Agent 的运行次数与平均耗时——以及一个占满整个应用的按钮,当作大屏来用。" ++ "颜色一律取自主题变量,明暗两种主题下都要好看。",},agentBenchmarkBuild: {label: "构建通用决策智能体和评测基准",diff --git a/packages/web/src/lib/workflow-tabs.ts b/packages/web/src/lib/workflow-tabs.tsnew file mode 100644index 00000000..220e7164--- /dev/null+++ b/packages/web/src/lib/workflow-tabs.ts@@ -0,0 +1,138 @@+/**+ * The tab strip's view of an Agent's workflows.+ *+ * A tab is a CONTRIBUTION: a workflow's manifest puts an entry into `WebModule.sessionTabs`+ * for each page it wants beside the chat — several, or none for a handler-only workflow —+ * and the server hands them over with each page's URL resolved. `uiRev`, the content hash+ * of the workflow's `ui/` tree, is only the cache key an open tab compares to notice its+ * page changed under it (the iframe reloads on a new one). A tab whose renderer this build+ * does not carry is left out: there is nothing to draw it with.+ *+ * Chat is not one of these. It is always present and always reachable, so a workflow tab+ * disappearing (folder removed, Agent switched) falls back to Chat rather than leaving+ * the strip pointing at nothing.+ */+import type { WorkflowInfo } from "@prismshadow/penguin-server/api";++export interface WorkflowTab {+ /** `<workflowId>/<key>`: what the strip selects by. */+ tabId: string;+ workflowId: string;+ /** The contribution's key, unique within its workflow; the fourth segment of the full-page route. */+ key: string;+ title: string;+ titleZh?: string;+ /** Where the page is served from. */+ src: string;+ /** The workflow's package name, for the frame's bar. */+ name: string;+ version: string | null;+ revision: string;+ /** The cache key of the page: the `ui/` revision (the folder's when there is no `ui/`). */+ uiRev: string;+ /** The load error of the CURRENT files; the tab still shows the last good UI. */+ error: string | null;+}++/**+ * Dispatched on `window` when the server says a workflow of some Agent was (re)loaded or+ * removed. The detail names the Agent only: the listener refetches the list, which is the+ * one shape that covers both.+ */+export const WORKFLOW_UPDATED_EVENT = "penguin:workflow-updated";++export interface WorkflowUpdatedDetail {+ projectId: string;+ agentId: string;+}++export function workflowsBase(projectId: string, agentId: string): string {+ return `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/workflows`;+}++/** A tab's page, keyed on the UI revision so a changed page is a new URL. */+export function workflowUiUrl(tab: Pick<WorkflowTab, "src" | "uiRev">): string {+ return `${tab.src}${tab.src.includes("?") ? "&" : "?"}rev=${tab.uiRev}`;+}++/**+ * A workflow the reader would otherwise never hear about: it contributes no tab, so nothing+ * of it can appear in the strip, and yet the server has something to say about it — the load+ * failed, or it loaded and the harness noticed the pages go nowhere (`hints`). A workflow+ * that HAS tabs carries its error on them instead, on the tab itself.+ *+ * The author is an Agent and reads `.build/status.json`, but the person watching the chat+ * page has only this.+ */+export interface WorkflowNotice {+ workflowId: string;+ error: string | null;+ hints: readonly string[];+}++export function workflowNoticesOf(workflows: readonly WorkflowInfo[]): WorkflowNotice[] {+ return workflows+ .filter((w) => w.tabs.length === 0 && (w.error !== null || (w.hints ?? []).length > 0))+ .map((w) => ({ workflowId: w.id, error: w.error, hints: w.hints ?? [] }));+}++export function workflowTabsOf(workflows: readonly WorkflowInfo[]): WorkflowTab[] {+ return workflows.flatMap((w) =>+ w.tabs.flatMap((tab) =>+ "iframe" in tab.renderer+ ? [+ {+ tabId: `${w.id}/${tab.key}`,+ workflowId: w.id,+ key: tab.key,+ title: tab.title,+ ...(tab.titleZh === undefined ? {} : { titleZh: tab.titleZh }),+ src: tab.renderer.iframe.src,+ name: w.name,+ version: w.version,+ revision: w.revision,+ uiRev: w.uiRev ?? w.revision,+ error: w.error,+ },+ ]+ : [],+ ),+ );+}++/** Which tab to show after the list changed: the active one if it still exists, else Chat. */+export function settleActiveTab(+ active: string | null,+ tabs: readonly WorkflowTab[],+): string | null {+ return active !== null && tabs.some((t) => t.tabId === active) ? active : null;+}++/**+ * The route that shows one workflow page as the whole app (no sidebar, no chat, no tab+ * strip): what `penguin web --app <project>/<agent>/<workflow>[/<tab>]` opens, and what a+ * tab's "fill the app" action navigates to. Without a tab key the workflow's first tab is+ * shown. The palette (Ctrl+P / Ctrl+Shift+P) is the way out.+ */+export function workflowAppPath(+ projectId: string,+ agentId: string,+ workflowId: string,+ tabKey?: string,+): string {+ const segments = [projectId, agentId, workflowId, ...(tabKey === undefined ? [] : [tabKey])];+ return `/app/${segments.map(encodeURIComponent).join("/")}`;+}++/** The tab a full-page route names: that key, or the workflow's first tab when it names none. */+export function appPageTab(+ tabs: readonly WorkflowTab[],+ workflowId: string,+ tabKey: string | undefined,+): WorkflowTab | null {+ const own = tabs.filter((t) => t.workflowId === workflowId);+ return (tabKey === undefined ? own[0] : own.find((t) => t.key === tabKey)) ?? null;+}++/** A page's own request to fill the app, posted to its parent: `{ type: "penguin:fill-app" }`. */+export const FILL_APP_MESSAGE = "penguin:fill-app";diff --git a/packages/web/src/lib/workflow-theme.ts b/packages/web/src/lib/workflow-theme.tsnew file mode 100644index 00000000..fa1af988--- /dev/null+++ b/packages/web/src/lib/workflow-theme.ts@@ -0,0 +1,153 @@+/**+ * Carrying the app's appearance into a workflow's page.+ *+ * The page is a separate document in a same-origin frame, so `html.dark`, the accent+ * variables and the root font size the app applies to ITS document reach nothing there.+ * Rather than recompute the palette (two copies of one fact), the app copies the values it+ * has already resolved onto the frame's root, and public/workflow-ui.css — injected first+ * in the frame's head, so the page's own rules still win — is written entirely in terms of+ * them. A page that hardcodes its colours keeps them; a page that writes plain HTML, or+ * uses the `--wf-*` tokens, follows the app into dark mode and through an accent change.+ */++/** Where the base stylesheet is served from (packages/web/public). */+export const WORKFLOW_THEME_HREF = "/workflow-ui.css";++/**+ * Custom properties copied from the app's root to the frame's. The gray scale is Tailwind's+ * (`@theme` in styles.css, with the dark overrides), the accent pair and font stack are the+ * app's own; every one is read RESOLVED, so light/dark and the chosen accent are already+ * applied and the frame needs none of that logic.+ */+export const WORKFLOW_THEME_VARS = [+ "--font-app-sans",+ "--accent-bg",+ "--accent-fg",+ "--color-gray-50",+ "--color-gray-100",+ "--color-gray-200",+ "--color-gray-300",+ "--color-gray-400",+ "--color-gray-500",+ "--color-gray-600",+ "--color-gray-700",+ "--color-gray-800",+ "--color-gray-900",+ "--color-gray-950",+] as const;++export interface WorkflowTheme {+ dark: boolean;+ /** Root font size the app resolved from the font-size setting (e.g. "16px"). */+ fontSize: string;+ /** Resolved custom properties, by name. */+ vars: Record<string, string>;+}++interface AppRoot {+ classList: { contains(token: string): boolean };+ style: { fontSize: string };+}++/**+ * The appearance the app has applied to its own document — read, not recomputed, so a new+ * accent or a changed gray needs no second definition here.+ */+export function readAppTheme(root: AppRoot, computed: (property: string) => string): WorkflowTheme {+ const vars: Record<string, string> = {};+ for (const name of WORKFLOW_THEME_VARS) {+ const value = computed(name).trim();+ if (value !== "") vars[name] = value;+ }+ return { dark: root.classList.contains("dark"), fontSize: root.style.fontSize, vars };+}++/** Reads the theme of the document the app itself renders in. */+export function readDocumentTheme(doc: Document): WorkflowTheme {+ const root = doc.documentElement;+ const style = doc.defaultView?.getComputedStyle(root);+ return readAppTheme(root, (property) => style?.getPropertyValue(property) ?? "");+}++/**+ * Applies a theme to a workflow page's document. Safe to call on every load and on every+ * appearance change: the stylesheet link is created once, and the class stamp is explicit in+ * both directions so the app's choice beats the viewer's system preference.+ */+export function applyWorkflowTheme(doc: Document, theme: WorkflowTheme): void {+ const root = doc.documentElement;+ if (!root) return;+ root.classList.toggle("dark", theme.dark);+ root.classList.toggle("light", !theme.dark);+ root.style.fontSize = theme.fontSize;+ for (const [name, value] of Object.entries(theme.vars)) root.style.setProperty(name, value);+ const head = doc.head;+ if (head && head.querySelector(`link[href="${WORKFLOW_THEME_HREF}"]`) === null) {+ const link = doc.createElement("link");+ link.rel = "stylesheet";+ link.href = WORKFLOW_THEME_HREF;+ head.prepend(link);+ }+}++/**+ * Themes a frame's document, if it is reachable. A cross-origin document (never the case for+ * a workflow, which the server serves same-origin) or a frame that has not finished loading+ * simply gets nothing.+ */+export function themeWorkflowFrame(frame: HTMLIFrameElement | null, theme: WorkflowTheme): void {+ try {+ const doc = frame?.contentDocument;+ if (doc && doc.readyState !== "loading") applyWorkflowTheme(doc, theme);+ } catch {+ // Not our document to style.+ }+}++/**+ * Sends the frame's own keyboard shortcuts on to the app.+ *+ * A page is a separate document, so a key pressed inside it never reaches the app's own+ * `window` — which is where the command palette listens. On the full-page route the palette+ * is the only way out, so it would stop working the moment the reader clicked into the page.+ * The frame is same-origin (that is what lets the theme be written into it), so the same+ * listener can be attached to its document and the event re-raised on the app's window.+ *+ * Returns a function that detaches it, and does nothing at all for a frame of another origin.+ */+export function forwardFrameKeys(+ frame: HTMLIFrameElement | null,+ host: Window = window,+): () => void {+ let doc: Document | null = null;+ const onKey = (e: KeyboardEvent) => {+ // Re-raised rather than handled here: whatever the app listens for decides, and a page+ // that has already acted on the key (preventDefault) is left alone.+ if (e.defaultPrevented) return;+ const copy = new KeyboardEvent(e.type, {+ key: e.key,+ code: e.code,+ ctrlKey: e.ctrlKey,+ metaKey: e.metaKey,+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ bubbles: true,+ cancelable: true,+ });+ const ran = host.dispatchEvent(copy);+ if (!ran) e.preventDefault();+ };+ try {+ doc = frame?.contentDocument ?? null;+ doc?.addEventListener("keydown", onKey);+ } catch {+ doc = null; // Not our document to listen to.+ }+ return () => {+ try {+ doc?.removeEventListener("keydown", onKey);+ } catch {+ // The frame is gone; nothing to detach.+ }+ };+}diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex d009034d..9d451a1b 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -29,6 +29,7 @@ import { FinancePage } from "./features/company/finance-page";import { ChannelView } from "./features/company/channel-view";import { HandbookPage } from "./features/company/handbook-page";import { MachinesPage } from "./features/machines/machines-page";+import { WorkflowAppPage } from "./features/workflows/workflow-app-page";import { PAGES } from "./lib/pages";import type { PageEntry } from "./lib/pages";@@ -107,6 +108,22 @@ export function AppRouter() {</RequireAuthBare>}/>+ {/* One workflow's page as the whole app: outside the shell, like the terminal; the+ command palette it mounts is the way back. */}+ {[+ "/app/:projectId/:agentId/:workflowId",+ "/app/:projectId/:agentId/:workflowId/:tabKey",+ ].map((appPath) => (+ <Route+ key={appPath}+ path={appPath}+ element={+ <RequireAuthBare>+ <WorkflowAppPage />+ </RequireAuthBare>+ }+ />+ ))}<Route element={<RequireAuth />}><Route index element={<Navigate to="/chat" replace />} />{/* Every page is a module.json entry (lib/pages.ts). Admin-only ones are refuseddiff --git a/packages/web/src/state/project.tsx b/packages/web/src/state/project.tsxindex 82357bb6..adb96463 100644--- a/packages/web/src/state/project.tsx+++ b/packages/web/src/state/project.tsx@@ -19,6 +19,15 @@ import * as api from "../api/endpoints";const PROJECT_KEY = "penguin.lastProjectId";const agentKey = (projectId: string) => `penguin.lastAgentId.${projectId}`;+/**+ * Remembers a Project and Agent the way the store does, for a surface that sits outside the+ * ProjectProvider (the full-page workflow route) and wants the shell to open on them next.+ */+export function rememberSelection(projectId: string, agentId: string): void {+ localStorage.setItem(PROJECT_KEY, projectId);+ localStorage.setItem(agentKey(projectId), agentId);+}+interface ProjectContextValue {projects: ProjectSummary[];projectsLoading: boolean;diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex 59909554..6a16369b 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -47,6 +47,7 @@ import { createStore } from "zustand/vanilla";import * as api from "../api/endpoints";import { openUserEvents } from "../api/sse";import { isCompanyEvent, publishCompanyEvent, publishCompanyResync } from "./company";+import { WORKFLOW_UPDATED_EVENT } from "../lib/workflow-tabs";import {FOLDER_CATEGORIES,SIDEBAR_PAGE_SIZE,@@ -733,6 +734,16 @@ export function applyUserEvent(}return;}+ // A workflow of some Agent was (re)loaded: the chat page's tab strip owns that list and+ // listens on window (it is mounted per page, this provider per app).+ if (ev.type === "workflow_updated" || ev.type === "workflow_removed") {+ window.dispatchEvent(+ new CustomEvent(WORKFLOW_UPDATED_EVENT, {+ detail: { projectId: ev.projectId, agentId: ev.agentId },+ }),+ );+ return;+ }// A scheduled task firing may have created a new Session (new-session mode); reload the list// so it appears immediately. schedule_queued doesn't change the list (the target Session// already exists), so it is ignored, as is every other Session-scoped event.diff --git a/packages/web/test/command-palette.test.ts b/packages/web/test/command-palette.test.tsindex 201e9559..8bee8f77 100644--- a/packages/web/test/command-palette.test.ts+++ b/packages/web/test/command-palette.test.ts@@ -20,10 +20,9 @@ describe("command palette shortcut", () => {expect(isCommandPaletteShortcut(key("p", { metaKey: true }), false)).toBe(false);expect(isCommandPaletteShortcut(key("p", { metaKey: true }), true)).toBe(true);expect(isCommandPaletteShortcut(key("p", { ctrlKey: true }), true)).toBe(false);- // The browser's own chords stay the browser's.- expect(isCommandPaletteShortcut(key("P", { ctrlKey: true, shiftKey: true }), false)).toBe(- false,- );+ // Ctrl+Shift+P too: a page filling the app may own Ctrl+P, and the palette is its way out.+ expect(isCommandPaletteShortcut(key("P", { ctrlKey: true, shiftKey: true }), false)).toBe(true);+ expect(isCommandPaletteShortcut(key("P", { metaKey: true, shiftKey: true }), true)).toBe(true);expect(isCommandPaletteShortcut(key("p", { ctrlKey: true, altKey: true }), false)).toBe(false);expect(isCommandPaletteShortcut(key("o", { ctrlKey: true }), false)).toBe(false);});diff --git a/packages/web/test/workflow-tabs.test.ts b/packages/web/test/workflow-tabs.test.tsnew file mode 100644index 00000000..42cf211e--- /dev/null+++ b/packages/web/test/workflow-tabs.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from "vitest";+import type { WorkflowInfo } from "@prismshadow/penguin-server/api";+import {+ appPageTab,+ settleActiveTab,+ workflowAppPath,+ workflowNoticesOf,+ workflowTabsOf,+ workflowUiUrl,+} from "../src/lib/workflow-tabs";++const UI = "/api/projects/p/agents/a/workflows/demo/ui";+const tab = (key: string, file: string) => ({+ id: `demo.${key}`,+ key,+ title: key,+ renderer: { iframe: { src: `${UI}/${file}` } },+});++const info = (over: Partial<WorkflowInfo>): WorkflowInfo => ({+ id: "demo",+ name: "Demo",+ version: "1.0.0",+ revision: "abcdef012345",+ uiRev: "0123456789ab",+ tabs: [tab("board", "index.html")],+ loadedAt: "2026-08-30T00:00:00Z",+ error: null,+ hints: [],+ ...over,+});++describe("workflow tabs", () => {+ it("shows one tab per contribution, keeping the workflow's load error", () => {+ const tabs = workflowTabsOf([+ info({+ tabs: [tab("board", "index.html"), { ...tab("stats", "stats.html"), titleZh: "统计" }],+ }),+ info({ id: "headless", tabs: [] }),+ info({ id: "broken", error: "module tree rejected" }),+ info({+ id: "other",+ tabs: [{ id: "other.x", key: "x", title: "X", renderer: { builtin: "nope" } }],+ }),+ ]);+ expect(tabs.map((t) => t.tabId)).toEqual(["demo/board", "demo/stats", "broken/board"]);+ expect(tabs[1]).toMatchObject({ key: "stats", titleZh: "统计", src: `${UI}/stats.html` });+ expect(tabs[2]!.error).toBe("module tree rejected");+ });++ it("falls back to Chat when the active tab is gone", () => {+ const tabs = workflowTabsOf([info({})]);+ expect(settleActiveTab("demo/board", tabs)).toBe("demo/board");+ expect(settleActiveTab("demo/gone", tabs)).toBeNull();+ expect(settleActiveTab(null, tabs)).toBeNull();+ });++ it("keys the page URL on the UI revision so a changed UI reloads", () => {+ expect(workflowUiUrl({ src: `${UI}/index.html`, uiRev: "0123456789ab" })).toBe(+ `${UI}/index.html?rev=0123456789ab`,+ );+ });++ it("names a full page by workflow and, optionally, tab", () => {+ expect(workflowAppPath("p 1", "a", "demo")).toBe("/app/p%201/a/demo");+ expect(workflowAppPath("p 1", "a", "demo", "stats")).toBe("/app/p%201/a/demo/stats");+ const tabs = workflowTabsOf([+ info({ tabs: [tab("board", "index.html"), tab("stats", "stats.html")] }),+ ]);+ expect(appPageTab(tabs, "demo", undefined)?.key).toBe("board");+ expect(appPageTab(tabs, "demo", "stats")?.key).toBe("stats");+ expect(appPageTab(tabs, "demo", "nope")).toBeNull();+ expect(appPageTab(tabs, "gone", undefined)).toBeNull();+ });+});++describe("workflows with nothing to show", () => {+ it("surfaces a workflow that contributes no tab but has an error or a hint", () => {+ // A workflow whose FIRST load fails has no tabs at all, so without this the reader sees+ // nothing anywhere in the app — no tab, no mark, no message.+ const broken = info({ id: "broken", tabs: [], error: "index.ts(3,1): TS1005" });+ const hinted = info({ id: "hinted", tabs: [], hints: ["ui/index.html is shown by no tab"] });+ expect(workflowNoticesOf([broken, hinted, info({})])).toEqual([+ { workflowId: "broken", error: "index.ts(3,1): TS1005", hints: [] },+ { workflowId: "hinted", error: null, hints: ["ui/index.html is shown by no tab"] },+ ]);+ });++ it("says nothing about a workflow that is fine, or one whose tabs can carry its error", () => {+ expect(workflowNoticesOf([info({})])).toEqual([]);+ expect(workflowNoticesOf([info({ error: "broken" })])).toEqual([]);+ expect(workflowNoticesOf([info({ tabs: [] })])).toEqual([]);+ });+});diff --git a/packages/web/test/workflow-theme.test.ts b/packages/web/test/workflow-theme.test.tsnew file mode 100644index 00000000..51417eba--- /dev/null+++ b/packages/web/test/workflow-theme.test.ts@@ -0,0 +1,75 @@+/**+ * Carrying the app's appearance into a workflow's page: what is read from the app's own+ * document, and what is stamped on the frame's.+ */+import { describe, expect, it } from "vitest";+import {+ applyWorkflowTheme,+ readAppTheme,+ WORKFLOW_THEME_HREF,+ type WorkflowTheme,+} from "../src/lib/workflow-theme";++const appRoot = (classes: string[], fontSize: string) => ({+ classList: { contains: (t: string) => classes.includes(t) },+ style: { fontSize },+});++describe("workflow theme", () => {+ it("reads the resolved appearance rather than recomputing it", () => {+ const values: Record<string, string> = {+ "--accent-bg": " #2563eb ",+ "--color-gray-950": "#000",+ "--color-gray-100": "",+ };+ const theme = readAppTheme(appRoot(["dark"], "16px"), (p) => values[p] ?? "");+ expect(theme.dark).toBe(true);+ expect(theme.fontSize).toBe("16px");+ // Trimmed, and a property the app does not define is not stamped as an empty value.+ expect(theme.vars).toEqual({ "--accent-bg": "#2563eb", "--color-gray-950": "#000" });+ });++ it("stamps light explicitly, so the app's choice beats the system preference", () => {+ expect(readAppTheme(appRoot([], "14px"), () => "").dark).toBe(false);+ });++ it("applies classes, variables and the stylesheet exactly once", () => {+ const doc = fakeDocument();+ const theme: WorkflowTheme = {+ dark: true,+ fontSize: "16px",+ vars: { "--accent-bg": "#2563eb" },+ };+ applyWorkflowTheme(doc.document, theme);+ applyWorkflowTheme(doc.document, theme);+ expect(doc.classes).toEqual({ dark: true, light: false });+ expect(doc.properties).toEqual({ "--accent-bg": "#2563eb" });+ expect(doc.root.style.fontSize).toBe("16px");+ expect(doc.links).toEqual([{ rel: "stylesheet", href: WORKFLOW_THEME_HREF }]);++ applyWorkflowTheme(doc.document, { ...theme, dark: false });+ expect(doc.classes).toEqual({ dark: false, light: true });+ expect(doc.links).toHaveLength(1);+ });+});++/** The few DOM operations applyWorkflowTheme performs, recorded. */+function fakeDocument() {+ const classes: Record<string, boolean> = {};+ const properties: Record<string, string> = {};+ const links: Array<{ rel: string; href: string }> = [];+ const root = {+ classList: { toggle: (token: string, on: boolean) => void (classes[token] = on) },+ style: { fontSize: "", setProperty: (n: string, v: string) => void (properties[n] = v) },+ };+ const head = {+ querySelector: (selector: string) => links.find((l) => selector.includes(l.href)) ?? null,+ prepend: (link: { rel: string; href: string }) => void links.unshift(link),+ };+ const document = {+ documentElement: root,+ head,+ createElement: () => ({ rel: "", href: "" }),+ } as unknown as Document;+ return { document, root, classes, properties, links };+}diff --git a/plugins/agent-development/plugin.json b/plugins/agent-development/plugin.jsonindex fa15bd9a..59bcd1c2 100644--- a/plugins/agent-development/plugin.json+++ b/plugins/agent-development/plugin.json@@ -3,6 +3,6 @@"description_zh": "基于 PenguinHarness 的智能体开发:用 SDK 构建应用、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。","short_description": "SDK, unified LLM API, config and orchestration.","short_description_zh": "SDK、统一 LLM API、配置与编排。",- "version": "2026.09.16.1",+ "version": "2026.09.20.2","category": "ai-app-development"}diff --git a/plugins/agent-development/skills/penguin-sdk/SKILL.md b/plugins/agent-development/skills/penguin-sdk/SKILL.mdindex 6e6f4eba..db401f68 100644--- a/plugins/agent-development/skills/penguin-sdk/SKILL.md+++ b/plugins/agent-development/skills/penguin-sdk/SKILL.md@@ -1,6 +1,6 @@---name: penguin-sdk-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.+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. Also use it for workflows — the tabs and pages beside the chat that an Agent keeps in its own `workflows/` folder inside PenguinHarness: building one, changing it, restoring an earlier version, and removing a tab or a whole workflow when the user wants the custom UI gone.---# Penguin Harness SDK@@ -344,6 +344,110 @@ http.createServer(async (req, res) => {**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.+## Workflows: pages and server code the Agent keeps for itself++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.++**Start here — the whole loop is files.** 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.++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.+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.+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.+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.++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).++Layout, under `<root>/<project_id>/agents/<agent_id>/workflows/<workflow_id>/` (beside `agent_state/`):++```+package.json "type": "module" and "penguin": { "modules": [ …manifests ] } — no dependency to install+index.ts default export { modules: { <Name>: { create(ctx) } } } satisfies WorkflowPackage — TypeScript only+ui/ the workflow's pages and their assets; which of them are tabs is what the manifest contributes+state.json the workflow's own document, kept by the server across reloads and rollbacks+.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+.build/ the server's: emitted JavaScript per revision, and status.json — the result of the last load; read it, never edit it+```++The root manifest is named `Workflow`; it requires the host, provides the handler, and contributes its tabs:++```json+{+ "name": "demo",+ "version": "0.1.0",+ "type": "module",+ "penguin": {+ "modules": [+ {+ "name": "Workflow",+ "requires": { "host": { "iface": "@prismshadow/penguin-server#WorkflowHost", "from": "Host" } },+ "provides": { "main": "@prismshadow/penguin-server#WorkflowMain" },+ "contributes": {+ "WebModule.sessionTabs": [+ { "id": "demo.main", "key": "main", "title": "Demo", "titleZh": "演示", "renderer": { "iframe": { "src": "ui/index.html" } } }+ ]+ }+ }+ ]+ }+}+```++```ts+import type { WorkflowPackage } from "@prismshadow/penguin-server/plugin";++export default {+ modules: {+ Workflow: {+ create({ use }) {+ const host = use.host;+ return {+ api: {+ main: {+ async handle(req) {+ // req = { method, path, query, body }; path is below the workflow's api/ mount+ if (req.path === "/ask" && req.method === "POST") {+ const { question } = req.body as { question: string };+ // The same two verbs as above: open a Session, run a turn in it.+ const { sessionId } = await host.createSession();+ await host.run(sessionId, [{ text: question }]);+ return { body: { sessionId } };+ }+ return { status: 404, body: { error: "no such route" } };+ },+ },+ },+ };+ },+ },+ },+} satisfies WorkflowPackage;+```++**TypeScript, checked by the server.** 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.++**Types come from the harness that runs you.** 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.++**Tabs are contributions.** 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.++`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.++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.++**Undoing, reverting, removing (撤销 / 还原 / 清掉界面).** 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.++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.)+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*.+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.+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.++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.++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.++**Theme.** 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.++**Filling the app.** 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 — Ctrl+P or Ctrl+Shift+P (⌘ on macOS), both, so a page may take one of them for itself but never both — whose *Exit full page* lands on that Agent's chat.+## Verify before you hand overNever declare the app done without running it:diff --git a/scripts/deploy.mjs b/scripts/deploy.mjsindex 66df4608..483d9e60 100644--- a/scripts/deploy.mjs+++ b/scripts/deploy.mjs@@ -257,10 +257,10 @@ async function readNativeAssets() {// small files is hundreds of blobs, probes and transfers, and stalls. The platform unpacks// `archives/*.tgz` before resolving anything from its assets (hmr/asset-archives.ts).files[`archives/${archiveName("", "node-pty")}`] = await packArchive(pty);- // The compiler a plugin's interfaces are checked with: the target's program may predate it- // being a dependency (or be a desktop bundle with no node_modules), and a platform that- // cannot find it makes no comparison. Content-addressed like everything here, so it- // crosses once.+ // The compiler plugin interfaces and workflows are checked with: the target's program may+ // predate it being a dependency (or be a desktop bundle with no node_modules), and a+ // platform that cannot find it compares no plugin interface and loads no workflow.+ // Content-addressed like everything here, so it crosses once.files[`archives/${archiveName("", "typescript")}`] = await packArchive(typescriptPayload(path.join(ROOT, "packages", "server")).map(({ rel, abs }) => ({rel: `node_modules/typescript/${rel}`,diff --git a/scripts/typescript-payload.mjs b/scripts/typescript-payload.mjsindex 1397b233..ff81f4c6 100644--- a/scripts/typescript-payload.mjs+++ b/scripts/typescript-payload.mjs@@ -1,8 +1,8 @@/*** The TypeScript compiler as something a build carries.*- * The server lets the compiler decide whether a package's interfaces still fit the platform- * (packages/server/src/plugin/typescript.ts). It+ * The server type-checks and transpiles workflows, and lets the compiler decide whether a+ * package's interfaces still fit the platform (packages/server/src/plugin/typescript.ts). It* is a dependency of the server package, which covers an npm install and a checkout — but a* hot push lands on machines whose program was installed before that, and the desktop build* bundles the server into one file with no `node_modules` of its own. Both therefore carry