pi-open-artifacts 0.0.0-stage → 0.23.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 Artifacts
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,102 @@
1
- # Temporary Holding Version
1
+ # Open Artifacts 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-artifacts 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-artifacts`) with one extension. It is a full adapter (L3) over the Harness API, built on
11
+ `@openartifactsai/harness-kit`, and it carries the Open Artifacts runtime (`@openartifactsai/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-artifacts
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
+ ## Switching from `pi-open-artifact`
31
+
32
+ Up to 0.22 this package was `pi-open-artifact`, with the `/open-artifact` command. It keeps working until you switch,
33
+ and `pi update --extensions` brings it one last update, 0.23.0 (see
34
+ [Switching from the `open-artifact` plugin](../README.md#switching-from-the-open-artifact-plugin)). To switch, then start a new Pi session:
35
+
36
+ ```bash
37
+ pi remove npm:pi-open-artifact
38
+ pi install npm:pi-open-artifacts
39
+ ```
40
+
41
+ ## What it gives Pi
42
+
43
+ | Part | Does |
44
+ | --- | --- |
45
+ | 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. |
46
+ | 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-artifacts` 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`). |
47
+ | System prompt | The always-on Open Artifacts prompt, as its own `<open_artifacts>` section of Pi's system prompt. |
48
+ | Skill `open-artifacts` | Rendered for Pi (native tools, pages in the computer's browser) into `~/.agents/open-artifacts/skills/pi/` and given to Pi on start. `/skill:open-artifacts` loads it. |
49
+ | Command `/open-artifacts <type> <what to make>` | Runs the skill with your request, with the installed types as completions. |
50
+ | 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. |
51
+
52
+ Pi has no page view of its own: `Artifact {action: "open"}` opens the page in the computer's browser, and the agent
53
+ gives you its `view_url` too.
54
+
55
+ ## Pages that ask a model
56
+
57
+ A page can ask a model for text (`sample`). When you pick Pi as the page's model source, Pi answers with the model
58
+ your session uses and the keys or logins Pi already has: nothing new to set up. You are asked before a page can use a
59
+ model at all, and the Shell shows how much each artifact has used. When Pi's key or login is missing or rejected, the
60
+ page tells you to sign in to Pi again; when its text does not fit the model's context, it says so.
61
+
62
+ The request goes straight to the model, outside the session: it is not added to the conversation, and Pi runs none of
63
+ its own tools for it (a page's tools run in the page). Limits:
64
+
65
+ - One model: the session's (`/model` changes it). There are no separate fast or most capable ones; a page that asks
66
+ for one gets the session's model.
67
+ - Images only when that model reads them, as of when Pi connected to Open Artifacts.
68
+ - An older Pi without `ctx.modelRegistry` does not offer this.
69
+
70
+ ## Where artifacts go
71
+
72
+ New artifacts go under your own Open Artifacts folder, one folder per project: `~/OpenArtifacts/<project>/<slug>`. Pi
73
+ lets its agent write there, and the repository stays clean. To keep them in the project instead
74
+ (`<session's folder>/artifacts/<slug>`), run `open-artifacts config set artifactsLocation workspace` in your terminal,
75
+ with `--local` for one project only. See [Settings](../../docs/settings.md).
76
+
77
+ ## How it starts the daemon
78
+
79
+ A Pi session that never makes an artifact starts nothing. When a daemon already runs at session start, the session
80
+ connects and attaches, so comments reach it. Otherwise the first Open Artifacts tool call starts the newest compatible
81
+ runtime on this computer (this package's `@openartifactsai/cli` is one) and connects. A reconnect attaches the session
82
+ again. `/new`, `/resume`, `/fork` and `/reload` close the old session's connection, and the new session makes its own.
83
+
84
+ The daemon's profile for Pi is `packages/daemon/harnesses/pi.json` (harness `pi`). Pi's shell commands carry
85
+ `PI_CODING_AGENT` and `PI_SESSION_ID`, so an `open-artifacts` command the agent runs is known as Pi's, and the commands
86
+ that are the person's (publishing, sites) refuse to run there.
87
+
88
+ Set `PI_OPEN_ARTIFACTS_DEBUG=1` to have the extension write what it does to stderr. To check a running session, run
89
+ `open-artifacts doctor --harness pi --session <id>` (the session id is Pi's `/session`).
90
+
91
+ ## Build and test
92
+
93
+ 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
94
+ depends on no copy of Pi.
95
+
96
+ ```bash
97
+ node --test plugins/pi/test/*.test.ts # against a fake Pi and the kit's fake daemon (part of npm test)
98
+ npm run e2e -- --only pi --no-browser # the real pi against a real daemon, with a scripted local model
99
+ ```
100
+
101
+ The e2e suite needs `pi` on `PATH`; it uses a temporary Pi agent folder, so your own Pi settings and sign-ins are not
102
+ read. See [e2e/README.md](../../e2e/README.md).
@@ -0,0 +1,74 @@
1
+ # Open Artifacts for Pi
2
+
3
+ [English](README.md)
4
+
5
+ 让 [Pi](https://pi.dev) 做幻灯片、设计画布、白板、电子表格、数据看板、文档、动画短片和设计系统:每件作品是一个文件夹,在同一个本地页面里查看、编辑和评论。输入 `/open-artifacts slides 为这个仓库做一份 6 页的路演稿`(或 `design …`、`whiteboard …`、`sheets …`、`data …`、`docs …`、`motion …`、`page …`)。
6
+
7
+ 这是一个 Pi 包(`pi-open-artifacts`),里面只有一个扩展。它基于 `@openartifactsai/harness-kit`,是 Harness API 上的完整适配器(L3),并自带 Open Artifacts 运行时(`@openartifactsai/cli`)。
8
+
9
+ ## 安装
10
+
11
+ 需要 Pi(已用 1.6.1 测试)和 Pi 要求的 Node.js 22.19 及以上。
12
+
13
+ ```bash
14
+ pi install npm:pi-open-artifacts
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-open-artifact` 换过来
26
+
27
+ 0.22 及以前这个包叫 `pi-open-artifact`,命令是 `/open-artifact`。换之前它照常能用,`pi update --extensions` 还会给它最后一次更新,0.23.0(见[Switching from the `open-artifact` plugin](../README.md#switching-from-the-open-artifact-plugin))。换装后开一个新的 Pi 会话:
28
+
29
+ ```bash
30
+ pi remove npm:pi-open-artifact
31
+ pi install npm:pi-open-artifacts
32
+ ```
33
+
34
+ ## 给 Pi 带来什么
35
+
36
+ | 部分 | 作用 |
37
+ | --- | --- |
38
+ | 工具 `Artifact`、`ArtifactData`、`ArtifactComments` | 以 daemon 自己的参数 schema 注册为 Pi 工具。每次调用都带上 Pi 的会话,做出的作品归这个会话。daemon 返回错误时调用失败,错误文本保留 daemon 说的全部内容(冲突时包括文件的当前内容)。按 Esc 停止等待;除此之外调用不设超时。 |
39
+ | 页面上的评论和请求 | 立刻送到拥有该作品的会话。你本人的话作为用户消息:Pi 空闲时开始新一轮,正在工作时插入当前这一轮。协作者的评论或系统消息(后台任务的结果)作为 `open-artifacts` 自定义消息交给模型,不会被当作你说的话;Pi 空闲时同样会被唤醒。会话关闭期间发来的消息,在你重新打开它(`pi --resume`)时送达。 |
40
+ | 系统提示词 | 常驻的 Open Artifacts 提示词,作为 Pi 系统提示词里单独的 `<open_artifacts>` 一节。 |
41
+ | Skill `open-artifacts` | 按 Pi 的方式渲染(原生工具、页面在电脑的浏览器里打开),写到 `~/.agents/open-artifacts/skills/pi/`,启动时交给 Pi。用 `/skill:open-artifacts` 加载。 |
42
+ | 命令 `/open-artifacts <类型> <要做什么>` | 带着你的要求运行这个 skill,并把已安装的类型作为补全。 |
43
+ | 会话状态 | Pi 工作时为 `running`,结束后为 `idle`,页面据此显示 agent 是否在忙。Pi 自己的 `write` 和 `edit` 工具改动的文件会上报(`agent.wrote`),打开着的页面立刻跟上。 |
44
+
45
+ Pi 没有自己的页面视图:`Artifact {action: "open"}` 在电脑的浏览器里打开页面,agent 也会把 `view_url` 给你。
46
+
47
+ ## 向模型提问的页面
48
+
49
+ 页面可以向模型要一段文字(`sample`)。你为页面选 Pi 作为模型来源时,Pi 用当前会话的模型、用 Pi 已有的密钥或登录来回答,不用另外设置。页面要用模型之前都会先问你,Shell 里能看到每个作品用了多少。Pi 的密钥或登录缺失、被拒时,页面会提示你重新登录 Pi;页面的文字超出模型的上下文时,页面也会说明。
50
+
51
+ 请求直接发给模型,不经过会话:不进入对话记录,Pi 也不为它运行自己的任何工具(页面的工具在页面里运行)。限制:
52
+
53
+ - 只有一个模型:会话正在用的那个(用 `/model` 换)。没有单独的快速模型或最强模型;页面要它们时,用的仍是会话的模型。
54
+ - 只有在 Pi 连上 Open Artifacts 时会话的模型能读图片,才接收图片。
55
+ - 没有 `ctx.modelRegistry` 的旧版 Pi 不提供这项功能。
56
+
57
+ ## 它怎样启动 daemon
58
+
59
+ 从不做作品的 Pi 会话什么也不启动。会话开始时如果已有 daemon 在运行,会话就连上并 attach,评论能送到它。否则,第一次调用 Open Artifacts 工具时,启动这台电脑上最新的兼容运行时(本包的 `@openartifactsai/cli` 是其中之一)并连接。重连后会话会再次 attach。`/new`、`/resume`、`/fork` 和 `/reload` 会关闭旧会话的连接,新会话自己建立连接。
60
+
61
+ daemon 里 Pi 的 profile 是 `packages/daemon/harnesses/pi.json`(harness 名 `pi`)。Pi 执行的 shell 命令带有 `PI_CODING_AGENT` 和 `PI_SESSION_ID`,所以 agent 运行的 `open-artifacts` 命令会被识别为 Pi 的,属于本人的命令(发布、站点)在那里会拒绝运行。
62
+
63
+ 设置 `PI_OPEN_ARTIFACTS_DEBUG=1`,扩展会把它做的事写到 stderr。要检查一个正在运行的会话,运行 `open-artifacts doctor --harness pi --session <id>`(会话 id 见 Pi 的 `/session`)。
64
+
65
+ ## 构建和测试
66
+
67
+ 不需要构建:Pi 直接加载 `src/index.ts`。Pi 的 API 在 `src/pi.ts` 里声明,所以这个包不依赖 Pi 的任何副本。
68
+
69
+ ```bash
70
+ node --test plugins/pi/test/*.test.ts # 用假的 Pi 和 kit 的假 daemon 测试(包含在 npm test 里)
71
+ npm run e2e -- --only pi --no-browser # 真实的 pi、真实的 daemon,加一个脚本化的本地模型
72
+ ```
73
+
74
+ 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-artifacts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.23.0",
4
+ "description": "Open Artifacts in Pi: the Artifact, ArtifactData and ArtifactComments tools, comments on artifact pages waking the Pi session that made them, the open-artifacts skill, and /open-artifacts <type> to make a new one.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "open-artifacts",
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
+ "@openartifactsai/cli": "0.23.0",
29
+ "@openartifactsai/harness-kit": "0.23.0",
30
+ "@openartifactsai/protocol": "0.23.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/openartifactsai/open-artifacts#readme",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/openartifactsai/open-artifacts.git",
44
+ "directory": "plugins/pi"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/openartifactsai/open-artifacts/issues"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Open Artifacts in Pi: an L3 adapter over the Harness API, through `@openartifactsai/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 Artifacts prompt as a section of Pi's system prompt; the `open-artifacts` skill, rendered for Pi,
12
+ * through `resources_discover`; `/open-artifacts <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
+ * - Pages asking a model for text (`sample.create`), answered with the session's model and Pi's own auth, outside the
16
+ * session's conversation (`src/sample.ts`).
17
+ *
18
+ * The daemon is only started by a tool call: a session that never makes an artifact starts nothing. When a daemon
19
+ * already runs, the session connects at start so comments reach it.
20
+ */
21
+ import { homedir } from 'node:os';
22
+ import { join, resolve } from 'node:path';
23
+ import { adoptLegacyEnv, createHarness, installSkill, openArtifactsHome, readDaemon, renderSkill, type Harness, type InstallSkillOptions } from '@openartifactsai/harness-kit';
24
+ import { AGENT_PROMPT, TOOL_DEFINITIONS, toolCallContent, type CommandEntry, type SessionParams, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverStatus } from '@openartifactsai/protocol';
25
+ import type { PiCompletion, PiContext, PiExtensionAPI, PiTextContent, PiToolResult } from './pi.ts';
26
+ import { hostRuntime } from './runtime.ts';
27
+ import { piSample } from './sample.ts';
28
+
29
+ /** The harness name: the daemon's profile `pi` (packages/daemon/harnesses/pi.json). */
30
+ export const HARNESS = 'pi';
31
+ /** What pages call the agent. */
32
+ export const AGENT_NAME = 'Pi';
33
+ /** The command, and the skill's name. */
34
+ export const COMMAND = 'open-artifacts';
35
+ /** The `customType` of the messages this extension puts in a session. */
36
+ export const MESSAGE_TYPE = 'open-artifacts';
37
+ /** The system prompt section the always-on prompt goes in (Pi wraps it in `<open_artifacts>`). */
38
+ export const PROMPT_SECTION = 'open_artifacts';
39
+
40
+ /** How the skill reads for Pi: native tools, and pages shown in the computer's browser (Pi has no page view). */
41
+ const SKILL: Omit<InstallSkillOptions, 'dir' | 'force'> = { command: COMMAND, agentName: AGENT_NAME, tools: 'native', opens: 'system' };
42
+
43
+ /**
44
+ * Pi's profile, also reported in `hello`: a daemon that does not ship `harnesses/pi.json` (an older one already running)
45
+ * keeps it, so it still knows Pi's commands by their variables and refuses the person's commands there.
46
+ */
47
+ export const PROFILE = {
48
+ title: 'Pi',
49
+ level: 'L3',
50
+ entry: 'harness-api',
51
+ plugin: 'pi-open-artifacts',
52
+ sessionEnv: 'PI_SESSION_ID',
53
+ markers: ['PI_CODING_AGENT', 'PI_SESSION_ID'],
54
+ wake: ['live', 'inbox'],
55
+ open: 'browser',
56
+ } as const;
57
+
58
+ /** Options of {@link openArtifacts}, for tests and hosts that embed Pi. */
59
+ export interface OpenArtifactsPiOptions {
60
+ /** The Open Artifacts home (default `$OPEN_ARTIFACTS_HOME`, else `~/.agents/open-artifacts`). */
61
+ home?: string;
62
+ /** The runtime this package carries (default {@link hostRuntime}); `null`: none, the kit finds one. */
63
+ runtime?: { dir: string; version: string } | null;
64
+ /** Where the skill is written (default `<home>/skills/pi`). */
65
+ skillsDir?: string;
66
+ /** Diagnostic log (default: stderr when `PI_OPEN_ARTIFACTS_DEBUG` is set). */
67
+ log?: (line: string) => void;
68
+ }
69
+
70
+ /** The prompt block's tag before the rename: a daemon from then still running sends `<open_artifact>` … in `skill.get`. */
71
+ const LEGACY_PROMPT_TAG = 'open_artifact';
72
+
73
+ /** The prompt's text without its outer `<open_artifacts>` tags (or the older ones), which Pi's section adds. */
74
+ export function promptSection(prompt: string): string {
75
+ return prompt
76
+ .trim()
77
+ .replace(new RegExp(`^<(?:open_artifacts|${LEGACY_PROMPT_TAG})>\\s*`), '')
78
+ .replace(new RegExp(`\\s*<\\/(?:open_artifacts|${LEGACY_PROMPT_TAG})>$`), '');
79
+ }
80
+
81
+ /** A path as Pi's file tools take it (`@` prefix, `~`), made absolute against the session's folder. */
82
+ export function absolutePath(path: string, cwd: string): string {
83
+ const bare = path.startsWith('@') ? path.slice(1) : path;
84
+ if (bare === '~') return homedir();
85
+ if (bare.startsWith('~/')) return join(homedir(), bare.slice(2));
86
+ return resolve(cwd, bare);
87
+ }
88
+
89
+ /** The text after the command in a `commands.list` entry (`/open-artifacts slides ` → `slides `). */
90
+ function argumentOf(entry: CommandEntry): string {
91
+ return entry.text.replace(/^\/\S+\s*/, '');
92
+ }
93
+
94
+ /** Rejects when `signal` aborts first. */
95
+ function untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
96
+ if (!signal) return work;
97
+ if (signal.aborted) return Promise.reject(new Error('Cancelled.'));
98
+ return new Promise<T>((done, fail) => {
99
+ const onAbort = () => fail(new Error('Cancelled.'));
100
+ signal.addEventListener('abort', onAbort, { once: true });
101
+ work.then(
102
+ (value) => {
103
+ signal.removeEventListener('abort', onAbort);
104
+ done(value);
105
+ },
106
+ (error) => {
107
+ signal.removeEventListener('abort', onAbort);
108
+ fail(error);
109
+ },
110
+ );
111
+ });
112
+ }
113
+
114
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
115
+
116
+ /** The extension: `export default openArtifacts()` is what Pi loads. */
117
+ export function openArtifacts(options: OpenArtifactsPiOptions = {}): (pi: PiExtensionAPI) => void {
118
+ return (pi) => setup(pi, options);
119
+ }
120
+
121
+ function setup(pi: PiExtensionAPI, options: OpenArtifactsPiOptions): void {
122
+ // Our variables' names from before 0.23 (`OPEN_ARTIFACT_*`) count, as their new ones.
123
+ adoptLegacyEnv();
124
+ const log = options.log ?? (process.env.PI_OPEN_ARTIFACTS_DEBUG ? (line: string) => process.stderr.write(`${line}\n`) : () => undefined);
125
+ const skillsDir = options.skillsDir ?? join(openArtifactsHome(options.home), 'skills', HARNESS);
126
+
127
+ /** The session's context, from `session_start` to `session_shutdown`. */
128
+ let ctx: PiContext | null = null;
129
+ let session: SessionParams = {};
130
+ /** The session ended: nothing connects again. */
131
+ let closed = false;
132
+ /** Whether Pi runs the agent now (`agent_start` … `agent_settled`). */
133
+ let running = false;
134
+ let pending: Promise<Harness> | null = null;
135
+ let harness: Harness | null = null;
136
+ let prompt = promptSection(AGENT_PROMPT);
137
+ let commands: CommandEntry[] = [];
138
+ let registered = '';
139
+
140
+ // ---- tools ----
141
+
142
+ const callerOf = (c: PiContext): SessionParams => ({ session: c.sessionManager.getSessionId(), workspace: c.cwd });
143
+
144
+ const runTool = async (name: string, args: Record<string, unknown>, signal: AbortSignal | undefined, c: PiContext): Promise<PiToolResult<ToolCallResult>> => {
145
+ const h = await untilAborted(connect(), signal);
146
+ const result = await untilAborted(h.call(name, args, callerOf(c)), signal);
147
+ const content = (toolCallContent(result).content as PiTextContent[]) ?? [];
148
+ // Pi shows a thrown error as the failed call's result: the text keeps all the daemon said (a conflict's `current`).
149
+ if (result?.error) throw new Error(content.map((block) => block.text).join('\n\n'));
150
+ return { content, details: result };
151
+ };
152
+
153
+ /** Registers the tools, again only when the definitions changed (a daemon of another version). */
154
+ const registerTools = (definitions: ToolDefinition[]): void => {
155
+ const key = JSON.stringify(definitions.map((d) => [d.name, d.description, d.inputSchema]));
156
+ if (key === registered) return;
157
+ registered = key;
158
+ for (const definition of definitions) {
159
+ pi.registerTool({
160
+ name: definition.name,
161
+ label: definition.name,
162
+ description: definition.description,
163
+ parameters: definition.inputSchema,
164
+ execute: (_id, params, signal, _onUpdate, c) => runTool(definition.name, params ?? {}, signal, c),
165
+ });
166
+ }
167
+ };
168
+ registerTools(TOOL_DEFINITIONS);
169
+
170
+ // ---- wakes ----
171
+
172
+ const wake = (params: WakeDeliverParams): WakeDeliverStatus => {
173
+ if (closed || !ctx) return 'failed';
174
+ if (params.session ? params.session !== session.session : params.workspace && params.workspace !== session.workspace) return 'failed';
175
+ const idle = ctx.isIdle();
176
+ if (params.source?.from?.kind === 'owner') {
177
+ // The person's own words: a user message, as if typed.
178
+ if (idle) pi.sendUserMessage(params.text);
179
+ else pi.sendUserMessage(params.text, { deliverAs: 'steer' });
180
+ } else {
181
+ // A collaborator's or the system's: the model reads it, and it is never taken for the person's words.
182
+ pi.sendMessage(
183
+ { customType: MESSAGE_TYPE, content: params.text, display: true, details: { artifact: params.artifact, source: params.source } },
184
+ { triggerTurn: true, deliverAs: idle ? 'followUp' : 'steer' },
185
+ );
186
+ }
187
+ return idle ? 'resumed' : 'delivered';
188
+ };
189
+
190
+ // ---- the connection ----
191
+
192
+ /** Tools, prompt, skill and commands as the daemon has them now; each step on its own. */
193
+ const refresh = async (h: Harness): Promise<void> => {
194
+ try {
195
+ registerTools(await h.tools());
196
+ } catch (error) {
197
+ log(`open-artifacts tools: ${messageOf(error)}`);
198
+ }
199
+ try {
200
+ const { skill } = await renderSkill(h.client, SKILL);
201
+ if (skill.prompt) prompt = promptSection(skill.prompt);
202
+ } catch (error) {
203
+ log(`open-artifacts prompt: ${messageOf(error)}`);
204
+ }
205
+ try {
206
+ await h.installSkill({ dir: skillsDir, ...SKILL });
207
+ } catch (error) {
208
+ log(`open-artifacts skill: ${messageOf(error)}`);
209
+ }
210
+ try {
211
+ commands = await h.commands({ command: COMMAND });
212
+ } catch (error) {
213
+ log(`open-artifacts commands: ${messageOf(error)}`);
214
+ }
215
+ };
216
+
217
+ const open = async (): Promise<Harness> => {
218
+ const runtime = options.runtime === undefined ? hostRuntime() : options.runtime;
219
+ // Pages may ask the session's model for text, outside the session's conversation.
220
+ const sample = piSample(() => ctx);
221
+ const h = await createHarness({
222
+ harness: HARNESS,
223
+ agentName: AGENT_NAME,
224
+ commands: [COMMAND],
225
+ caps: { tools: 'native', wake: { resume: true } },
226
+ profile: { ...PROFILE, markers: [...PROFILE.markers], wake: [...PROFILE.wake] },
227
+ wake,
228
+ log,
229
+ ...(sample ? { sample } : {}),
230
+ ...(options.home ? { home: options.home } : {}),
231
+ ...(runtime ? { runtime } : {}),
232
+ });
233
+ try {
234
+ // `createHarness` keeps trying in the background when its first try failed; this says why it could not.
235
+ await h.ready();
236
+ if (closed) throw new Error('The Pi session ended.');
237
+ const { inbox } = await h.attach({ ...session, status: running ? 'running' : 'idle', pid: process.pid });
238
+ // The attach took them out of the daemon; what `wake` did not take (a note, say) waits for the next tool call.
239
+ if (inbox.length && h.features.includes('inbox.return')) {
240
+ await h.client
241
+ .request('inbox.return', { session: session.session ?? null, workspace: session.workspace ?? null, messages: inbox })
242
+ .catch((error: unknown) => log(`open-artifacts inbox.return: ${messageOf(error)}`));
243
+ }
244
+ } catch (error) {
245
+ h.close();
246
+ throw error;
247
+ }
248
+ harness = h;
249
+ h.on('state', (state) => {
250
+ if (state === 'connected') void refresh(h);
251
+ });
252
+ await refresh(h);
253
+ return h;
254
+ };
255
+
256
+ /** The connection, made once (starting the daemon when none runs); a failure lets the next call try again. */
257
+ const connect = (): Promise<Harness> => {
258
+ if (closed) return Promise.reject(new Error('The Pi session ended.'));
259
+ pending ??= open().catch((error: unknown) => {
260
+ pending = null;
261
+ throw error;
262
+ });
263
+ return pending;
264
+ };
265
+
266
+ // ---- Pi's events ----
267
+
268
+ pi.on('session_start', (_event, c) => {
269
+ ctx = c;
270
+ session = callerOf(c);
271
+ // Only a daemon that already runs: the session takes the comments made while it was away, and new ones.
272
+ void readDaemon(options.home)
273
+ .then((state) => (state && !closed ? connect() : null))
274
+ .catch((error: unknown) => closed || log(`open-artifacts connect: ${messageOf(error)}`));
275
+ });
276
+
277
+ pi.on('session_shutdown', () => {
278
+ closed = true;
279
+ ctx = null;
280
+ harness?.close();
281
+ harness = null;
282
+ void pending?.then(
283
+ (h) => h.close(),
284
+ () => undefined,
285
+ );
286
+ });
287
+
288
+ pi.on('resources_discover', async () => {
289
+ try {
290
+ if (harness?.connected) await harness.installSkill({ dir: skillsDir, ...SKILL });
291
+ else await installSkill(null, { dir: skillsDir, ...SKILL });
292
+ } catch (error) {
293
+ log(`open-artifacts skill: ${messageOf(error)}`);
294
+ }
295
+ return { skillPaths: [skillsDir] };
296
+ });
297
+
298
+ pi.on('before_agent_start', (event) => {
299
+ const options = event.systemPromptOptions;
300
+ if (!options) return;
301
+ options.sections ??= {};
302
+ options.sections[PROMPT_SECTION] = prompt;
303
+ });
304
+
305
+ /**
306
+ * Runs `work` on the connection once it is made, if one is made or being made; never starts one. A call that the
307
+ * session's own shutdown cut off (Pi's last `idle` as it exits) is not an error.
308
+ */
309
+ const onceConnected = (what: string, work: (h: Harness) => Promise<unknown>): void => {
310
+ void pending
311
+ ?.then(work, () => undefined)
312
+ .catch((error: unknown) => closed || log(`open-artifacts ${what}: ${messageOf(error)}`));
313
+ };
314
+
315
+ const status = (state: 'running' | 'idle'): void => {
316
+ running = state === 'running';
317
+ onceConnected('status', (h) => h.status(session, state));
318
+ };
319
+ pi.on('agent_start', () => status('running'));
320
+ pi.on('agent_settled', () => status('idle'));
321
+
322
+ pi.on('tool_result', (event, c) => {
323
+ if (event.isError || (event.toolName !== 'write' && event.toolName !== 'edit')) return;
324
+ const path = event.input?.path;
325
+ if (typeof path !== 'string' || !path) return;
326
+ const paths = [absolutePath(path, c.cwd)];
327
+ const caller = callerOf(c);
328
+ onceConnected('wrote', (h) => h.wrote(paths, caller));
329
+ });
330
+
331
+ pi.registerCommand(COMMAND, {
332
+ description: 'Make an Open Artifacts: /open-artifacts <type> <what to make>',
333
+ getArgumentCompletions: (prefix) => {
334
+ const items: PiCompletion[] = commands
335
+ .map((entry) => ({ value: argumentOf(entry), label: entry.type, description: entry.title }))
336
+ .filter((item) => item.value.startsWith(prefix));
337
+ return items.length ? items : null;
338
+ },
339
+ handler: (args, c) => {
340
+ const text = `/skill:${COMMAND}${args.trim() ? ` ${args.trim()}` : ''}`;
341
+ if (c.isIdle()) pi.sendUserMessage(text, { expandPromptTemplates: true });
342
+ else pi.sendUserMessage(text, { expandPromptTemplates: true, deliverAs: 'followUp' });
343
+ },
344
+ });
345
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The Pi extension `pi-open-artifacts` loads (`package.json` → `pi.extensions`). See `extension.ts`.
3
+ */
4
+ import { openArtifacts } from './extension.ts';
5
+
6
+ export { openArtifacts, type OpenArtifactsPiOptions } from './extension.ts';
7
+
8
+ export default openArtifacts();
package/src/pi.ts ADDED
@@ -0,0 +1,241 @@
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
+ /** The model the session uses now (a live getter), or none when no model is set up. */
37
+ model?: PiModel | undefined;
38
+ /** Pi's models and their configured auth: a call made here is outside the session's conversation. */
39
+ modelRegistry?: PiModelRegistry;
40
+ }
41
+
42
+ // ---- models (`@earendil-works/pi-ai`, as `ctx.modelRegistry` hands them over) ----
43
+
44
+ /** A model Pi knows. */
45
+ export interface PiModel {
46
+ id: string;
47
+ name?: string;
48
+ provider: string;
49
+ /** The wire protocol Pi speaks to it (`anthropic-messages`, `openai-responses`, …). */
50
+ api?: string;
51
+ /** What it reads: `text`, and `image` when it takes images. */
52
+ input?: string[];
53
+ /** It can think before it answers. */
54
+ reasoning?: boolean;
55
+ maxTokens?: number;
56
+ }
57
+
58
+ /** How long a model thinks. */
59
+ export type PiThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
60
+
61
+ export interface PiImageContent {
62
+ type: 'image';
63
+ /** Base64 bytes. */
64
+ data: string;
65
+ mimeType: string;
66
+ }
67
+
68
+ export interface PiThinkingContent {
69
+ type: 'thinking';
70
+ thinking: string;
71
+ }
72
+
73
+ export interface PiToolCall {
74
+ type: 'toolCall';
75
+ id: string;
76
+ name: string;
77
+ arguments: Record<string, unknown>;
78
+ }
79
+
80
+ export interface PiUsage {
81
+ input: number;
82
+ output: number;
83
+ cacheRead?: number;
84
+ cacheWrite?: number;
85
+ totalTokens?: number;
86
+ }
87
+
88
+ export type PiStopReason = 'stop' | 'length' | 'toolUse' | 'error' | 'aborted';
89
+
90
+ export interface PiUserMessage {
91
+ role: 'user';
92
+ content: string | Array<PiTextContent | PiImageContent>;
93
+ timestamp: number;
94
+ }
95
+
96
+ export interface PiAssistantMessage {
97
+ role: 'assistant';
98
+ content: Array<PiTextContent | PiThinkingContent | PiToolCall>;
99
+ api?: string;
100
+ provider: string;
101
+ model: string;
102
+ usage: PiUsage;
103
+ stopReason: PiStopReason;
104
+ /** The provider's own stop reason, when it said one (`refusal`, `content_filter`, `SAFETY`, …). */
105
+ rawStopReason?: string;
106
+ errorMessage?: string;
107
+ timestamp: number;
108
+ }
109
+
110
+ export interface PiToolResultMessage {
111
+ role: 'toolResult';
112
+ toolCallId: string;
113
+ toolName: string;
114
+ content: PiTextContent[];
115
+ isError: boolean;
116
+ timestamp: number;
117
+ }
118
+
119
+ export type PiMessage = PiUserMessage | PiAssistantMessage | PiToolResultMessage;
120
+
121
+ /** What one model call reads. */
122
+ export interface PiLlmContext {
123
+ systemPrompt?: string;
124
+ messages: PiMessage[];
125
+ tools?: Array<{ name: string; description: string; parameters: unknown }>;
126
+ }
127
+
128
+ export interface PiStreamOptions {
129
+ signal?: AbortSignal;
130
+ maxTokens?: number;
131
+ reasoning?: PiThinkingLevel;
132
+ toolChoice?: 'auto' | 'none';
133
+ /** Neither use nor record the provider's server-side conversation state. */
134
+ disableContinuation?: boolean;
135
+ }
136
+
137
+ /** One event of a model call's stream (the ones this package reads; Pi sends more). */
138
+ export type PiStreamEvent =
139
+ | { type: 'text_delta'; delta: string }
140
+ | { type: 'toolcall_end'; toolCall: PiToolCall }
141
+ | { type: 'done'; reason: PiStopReason; message: PiAssistantMessage }
142
+ | { type: 'error'; reason: 'aborted' | 'error'; error: PiAssistantMessage }
143
+ | { type: string; [key: string]: unknown };
144
+
145
+ /** A model call's stream: its events, then `result()` with the final message. */
146
+ export interface PiEventStream extends AsyncIterable<PiStreamEvent> {
147
+ result(): Promise<PiAssistantMessage>;
148
+ }
149
+
150
+ export interface PiModelRegistry {
151
+ /** Streams one call with the model's configured auth. Throws when the model has no auth. */
152
+ streamSimple(model: PiModel, context: PiLlmContext, options?: PiStreamOptions): PiEventStream | Promise<PiEventStream>;
153
+ find?(provider: string, id: string): PiModel | undefined;
154
+ /** The models that have auth configured. */
155
+ getAvailable?(): PiModel[] | Promise<PiModel[]>;
156
+ }
157
+
158
+ /** A tool the model can call. */
159
+ export interface PiTool {
160
+ name: string;
161
+ label: string;
162
+ description: string;
163
+ /** JSON Schema of the arguments. */
164
+ parameters: unknown;
165
+ execute(
166
+ toolCallId: string,
167
+ params: Record<string, unknown>,
168
+ signal: AbortSignal | undefined,
169
+ onUpdate: ((partial: PiToolResult) => void) | undefined,
170
+ ctx: PiContext,
171
+ ): Promise<PiToolResult>;
172
+ }
173
+
174
+ /** One line of a command's argument completions. */
175
+ export interface PiCompletion {
176
+ value: string;
177
+ label: string;
178
+ description?: string;
179
+ }
180
+
181
+ /** A slash command. */
182
+ export interface PiCommand {
183
+ description?: string;
184
+ getArgumentCompletions?(prefix: string): PiCompletion[] | null | Promise<PiCompletion[] | null>;
185
+ handler(args: string, ctx: PiContext): void | Promise<void>;
186
+ }
187
+
188
+ /** A custom message: in the model's context, shown in the transcript when `display` is true. */
189
+ export interface PiCustomMessage {
190
+ customType: string;
191
+ content: string;
192
+ display: boolean;
193
+ details?: unknown;
194
+ }
195
+
196
+ /** How a message enters a session: steered into a running turn, after it, or with the next prompt. */
197
+ export type PiDelivery = 'steer' | 'followUp' | 'nextTurn';
198
+
199
+ export interface PiSessionStartEvent {
200
+ reason: 'startup' | 'reload' | 'new' | 'resume' | 'fork';
201
+ }
202
+
203
+ export interface PiSessionShutdownEvent {
204
+ reason: 'quit' | 'reload' | 'new' | 'resume' | 'fork';
205
+ }
206
+
207
+ export interface PiBeforeAgentStartEvent {
208
+ /** Mutable: Pi patches the model's prompt with what changed. `sections[tag]` is wrapped in `<tag>…</tag>`. */
209
+ systemPromptOptions: { sections?: Record<string, string> };
210
+ }
211
+
212
+ export interface PiToolResultEvent {
213
+ toolName: string;
214
+ input: Record<string, unknown>;
215
+ isError: boolean;
216
+ }
217
+
218
+ export interface PiResourcesDiscoverEvent {
219
+ cwd: string;
220
+ reason: 'startup' | 'reload';
221
+ }
222
+
223
+ export interface PiResources {
224
+ skillPaths?: string[];
225
+ promptPaths?: string[];
226
+ themePaths?: string[];
227
+ }
228
+
229
+ /** The `pi` object an extension's default export is called with. */
230
+ export interface PiExtensionAPI {
231
+ registerTool(tool: PiTool): void;
232
+ registerCommand(name: string, command: PiCommand): void;
233
+ sendMessage(message: PiCustomMessage, options?: { triggerTurn?: boolean; deliverAs?: PiDelivery }): void;
234
+ sendUserMessage(content: string, options?: { deliverAs?: 'steer' | 'followUp'; expandPromptTemplates?: boolean }): void;
235
+ on(event: 'session_start', handler: (event: PiSessionStartEvent, ctx: PiContext) => unknown): void;
236
+ on(event: 'session_shutdown', handler: (event: PiSessionShutdownEvent, ctx: PiContext) => unknown): void;
237
+ on(event: 'before_agent_start', handler: (event: PiBeforeAgentStartEvent, ctx: PiContext) => unknown): void;
238
+ on(event: 'agent_start' | 'agent_settled', handler: (event: unknown, ctx: PiContext) => unknown): void;
239
+ on(event: 'tool_result', handler: (event: PiToolResultEvent, ctx: PiContext) => unknown): void;
240
+ on(event: 'resources_discover', handler: (event: PiResourcesDiscoverEvent, ctx: PiContext) => PiResources | Promise<PiResources>): void;
241
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The Open Artifacts runtime this package carries: the `@openartifactsai/cli` dependency when installed from npm, else,
3
+ * inside the Open Artifacts 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 '@openartifactsai/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('@openartifactsai/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-artifacts');
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_ARTIFACTS_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
+ }
package/src/sample.ts ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Pages asking Pi's model for text (`sample.create`, one round at a time). The round goes straight to the model through
3
+ * `ctx.modelRegistry.streamSimple`, with the auth Pi already has: it is not a turn of the session, so it reads and
4
+ * writes no session history, Pi runs none of its tools, and page tools come back to the daemon as `toolCalls`.
5
+ */
6
+ import type { AdapterSampleCaps, SampleOptions, SampleRound, SampleRoundResult, SampleRunContext, SampleToolCall } from '@openartifactsai/harness-kit';
7
+ import type { PiAssistantMessage, PiContext, PiEventStream, PiLlmContext, PiMessage, PiModel, PiStreamOptions, PiTextContent, PiImageContent, PiToolCall } from './pi.ts';
8
+
9
+ /** An error the kit answers as a refusal with this code. */
10
+ const refuse = (code: 'rate_limited' | 'unavailable' | 'session_expired' | 'prompt_too_large', message: string): Error => Object.assign(new Error(message), { code });
11
+
12
+ /** A context-window overflow, in the words providers use for it (the unambiguous patterns of pi-ai's `isContextOverflow`). */
13
+ const CONTEXT_OVERFLOW = /prompt (?:is )?too long|prompt exceeds max length|\brequest_too_large\b|input is too long for requested model|exceeds the context window|maximum context length|context window exceeded|context.?length.?exceeded|input token count.*exceeds the maximum|maximum prompt length is \d+|reduce the length of the messages|maximum allowed input length|longer than the model'?s context length|exceeds the available context size|greater than the context length|context window exceeds limit|exceeded model token limit/i;
14
+
15
+ const abortError = (): Error => Object.assign(new Error('The round was cancelled.'), { name: 'AbortError' });
16
+
17
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
18
+
19
+ /**
20
+ * The provider's words, read for the refusals a page can act on: a context overflow, a rate limit, a sign-in or key
21
+ * that is missing or was rejected (`session_expired`: the person signs in to Pi again); anything else is a failed round.
22
+ */
23
+ export function piFailure(message: string): Error {
24
+ if (CONTEXT_OVERFLOW.test(message)) return refuse('prompt_too_large', message);
25
+ if (/\b429\b|rate.?limit|too many requests|quota/i.test(message)) return refuse('rate_limited', message);
26
+ if (/\b40[13]\b|unauthori[sz]ed|forbidden|api.?key|credential|not logged in|log ?in|authenticat|no auth/i.test(message)) return refuse('session_expired', message);
27
+ return new Error(message);
28
+ }
29
+
30
+ /** Provider stop reasons that mean the model declined. */
31
+ const REFUSAL = /refus|content.?filter|safety|blocked|prohibited/i;
32
+
33
+ /** Whether the model reads images. */
34
+ const takesImages = (model: PiModel | undefined): boolean => Array.isArray(model?.input) && model.input.includes('image');
35
+
36
+ /** The model a round names, when Pi has it with auth: `provider/id`, or an id alone. */
37
+ async function namedModel(ctx: PiContext, name: string): Promise<PiModel | undefined> {
38
+ const registry = ctx.modelRegistry;
39
+ if (!registry) return undefined;
40
+ const available = (await registry.getAvailable?.()) ?? [];
41
+ const slash = name.indexOf('/');
42
+ if (slash > 0) {
43
+ const provider = name.slice(0, slash);
44
+ const id = name.slice(slash + 1);
45
+ const found = available.find((m) => m.provider === provider && m.id === id);
46
+ if (found) return found;
47
+ }
48
+ return available.find((m) => m.id === name);
49
+ }
50
+
51
+ /** The round's turns as Pi's messages. A tool result names its tool, so the calls before it are remembered. */
52
+ export function piMessages(turns: SampleRound['turns'], model: PiModel): PiMessage[] {
53
+ const names = new Map<string, string>();
54
+ const at = Date.now();
55
+ const messages: PiMessage[] = [];
56
+ for (const turn of turns) {
57
+ if (turn.role === 'user') {
58
+ const images = turn.images ?? [];
59
+ const content: string | Array<PiTextContent | PiImageContent> = images.length
60
+ ? [{ type: 'text', text: turn.content }, ...images.map((image): PiImageContent => ({ type: 'image', data: image.data, mimeType: image.mediaType }))]
61
+ : turn.content;
62
+ messages.push({ role: 'user', content, timestamp: at });
63
+ } else if (turn.role === 'assistant') {
64
+ const calls = turn.toolCalls ?? [];
65
+ for (const call of calls) names.set(call.id, call.name);
66
+ messages.push({
67
+ role: 'assistant',
68
+ content: [
69
+ ...(turn.content ? [{ type: 'text', text: turn.content } as PiTextContent] : []),
70
+ ...calls.map((call): PiToolCall => ({ type: 'toolCall', id: call.id, name: call.name, arguments: call.input ?? {} })),
71
+ ],
72
+ ...(model.api ? { api: model.api } : {}),
73
+ provider: model.provider,
74
+ model: model.id,
75
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 },
76
+ stopReason: calls.length ? 'toolUse' : 'stop',
77
+ timestamp: at,
78
+ });
79
+ } else {
80
+ for (const result of turn.results) {
81
+ messages.push({
82
+ role: 'toolResult',
83
+ toolCallId: result.id,
84
+ toolName: names.get(result.id) ?? '',
85
+ content: [{ type: 'text', text: result.content }],
86
+ isError: result.isError === true,
87
+ timestamp: at,
88
+ });
89
+ }
90
+ }
91
+ }
92
+ return messages;
93
+ }
94
+
95
+ /** Reads the stream to its end, handing text over as it comes; a cancel stops the wait at once. */
96
+ async function drain(stream: PiEventStream, onText: (delta: string) => void, signal: AbortSignal): Promise<{ text: string; final: PiAssistantMessage | undefined }> {
97
+ let text = '';
98
+ let final: PiAssistantMessage | undefined;
99
+ const read = (async () => {
100
+ for await (const event of stream) {
101
+ if (signal.aborted) break;
102
+ if (event.type === 'text_delta' && typeof event.delta === 'string' && event.delta) {
103
+ text += event.delta;
104
+ onText(event.delta);
105
+ } else if (event.type === 'done') final = event.message as PiAssistantMessage;
106
+ else if (event.type === 'error') final = event.error as PiAssistantMessage;
107
+ }
108
+ })();
109
+ let onAbort = (): void => undefined;
110
+ const aborted = new Promise<never>((_, reject) => {
111
+ onAbort = () => reject(abortError());
112
+ if (signal.aborted) onAbort();
113
+ else signal.addEventListener('abort', onAbort, { once: true });
114
+ });
115
+ aborted.catch(() => undefined);
116
+ try {
117
+ await Promise.race([read, aborted]);
118
+ } finally {
119
+ signal.removeEventListener('abort', onAbort);
120
+ }
121
+ if (signal.aborted) throw abortError();
122
+ final ??= await stream.result();
123
+ return { text, final };
124
+ }
125
+
126
+ /** One round on Pi's model. */
127
+ export async function runPiRound(ctx: PiContext | null, round: SampleRound, { onText, signal }: SampleRunContext): Promise<SampleRoundResult> {
128
+ if (!ctx?.modelRegistry) throw refuse('unavailable', 'This Pi session is over, or this Pi cannot call its model for an extension.');
129
+ const registry = ctx.modelRegistry;
130
+ const model = (round.model ? await namedModel(ctx, round.model) : undefined) ?? ctx.model;
131
+ if (!model) throw refuse('unavailable', 'Pi has no model set up: choose one with /model.');
132
+ if (round.turns.some((turn) => turn.role === 'user' && turn.images?.length) && !takesImages(model)) {
133
+ throw refuse('unavailable', `${model.id} does not read images.`);
134
+ }
135
+
136
+ const hasToolTurns = round.turns.some((turn) => turn.role === 'tool');
137
+ // The last round answers: its tools stay only so the earlier calls read right, and the model may not call them.
138
+ const tools = round.tools?.length && (!round.lastRound || hasToolTurns) ? round.tools : undefined;
139
+ const context: PiLlmContext = {
140
+ ...(round.system ? { systemPrompt: round.system } : {}),
141
+ messages: piMessages(round.turns, model),
142
+ ...(tools ? { tools: tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.inputSchema ?? { type: 'object', properties: {} } })) } : {}),
143
+ };
144
+ const maxTokens = model.maxTokens && model.maxTokens > 0 ? Math.min(round.maxOutputTokens, model.maxTokens) : round.maxOutputTokens;
145
+ const options: PiStreamOptions = {
146
+ signal,
147
+ maxTokens,
148
+ disableContinuation: true,
149
+ ...(round.effort && model.reasoning ? { reasoning: round.effort } : {}),
150
+ ...(tools && round.lastRound ? { toolChoice: 'none' as const } : {}),
151
+ };
152
+
153
+ let stream: PiEventStream;
154
+ try {
155
+ stream = await registry.streamSimple(model, context, options);
156
+ } catch (error) {
157
+ if (signal.aborted) throw abortError();
158
+ throw piFailure(messageOf(error));
159
+ }
160
+ const { text: streamed, final } = await drain(stream, onText, signal);
161
+ if (!final) throw new Error(`${model.id} ended without an answer.`);
162
+ if (final.stopReason === 'aborted') throw signal.aborted ? abortError() : new Error(final.errorMessage || `${model.id} stopped the answer.`);
163
+ if (final.stopReason === 'error') throw piFailure(final.errorMessage || `${model.id} failed.`);
164
+
165
+ let text = streamed;
166
+ if (!text) {
167
+ // A provider that does not stream: the answer comes whole.
168
+ text = final.content.filter((block): block is PiTextContent => block.type === 'text').map((block) => block.text).join('');
169
+ if (text) onText(text);
170
+ }
171
+ const toolCalls: SampleToolCall[] = final.content
172
+ .filter((block): block is PiToolCall => block.type === 'toolCall')
173
+ .map((call) => ({ id: call.id, name: call.name, input: call.arguments && typeof call.arguments === 'object' ? call.arguments : {} }));
174
+ const stop: SampleRoundResult['stop'] =
175
+ final.rawStopReason && REFUSAL.test(final.rawStopReason) ? 'refusal' : toolCalls.length ? 'tools' : final.stopReason === 'length' ? 'length' : 'end';
176
+ const usage = final.usage;
177
+ return {
178
+ text: stop === 'refusal' ? '' : text,
179
+ stop,
180
+ ...(toolCalls.length && stop === 'tools' ? { toolCalls } : {}),
181
+ model: final.model || model.id,
182
+ ...(usage && typeof usage.input === 'number' && typeof usage.output === 'number'
183
+ ? { usage: { input: usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0), output: usage.output } }
184
+ : {}),
185
+ };
186
+ }
187
+
188
+ /**
189
+ * The `sample` option of `createHarness`, or none when this Pi has no `ctx.modelRegistry`. One tier (the session's
190
+ * model, which `inherit` also names); images only when that model reads them as the connection opens.
191
+ */
192
+ export function piSample(context: () => PiContext | null): SampleOptions | undefined {
193
+ const ctx = context();
194
+ if (!ctx?.modelRegistry) return undefined;
195
+ const caps: AdapterSampleCaps = { tiers: ['default'], inherit: true, stream: true, tools: true, ...(takesImages(ctx.model) ? { images: true } : {}) };
196
+ return { caps, run: (round, run) => runPiRound(context(), round, run) };
197
+ }