omp-open-artifact 0.17.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 +17 -0
- package/README.zh-CN.md +10 -0
- package/package.json +4 -4
- package/skills/open-artifact/SKILL.md +1 -1
- package/src/extension.ts +9 -1
- package/src/omp.ts +129 -0
- package/src/sample.ts +217 -0
package/README.md
CHANGED
|
@@ -43,6 +43,23 @@ To try it for one run without installing it, use `omp -e ./plugins/omp`. Upgrade
|
|
|
43
43
|
OMP has no page view of its own: `Artifact {action: "open"}` opens the page in the computer's browser, and the agent
|
|
44
44
|
gives you its `view_url` too.
|
|
45
45
|
|
|
46
|
+
## Pages that ask a model
|
|
47
|
+
|
|
48
|
+
A page can ask a model for text (`sample`). When you pick OMP as the page's model source, OMP answers with its own
|
|
49
|
+
models and the keys or logins it already has: nothing new to set up. You are asked before a page can use a model at
|
|
50
|
+
all, and the Shell shows how much each artifact has used. When OMP's key or login is missing or rejected, the page
|
|
51
|
+
tells you to sign in to OMP again; when its text does not fit the model's context, it says so.
|
|
52
|
+
|
|
53
|
+
The request goes straight to the model, outside the session: it is not added to the conversation, no provider-side
|
|
54
|
+
thread is kept, and OMP runs none of its own tools for it (a page's tools run in the page). A page's fast tier uses
|
|
55
|
+
your `smol` role, its most capable tier your `slow` role, and its default tier your `default` role (else the session's
|
|
56
|
+
model); "the model you use" is the session's. Limits:
|
|
57
|
+
|
|
58
|
+
- The tiers offered are the roles your settings name when OMP connects to Open Artifact.
|
|
59
|
+
- Images only when the session's model reads them, as of that moment; a role's model that does not read them refuses
|
|
60
|
+
them.
|
|
61
|
+
- An OMP without `ctx.models` and `ctx.modelRegistry` does not offer this.
|
|
62
|
+
|
|
46
63
|
## Where artifacts go
|
|
47
64
|
|
|
48
65
|
New artifacts go under your own Open Artifact folder, one folder per project: `~/OpenArtifact/<project>/<slug>`. OMP
|
package/README.zh-CN.md
CHANGED
|
@@ -37,6 +37,16 @@ omp plugin install ./plugins/omp
|
|
|
37
37
|
|
|
38
38
|
OMP 没有自己的页面视图:`Artifact {action: "open"}` 在电脑的浏览器里打开页面,agent 也会把 `view_url` 给你。
|
|
39
39
|
|
|
40
|
+
## 向模型提问的页面
|
|
41
|
+
|
|
42
|
+
页面可以向模型要一段文字(`sample`)。你为页面选 OMP 作为模型来源时,OMP 用它自己的模型、用它已有的密钥或登录来回答,不用另外设置。页面要用模型之前都会先问你,Shell 里能看到每个作品用了多少。OMP 的密钥或登录缺失、被拒时,页面会提示你重新登录 OMP;页面的文字超出模型的上下文时,页面也会说明。
|
|
43
|
+
|
|
44
|
+
请求直接发给模型,不经过会话:不进入对话记录,不在服务商那边续接对话,OMP 也不为它运行自己的任何工具(页面的工具在页面里运行)。页面的快速档用你的 `smol` 角色,最强档用 `slow` 角色,默认档用 `default` 角色(没有时用会话的模型);"你正在用的模型"就是会话的模型。限制:
|
|
45
|
+
|
|
46
|
+
- 提供哪些档,取决于 OMP 连上 Open Artifact 时你的设置里配了哪些角色。
|
|
47
|
+
- 只有那时会话的模型能读图片,才接收图片;某个角色的模型读不了图片时会拒绝。
|
|
48
|
+
- 没有 `ctx.models` 和 `ctx.modelRegistry` 的 OMP 不提供这项功能。
|
|
49
|
+
|
|
40
50
|
## 作品放在哪里
|
|
41
51
|
|
|
42
52
|
新作品放在你自己的 Open Artifact 文件夹里,一个项目一个文件夹:`~/OpenArtifact/<项目>/<slug>`。OMP 允许它的 agent 写这里,仓库保持干净。想放回项目里(`<会话所在文件夹>/artifacts/<slug>`),在终端运行 `open-artifact config set artifactsLocation workspace`,只对当前项目生效加 `--local`。见 [设置](../../docs/settings.zh-CN.md)。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omp-open-artifact",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"description": "Open Artifact in OMP: the Artifact, ArtifactData and ArtifactComments tools, comments on artifact pages waking the OMP session that made them, the open-artifact skill, and /open-artifact <type> to make a new one.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -26,9 +26,9 @@
|
|
|
26
26
|
]
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@open-artifact/cli": "0.
|
|
30
|
-
"@open-artifact/harness-kit": "0.
|
|
31
|
-
"@open-artifact/protocol": "0.
|
|
29
|
+
"@open-artifact/cli": "0.19.0",
|
|
30
|
+
"@open-artifact/harness-kit": "0.19.0",
|
|
31
|
+
"@open-artifact/protocol": "0.19.0"
|
|
32
32
|
},
|
|
33
33
|
"engines": {
|
|
34
34
|
"bun": ">=1.4.4"
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: open-artifact
|
|
3
3
|
description: Make an Open Artifact (a slide deck, a design canvas, a whiteboard, a data dashboard, a doc, a short animated motion piece, …) as a folder of files that opens as a live local page where the person views, edits, comments and exports, with their comments coming back to you. Use when the person types `/open-artifact <type> <what to make>`, or asks for something they will look at closely, keep, change, comment on or present - a presentation, pitch or talk deck; app screens, a mockup, a landing page, a poster, flyer or graphic, or "a few options" to look at; a brainstorm or retro board, a flowchart or an architecture sketch; a dashboard, metrics page, KPI tracker or recurring report from their data; a document, report, proposal, plan, spec, memo, notes or other writing to keep, share or comment on; a short animated video, an explainer, a promo, motion graphics or a GIF; a widget or mini game - or asks to keep or share a diagram you drew. Not for answers read once, code, or a file in a format they named.
|
|
4
4
|
argument-hint: <type> <what to make>
|
|
5
|
-
generated-by: open-artifact 0.
|
|
5
|
+
generated-by: open-artifact 0.19.0
|
|
6
6
|
etag: 060ad4fa66ebeae3
|
|
7
7
|
---
|
|
8
8
|
|
package/src/extension.ts
CHANGED
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
* the skill and the request as one user message (OMP does not expand prompt templates in `sendUserMessage`).
|
|
17
17
|
* - The session's state (`running` / `idle`) and the files OMP's own `write` and `edit` tools wrote (`agent.wrote`), so
|
|
18
18
|
* open pages follow at once.
|
|
19
|
+
* - Pages asking a model for text (`sample.create`), answered with OMP's models and auth, outside the session's
|
|
20
|
+
* conversation (`src/sample.ts`).
|
|
19
21
|
*
|
|
20
22
|
* The daemon is only started by a tool call: a session that never makes an artifact starts nothing. When a daemon
|
|
21
23
|
* already runs, the session connects at start so comments reach it.
|
|
@@ -26,8 +28,9 @@ import { join, resolve } from 'node:path';
|
|
|
26
28
|
import { fileURLToPath } from 'node:url';
|
|
27
29
|
import { createHarness, installSkill, localSkill, readDaemon, renderSkill, type Harness, type InstallSkillOptions } from '@open-artifact/harness-kit';
|
|
28
30
|
import { AGENT_PROMPT, TOOL_DEFINITIONS, toolCallContent, type CommandEntry, type SessionParams, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverStatus } from '@open-artifact/protocol';
|
|
29
|
-
import type { OmpAgentEndEvent, OmpCompletion, OmpContext, OmpExtensionAPI, OmpTextContent, OmpToolResult } from './omp.ts';
|
|
31
|
+
import type { OmpAgentEndEvent, OmpAi, OmpCompletion, OmpContext, OmpExtensionAPI, OmpTextContent, OmpToolResult } from './omp.ts';
|
|
30
32
|
import { hostRuntime } from './runtime.ts';
|
|
33
|
+
import { hostAi, ompSample } from './sample.ts';
|
|
31
34
|
|
|
32
35
|
/** The harness name: the daemon's profile `omp` (packages/daemon/harnesses/omp.json). */
|
|
33
36
|
export const HARNESS = 'omp';
|
|
@@ -74,6 +77,8 @@ export interface OpenArtifactOmpOptions {
|
|
|
74
77
|
refusalWindowMs?: number;
|
|
75
78
|
/** Diagnostic log (default: stderr when `OMP_OPEN_ARTIFACT_DEBUG` is set). */
|
|
76
79
|
log?: (line: string) => void;
|
|
80
|
+
/** OMP's model library, which pages' model rounds call (default: the one OMP serves, `@oh-my-pi/pi-ai`). */
|
|
81
|
+
ai?: () => Promise<OmpAi>;
|
|
77
82
|
}
|
|
78
83
|
|
|
79
84
|
/** A path as OMP's file tools take it (`@` prefix, `~`), made absolute against the session's folder. */
|
|
@@ -287,6 +292,8 @@ function setup(omp: OmpExtensionAPI, options: OpenArtifactOmpOptions): void {
|
|
|
287
292
|
|
|
288
293
|
const open = async (): Promise<Harness> => {
|
|
289
294
|
const runtime = options.runtime === undefined ? hostRuntime() : options.runtime;
|
|
295
|
+
// Pages may ask the session's model for text, outside the session's conversation.
|
|
296
|
+
const sample = ompSample(() => ctx, options.ai ?? hostAi);
|
|
290
297
|
const h = await createHarness({
|
|
291
298
|
harness: HARNESS,
|
|
292
299
|
agentName: AGENT_NAME,
|
|
@@ -295,6 +302,7 @@ function setup(omp: OmpExtensionAPI, options: OpenArtifactOmpOptions): void {
|
|
|
295
302
|
profile: { ...PROFILE, markers: [...PROFILE.markers], wake: [...PROFILE.wake] },
|
|
296
303
|
wake,
|
|
297
304
|
log,
|
|
305
|
+
...(sample ? { sample } : {}),
|
|
298
306
|
...(options.home ? { home: options.home } : {}),
|
|
299
307
|
...(runtime ? { runtime } : {}),
|
|
300
308
|
});
|
package/src/omp.ts
CHANGED
|
@@ -32,6 +32,135 @@ export interface OmpContext {
|
|
|
32
32
|
sessionManager: OmpSessionManager;
|
|
33
33
|
/** False while OMP runs the agent, retries, compacts or continues with queued messages. */
|
|
34
34
|
isIdle(): boolean;
|
|
35
|
+
/** The session's model now, or none when no model is set up. */
|
|
36
|
+
model?: OmpModel | undefined;
|
|
37
|
+
/** OMP's models and their auth: here, only to read a model's key and headers. */
|
|
38
|
+
modelRegistry?: OmpModelRegistry;
|
|
39
|
+
/** Model lookups as OMP's own selection does them: role aliases (`@smol`, `@slow`), `provider/id`, bare ids. */
|
|
40
|
+
models?: OmpModelQuery;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ---- models (`@oh-my-pi/pi-ai`, which OMP serves to an extension that imports it) ----
|
|
44
|
+
|
|
45
|
+
/** A model OMP knows. */
|
|
46
|
+
export interface OmpModel {
|
|
47
|
+
id: string;
|
|
48
|
+
name?: string;
|
|
49
|
+
provider: string;
|
|
50
|
+
/** The wire protocol OMP speaks to it. */
|
|
51
|
+
api?: string;
|
|
52
|
+
/** What it reads: `text`, and `image` when it takes images. */
|
|
53
|
+
input?: string[];
|
|
54
|
+
/** It can think before it answers. */
|
|
55
|
+
reasoning?: boolean;
|
|
56
|
+
maxTokens?: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** How long a model thinks. */
|
|
60
|
+
export type OmpEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
61
|
+
|
|
62
|
+
export interface OmpImageContent {
|
|
63
|
+
type: 'image';
|
|
64
|
+
/** Base64 bytes. */
|
|
65
|
+
data: string;
|
|
66
|
+
mimeType: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface OmpToolCall {
|
|
70
|
+
type: 'toolCall';
|
|
71
|
+
id: string;
|
|
72
|
+
name: string;
|
|
73
|
+
arguments: Record<string, unknown>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface OmpUsage {
|
|
77
|
+
input: number;
|
|
78
|
+
output: number;
|
|
79
|
+
cacheRead?: number;
|
|
80
|
+
cacheWrite?: number;
|
|
81
|
+
totalTokens?: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export type OmpStopReason = 'stop' | 'length' | 'toolUse' | 'error' | 'aborted';
|
|
85
|
+
|
|
86
|
+
export interface OmpUserMessage {
|
|
87
|
+
role: 'user';
|
|
88
|
+
content: string | Array<OmpTextContent | OmpImageContent>;
|
|
89
|
+
timestamp: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface OmpAssistantMessage {
|
|
93
|
+
role: 'assistant';
|
|
94
|
+
content: Array<OmpTextContent | OmpToolCall | { type: string; [key: string]: unknown }>;
|
|
95
|
+
api?: string;
|
|
96
|
+
provider: string;
|
|
97
|
+
model: string;
|
|
98
|
+
usage: OmpUsage;
|
|
99
|
+
stopReason: OmpStopReason;
|
|
100
|
+
/** Why the provider stopped, when it said (Anthropic's `{type: 'refusal'}`). */
|
|
101
|
+
stopDetails?: { type?: string; [key: string]: unknown } | null;
|
|
102
|
+
errorMessage?: string;
|
|
103
|
+
/** The HTTP status of a failed request. */
|
|
104
|
+
errorStatus?: number;
|
|
105
|
+
timestamp: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface OmpToolResultMessage {
|
|
109
|
+
role: 'toolResult';
|
|
110
|
+
toolCallId: string;
|
|
111
|
+
toolName: string;
|
|
112
|
+
content: OmpTextContent[];
|
|
113
|
+
isError: boolean;
|
|
114
|
+
timestamp: number;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export type OmpMessage = OmpUserMessage | OmpAssistantMessage | OmpToolResultMessage;
|
|
118
|
+
|
|
119
|
+
/** What one model call reads. OMP's system prompt is a list of blocks. */
|
|
120
|
+
export interface OmpLlmContext {
|
|
121
|
+
systemPrompt?: string[];
|
|
122
|
+
messages: OmpMessage[];
|
|
123
|
+
tools?: Array<{ name: string; description: string; parameters: unknown }>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface OmpStreamOptions {
|
|
127
|
+
apiKey?: string;
|
|
128
|
+
headers?: Record<string, string>;
|
|
129
|
+
signal?: AbortSignal;
|
|
130
|
+
maxTokens?: number;
|
|
131
|
+
reasoning?: OmpEffort;
|
|
132
|
+
toolChoice?: 'auto' | 'none';
|
|
133
|
+
/** `false`: no server-side turn chaining (OpenAI's `previous_response_id`, Anthropic's threads). */
|
|
134
|
+
statefulResponses?: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** One event of a model call's stream (the ones this package reads; OMP sends more). */
|
|
138
|
+
export type OmpStreamEvent =
|
|
139
|
+
| { type: 'text_delta'; delta: string }
|
|
140
|
+
| { type: 'done'; reason: OmpStopReason; message: OmpAssistantMessage }
|
|
141
|
+
| { type: 'error'; reason: 'aborted' | 'error'; error: OmpAssistantMessage }
|
|
142
|
+
| { type: string; [key: string]: unknown };
|
|
143
|
+
|
|
144
|
+
/** A model call's stream: its events, then `result()` with the final message. */
|
|
145
|
+
export interface OmpEventStream extends AsyncIterable<OmpStreamEvent> {
|
|
146
|
+
result(): Promise<OmpAssistantMessage>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The part of `@oh-my-pi/pi-ai` this package calls. */
|
|
150
|
+
export interface OmpAi {
|
|
151
|
+
streamSimple(model: OmpModel, context: OmpLlmContext, options?: OmpStreamOptions): OmpEventStream;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface OmpModelRegistry {
|
|
155
|
+
getApiKeyAndHeaders(model: OmpModel): Promise<{ ok: true; apiKey: string; headers?: Record<string, string> } | { ok: false; error: string }>;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface OmpModelQuery {
|
|
159
|
+
/** Authenticated models available this session. */
|
|
160
|
+
list(): OmpModel[];
|
|
161
|
+
current(): OmpModel | undefined;
|
|
162
|
+
/** A model string or role alias → a model, or undefined when nothing matches. */
|
|
163
|
+
resolve(spec: string): OmpModel | undefined;
|
|
35
164
|
}
|
|
36
165
|
|
|
37
166
|
/** How a tool is presented when enabled: `essential` stays top-level, `discoverable` is hidden until found. */
|
package/src/sample.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pages asking OMP's model for text (`sample.create`, one round at a time). The round goes straight to the model
|
|
3
|
+
* through `streamSimple` of `@oh-my-pi/pi-ai` (the copy OMP serves to an extension that imports it), with the key and
|
|
4
|
+
* headers `ctx.modelRegistry` has for that model. It is not a turn of the session: it reads and writes no session
|
|
5
|
+
* history, chains no server-side state, OMP runs none of its tools, and page tools come back to the daemon as
|
|
6
|
+
* `toolCalls`.
|
|
7
|
+
*/
|
|
8
|
+
import type { AdapterSampleCaps, SampleOptions, SampleRound, SampleRoundResult, SampleRunContext, SampleToolCall } from '@open-artifact/harness-kit';
|
|
9
|
+
import type { ModelTier } from '@open-artifact/protocol';
|
|
10
|
+
import type { OmpAi, OmpAssistantMessage, OmpContext, OmpEventStream, OmpImageContent, OmpLlmContext, OmpMessage, OmpModel, OmpStreamOptions, OmpTextContent, OmpToolCall } from './omp.ts';
|
|
11
|
+
|
|
12
|
+
/** OMP's model library, as OMP serves it to an extension (its loader maps this specifier to its bundled copy). */
|
|
13
|
+
export const hostAi = (): Promise<OmpAi> =>
|
|
14
|
+
// @ts-ignore: provided by OMP at load time; this package does not depend on it.
|
|
15
|
+
import('@oh-my-pi/pi-ai') as Promise<OmpAi>;
|
|
16
|
+
|
|
17
|
+
/** The role alias OMP's settings give each tier: `smol` (fast), `default`, `slow` (thinks longest). */
|
|
18
|
+
export const TIER_ROLES: Readonly<Record<ModelTier, string>> = Object.freeze({ quick: '@smol', default: '@default', complex: '@slow' });
|
|
19
|
+
|
|
20
|
+
/** An error the kit answers as a refusal with this code. */
|
|
21
|
+
const refuse = (code: 'rate_limited' | 'unavailable' | 'session_expired' | 'prompt_too_large', message: string): Error => Object.assign(new Error(message), { code });
|
|
22
|
+
|
|
23
|
+
/** A context-window overflow, in the words providers use for it (the unambiguous patterns of pi-ai's `isContextOverflow`). */
|
|
24
|
+
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;
|
|
25
|
+
|
|
26
|
+
const abortError = (): Error => Object.assign(new Error('The round was cancelled.'), { name: 'AbortError' });
|
|
27
|
+
|
|
28
|
+
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A failed request, read for the refusals a page can act on: a context overflow (or 413), a rate limit, a sign-in or
|
|
32
|
+
* key that is missing or was rejected (`session_expired`: the person signs in to OMP again); anything else is a failed
|
|
33
|
+
* round.
|
|
34
|
+
*/
|
|
35
|
+
export function ompFailure(message: string, status?: number): Error {
|
|
36
|
+
if (status === 413 || CONTEXT_OVERFLOW.test(message)) return refuse('prompt_too_large', message);
|
|
37
|
+
if (status === 429 || /\b429\b|rate.?limit|too many requests|quota/i.test(message)) return refuse('rate_limited', message);
|
|
38
|
+
if (status === 401 || status === 403 || /\b40[13]\b|unauthori[sz]ed|forbidden|api.?key|credential|not logged in|log ?in|authenticat/i.test(message)) return refuse('session_expired', message);
|
|
39
|
+
return new Error(message);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Provider stop reasons that mean the model declined. */
|
|
43
|
+
const REFUSAL = /refus|content.?filter|safety|blocked|prohibited/i;
|
|
44
|
+
|
|
45
|
+
const takesImages = (model: OmpModel | undefined): boolean => Array.isArray(model?.input) && model.input.includes('image');
|
|
46
|
+
|
|
47
|
+
/** The model for a round: a named one OMP has with auth, else the tier's role, else the session's. */
|
|
48
|
+
function pickModel(ctx: OmpContext, round: SampleRound): OmpModel | undefined {
|
|
49
|
+
const session = ctx.model ?? ctx.models?.current();
|
|
50
|
+
if (round.model && ctx.models) {
|
|
51
|
+
const named = ctx.models.resolve(round.model);
|
|
52
|
+
if (named && ctx.models.list().some((m) => m.provider === named.provider && m.id === named.id)) return named;
|
|
53
|
+
}
|
|
54
|
+
if (round.tier === 'inherit') return session;
|
|
55
|
+
return ctx.models?.resolve(TIER_ROLES[round.tier] ?? TIER_ROLES.default) ?? session;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The round's turns as OMP's messages. A tool result names its tool, so the calls before it are remembered. */
|
|
59
|
+
export function ompMessages(turns: SampleRound['turns'], model: OmpModel): OmpMessage[] {
|
|
60
|
+
const names = new Map<string, string>();
|
|
61
|
+
const at = Date.now();
|
|
62
|
+
const messages: OmpMessage[] = [];
|
|
63
|
+
for (const turn of turns) {
|
|
64
|
+
if (turn.role === 'user') {
|
|
65
|
+
const images = turn.images ?? [];
|
|
66
|
+
const content: string | Array<OmpTextContent | OmpImageContent> = images.length
|
|
67
|
+
? [{ type: 'text', text: turn.content }, ...images.map((image): OmpImageContent => ({ type: 'image', data: image.data, mimeType: image.mediaType }))]
|
|
68
|
+
: turn.content;
|
|
69
|
+
messages.push({ role: 'user', content, timestamp: at });
|
|
70
|
+
} else if (turn.role === 'assistant') {
|
|
71
|
+
const calls = turn.toolCalls ?? [];
|
|
72
|
+
for (const call of calls) names.set(call.id, call.name);
|
|
73
|
+
messages.push({
|
|
74
|
+
role: 'assistant',
|
|
75
|
+
content: [
|
|
76
|
+
...(turn.content ? [{ type: 'text', text: turn.content } as OmpTextContent] : []),
|
|
77
|
+
...calls.map((call): OmpToolCall => ({ type: 'toolCall', id: call.id, name: call.name, arguments: call.input ?? {} })),
|
|
78
|
+
],
|
|
79
|
+
...(model.api ? { api: model.api } : {}),
|
|
80
|
+
provider: model.provider,
|
|
81
|
+
model: model.id,
|
|
82
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 },
|
|
83
|
+
stopReason: calls.length ? 'toolUse' : 'stop',
|
|
84
|
+
timestamp: at,
|
|
85
|
+
});
|
|
86
|
+
} else {
|
|
87
|
+
for (const result of turn.results) {
|
|
88
|
+
messages.push({
|
|
89
|
+
role: 'toolResult',
|
|
90
|
+
toolCallId: result.id,
|
|
91
|
+
toolName: names.get(result.id) ?? '',
|
|
92
|
+
content: [{ type: 'text', text: result.content }],
|
|
93
|
+
isError: result.isError === true,
|
|
94
|
+
timestamp: at,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return messages;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Reads the stream to its end, handing text over as it comes; a cancel stops the wait at once. */
|
|
103
|
+
async function drain(stream: OmpEventStream, onText: (delta: string) => void, signal: AbortSignal): Promise<{ text: string; final: OmpAssistantMessage | undefined }> {
|
|
104
|
+
let text = '';
|
|
105
|
+
let final: OmpAssistantMessage | undefined;
|
|
106
|
+
const read = (async () => {
|
|
107
|
+
for await (const event of stream) {
|
|
108
|
+
if (signal.aborted) break;
|
|
109
|
+
if (event.type === 'text_delta' && typeof event.delta === 'string' && event.delta) {
|
|
110
|
+
text += event.delta;
|
|
111
|
+
onText(event.delta);
|
|
112
|
+
} else if (event.type === 'done') final = event.message as OmpAssistantMessage;
|
|
113
|
+
else if (event.type === 'error') final = event.error as OmpAssistantMessage;
|
|
114
|
+
}
|
|
115
|
+
})();
|
|
116
|
+
let onAbort = (): void => undefined;
|
|
117
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
118
|
+
onAbort = () => reject(abortError());
|
|
119
|
+
if (signal.aborted) onAbort();
|
|
120
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
121
|
+
});
|
|
122
|
+
aborted.catch(() => undefined);
|
|
123
|
+
try {
|
|
124
|
+
await Promise.race([read, aborted]);
|
|
125
|
+
} finally {
|
|
126
|
+
signal.removeEventListener('abort', onAbort);
|
|
127
|
+
}
|
|
128
|
+
if (signal.aborted) throw abortError();
|
|
129
|
+
final ??= await stream.result();
|
|
130
|
+
return { text, final };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** One round on OMP's model. */
|
|
134
|
+
export async function runOmpRound(ctx: OmpContext | null, ai: () => Promise<OmpAi>, round: SampleRound, { onText, signal }: SampleRunContext): Promise<SampleRoundResult> {
|
|
135
|
+
if (!ctx?.modelRegistry) throw refuse('unavailable', 'This OMP session is over, or this OMP cannot call its model for an extension.');
|
|
136
|
+
const model = pickModel(ctx, round);
|
|
137
|
+
if (!model) throw refuse('unavailable', 'OMP has no model set up: choose one with /model.');
|
|
138
|
+
if (round.turns.some((turn) => turn.role === 'user' && turn.images?.length) && !takesImages(model)) {
|
|
139
|
+
throw refuse('unavailable', `${model.id} does not read images.`);
|
|
140
|
+
}
|
|
141
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
142
|
+
// No key, or a sign-in OMP cannot renew: the person signs in to OMP again.
|
|
143
|
+
if (!auth.ok) throw refuse('session_expired', auth.error);
|
|
144
|
+
let library: OmpAi;
|
|
145
|
+
try {
|
|
146
|
+
library = await ai();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
throw refuse('unavailable', `This OMP does not serve its model library to extensions: ${messageOf(error)}`);
|
|
149
|
+
}
|
|
150
|
+
if (signal.aborted) throw abortError();
|
|
151
|
+
|
|
152
|
+
const hasToolTurns = round.turns.some((turn) => turn.role === 'tool');
|
|
153
|
+
// The last round answers: its tools stay only so the earlier calls read right, and the model may not call them.
|
|
154
|
+
const tools = round.tools?.length && (!round.lastRound || hasToolTurns) ? round.tools : undefined;
|
|
155
|
+
const context: OmpLlmContext = {
|
|
156
|
+
...(round.system ? { systemPrompt: [round.system] } : {}),
|
|
157
|
+
messages: ompMessages(round.turns, model),
|
|
158
|
+
...(tools ? { tools: tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.inputSchema ?? { type: 'object', properties: {} } })) } : {}),
|
|
159
|
+
};
|
|
160
|
+
const options: OmpStreamOptions = {
|
|
161
|
+
apiKey: auth.apiKey,
|
|
162
|
+
...(auth.headers ? { headers: auth.headers } : {}),
|
|
163
|
+
signal,
|
|
164
|
+
maxTokens: model.maxTokens && model.maxTokens > 0 ? Math.min(round.maxOutputTokens, model.maxTokens) : round.maxOutputTokens,
|
|
165
|
+
statefulResponses: false,
|
|
166
|
+
...(round.effort && model.reasoning ? { reasoning: round.effort } : {}),
|
|
167
|
+
...(tools && round.lastRound ? { toolChoice: 'none' as const } : {}),
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
let stream: OmpEventStream;
|
|
171
|
+
try {
|
|
172
|
+
stream = library.streamSimple(model, context, options);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (signal.aborted) throw abortError();
|
|
175
|
+
throw ompFailure(messageOf(error));
|
|
176
|
+
}
|
|
177
|
+
const { text: streamed, final } = await drain(stream, onText, signal);
|
|
178
|
+
if (!final) throw new Error(`${model.id} ended without an answer.`);
|
|
179
|
+
if (final.stopReason === 'aborted') throw signal.aborted ? abortError() : new Error(final.errorMessage || `${model.id} stopped the answer.`);
|
|
180
|
+
if (final.stopReason === 'error') throw ompFailure(final.errorMessage || `${model.id} failed.`, final.errorStatus);
|
|
181
|
+
|
|
182
|
+
let text = streamed;
|
|
183
|
+
if (!text) {
|
|
184
|
+
// A provider that does not stream: the answer comes whole.
|
|
185
|
+
text = final.content.filter((block): block is OmpTextContent => block.type === 'text').map((block) => block.text).join('');
|
|
186
|
+
if (text) onText(text);
|
|
187
|
+
}
|
|
188
|
+
const toolCalls: SampleToolCall[] = final.content
|
|
189
|
+
.filter((block): block is OmpToolCall => block.type === 'toolCall')
|
|
190
|
+
.map((call) => ({ id: call.id, name: call.name, input: call.arguments && typeof call.arguments === 'object' ? call.arguments : {} }));
|
|
191
|
+
const refused = typeof final.stopDetails?.type === 'string' && REFUSAL.test(final.stopDetails.type);
|
|
192
|
+
const stop: SampleRoundResult['stop'] = refused ? 'refusal' : toolCalls.length ? 'tools' : final.stopReason === 'length' ? 'length' : 'end';
|
|
193
|
+
const usage = final.usage;
|
|
194
|
+
return {
|
|
195
|
+
text: refused ? '' : text,
|
|
196
|
+
stop,
|
|
197
|
+
...(stop === 'tools' ? { toolCalls } : {}),
|
|
198
|
+
model: final.model || model.id,
|
|
199
|
+
...(usage && typeof usage.input === 'number' && typeof usage.output === 'number'
|
|
200
|
+
? { usage: { input: usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0), output: usage.output } }
|
|
201
|
+
: {}),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The `sample` option of `createHarness`, or none when this OMP has no `ctx.modelRegistry` or `ctx.models`. The
|
|
207
|
+
* tiers are the roles OMP's settings name as the connection opens (`default` always, answered by the session's model
|
|
208
|
+
* when no `default` role is set); `inherit` is the session's model; images only when the session's model reads them.
|
|
209
|
+
*/
|
|
210
|
+
export function ompSample(context: () => OmpContext | null, ai: () => Promise<OmpAi> = hostAi): SampleOptions | undefined {
|
|
211
|
+
const ctx = context();
|
|
212
|
+
if (!ctx?.modelRegistry || !ctx.models) return undefined;
|
|
213
|
+
const models = ctx.models;
|
|
214
|
+
const tiers: ModelTier[] = (['quick', 'default', 'complex'] as const).filter((tier) => tier === 'default' || models.resolve(TIER_ROLES[tier]) !== undefined);
|
|
215
|
+
const caps: AdapterSampleCaps = { tiers, inherit: true, stream: true, tools: true, ...(takesImages(ctx.model ?? models.current()) ? { images: true } : {}) };
|
|
216
|
+
return { caps, run: (round, run) => runOmpRound(context(), ai, round, run) };
|
|
217
|
+
}
|