@open-artifact/harness-kit 0.0.0-stage → 0.14.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 +202 -0
- package/NOTICE +5 -0
- package/README.md +96 -2
- package/package.json +48 -4
- package/src/client.d.ts +110 -0
- package/src/client.js +272 -0
- package/src/context.d.ts +31 -0
- package/src/context.js +61 -0
- package/src/daemon.d.ts +108 -0
- package/src/daemon.js +200 -0
- package/src/embed/index.d.ts +183 -0
- package/src/embed/index.js +343 -0
- package/src/embed/remote.d.ts +39 -0
- package/src/embed/remote.js +51 -0
- package/src/harness.d.ts +237 -0
- package/src/harness.js +424 -0
- package/src/index.d.ts +18 -0
- package/src/index.js +17 -0
- package/src/runtimes.d.ts +138 -0
- package/src/runtimes.js +357 -0
- package/src/skill.d.ts +58 -0
- package/src/skill.js +88 -0
- package/src/testing-ws.d.ts +35 -0
- package/src/testing-ws.js +173 -0
- package/src/testing.d.ts +143 -0
- package/src/testing.js +424 -0
package/src/harness.d.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createHarness`: everything an agent app's adapter does with the daemon, behind one object.
|
|
3
|
+
*
|
|
4
|
+
* It finds or starts the daemon, connects, and keeps the connection: a dropped one comes back with backoff, attaches
|
|
5
|
+
* every session again and hands what waited in their inboxes to the `wake` callback. The app answers two callbacks,
|
|
6
|
+
* `wake` (give a message to a session) and `open` (show a page in its own UI), and calls the rest: sessions, tools,
|
|
7
|
+
* files its agent wrote, and the artifacts its sessions make.
|
|
8
|
+
*/
|
|
9
|
+
import { type AdapterCaps, type AttachParams, type CommandEntry, type EmbedOriginsResult, type HarnessEvent, type HostToShell, type ShellEventParams, type HarnessPolicy, type HarnessProfile, type HarnessRuntime, type HelloResult, type InboxMessage, type RuntimeStatus, type RuntimeUpdateResult, type SessionParams, type SessionStatus, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverResult, type WakeDeliverStatus } from '@open-artifact/protocol';
|
|
10
|
+
import { HarnessClient, type HarnessConnectionState } from './client.ts';
|
|
11
|
+
import { type EnsureDaemonOptions } from './daemon.ts';
|
|
12
|
+
import { type InstallSkillOptions, type InstallSkillResult } from './skill.ts';
|
|
13
|
+
import { type ArtifactContext } from './context.ts';
|
|
14
|
+
import { type AllowRemote, type RemotePage, type RemotePagePolicy } from './embed/remote.ts';
|
|
15
|
+
/** This kit's name and version, said in `hello` (`kit`). */
|
|
16
|
+
export declare const KIT: {
|
|
17
|
+
readonly name: "@open-artifact/harness-kit";
|
|
18
|
+
readonly version: string;
|
|
19
|
+
};
|
|
20
|
+
/** What the `wake` callback answers: a status, or a status with the session that took the message instead. */
|
|
21
|
+
export type WakeAnswer = WakeDeliverStatus | WakeDeliverResult;
|
|
22
|
+
/** What the `open` callback gets: show this artifact for this session. */
|
|
23
|
+
export interface OpenRequest {
|
|
24
|
+
/** The session that asked, or `null` when no session did. */
|
|
25
|
+
session: string | null;
|
|
26
|
+
/** `open-artifact://artifact/<id>`. */
|
|
27
|
+
url: string;
|
|
28
|
+
/** The Shell page. */
|
|
29
|
+
viewUrl: string;
|
|
30
|
+
/** What a top-level view loads: `viewUrl` with a view ticket when the daemon gave one, else `viewUrl`. */
|
|
31
|
+
embedUrl: string;
|
|
32
|
+
/** The view ticket, when the daemon gave one. */
|
|
33
|
+
view?: string;
|
|
34
|
+
title?: string;
|
|
35
|
+
/**
|
|
36
|
+
* The artifact's type is on another computer: its page comes from these origins. Present only once the host's
|
|
37
|
+
* `embed.remote` policy let it through (`allow`, or `ask` answered yes); the host lets these origins in to show it.
|
|
38
|
+
*/
|
|
39
|
+
remote?: RemotePage;
|
|
40
|
+
}
|
|
41
|
+
/** An artifact as `on('artifact')` reports it. */
|
|
42
|
+
export interface HarnessArtifact {
|
|
43
|
+
/** `open-artifact://artifact/<id>`: what to store in messages and cards (it does not change with the daemon's port). */
|
|
44
|
+
url: string;
|
|
45
|
+
id: string;
|
|
46
|
+
title: string;
|
|
47
|
+
/** The type id. */
|
|
48
|
+
type: string;
|
|
49
|
+
/** The local Shell page (also when it is published: the person's own copy); `null` once removed. */
|
|
50
|
+
viewUrl: string | null;
|
|
51
|
+
/** Its address on the site it is published to, or `null` when it is not published. */
|
|
52
|
+
publicUrl?: string | null;
|
|
53
|
+
/** The Library API address of its thumbnail, when one was captured. */
|
|
54
|
+
thumbnail: string | null;
|
|
55
|
+
updatedAt: string;
|
|
56
|
+
}
|
|
57
|
+
/** What changed about an artifact. */
|
|
58
|
+
export type ArtifactChange = 'created' | 'updated' | 'removed';
|
|
59
|
+
/** An `on('artifact')` report. */
|
|
60
|
+
export interface ArtifactReport {
|
|
61
|
+
/** The session of this harness that owns the artifact, or `null` when it is not one of this harness's sessions. */
|
|
62
|
+
session: string | null;
|
|
63
|
+
/** That session's workspace, when known. */
|
|
64
|
+
workspace: string | null;
|
|
65
|
+
artifact: HarnessArtifact;
|
|
66
|
+
change: ArtifactChange;
|
|
67
|
+
/** Who changed it, as the daemon said (`agent`, or the person's page). */
|
|
68
|
+
author?: string;
|
|
69
|
+
/** The files that changed, when the daemon said. */
|
|
70
|
+
paths?: string[];
|
|
71
|
+
}
|
|
72
|
+
/** Options of {@link createHarness}. */
|
|
73
|
+
export interface HarnessOptions {
|
|
74
|
+
/** The harness name (`^[a-z0-9][a-z0-9._-]{0,40}$`). */
|
|
75
|
+
harness: string;
|
|
76
|
+
/** What the harness calls its agent. */
|
|
77
|
+
agentName?: string;
|
|
78
|
+
/** The harness's command names, e.g. `['artifact']`. */
|
|
79
|
+
commands?: string[];
|
|
80
|
+
/** Capabilities beyond what the callbacks and options imply (see {@link createHarness}). */
|
|
81
|
+
caps?: AdapterCaps;
|
|
82
|
+
/** The harness's rules that are data (the daemon writes its instructions by them, or refuses calls). */
|
|
83
|
+
policy?: HarnessPolicy;
|
|
84
|
+
/** The harness's rules that are only text. */
|
|
85
|
+
rules?: string;
|
|
86
|
+
/** More of the harness's profile, reported in `hello` (`nudge` is never sent). */
|
|
87
|
+
profile?: Omit<Partial<HarnessProfile>, 'nudge' | 'name' | 'source'>;
|
|
88
|
+
/** The runtime the harness carries (`@open-artifact/cli`): it starts the daemon when none runs. */
|
|
89
|
+
runtime?: HarnessRuntime;
|
|
90
|
+
/**
|
|
91
|
+
* How the harness embeds pages, when it shows them itself (`open`). `remote` is what it does with a remote type's
|
|
92
|
+
* page (one on another computer): `allow` shows it, `deny` answers not-opened without calling `open`, `ask` (the
|
|
93
|
+
* default) asks `allowRemote`, keeping a yes per origin for the life of the process and asking again after a no.
|
|
94
|
+
*/
|
|
95
|
+
embed?: {
|
|
96
|
+
origins: string[];
|
|
97
|
+
mode?: 'frame' | 'view';
|
|
98
|
+
remote?: RemotePagePolicy;
|
|
99
|
+
};
|
|
100
|
+
/** Asked under `embed.remote: 'ask'` before a remote type's page is shown; without it the answer is no. */
|
|
101
|
+
allowRemote?: AllowRemote;
|
|
102
|
+
/** An Open Artifact home of the harness's own: its own daemon and library, apart from the other apps'. */
|
|
103
|
+
home?: string;
|
|
104
|
+
/** Start the daemon when none runs (default `true`). */
|
|
105
|
+
autoStart?: boolean;
|
|
106
|
+
/** More options for starting the daemon (`env`, `bin`, `timeoutMs`). */
|
|
107
|
+
daemon?: EnsureDaemonOptions;
|
|
108
|
+
/** Gives a message to a session (`wake.deliver`); see {@link createHarness}. */
|
|
109
|
+
wake?: (params: WakeDeliverParams) => WakeAnswer | Promise<WakeAnswer>;
|
|
110
|
+
/** Shows a page in the harness's own UI (`host.open`). `false`: it was not shown. */
|
|
111
|
+
open?: (request: OpenRequest) => boolean | void | Promise<boolean | void>;
|
|
112
|
+
/** How long `wake` may take before the daemon is told it failed (and keeps the message), ms. Default 25 s. */
|
|
113
|
+
wakeTimeoutMs?: number;
|
|
114
|
+
/** Reconnect delays, ms: from `minMs` (default 1 s) doubling to `maxMs` (default 30 s). */
|
|
115
|
+
reconnect?: {
|
|
116
|
+
minMs?: number;
|
|
117
|
+
maxMs?: number;
|
|
118
|
+
};
|
|
119
|
+
/** Diagnostic log. */
|
|
120
|
+
log?: (line: string) => void;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The runtime calls (feature `runtime.update`): what runtimes this computer has and which starts, and the host's yes
|
|
124
|
+
* to an update. Both connect first, and throw `unsupported` when the daemon does not list the feature.
|
|
125
|
+
*/
|
|
126
|
+
export interface HarnessRuntimeCalls {
|
|
127
|
+
/** `runtime.status`: the runtimes here, the update policy, the last check and a waiting switch. */
|
|
128
|
+
status(): Promise<RuntimeStatus>;
|
|
129
|
+
/**
|
|
130
|
+
* `runtime.update`: downloads the newest compatible runtime (or `version`) into the shared folder; the daemon
|
|
131
|
+
* switches once idle. Refused (`not_granted`) when updates are off for the whole computer.
|
|
132
|
+
*/
|
|
133
|
+
update(version?: string): Promise<RuntimeUpdateResult>;
|
|
134
|
+
}
|
|
135
|
+
/** The connection to the daemon, as {@link createHarness} returns it. */
|
|
136
|
+
export interface Harness {
|
|
137
|
+
/** The underlying connection, for calls the kit does not wrap (`client.request(method, params)`). */
|
|
138
|
+
readonly client: HarnessClient;
|
|
139
|
+
/** Whether the connection is up. */
|
|
140
|
+
readonly connected: boolean;
|
|
141
|
+
/** The daemon's features (see `HarnessFeature`); empty while not connected. */
|
|
142
|
+
readonly features: readonly string[];
|
|
143
|
+
/** Connects now if it is not connected (starting the daemon unless `autoStart` is false). */
|
|
144
|
+
ready(): Promise<HelloResult>;
|
|
145
|
+
/**
|
|
146
|
+
* Attaches a session; a reconnect attaches it again. What waited in its inbox goes to the `wake` callback; the
|
|
147
|
+
* answer's `inbox` holds what the callback did not take (all of it without a callback).
|
|
148
|
+
*/
|
|
149
|
+
attach(params: AttachParams): Promise<{
|
|
150
|
+
key: string;
|
|
151
|
+
inbox: InboxMessage[];
|
|
152
|
+
}>;
|
|
153
|
+
/** The session's agent is `running` or `idle` now. */
|
|
154
|
+
status(session: string | SessionParams, status: SessionStatus): Promise<void>;
|
|
155
|
+
/** Detaches a session. */
|
|
156
|
+
detach(session: string | SessionParams): Promise<void>;
|
|
157
|
+
/** Renames a session. */
|
|
158
|
+
rename(session: string | SessionParams, title: string): Promise<void>;
|
|
159
|
+
/** The tool definitions: the daemon's when connected, else the ones this kit carries. */
|
|
160
|
+
tools(): Promise<ToolDefinition[]>;
|
|
161
|
+
/** Calls a tool for a session. */
|
|
162
|
+
call(name: string, args: Record<string, unknown>, caller?: SessionParams): Promise<ToolCallResult>;
|
|
163
|
+
/** The agent wrote these files (absolute paths) with its own tools. */
|
|
164
|
+
wrote(paths: string[], caller?: SessionParams): Promise<{
|
|
165
|
+
ok: true;
|
|
166
|
+
artifacts?: string[];
|
|
167
|
+
}>;
|
|
168
|
+
/** Shows an artifact for a session (through `open`, when the harness shows pages). */
|
|
169
|
+
open(url: string, options?: SessionParams): Promise<{
|
|
170
|
+
opened: boolean;
|
|
171
|
+
view_url?: string;
|
|
172
|
+
}>;
|
|
173
|
+
/** Whether a tool call is about an Open Artifact link (`url` or `type_url` is `open-artifact://…`). */
|
|
174
|
+
owns(args: Record<string, unknown> | null | undefined): boolean;
|
|
175
|
+
/**
|
|
176
|
+
* The artifact's local Shell page (stable while the daemon keeps its port; also for a published artifact), or `null`
|
|
177
|
+
* when the daemon does not know it. The published address is {@link Harness.publicUrl}.
|
|
178
|
+
*/
|
|
179
|
+
viewUrl(url: string): Promise<string | null>;
|
|
180
|
+
/** The artifact's address on the site it is published to, or `null` (not published, or unknown). */
|
|
181
|
+
publicUrl(url: string): Promise<string | null>;
|
|
182
|
+
/** The origins a host must let in to show pages (feature `embed.origins`); `on('event')` gets `embed/origins` changes. */
|
|
183
|
+
embedOrigins(): Promise<EmbedOriginsResult>;
|
|
184
|
+
/** Sends a host message to the Shell of a top-level view this harness opened (feature `shell.command`). */
|
|
185
|
+
shellCommand(view: string, command: HostToShell): Promise<void>;
|
|
186
|
+
/**
|
|
187
|
+
* What the person selected on the artifact's page, read as its owner session (feature `view.context`); turn it into
|
|
188
|
+
* prompt text with {@link Harness.contextBlock}. `on('event')` gets `view/context` when it changes (best effort).
|
|
189
|
+
*/
|
|
190
|
+
context(url: string, options?: {
|
|
191
|
+
session?: string | null;
|
|
192
|
+
workspace?: string | null;
|
|
193
|
+
}): Promise<ArtifactContext>;
|
|
194
|
+
/** The prompt block of a context (see `contextBlock`): `''` when there is nothing to say. */
|
|
195
|
+
contextBlock(context: ArtifactContext | null | undefined): string;
|
|
196
|
+
/** Saves a captured thumbnail (JPEG bytes) for the artifact, for libraries and cards. */
|
|
197
|
+
saveThumbnail(url: string, jpeg: Uint8Array): Promise<void>;
|
|
198
|
+
/** What the Shell of a top-level view this harness opened says (`shell.event`). Returns a function that stops. */
|
|
199
|
+
on(event: 'shell', listener: (event: ShellEventParams) => void): () => void;
|
|
200
|
+
/** Reports artifacts created, changed or removed. Returns a function that stops. */
|
|
201
|
+
on(event: 'artifact', listener: (report: ArtifactReport) => void): () => void;
|
|
202
|
+
/** Every event the daemon sends. Returns a function that stops. */
|
|
203
|
+
on(event: 'event', listener: (event: HarnessEvent) => void): () => void;
|
|
204
|
+
/** The connection went up or down. Returns a function that stops. */
|
|
205
|
+
on(event: 'state', listener: (state: HarnessConnectionState) => void): () => void;
|
|
206
|
+
/**
|
|
207
|
+
* Writes the skill for this harness into `<dir>/<command>/SKILL.md` (rendered by the daemon, `skill.get`, else by
|
|
208
|
+
* this kit), only when it changed; again after a reconnect to another runtime.
|
|
209
|
+
*/
|
|
210
|
+
installSkill(options: InstallSkillOptions): Promise<InstallSkillResult>;
|
|
211
|
+
/** One command per installed type, for the harness's command menu (`commands.list`; `[]` without it). */
|
|
212
|
+
commands(options?: {
|
|
213
|
+
command?: string;
|
|
214
|
+
locale?: string;
|
|
215
|
+
}): Promise<CommandEntry[]>;
|
|
216
|
+
/** The runtime's status and updates (feature `runtime.update`); `on('event')` gets `runtime/update` when one exists. */
|
|
217
|
+
readonly runtime: HarnessRuntimeCalls;
|
|
218
|
+
/** Closes the connection for good. */
|
|
219
|
+
close(): void;
|
|
220
|
+
}
|
|
221
|
+
/** Whether a tool call is about an Open Artifact link (`url` or `type_url`), so a harness with its own tools can route it. */
|
|
222
|
+
export declare function ownsCall(args: Record<string, unknown> | null | undefined): boolean;
|
|
223
|
+
/**
|
|
224
|
+
* Connects an agent app to the daemon. Resolves once the first connection attempt is over: when it failed (no daemon
|
|
225
|
+
* and `autoStart: false`, say), the harness keeps trying in the background and calls connect on demand.
|
|
226
|
+
*
|
|
227
|
+
* What `hello` says follows from the options: `caps.wake` when there is a `wake` callback, `caps.open` when there is
|
|
228
|
+
* an `open` callback (`{ embed, origins }` with `embed`), `caps.commands` from `commands`, `caps.agentName` from
|
|
229
|
+
* `agentName`; `options.caps` adds the rest (`tools`, `library`, `wake.resume`, `wake.mode`). The profile carries
|
|
230
|
+
* `agentName`, `commands`, `policy`, `rules`, the caps and `options.profile`.
|
|
231
|
+
*
|
|
232
|
+
* `wake` answers how it handed the message over: `resumed` (started a turn), `delivered` (put it into the running
|
|
233
|
+
* turn), `drafted` (put it in the session's draft, for a harness whose `caps.wake.mode` is `draft`) or `failed` (the
|
|
234
|
+
* daemon keeps it for later). It may name the session that took it instead: `{ status, session }`. A callback that
|
|
235
|
+
* throws, or takes longer than `wakeTimeoutMs`, answers `failed`.
|
|
236
|
+
*/
|
|
237
|
+
export declare function createHarness(options: HarnessOptions): Promise<Harness>;
|
package/src/harness.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createHarness`: everything an agent app's adapter does with the daemon, behind one object.
|
|
3
|
+
*
|
|
4
|
+
* It finds or starts the daemon, connects, and keeps the connection: a dropped one comes back with backoff, attaches
|
|
5
|
+
* every session again and hands what waited in their inboxes to the `wake` callback. The app answers two callbacks,
|
|
6
|
+
* `wake` (give a message to a session) and `open` (show a page in its own UI), and calls the rest: sessions, tools,
|
|
7
|
+
* files its agent wrote, and the artifacts its sessions make.
|
|
8
|
+
*/
|
|
9
|
+
import { LIBRARY_ROUTES, OpenArtifactError, TOOL_DEFINITIONS, artifactIdOf, artifactUrl, wakeSourceOf, } from '@open-artifact/protocol';
|
|
10
|
+
import { HarnessClient } from "./client.js";
|
|
11
|
+
import { api } from "./daemon.js";
|
|
12
|
+
import { commands, keepSkillInstalled } from "./skill.js";
|
|
13
|
+
import { contextBlock, readContext } from "./context.js";
|
|
14
|
+
import { remoteGate, remotePolicyOf } from "./embed/remote.js";
|
|
15
|
+
import pkg from '../package.json' with { type: 'json' };
|
|
16
|
+
/** This kit's name and version, said in `hello` (`kit`). */
|
|
17
|
+
export const KIT = { name: '@open-artifact/harness-kit', version: pkg.version ?? '0.0.0' };
|
|
18
|
+
/** Default of {@link HarnessOptions.wakeTimeoutMs}: under the daemon's own 30 s wait for an answer. */
|
|
19
|
+
const WAKE_TIMEOUT_MS = 25_000;
|
|
20
|
+
const sessionParams = (session) => (typeof session === 'string' ? { session } : session);
|
|
21
|
+
/** A string that is an Open Artifact link. */
|
|
22
|
+
const isLink = (value) => typeof value === 'string' && value.trim().startsWith('open-artifact://');
|
|
23
|
+
/** Whether a tool call is about an Open Artifact link (`url` or `type_url`), so a harness with its own tools can route it. */
|
|
24
|
+
export function ownsCall(args) {
|
|
25
|
+
return !!args && (isLink(args.url) || isLink(args.type_url));
|
|
26
|
+
}
|
|
27
|
+
/** The caps `hello` says: `options.caps`, plus what the callbacks and options imply. */
|
|
28
|
+
function capsOf(options) {
|
|
29
|
+
const caps = { ...options.caps };
|
|
30
|
+
if (options.agentName && !caps.agentName)
|
|
31
|
+
caps.agentName = options.agentName;
|
|
32
|
+
// Without a callback the adapter cannot answer the call, so it does not claim it.
|
|
33
|
+
if (options.wake)
|
|
34
|
+
caps.wake = caps.wake ?? {};
|
|
35
|
+
else
|
|
36
|
+
delete caps.wake;
|
|
37
|
+
if (options.open) {
|
|
38
|
+
if (caps.open === undefined || caps.open === true)
|
|
39
|
+
caps.open = options.embed ? { embed: options.embed.mode ?? 'frame', origins: [...options.embed.origins], remote: remotePolicyOf(options.embed.remote) } : true;
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
delete caps.open;
|
|
43
|
+
if (options.commands?.length && !caps.commands)
|
|
44
|
+
caps.commands = { names: [...options.commands] };
|
|
45
|
+
return caps;
|
|
46
|
+
}
|
|
47
|
+
/** The profile `hello` reports, or `undefined` when there is nothing to say. */
|
|
48
|
+
function profileOf(options, caps) {
|
|
49
|
+
const { nudge: _nudge, ...given } = (options.profile ?? {});
|
|
50
|
+
const profile = {
|
|
51
|
+
...given,
|
|
52
|
+
...(options.agentName ? { agentName: options.agentName } : {}),
|
|
53
|
+
...(options.commands?.length ? { commands: [...options.commands] } : {}),
|
|
54
|
+
...(options.policy ? { policy: options.policy } : {}),
|
|
55
|
+
...(options.rules ? { rules: options.rules } : {}),
|
|
56
|
+
...(Object.keys(caps).length ? { caps } : {}),
|
|
57
|
+
};
|
|
58
|
+
return Object.keys(profile).length ? profile : undefined;
|
|
59
|
+
}
|
|
60
|
+
/** Runs `work`, or gives `fallback` when it takes longer than `ms`. */
|
|
61
|
+
function within(work, ms, fallback) {
|
|
62
|
+
return new Promise((resolveIt, rejectIt) => {
|
|
63
|
+
const timer = setTimeout(() => resolveIt(fallback()), ms);
|
|
64
|
+
timer.unref?.();
|
|
65
|
+
work.then((value) => {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
resolveIt(value);
|
|
68
|
+
}, (error) => {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
rejectIt(error);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** The wake to hand to the `wake` callback for one inbox message, or `null` when it is not a whole wake. */
|
|
75
|
+
function inboxWake(message, ref) {
|
|
76
|
+
if (message.kind !== 'wake' || typeof message.text !== 'string' || !message.text || !message.source || typeof message.source !== 'object')
|
|
77
|
+
return null;
|
|
78
|
+
return {
|
|
79
|
+
session: ref.session ?? null,
|
|
80
|
+
workspace: ref.workspace ?? null,
|
|
81
|
+
artifact: message.artifact ?? message.source.url ?? '',
|
|
82
|
+
artifactId: message.artifactId ?? message.source.artifactId ?? '',
|
|
83
|
+
text: message.text,
|
|
84
|
+
source: message.source,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Connects an agent app to the daemon. Resolves once the first connection attempt is over: when it failed (no daemon
|
|
89
|
+
* and `autoStart: false`, say), the harness keeps trying in the background and calls connect on demand.
|
|
90
|
+
*
|
|
91
|
+
* What `hello` says follows from the options: `caps.wake` when there is a `wake` callback, `caps.open` when there is
|
|
92
|
+
* an `open` callback (`{ embed, origins }` with `embed`), `caps.commands` from `commands`, `caps.agentName` from
|
|
93
|
+
* `agentName`; `options.caps` adds the rest (`tools`, `library`, `wake.resume`, `wake.mode`). The profile carries
|
|
94
|
+
* `agentName`, `commands`, `policy`, `rules`, the caps and `options.profile`.
|
|
95
|
+
*
|
|
96
|
+
* `wake` answers how it handed the message over: `resumed` (started a turn), `delivered` (put it into the running
|
|
97
|
+
* turn), `drafted` (put it in the session's draft, for a harness whose `caps.wake.mode` is `draft`) or `failed` (the
|
|
98
|
+
* daemon keeps it for later). It may name the session that took it instead: `{ status, session }`. A callback that
|
|
99
|
+
* throws, or takes longer than `wakeTimeoutMs`, answers `failed`.
|
|
100
|
+
*/
|
|
101
|
+
export async function createHarness(options) {
|
|
102
|
+
const log = options.log ?? (() => undefined);
|
|
103
|
+
const caps = capsOf(options);
|
|
104
|
+
// A remote type's page passes this gate before `open` sees it (the policy `hello` said; `ask` by default).
|
|
105
|
+
const remoteOk = remoteGate(typeof caps.open === 'object' && caps.open.remote ? caps.open.remote : remotePolicyOf(options.embed?.remote), options.allowRemote);
|
|
106
|
+
const profile = profileOf(options, caps);
|
|
107
|
+
const daemon = {
|
|
108
|
+
...options.daemon,
|
|
109
|
+
...(options.home ? { home: options.home } : {}),
|
|
110
|
+
};
|
|
111
|
+
// The harness's runtime is one candidate: the newest compatible runtime on this computer starts (`runtimes.ts`);
|
|
112
|
+
// `daemon.bin` and $OPEN_ARTIFACT_DAEMON_BIN override the choice.
|
|
113
|
+
if (!daemon.bin && !daemon.own && options.runtime?.dir)
|
|
114
|
+
daemon.own = { dir: options.runtime.dir.replace(/[\\/]+$/, ''), version: options.runtime.version };
|
|
115
|
+
if (!daemon.version && options.runtime?.version)
|
|
116
|
+
daemon.version = options.runtime.version;
|
|
117
|
+
const listeners = {
|
|
118
|
+
artifact: new Set(),
|
|
119
|
+
event: new Set(),
|
|
120
|
+
state: new Set(),
|
|
121
|
+
shell: new Set(),
|
|
122
|
+
};
|
|
123
|
+
const emit = (kind, value) => {
|
|
124
|
+
for (const listener of listeners[kind]) {
|
|
125
|
+
try {
|
|
126
|
+
listener(value);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
log(`open-artifact ${kind} listener: ${error?.message ?? error}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
/** Inbox messages the `wake` callback did not take on a re-attach, handed back by the session's next attach. */
|
|
134
|
+
const leftovers = new Map();
|
|
135
|
+
const sessionKey = (ref) => (ref.session ? `s:${ref.session}` : `w:${ref.workspace ?? ''}`);
|
|
136
|
+
const timeout = options.wakeTimeoutMs ?? WAKE_TIMEOUT_MS;
|
|
137
|
+
/** Asks the `wake` callback; never throws. */
|
|
138
|
+
const wake = async (params) => {
|
|
139
|
+
if (!options.wake)
|
|
140
|
+
return { status: 'failed' };
|
|
141
|
+
try {
|
|
142
|
+
// An older daemon's wake has no `reason` or `from`: they are read from its text, so the callback always has them.
|
|
143
|
+
const filled = { ...params, source: wakeSourceOf(params.source, params.text) };
|
|
144
|
+
const answer = await within(Promise.resolve(options.wake(filled)), timeout, () => {
|
|
145
|
+
log(`open-artifact wake for ${params.session ?? params.workspace}: no answer in ${timeout} ms`);
|
|
146
|
+
return 'failed';
|
|
147
|
+
});
|
|
148
|
+
const result = typeof answer === 'string' ? { status: answer } : answer;
|
|
149
|
+
if (!result || typeof result.status !== 'string')
|
|
150
|
+
return { status: 'failed' };
|
|
151
|
+
return { status: result.status, ...(typeof result.session === 'string' && result.session ? { session: result.session } : {}) };
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
log(`open-artifact wake for ${params.session ?? params.workspace}: ${error?.message ?? error}`);
|
|
155
|
+
return { status: 'failed' };
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
/** Hands an attach's inbox to `wake`; returns what it did not take. */
|
|
159
|
+
const handOver = async (ref, inbox) => {
|
|
160
|
+
const left = [];
|
|
161
|
+
for (const message of inbox ?? []) {
|
|
162
|
+
const params = options.wake ? inboxWake(message, ref) : null;
|
|
163
|
+
if (!params || (await wake(params)).status === 'failed')
|
|
164
|
+
left.push(message);
|
|
165
|
+
}
|
|
166
|
+
return left;
|
|
167
|
+
};
|
|
168
|
+
// ---- artifacts ----
|
|
169
|
+
const known = new Map();
|
|
170
|
+
let since = Date.now();
|
|
171
|
+
const queued = new Map();
|
|
172
|
+
const chains = new Map();
|
|
173
|
+
const lookup = async (id) => {
|
|
174
|
+
const state = client.state ?? (await client.connect().then(() => client.state));
|
|
175
|
+
if (!state)
|
|
176
|
+
return null;
|
|
177
|
+
const record = await api(state, LIBRARY_ROUTES.artifact, undefined, { query: { id } }).catch(() => null);
|
|
178
|
+
return record && typeof record.id === 'string' && record.id === id ? record : null;
|
|
179
|
+
};
|
|
180
|
+
const toArtifact = (record) => {
|
|
181
|
+
const base = client.state?.url ?? '';
|
|
182
|
+
return {
|
|
183
|
+
url: record.url || artifactUrl(record.id),
|
|
184
|
+
id: record.id,
|
|
185
|
+
title: record.title,
|
|
186
|
+
type: record.type,
|
|
187
|
+
// The local Shell, also for a published artifact (its site's address is `publicUrl`).
|
|
188
|
+
viewUrl: base ? `${base}/a/${encodeURIComponent(record.id)}` : record.view_url || null,
|
|
189
|
+
publicUrl: record.remote?.url || null,
|
|
190
|
+
thumbnail: record.thumbnail ? `${base}/api/open-artifact.${LIBRARY_ROUTES.thumbnail}?id=${encodeURIComponent(record.id)}&v=${encodeURIComponent(record.thumbnail)}` : null,
|
|
191
|
+
updatedAt: record.updatedAt,
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
const report = async (id) => {
|
|
195
|
+
const item = queued.get(id);
|
|
196
|
+
queued.delete(id);
|
|
197
|
+
if (!item)
|
|
198
|
+
return;
|
|
199
|
+
const extra = { ...(item.author ? { author: item.author } : {}), ...(item.paths.size ? { paths: [...item.paths] } : {}) };
|
|
200
|
+
if (item.removed) {
|
|
201
|
+
const last = known.get(id);
|
|
202
|
+
known.delete(id);
|
|
203
|
+
const artifact = last ? { ...last, viewUrl: null, publicUrl: null } : { url: artifactUrl(id), id, title: '', type: '', viewUrl: null, publicUrl: null, thumbnail: null, updatedAt: new Date().toISOString() };
|
|
204
|
+
emit('artifact', { session: null, workspace: null, artifact, change: 'removed', ...extra });
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const record = await lookup(id);
|
|
208
|
+
if (!record)
|
|
209
|
+
return;
|
|
210
|
+
const artifact = toArtifact(record);
|
|
211
|
+
// The first report of an artifact made since the kit started following is its creation.
|
|
212
|
+
const change = !known.has(id) && Date.parse(record.createdAt) >= since - 1000 ? 'created' : 'updated';
|
|
213
|
+
known.set(id, artifact);
|
|
214
|
+
const owner = record.owner && record.owner.harness === options.harness ? record.owner : null;
|
|
215
|
+
emit('artifact', { session: owner?.session ?? null, workspace: owner?.workspace ?? null, artifact, change, ...extra });
|
|
216
|
+
};
|
|
217
|
+
const onEvent = (event) => {
|
|
218
|
+
emit('event', event);
|
|
219
|
+
if (event.type !== 'artifacts/changed' || !listeners.artifact.size)
|
|
220
|
+
return;
|
|
221
|
+
const waiting = queued.get(event.id);
|
|
222
|
+
if (waiting) {
|
|
223
|
+
// Not looked up yet: one report covers both.
|
|
224
|
+
waiting.removed ||= !!event.removed;
|
|
225
|
+
if (event.author)
|
|
226
|
+
waiting.author = event.author;
|
|
227
|
+
for (const path of event.paths ?? [])
|
|
228
|
+
waiting.paths.add(path);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
queued.set(event.id, { removed: !!event.removed, ...(event.author ? { author: event.author } : {}), paths: new Set(event.paths ?? []) });
|
|
232
|
+
const next = (chains.get(event.id) ?? Promise.resolve()).then(() => report(event.id)).catch((error) => log(`open-artifact artifact ${event.id}: ${error.message}`));
|
|
233
|
+
chains.set(event.id, next);
|
|
234
|
+
void next.finally(() => {
|
|
235
|
+
if (chains.get(event.id) === next)
|
|
236
|
+
chains.delete(event.id);
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
// ---- the connection ----
|
|
240
|
+
const client = new HarnessClient({
|
|
241
|
+
harness: options.harness,
|
|
242
|
+
caps,
|
|
243
|
+
hello: { kit: { ...KIT }, ...(profile ? { profile } : {}), ...(options.runtime ? { runtime: options.runtime } : {}) },
|
|
244
|
+
daemon,
|
|
245
|
+
...(options.autoStart !== undefined ? { autoStart: options.autoStart } : {}),
|
|
246
|
+
reconnect: { minMs: options.reconnect?.minMs ?? 1000, maxMs: options.reconnect?.maxMs ?? 30_000 },
|
|
247
|
+
log,
|
|
248
|
+
onEvent,
|
|
249
|
+
onState: (state) => emit('state', state),
|
|
250
|
+
onReattach: async (params, result) => {
|
|
251
|
+
const left = await handOver(params, result.inbox);
|
|
252
|
+
if (left.length) {
|
|
253
|
+
const key = sessionKey(params);
|
|
254
|
+
leftovers.set(key, [...(leftovers.get(key) ?? []), ...left]);
|
|
255
|
+
log(`open-artifact: ${left.length} message(s) for ${params.session ?? params.workspace} were not taken; the next attach returns them`);
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
handlers: {
|
|
259
|
+
...(options.wake ? { 'wake.deliver': (params) => wake(params) } : {}),
|
|
260
|
+
'shell.event': (params) => {
|
|
261
|
+
emit('shell', params);
|
|
262
|
+
return { ok: true };
|
|
263
|
+
},
|
|
264
|
+
...(options.open
|
|
265
|
+
? {
|
|
266
|
+
'host.open': async (params) => {
|
|
267
|
+
const remote = params.remote && typeof params.remote.type === 'string' && Array.isArray(params.remote.origins) ? { type: params.remote.type, origins: params.remote.origins.filter((o) => typeof o === 'string') } : undefined;
|
|
268
|
+
try {
|
|
269
|
+
if (!(await remoteOk(remote, params.title))) {
|
|
270
|
+
log(`open-artifact open ${params.url}: a page from ${remote.origins.join(', ')} (another computer) was not allowed`);
|
|
271
|
+
return { opened: false };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
return { opened: false };
|
|
276
|
+
}
|
|
277
|
+
const request = {
|
|
278
|
+
session: params.session ?? null,
|
|
279
|
+
url: params.url,
|
|
280
|
+
viewUrl: params.view_url,
|
|
281
|
+
embedUrl: params.embed_url || params.view_url,
|
|
282
|
+
...(params.view ? { view: params.view } : {}),
|
|
283
|
+
...(params.title !== undefined ? { title: params.title } : {}),
|
|
284
|
+
...(remote?.origins.length ? { remote } : {}),
|
|
285
|
+
};
|
|
286
|
+
try {
|
|
287
|
+
return { opened: (await options.open(request)) !== false };
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
log(`open-artifact open ${params.url}: ${error?.message ?? error}`);
|
|
291
|
+
return { opened: false };
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
}
|
|
295
|
+
: {}),
|
|
296
|
+
},
|
|
297
|
+
});
|
|
298
|
+
// Events are only asked for while someone listens.
|
|
299
|
+
await client.subscribe(false);
|
|
300
|
+
try {
|
|
301
|
+
await client.connect();
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
log(`open-artifact connect: ${error?.message ?? error}`);
|
|
305
|
+
client.reconnect();
|
|
306
|
+
}
|
|
307
|
+
/** Connects if needed, then throws `unsupported` unless the daemon lists `feature`. */
|
|
308
|
+
const needs = async (feature, method) => {
|
|
309
|
+
if (!client.connected)
|
|
310
|
+
await client.connect();
|
|
311
|
+
if (!client.features.includes(feature)) {
|
|
312
|
+
throw new OpenArtifactError('unsupported', `${method} needs feature ${feature}, which daemon ${client.hello?.daemon ?? '(unknown)'} does not list.`, { fix: 'Update the Open Artifact runtime this computer runs.' });
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
const harness = {
|
|
316
|
+
client,
|
|
317
|
+
get connected() {
|
|
318
|
+
return client.connected;
|
|
319
|
+
},
|
|
320
|
+
get features() {
|
|
321
|
+
return client.features;
|
|
322
|
+
},
|
|
323
|
+
ready: () => client.connect(),
|
|
324
|
+
async attach(params) {
|
|
325
|
+
const result = await client.attach(params);
|
|
326
|
+
const key = sessionKey(params);
|
|
327
|
+
const earlier = leftovers.get(key) ?? [];
|
|
328
|
+
leftovers.delete(key);
|
|
329
|
+
return { key: result.key, inbox: [...earlier, ...(await handOver(params, result.inbox))] };
|
|
330
|
+
},
|
|
331
|
+
async status(session, status) {
|
|
332
|
+
await client.status({ ...sessionParams(session), status });
|
|
333
|
+
},
|
|
334
|
+
async detach(session) {
|
|
335
|
+
leftovers.delete(sessionKey(sessionParams(session)));
|
|
336
|
+
await client.detach(sessionParams(session));
|
|
337
|
+
},
|
|
338
|
+
async rename(session, title) {
|
|
339
|
+
await client.rename({ ...sessionParams(session), title });
|
|
340
|
+
},
|
|
341
|
+
async tools() {
|
|
342
|
+
if (client.connected) {
|
|
343
|
+
try {
|
|
344
|
+
return await client.tools();
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
log(`open-artifact tools.list: ${error?.message ?? error}`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return TOOL_DEFINITIONS.map((tool) => ({ ...tool }));
|
|
351
|
+
},
|
|
352
|
+
call: (name, args, caller) => client.callTool(name, args, caller),
|
|
353
|
+
wrote: (paths, caller) => client.request('agent.wrote', { paths, ...(caller ? { caller } : {}) }),
|
|
354
|
+
open: (url, opts) => client.request('artifact.open', { url, ...(opts ? { caller: opts } : {}) }),
|
|
355
|
+
owns: ownsCall,
|
|
356
|
+
async viewUrl(url) {
|
|
357
|
+
const id = artifactIdOf(url);
|
|
358
|
+
if (!id)
|
|
359
|
+
throw new OpenArtifactError('invalid_argument', `Not an artifact: ${url}`);
|
|
360
|
+
const record = await lookup(id);
|
|
361
|
+
return record ? toArtifact(record).viewUrl : null;
|
|
362
|
+
},
|
|
363
|
+
async publicUrl(url) {
|
|
364
|
+
const id = artifactIdOf(url);
|
|
365
|
+
if (!id)
|
|
366
|
+
throw new OpenArtifactError('invalid_argument', `Not an artifact: ${url}`);
|
|
367
|
+
const record = await lookup(id);
|
|
368
|
+
return record?.remote?.url || null;
|
|
369
|
+
},
|
|
370
|
+
embedOrigins: () => client.request('embed.origins', {}),
|
|
371
|
+
async shellCommand(view, command) {
|
|
372
|
+
await client.request('shell.command', { view, command });
|
|
373
|
+
},
|
|
374
|
+
context: (url, opts) => readContext(client, url, opts),
|
|
375
|
+
contextBlock,
|
|
376
|
+
async saveThumbnail(url, jpeg) {
|
|
377
|
+
const id = artifactIdOf(url);
|
|
378
|
+
if (!id)
|
|
379
|
+
throw new OpenArtifactError('invalid_argument', `Not an artifact: ${url}`);
|
|
380
|
+
const state = client.state ?? (await client.connect().then(() => client.state));
|
|
381
|
+
if (!state)
|
|
382
|
+
throw new OpenArtifactError('no_daemon', 'Not connected to the daemon.');
|
|
383
|
+
const target = new URL(`/api/open-artifact.${LIBRARY_ROUTES.thumbnail}`, state.url);
|
|
384
|
+
target.searchParams.set('id', id);
|
|
385
|
+
const response = await fetch(target, { method: 'POST', headers: { Authorization: `Bearer ${state.token}`, 'Content-Type': 'image/jpeg' }, body: new Blob([new Uint8Array(jpeg)]) });
|
|
386
|
+
if (!response.ok) {
|
|
387
|
+
const body = (await response.json().catch(() => ({})));
|
|
388
|
+
throw new OpenArtifactError(body.code ?? 'error', body.message ?? `thumbnail: HTTP ${response.status}`);
|
|
389
|
+
}
|
|
390
|
+
},
|
|
391
|
+
on(kind, listener) {
|
|
392
|
+
const set = listeners[kind];
|
|
393
|
+
const wantsEvents = () => listeners.artifact.size + listeners.event.size > 0;
|
|
394
|
+
const before = wantsEvents();
|
|
395
|
+
set.add(listener);
|
|
396
|
+
if (!before && wantsEvents()) {
|
|
397
|
+
since = Date.now();
|
|
398
|
+
void client.subscribe(true).catch((error) => log(`open-artifact subscribe: ${error.message}`));
|
|
399
|
+
}
|
|
400
|
+
return () => {
|
|
401
|
+
if (!set.delete(listener))
|
|
402
|
+
return;
|
|
403
|
+
if (kind !== 'state' && kind !== 'shell' && !wantsEvents())
|
|
404
|
+
void client.subscribe(false).catch(() => undefined);
|
|
405
|
+
};
|
|
406
|
+
},
|
|
407
|
+
async installSkill(opts) {
|
|
408
|
+
return (await keepSkillInstalled(client, opts, (listener) => harness.on('state', listener), log)).result;
|
|
409
|
+
},
|
|
410
|
+
commands: (opts) => commands(client, opts),
|
|
411
|
+
runtime: {
|
|
412
|
+
async status() {
|
|
413
|
+
await needs('runtime.update', 'runtime.status');
|
|
414
|
+
return client.request('runtime.status', {});
|
|
415
|
+
},
|
|
416
|
+
async update(version) {
|
|
417
|
+
await needs('runtime.update', 'runtime.update');
|
|
418
|
+
return client.request('runtime.update', version ? { version } : {});
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
close: () => client.close(),
|
|
422
|
+
};
|
|
423
|
+
return harness;
|
|
424
|
+
}
|