pi-open-artifact 0.0.0-stage → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Open Artifact
2
+ Copyright 2026 Jim Liu 宝玉
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ It was formerly published as baoyu-design.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # Open Artifact for Pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [中文](README.zh-CN.md)
4
+
5
+ Slide decks, design canvases, whiteboards, spreadsheets, data dashboards, docs, animated films and design systems as
6
+ folders of files that open in one local page where you view, edit and comment, made by
7
+ [Pi](https://pi.dev). Type `/open-artifact slides a 6-slide pitch for this repo` (or `design …`, `whiteboard …`,
8
+ `sheets …`, `data …`, `docs …`, `motion …`, `page …`).
9
+
10
+ This is a Pi package (`pi-open-artifact`) with one extension. It is a full adapter (L3) over the Harness API, built on
11
+ `@open-artifact/harness-kit`, and it carries the Open Artifact runtime (`@open-artifact/cli`).
12
+
13
+ ## Install
14
+
15
+ Pi (tested with 1.6.1) on Node.js 22.19 or later, as Pi needs.
16
+
17
+ ```bash
18
+ pi install npm:pi-open-artifact
19
+ ```
20
+
21
+ From a source checkout of this repository, after `npm ci`, `npm run build` and `node scripts/build-skill.mjs` (the
22
+ runtime the extension starts):
23
+
24
+ ```bash
25
+ pi install ./plugins/pi
26
+ ```
27
+
28
+ To try it for one run without installing it, use `pi -e ./plugins/pi`. Upgrade with `pi update --extensions`.
29
+
30
+ ## What it gives Pi
31
+
32
+ | Part | Does |
33
+ | --- | --- |
34
+ | Tools `Artifact`, `ArtifactData`, `ArtifactComments` | Registered as Pi tools with the daemon's own schemas. Each call names the Pi session, so the artifacts it makes belong to that session. A daemon error fails the call, and its text keeps everything the daemon said (a conflict's current files included). Esc stops waiting for a call; nothing else times a call out. |
35
+ | Comments and requests from the page | They reach the session that owns the artifact right away. Your own words become a user message: a new turn when Pi is idle, steered into the running turn otherwise. A collaborator's comment or a system message (a background task's result) becomes an `open-artifact` custom message that the model reads and that is never taken for your words; it wakes an idle Pi the same way. What was sent while the session was closed comes when you open it again (`pi --resume`). |
36
+ | System prompt | The always-on Open Artifact prompt, as its own `<open_artifact>` section of Pi's system prompt. |
37
+ | Skill `open-artifact` | Rendered for Pi (native tools, pages in the computer's browser) into `~/.open-artifact/skills/pi/` and given to Pi on start. `/skill:open-artifact` loads it. |
38
+ | Command `/open-artifact <type> <what to make>` | Runs the skill with your request, with the installed types as completions. |
39
+ | Session state | `running` while Pi works and `idle` when it has settled, so pages say whether the agent is busy. Files Pi's own `write` and `edit` tools change are reported (`agent.wrote`), so an open page follows at once. |
40
+
41
+ Pi has no page view of its own: `Artifact {action: "open"}` opens the page in the computer's browser, and the agent
42
+ gives you its `view_url` too.
43
+
44
+ ## How it starts the daemon
45
+
46
+ A Pi session that never makes an artifact starts nothing. When a daemon already runs at session start, the session
47
+ connects and attaches, so comments reach it. Otherwise the first Open Artifact tool call starts the newest compatible
48
+ runtime on this computer (this package's `@open-artifact/cli` is one) and connects. A reconnect attaches the session
49
+ again. `/new`, `/resume`, `/fork` and `/reload` close the old session's connection, and the new session makes its own.
50
+
51
+ The daemon's profile for Pi is `packages/daemon/harnesses/pi.json` (harness `pi`). Pi's shell commands carry
52
+ `PI_CODING_AGENT` and `PI_SESSION_ID`, so an `open-artifact` command the agent runs is known as Pi's, and the commands
53
+ that are the person's (publishing, sites) refuse to run there.
54
+
55
+ Set `PI_OPEN_ARTIFACT_DEBUG=1` to have the extension write what it does to stderr. To check a running session, run
56
+ `open-artifact doctor --harness pi --session <id>` (the session id is Pi's `/session`).
57
+
58
+ ## Build and test
59
+
60
+ There is nothing to build: Pi loads `src/index.ts` as it is. Pi's API is declared in `src/pi.ts`, so the package
61
+ depends on no copy of Pi.
62
+
63
+ ```bash
64
+ node --test plugins/pi/test/*.test.ts # against a fake Pi and the kit's fake daemon (part of npm test)
65
+ npm run e2e -- --only pi --no-browser # the real pi against a real daemon, with a scripted local model
66
+ ```
67
+
68
+ The e2e suite needs `pi` on `PATH`; it uses a temporary Pi agent folder, so your own Pi settings and sign-ins are not
69
+ read. See [e2e/README.md](../../e2e/README.md).
@@ -0,0 +1,55 @@
1
+ # Open Artifact for Pi
2
+
3
+ [English](README.md)
4
+
5
+ 让 [Pi](https://pi.dev) 做幻灯片、设计画布、白板、电子表格、数据看板、文档、动画短片和设计系统:每件作品是一个文件夹,在同一个本地页面里查看、编辑和评论。输入 `/open-artifact slides 为这个仓库做一份 6 页的路演稿`(或 `design …`、`whiteboard …`、`sheets …`、`data …`、`docs …`、`motion …`、`page …`)。
6
+
7
+ 这是一个 Pi 包(`pi-open-artifact`),里面只有一个扩展。它基于 `@open-artifact/harness-kit`,是 Harness API 上的完整适配器(L3),并自带 Open Artifact 运行时(`@open-artifact/cli`)。
8
+
9
+ ## 安装
10
+
11
+ 需要 Pi(已用 1.6.1 测试)和 Pi 要求的 Node.js 22.19 及以上。
12
+
13
+ ```bash
14
+ pi install npm:pi-open-artifact
15
+ ```
16
+
17
+ 在本仓库的源码目录里,先运行 `npm ci`、`npm run build` 和 `node scripts/build-skill.mjs`(构建扩展要启动的运行时),再:
18
+
19
+ ```bash
20
+ pi install ./plugins/pi
21
+ ```
22
+
23
+ 只想试一次、不安装,用 `pi -e ./plugins/pi`。升级用 `pi update --extensions`。
24
+
25
+ ## 给 Pi 带来什么
26
+
27
+ | 部分 | 作用 |
28
+ | --- | --- |
29
+ | 工具 `Artifact`、`ArtifactData`、`ArtifactComments` | 以 daemon 自己的参数 schema 注册为 Pi 工具。每次调用都带上 Pi 的会话,做出的作品归这个会话。daemon 返回错误时调用失败,错误文本保留 daemon 说的全部内容(冲突时包括文件的当前内容)。按 Esc 停止等待;除此之外调用不设超时。 |
30
+ | 页面上的评论和请求 | 立刻送到拥有该作品的会话。你本人的话作为用户消息:Pi 空闲时开始新一轮,正在工作时插入当前这一轮。协作者的评论或系统消息(后台任务的结果)作为 `open-artifact` 自定义消息交给模型,不会被当作你说的话;Pi 空闲时同样会被唤醒。会话关闭期间发来的消息,在你重新打开它(`pi --resume`)时送达。 |
31
+ | 系统提示词 | 常驻的 Open Artifact 提示词,作为 Pi 系统提示词里单独的 `<open_artifact>` 一节。 |
32
+ | Skill `open-artifact` | 按 Pi 的方式渲染(原生工具、页面在电脑的浏览器里打开),写到 `~/.open-artifact/skills/pi/`,启动时交给 Pi。用 `/skill:open-artifact` 加载。 |
33
+ | 命令 `/open-artifact <类型> <要做什么>` | 带着你的要求运行这个 skill,并把已安装的类型作为补全。 |
34
+ | 会话状态 | Pi 工作时为 `running`,结束后为 `idle`,页面据此显示 agent 是否在忙。Pi 自己的 `write` 和 `edit` 工具改动的文件会上报(`agent.wrote`),打开着的页面立刻跟上。 |
35
+
36
+ Pi 没有自己的页面视图:`Artifact {action: "open"}` 在电脑的浏览器里打开页面,agent 也会把 `view_url` 给你。
37
+
38
+ ## 它怎样启动 daemon
39
+
40
+ 从不做作品的 Pi 会话什么也不启动。会话开始时如果已有 daemon 在运行,会话就连上并 attach,评论能送到它。否则,第一次调用 Open Artifact 工具时,启动这台电脑上最新的兼容运行时(本包的 `@open-artifact/cli` 是其中之一)并连接。重连后会话会再次 attach。`/new`、`/resume`、`/fork` 和 `/reload` 会关闭旧会话的连接,新会话自己建立连接。
41
+
42
+ daemon 里 Pi 的 profile 是 `packages/daemon/harnesses/pi.json`(harness 名 `pi`)。Pi 执行的 shell 命令带有 `PI_CODING_AGENT` 和 `PI_SESSION_ID`,所以 agent 运行的 `open-artifact` 命令会被识别为 Pi 的,属于本人的命令(发布、站点)在那里会拒绝运行。
43
+
44
+ 设置 `PI_OPEN_ARTIFACT_DEBUG=1`,扩展会把它做的事写到 stderr。要检查一个正在运行的会话,运行 `open-artifact doctor --harness pi --session <id>`(会话 id 见 Pi 的 `/session`)。
45
+
46
+ ## 构建和测试
47
+
48
+ 不需要构建:Pi 直接加载 `src/index.ts`。Pi 的 API 在 `src/pi.ts` 里声明,所以这个包不依赖 Pi 的任何副本。
49
+
50
+ ```bash
51
+ node --test plugins/pi/test/*.test.ts # 用假的 Pi 和 kit 的假 daemon 测试(包含在 npm test 里)
52
+ npm run e2e -- --only pi --no-browser # 真实的 pi、真实的 daemon,加一个脚本化的本地模型
53
+ ```
54
+
55
+ e2e 测试需要 `PATH` 上有 `pi`;它使用临时的 Pi agent 目录,不会读取你自己的 Pi 设置和登录信息。见 [e2e/README.md](../../e2e/README.md)。
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "pi-open-artifact",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.15.0",
4
+ "description": "Open Artifact in Pi: the Artifact, ArtifactData and ArtifactComments tools, comments on artifact pages waking the Pi session that made them, the open-artifact skill, and /open-artifact <type> to make a new one.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "open-artifact",
9
+ "artifacts"
10
+ ],
11
+ "exports": {
12
+ ".": "./src/index.ts",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "README.md",
18
+ "README.zh-CN.md",
19
+ "LICENSE",
20
+ "NOTICE"
21
+ ],
22
+ "pi": {
23
+ "extensions": [
24
+ "./src/index.ts"
25
+ ]
26
+ },
27
+ "dependencies": {
28
+ "@open-artifact/cli": "0.15.0",
29
+ "@open-artifact/harness-kit": "0.15.0",
30
+ "@open-artifact/protocol": "0.15.0"
31
+ },
32
+ "engines": {
33
+ "node": ">=22.19"
34
+ },
35
+ "license": "Apache-2.0",
36
+ "author": {
37
+ "name": "Jim Liu 宝玉",
38
+ "url": "https://github.com/JimLiu"
39
+ },
40
+ "homepage": "https://github.com/JimLiu/open-artifact#readme",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/JimLiu/open-artifact.git",
44
+ "directory": "plugins/pi"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/JimLiu/open-artifact/issues"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Open Artifact in Pi: an L3 adapter over the Harness API, through `@open-artifact/harness-kit`.
3
+ *
4
+ * - The Artifact, ArtifactData and ArtifactComments tools, registered as Pi tools with the daemon's own schemas. A call
5
+ * names its session (`caller`), so the artifacts it makes belong to this Pi session. A daemon error fails the call
6
+ * (Pi shows it as an error), with the whole answer as its text; Esc cancels the wait.
7
+ * - Comments and edit requests from artifact pages wake this session: the owner's words become a user message, which
8
+ * starts a turn when Pi is idle and is steered into the running turn otherwise; a collaborator's or the system's
9
+ * become a custom message the model reads (never a user message), the same way. What waited in the session's inbox
10
+ * comes the same way when the session attaches (a resumed session gets what came while it was away).
11
+ * - The always-on Open Artifact prompt as a section of Pi's system prompt; the `open-artifact` skill, rendered for Pi,
12
+ * through `resources_discover`; `/open-artifact <type> <what to make>` with the installed types as completions.
13
+ * - The session's state (`running` / `idle`) and the files Pi's own `write` and `edit` tools wrote (`agent.wrote`), so
14
+ * open pages follow at once.
15
+ *
16
+ * The daemon is only started by a tool call: a session that never makes an artifact starts nothing. When a daemon
17
+ * already runs, the session connects at start so comments reach it.
18
+ */
19
+ import { homedir } from 'node:os';
20
+ import { join, resolve } from 'node:path';
21
+ import { createHarness, installSkill, openArtifactHome, readDaemon, renderSkill, type Harness, type InstallSkillOptions } from '@open-artifact/harness-kit';
22
+ import { AGENT_PROMPT, TOOL_DEFINITIONS, toolCallContent, type CommandEntry, type SessionParams, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverStatus } from '@open-artifact/protocol';
23
+ import type { PiCompletion, PiContext, PiExtensionAPI, PiTextContent, PiToolResult } from './pi.ts';
24
+ import { hostRuntime } from './runtime.ts';
25
+
26
+ /** The harness name: the daemon's profile `pi` (packages/daemon/harnesses/pi.json). */
27
+ export const HARNESS = 'pi';
28
+ /** What pages call the agent. */
29
+ export const AGENT_NAME = 'Pi';
30
+ /** The command, and the skill's name. */
31
+ export const COMMAND = 'open-artifact';
32
+ /** The `customType` of the messages this extension puts in a session. */
33
+ export const MESSAGE_TYPE = 'open-artifact';
34
+ /** The system prompt section the always-on prompt goes in (Pi wraps it in `<open_artifact>`). */
35
+ export const PROMPT_SECTION = 'open_artifact';
36
+
37
+ /** How the skill reads for Pi: native tools, and pages shown in the computer's browser (Pi has no page view). */
38
+ const SKILL: Omit<InstallSkillOptions, 'dir' | 'force'> = { command: COMMAND, agentName: AGENT_NAME, tools: 'native', opens: 'system' };
39
+
40
+ /**
41
+ * Pi's profile, also reported in `hello`: a daemon that does not ship `harnesses/pi.json` (an older one already running)
42
+ * keeps it, so it still knows Pi's commands by their variables and refuses the person's commands there.
43
+ */
44
+ export const PROFILE = {
45
+ title: 'Pi',
46
+ level: 'L3',
47
+ entry: 'harness-api',
48
+ plugin: 'pi-open-artifact',
49
+ sessionEnv: 'PI_SESSION_ID',
50
+ markers: ['PI_CODING_AGENT', 'PI_SESSION_ID'],
51
+ wake: ['live', 'inbox'],
52
+ open: 'browser',
53
+ } as const;
54
+
55
+ /** Options of {@link openArtifact}, for tests and hosts that embed Pi. */
56
+ export interface OpenArtifactPiOptions {
57
+ /** The Open Artifact home (default `$OPEN_ARTIFACT_HOME`, else `~/.open-artifact`). */
58
+ home?: string;
59
+ /** The runtime this package carries (default {@link hostRuntime}); `null`: none, the kit finds one. */
60
+ runtime?: { dir: string; version: string } | null;
61
+ /** Where the skill is written (default `<home>/skills/pi`). */
62
+ skillsDir?: string;
63
+ /** Diagnostic log (default: stderr when `PI_OPEN_ARTIFACT_DEBUG` is set). */
64
+ log?: (line: string) => void;
65
+ }
66
+
67
+ /** The prompt's text without its outer `<open_artifact>` tags, which Pi's section adds. */
68
+ export function promptSection(prompt: string): string {
69
+ return prompt
70
+ .trim()
71
+ .replace(/^<open_artifact>\s*/, '')
72
+ .replace(/\s*<\/open_artifact>$/, '');
73
+ }
74
+
75
+ /** A path as Pi's file tools take it (`@` prefix, `~`), made absolute against the session's folder. */
76
+ export function absolutePath(path: string, cwd: string): string {
77
+ const bare = path.startsWith('@') ? path.slice(1) : path;
78
+ if (bare === '~') return homedir();
79
+ if (bare.startsWith('~/')) return join(homedir(), bare.slice(2));
80
+ return resolve(cwd, bare);
81
+ }
82
+
83
+ /** The text after the command in a `commands.list` entry (`/open-artifact slides ` → `slides `). */
84
+ function argumentOf(entry: CommandEntry): string {
85
+ return entry.text.replace(/^\/\S+\s*/, '');
86
+ }
87
+
88
+ /** Rejects when `signal` aborts first. */
89
+ function untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
90
+ if (!signal) return work;
91
+ if (signal.aborted) return Promise.reject(new Error('Cancelled.'));
92
+ return new Promise<T>((done, fail) => {
93
+ const onAbort = () => fail(new Error('Cancelled.'));
94
+ signal.addEventListener('abort', onAbort, { once: true });
95
+ work.then(
96
+ (value) => {
97
+ signal.removeEventListener('abort', onAbort);
98
+ done(value);
99
+ },
100
+ (error) => {
101
+ signal.removeEventListener('abort', onAbort);
102
+ fail(error);
103
+ },
104
+ );
105
+ });
106
+ }
107
+
108
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
109
+
110
+ /** The extension: `export default openArtifact()` is what Pi loads. */
111
+ export function openArtifact(options: OpenArtifactPiOptions = {}): (pi: PiExtensionAPI) => void {
112
+ return (pi) => setup(pi, options);
113
+ }
114
+
115
+ function setup(pi: PiExtensionAPI, options: OpenArtifactPiOptions): void {
116
+ const log = options.log ?? (process.env.PI_OPEN_ARTIFACT_DEBUG ? (line: string) => process.stderr.write(`${line}\n`) : () => undefined);
117
+ const skillsDir = options.skillsDir ?? join(openArtifactHome(options.home), 'skills', HARNESS);
118
+
119
+ /** The session's context, from `session_start` to `session_shutdown`. */
120
+ let ctx: PiContext | null = null;
121
+ let session: SessionParams = {};
122
+ /** The session ended: nothing connects again. */
123
+ let closed = false;
124
+ /** Whether Pi runs the agent now (`agent_start` … `agent_settled`). */
125
+ let running = false;
126
+ let pending: Promise<Harness> | null = null;
127
+ let harness: Harness | null = null;
128
+ let prompt = promptSection(AGENT_PROMPT);
129
+ let commands: CommandEntry[] = [];
130
+ let registered = '';
131
+
132
+ // ---- tools ----
133
+
134
+ const callerOf = (c: PiContext): SessionParams => ({ session: c.sessionManager.getSessionId(), workspace: c.cwd });
135
+
136
+ const runTool = async (name: string, args: Record<string, unknown>, signal: AbortSignal | undefined, c: PiContext): Promise<PiToolResult<ToolCallResult>> => {
137
+ const h = await untilAborted(connect(), signal);
138
+ const result = await untilAborted(h.call(name, args, callerOf(c)), signal);
139
+ const content = (toolCallContent(result).content as PiTextContent[]) ?? [];
140
+ // Pi shows a thrown error as the failed call's result: the text keeps all the daemon said (a conflict's `current`).
141
+ if (result?.error) throw new Error(content.map((block) => block.text).join('\n\n'));
142
+ return { content, details: result };
143
+ };
144
+
145
+ /** Registers the tools, again only when the definitions changed (a daemon of another version). */
146
+ const registerTools = (definitions: ToolDefinition[]): void => {
147
+ const key = JSON.stringify(definitions.map((d) => [d.name, d.description, d.inputSchema]));
148
+ if (key === registered) return;
149
+ registered = key;
150
+ for (const definition of definitions) {
151
+ pi.registerTool({
152
+ name: definition.name,
153
+ label: definition.name,
154
+ description: definition.description,
155
+ parameters: definition.inputSchema,
156
+ execute: (_id, params, signal, _onUpdate, c) => runTool(definition.name, params ?? {}, signal, c),
157
+ });
158
+ }
159
+ };
160
+ registerTools(TOOL_DEFINITIONS);
161
+
162
+ // ---- wakes ----
163
+
164
+ const wake = (params: WakeDeliverParams): WakeDeliverStatus => {
165
+ if (closed || !ctx) return 'failed';
166
+ if (params.session ? params.session !== session.session : params.workspace && params.workspace !== session.workspace) return 'failed';
167
+ const idle = ctx.isIdle();
168
+ if (params.source?.from?.kind === 'owner') {
169
+ // The person's own words: a user message, as if typed.
170
+ if (idle) pi.sendUserMessage(params.text);
171
+ else pi.sendUserMessage(params.text, { deliverAs: 'steer' });
172
+ } else {
173
+ // A collaborator's or the system's: the model reads it, and it is never taken for the person's words.
174
+ pi.sendMessage(
175
+ { customType: MESSAGE_TYPE, content: params.text, display: true, details: { artifact: params.artifact, source: params.source } },
176
+ { triggerTurn: true, deliverAs: idle ? 'followUp' : 'steer' },
177
+ );
178
+ }
179
+ return idle ? 'resumed' : 'delivered';
180
+ };
181
+
182
+ // ---- the connection ----
183
+
184
+ /** Tools, prompt, skill and commands as the daemon has them now; each step on its own. */
185
+ const refresh = async (h: Harness): Promise<void> => {
186
+ try {
187
+ registerTools(await h.tools());
188
+ } catch (error) {
189
+ log(`open-artifact tools: ${messageOf(error)}`);
190
+ }
191
+ try {
192
+ const { skill } = await renderSkill(h.client, SKILL);
193
+ if (skill.prompt) prompt = promptSection(skill.prompt);
194
+ } catch (error) {
195
+ log(`open-artifact prompt: ${messageOf(error)}`);
196
+ }
197
+ try {
198
+ await h.installSkill({ dir: skillsDir, ...SKILL });
199
+ } catch (error) {
200
+ log(`open-artifact skill: ${messageOf(error)}`);
201
+ }
202
+ try {
203
+ commands = await h.commands({ command: COMMAND });
204
+ } catch (error) {
205
+ log(`open-artifact commands: ${messageOf(error)}`);
206
+ }
207
+ };
208
+
209
+ const open = async (): Promise<Harness> => {
210
+ const runtime = options.runtime === undefined ? hostRuntime() : options.runtime;
211
+ const h = await createHarness({
212
+ harness: HARNESS,
213
+ agentName: AGENT_NAME,
214
+ commands: [COMMAND],
215
+ caps: { tools: 'native', wake: { resume: true } },
216
+ profile: { ...PROFILE, markers: [...PROFILE.markers], wake: [...PROFILE.wake] },
217
+ wake,
218
+ log,
219
+ ...(options.home ? { home: options.home } : {}),
220
+ ...(runtime ? { runtime } : {}),
221
+ });
222
+ try {
223
+ // `createHarness` keeps trying in the background when its first try failed; this says why it could not.
224
+ await h.ready();
225
+ if (closed) throw new Error('The Pi session ended.');
226
+ await h.attach({ ...session, status: running ? 'running' : 'idle', pid: process.pid });
227
+ } catch (error) {
228
+ h.close();
229
+ throw error;
230
+ }
231
+ harness = h;
232
+ h.on('state', (state) => {
233
+ if (state === 'connected') void refresh(h);
234
+ });
235
+ await refresh(h);
236
+ return h;
237
+ };
238
+
239
+ /** The connection, made once (starting the daemon when none runs); a failure lets the next call try again. */
240
+ const connect = (): Promise<Harness> => {
241
+ if (closed) return Promise.reject(new Error('The Pi session ended.'));
242
+ pending ??= open().catch((error: unknown) => {
243
+ pending = null;
244
+ throw error;
245
+ });
246
+ return pending;
247
+ };
248
+
249
+ // ---- Pi's events ----
250
+
251
+ pi.on('session_start', (_event, c) => {
252
+ ctx = c;
253
+ session = callerOf(c);
254
+ // Only a daemon that already runs: the session takes the comments made while it was away, and new ones.
255
+ void readDaemon(options.home)
256
+ .then((state) => (state && !closed ? connect() : null))
257
+ .catch((error: unknown) => closed || log(`open-artifact connect: ${messageOf(error)}`));
258
+ });
259
+
260
+ pi.on('session_shutdown', () => {
261
+ closed = true;
262
+ ctx = null;
263
+ harness?.close();
264
+ harness = null;
265
+ void pending?.then(
266
+ (h) => h.close(),
267
+ () => undefined,
268
+ );
269
+ });
270
+
271
+ pi.on('resources_discover', async () => {
272
+ try {
273
+ if (harness?.connected) await harness.installSkill({ dir: skillsDir, ...SKILL });
274
+ else await installSkill(null, { dir: skillsDir, ...SKILL });
275
+ } catch (error) {
276
+ log(`open-artifact skill: ${messageOf(error)}`);
277
+ }
278
+ return { skillPaths: [skillsDir] };
279
+ });
280
+
281
+ pi.on('before_agent_start', (event) => {
282
+ const options = event.systemPromptOptions;
283
+ if (!options) return;
284
+ options.sections ??= {};
285
+ options.sections[PROMPT_SECTION] = prompt;
286
+ });
287
+
288
+ /**
289
+ * Runs `work` on the connection once it is made, if one is made or being made; never starts one. A call that the
290
+ * session's own shutdown cut off (Pi's last `idle` as it exits) is not an error.
291
+ */
292
+ const onceConnected = (what: string, work: (h: Harness) => Promise<unknown>): void => {
293
+ void pending
294
+ ?.then(work, () => undefined)
295
+ .catch((error: unknown) => closed || log(`open-artifact ${what}: ${messageOf(error)}`));
296
+ };
297
+
298
+ const status = (state: 'running' | 'idle'): void => {
299
+ running = state === 'running';
300
+ onceConnected('status', (h) => h.status(session, state));
301
+ };
302
+ pi.on('agent_start', () => status('running'));
303
+ pi.on('agent_settled', () => status('idle'));
304
+
305
+ pi.on('tool_result', (event, c) => {
306
+ if (event.isError || (event.toolName !== 'write' && event.toolName !== 'edit')) return;
307
+ const path = event.input?.path;
308
+ if (typeof path !== 'string' || !path) return;
309
+ const paths = [absolutePath(path, c.cwd)];
310
+ const caller = callerOf(c);
311
+ onceConnected('wrote', (h) => h.wrote(paths, caller));
312
+ });
313
+
314
+ pi.registerCommand(COMMAND, {
315
+ description: 'Make an Open Artifact: /open-artifact <type> <what to make>',
316
+ getArgumentCompletions: (prefix) => {
317
+ const items: PiCompletion[] = commands
318
+ .map((entry) => ({ value: argumentOf(entry), label: entry.type, description: entry.title }))
319
+ .filter((item) => item.value.startsWith(prefix));
320
+ return items.length ? items : null;
321
+ },
322
+ handler: (args, c) => {
323
+ const text = `/skill:${COMMAND}${args.trim() ? ` ${args.trim()}` : ''}`;
324
+ if (c.isIdle()) pi.sendUserMessage(text, { expandPromptTemplates: true });
325
+ else pi.sendUserMessage(text, { expandPromptTemplates: true, deliverAs: 'followUp' });
326
+ },
327
+ });
328
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The Pi extension `pi-open-artifact` loads (`package.json` → `pi.extensions`). See `extension.ts`.
3
+ */
4
+ import { openArtifact } from './extension.ts';
5
+
6
+ export { openArtifact, type OpenArtifactPiOptions } from './extension.ts';
7
+
8
+ export default openArtifact();
package/src/pi.ts ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The part of Pi's extension API this package uses (`@earendil-works/pi-coding-agent`, docs/extensions.md), declared
3
+ * here so the package needs no copy of Pi: Pi provides its API to an extension at load time, and a package must not
4
+ * list Pi among its dependencies. Pi validates tool parameters as JSON Schema, so the tools pass the daemon's schemas
5
+ * as they are.
6
+ */
7
+
8
+ /** One block of a tool result or a message. */
9
+ export interface PiTextContent {
10
+ type: 'text';
11
+ text: string;
12
+ }
13
+
14
+ /** What a tool's `execute` answers. Throwing marks the call as failed, with the error's message as its text. */
15
+ export interface PiToolResult<Details = unknown> {
16
+ content: PiTextContent[];
17
+ details: Details;
18
+ }
19
+
20
+ /** A session, as `ctx.sessionManager` reads it. */
21
+ export interface PiSessionManager {
22
+ getSessionId(): string;
23
+ getSessionName?(): string | undefined;
24
+ }
25
+
26
+ /** The context every handler gets. Stale once its session is replaced (`/new`, `/resume`, `/fork`, `/reload`). */
27
+ export interface PiContext {
28
+ cwd: string;
29
+ /** `interactive`, `print`, `json` or `rpc`. */
30
+ mode?: string;
31
+ hasUI: boolean;
32
+ sessionManager: PiSessionManager;
33
+ /** False while Pi runs the agent, retries, compacts or continues with queued messages. */
34
+ isIdle(): boolean;
35
+ ui: { notify(message: string, level?: 'info' | 'warning' | 'error'): void };
36
+ }
37
+
38
+ /** A tool the model can call. */
39
+ export interface PiTool {
40
+ name: string;
41
+ label: string;
42
+ description: string;
43
+ /** JSON Schema of the arguments. */
44
+ parameters: unknown;
45
+ execute(
46
+ toolCallId: string,
47
+ params: Record<string, unknown>,
48
+ signal: AbortSignal | undefined,
49
+ onUpdate: ((partial: PiToolResult) => void) | undefined,
50
+ ctx: PiContext,
51
+ ): Promise<PiToolResult>;
52
+ }
53
+
54
+ /** One line of a command's argument completions. */
55
+ export interface PiCompletion {
56
+ value: string;
57
+ label: string;
58
+ description?: string;
59
+ }
60
+
61
+ /** A slash command. */
62
+ export interface PiCommand {
63
+ description?: string;
64
+ getArgumentCompletions?(prefix: string): PiCompletion[] | null | Promise<PiCompletion[] | null>;
65
+ handler(args: string, ctx: PiContext): void | Promise<void>;
66
+ }
67
+
68
+ /** A custom message: in the model's context, shown in the transcript when `display` is true. */
69
+ export interface PiCustomMessage {
70
+ customType: string;
71
+ content: string;
72
+ display: boolean;
73
+ details?: unknown;
74
+ }
75
+
76
+ /** How a message enters a session: steered into a running turn, after it, or with the next prompt. */
77
+ export type PiDelivery = 'steer' | 'followUp' | 'nextTurn';
78
+
79
+ export interface PiSessionStartEvent {
80
+ reason: 'startup' | 'reload' | 'new' | 'resume' | 'fork';
81
+ }
82
+
83
+ export interface PiSessionShutdownEvent {
84
+ reason: 'quit' | 'reload' | 'new' | 'resume' | 'fork';
85
+ }
86
+
87
+ export interface PiBeforeAgentStartEvent {
88
+ /** Mutable: Pi patches the model's prompt with what changed. `sections[tag]` is wrapped in `<tag>…</tag>`. */
89
+ systemPromptOptions: { sections?: Record<string, string> };
90
+ }
91
+
92
+ export interface PiToolResultEvent {
93
+ toolName: string;
94
+ input: Record<string, unknown>;
95
+ isError: boolean;
96
+ }
97
+
98
+ export interface PiResourcesDiscoverEvent {
99
+ cwd: string;
100
+ reason: 'startup' | 'reload';
101
+ }
102
+
103
+ export interface PiResources {
104
+ skillPaths?: string[];
105
+ promptPaths?: string[];
106
+ themePaths?: string[];
107
+ }
108
+
109
+ /** The `pi` object an extension's default export is called with. */
110
+ export interface PiExtensionAPI {
111
+ registerTool(tool: PiTool): void;
112
+ registerCommand(name: string, command: PiCommand): void;
113
+ sendMessage(message: PiCustomMessage, options?: { triggerTurn?: boolean; deliverAs?: PiDelivery }): void;
114
+ sendUserMessage(content: string, options?: { deliverAs?: 'steer' | 'followUp'; expandPromptTemplates?: boolean }): void;
115
+ on(event: 'session_start', handler: (event: PiSessionStartEvent, ctx: PiContext) => unknown): void;
116
+ on(event: 'session_shutdown', handler: (event: PiSessionShutdownEvent, ctx: PiContext) => unknown): void;
117
+ on(event: 'before_agent_start', handler: (event: PiBeforeAgentStartEvent, ctx: PiContext) => unknown): void;
118
+ on(event: 'agent_start' | 'agent_settled', handler: (event: unknown, ctx: PiContext) => unknown): void;
119
+ on(event: 'tool_result', handler: (event: PiToolResultEvent, ctx: PiContext) => unknown): void;
120
+ on(event: 'resources_discover', handler: (event: PiResourcesDiscoverEvent, ctx: PiContext) => PiResources | Promise<PiResources>): void;
121
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The Open Artifact runtime this package carries: the `@open-artifact/cli` dependency when installed from npm, else,
3
+ * inside the Open Artifact repository, the skill folder `node scripts/build-plugins.mjs` builds. The kit starts the
4
+ * newest compatible runtime on this computer when no daemon runs; this one is a candidate.
5
+ */
6
+ import { existsSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { dirname, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { runtimeInfo } from '@open-artifact/harness-kit';
11
+
12
+ /** Where a runtime may be, best first. */
13
+ export function runtimeFolders(from: string = import.meta.url): string[] {
14
+ const folders: string[] = [];
15
+ try {
16
+ folders.push(dirname(createRequire(from).resolve('@open-artifact/cli/package.json')));
17
+ } catch {
18
+ // not installed
19
+ }
20
+ for (let dir = dirname(fileURLToPath(from)); dir !== dirname(dir); dir = dirname(dir)) {
21
+ const skill = join(dir, 'skills', 'open-artifact');
22
+ if (existsSync(join(skill, 'SKILL.md'))) {
23
+ folders.push(skill);
24
+ break;
25
+ }
26
+ }
27
+ return folders;
28
+ }
29
+
30
+ /**
31
+ * The runtime as `createHarness({ runtime })` takes it, or `undefined` when there is none here: then the kit starts
32
+ * `$OPEN_ARTIFACT_DAEMON_BIN`, or another runtime on this computer, and fails with its own message when there is none.
33
+ */
34
+ export function hostRuntime(folders: string[] = runtimeFolders()): { dir: string; version: string } | undefined {
35
+ for (const dir of folders) {
36
+ const version = runtimeInfo(dir)?.version;
37
+ if (version) return { dir, version };
38
+ }
39
+ return undefined;
40
+ }