pi-open-artifact 0.18.0 → 0.19.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/README.md CHANGED
@@ -41,6 +41,21 @@ To try it for one run without installing it, use `pi -e ./plugins/pi`. Upgrade w
41
41
  Pi has no page view of its own: `Artifact {action: "open"}` opens the page in the computer's browser, and the agent
42
42
  gives you its `view_url` too.
43
43
 
44
+ ## Pages that ask a model
45
+
46
+ A page can ask a model for text (`sample`). When you pick Pi as the page's model source, Pi answers with the model
47
+ 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
48
+ model at all, and the Shell shows how much each artifact has used. When Pi's key or login is missing or rejected, the
49
+ page tells you to sign in to Pi again; when its text does not fit the model's context, it says so.
50
+
51
+ The request goes straight to the model, outside the session: it is not added to the conversation, and Pi runs none of
52
+ its own tools for it (a page's tools run in the page). Limits:
53
+
54
+ - One model: the session's (`/model` changes it). There are no separate fast or most capable ones; a page that asks
55
+ for one gets the session's model.
56
+ - Images only when that model reads them, as of when Pi connected to Open Artifact.
57
+ - An older Pi without `ctx.modelRegistry` does not offer this.
58
+
44
59
  ## Where artifacts go
45
60
 
46
61
  New artifacts go under your own Open Artifact folder, one folder per project: `~/OpenArtifact/<project>/<slug>`. Pi
package/README.zh-CN.md CHANGED
@@ -35,6 +35,16 @@ pi install ./plugins/pi
35
35
 
36
36
  Pi 没有自己的页面视图:`Artifact {action: "open"}` 在电脑的浏览器里打开页面,agent 也会把 `view_url` 给你。
37
37
 
38
+ ## 向模型提问的页面
39
+
40
+ 页面可以向模型要一段文字(`sample`)。你为页面选 Pi 作为模型来源时,Pi 用当前会话的模型、用 Pi 已有的密钥或登录来回答,不用另外设置。页面要用模型之前都会先问你,Shell 里能看到每个作品用了多少。Pi 的密钥或登录缺失、被拒时,页面会提示你重新登录 Pi;页面的文字超出模型的上下文时,页面也会说明。
41
+
42
+ 请求直接发给模型,不经过会话:不进入对话记录,Pi 也不为它运行自己的任何工具(页面的工具在页面里运行)。限制:
43
+
44
+ - 只有一个模型:会话正在用的那个(用 `/model` 换)。没有单独的快速模型或最强模型;页面要它们时,用的仍是会话的模型。
45
+ - 只有在 Pi 连上 Open Artifact 时会话的模型能读图片,才接收图片。
46
+ - 没有 `ctx.modelRegistry` 的旧版 Pi 不提供这项功能。
47
+
38
48
  ## 它怎样启动 daemon
39
49
 
40
50
  从不做作品的 Pi 会话什么也不启动。会话开始时如果已有 daemon 在运行,会话就连上并 attach,评论能送到它。否则,第一次调用 Open Artifact 工具时,启动这台电脑上最新的兼容运行时(本包的 `@open-artifact/cli` 是其中之一)并连接。重连后会话会再次 attach。`/new`、`/resume`、`/fork` 和 `/reload` 会关闭旧会话的连接,新会话自己建立连接。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-open-artifact",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
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
5
  "type": "module",
6
6
  "keywords": [
@@ -25,9 +25,9 @@
25
25
  ]
26
26
  },
27
27
  "dependencies": {
28
- "@open-artifact/cli": "0.18.0",
29
- "@open-artifact/harness-kit": "0.18.0",
30
- "@open-artifact/protocol": "0.18.0"
28
+ "@open-artifact/cli": "0.19.0",
29
+ "@open-artifact/harness-kit": "0.19.0",
30
+ "@open-artifact/protocol": "0.19.0"
31
31
  },
32
32
  "engines": {
33
33
  "node": ">=22.19"
package/src/extension.ts CHANGED
@@ -12,6 +12,8 @@
12
12
  * through `resources_discover`; `/open-artifact <type> <what to make>` with the installed types as completions.
13
13
  * - The session's state (`running` / `idle`) and the files Pi's own `write` and `edit` tools wrote (`agent.wrote`), so
14
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`).
15
17
  *
16
18
  * The daemon is only started by a tool call: a session that never makes an artifact starts nothing. When a daemon
17
19
  * already runs, the session connects at start so comments reach it.
@@ -22,6 +24,7 @@ import { createHarness, installSkill, openArtifactHome, readDaemon, renderSkill,
22
24
  import { AGENT_PROMPT, TOOL_DEFINITIONS, toolCallContent, type CommandEntry, type SessionParams, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverStatus } from '@open-artifact/protocol';
23
25
  import type { PiCompletion, PiContext, PiExtensionAPI, PiTextContent, PiToolResult } from './pi.ts';
24
26
  import { hostRuntime } from './runtime.ts';
27
+ import { piSample } from './sample.ts';
25
28
 
26
29
  /** The harness name: the daemon's profile `pi` (packages/daemon/harnesses/pi.json). */
27
30
  export const HARNESS = 'pi';
@@ -208,6 +211,8 @@ function setup(pi: PiExtensionAPI, options: OpenArtifactPiOptions): void {
208
211
 
209
212
  const open = async (): Promise<Harness> => {
210
213
  const runtime = options.runtime === undefined ? hostRuntime() : options.runtime;
214
+ // Pages may ask the session's model for text, outside the session's conversation.
215
+ const sample = piSample(() => ctx);
211
216
  const h = await createHarness({
212
217
  harness: HARNESS,
213
218
  agentName: AGENT_NAME,
@@ -216,6 +221,7 @@ function setup(pi: PiExtensionAPI, options: OpenArtifactPiOptions): void {
216
221
  profile: { ...PROFILE, markers: [...PROFILE.markers], wake: [...PROFILE.wake] },
217
222
  wake,
218
223
  log,
224
+ ...(sample ? { sample } : {}),
219
225
  ...(options.home ? { home: options.home } : {}),
220
226
  ...(runtime ? { runtime } : {}),
221
227
  });
package/src/pi.ts CHANGED
@@ -33,6 +33,126 @@ export interface PiContext {
33
33
  /** False while Pi runs the agent, retries, compacts or continues with queued messages. */
34
34
  isIdle(): boolean;
35
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[]>;
36
156
  }
37
157
 
38
158
  /** A tool the model can call. */
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 '@open-artifact/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
+ }