@openartifactsai/harness-kit 0.0.0-stage → 0.23.0-rc.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 +210 -2
- package/package.json +52 -4
- package/src/client.d.ts +160 -0
- package/src/client.js +409 -0
- package/src/context.d.ts +31 -0
- package/src/context.js +61 -0
- package/src/daemon.d.ts +177 -0
- package/src/daemon.js +293 -0
- package/src/embed/index.d.ts +230 -0
- package/src/embed/index.js +376 -0
- package/src/embed/remote.d.ts +39 -0
- package/src/embed/remote.js +51 -0
- package/src/harness.d.ts +383 -0
- package/src/harness.js +678 -0
- package/src/index.d.ts +28 -0
- package/src/index.js +20 -0
- package/src/legacy.d.ts +106 -0
- package/src/legacy.js +278 -0
- package/src/mcp.d.ts +39 -0
- package/src/mcp.js +85 -0
- package/src/runtimes.d.ts +174 -0
- package/src/runtimes.js +398 -0
- package/src/skill.d.ts +58 -0
- package/src/skill.js +88 -0
- package/src/testing-ws.d.ts +44 -0
- package/src/testing-ws.js +204 -0
- package/src/testing.d.ts +227 -0
- package/src/testing.js +564 -0
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@openartifactsai/harness-kit`: how an agent app connects to Open Artifacts.
|
|
3
|
+
*
|
|
4
|
+
* `createHarness` is the whole adapter for most apps: it finds or starts the daemon, keeps the Harness API
|
|
5
|
+
* connection, hands messages to sessions and pages to the app's UI. `HarnessClient` is the connection under it, for an
|
|
6
|
+
* app that wants the calls themselves; `ensureDaemon`, `readDaemon` and `api` find the daemon and call its Library API.
|
|
7
|
+
*
|
|
8
|
+
* Entry points: `.` (this file), `./testing` (a fake daemon for an adapter's tests), `./embed` (browser code that
|
|
9
|
+
* puts a Shell page or the home page into the app's own UI: `embedArtifact`, `embedLibrary`) and `./legacy` (the
|
|
10
|
+
* names before 0.23 that are still read: `adoptLegacyEnv`, `resolveHome`; also exported here).
|
|
11
|
+
*/
|
|
12
|
+
export { api, daemonHealth, daemonStartPlan, defaultDaemonBin, ensureDaemon, isOlderVersion, openArtifactsHome, readDaemon, restartDaemon, startDaemonProcess, stopDaemon, type ApiOptions, type DaemonExitSource, type DaemonSpawn, type DaemonStart, type DaemonStartPlan, type EnsureDaemonOptions, type RestartDaemonOptions, type RestartDaemonResult, type StopDaemonOptions } from './daemon.js';
|
|
13
|
+
export { LEGACY_PROTOCOLS, LEGACY_RUNTIME, LEGACY_RUNTIME_VARIABLES, RUNTIME_ENTRY, compareVersions, isPrerelease, missingRuntimes, packageProtocols, parseVersion, protocolRangeOf, rangesMeet, rankRuntimes, readRuntimePin, readRuntimesFile, runtimeCandidates, runtimeEnv, runtimeInfo, runtimesFileOf, satisfies, selectRuntime, sharedRuntimes, sharedRuntimesOf, validRange, type OwnRuntime, type RuntimeCandidate, type RuntimeRecord, type RuntimesFile, } from './runtimes.js';
|
|
14
|
+
export { DEFAULT_HOME, DEFAULT_HOME_WORKSPACE, ENV_PREFIX, LEGACY_ENV_PREFIX, LEGACY_HOME, LEGACY_HOME_WORKSPACE, adoptLegacyEnv, defaultHomeWorkspace, envValue, expandUserHome, homeFromEnv, legacyEnvName, resolveHome, resolveHomeDetail, withLegacyEnv, type HomeChoice, type HomeResolution, type ResolveHomeOptions, } from './legacy.js';
|
|
15
|
+
export { HarnessClient, NO_REPLY, type ClientCallHandlers, type HarnessClientOptions, type HarnessConnectionState, type HelloExtras } from './client.js';
|
|
16
|
+
export { KIT, SAMPLE_REFUSAL_CODES, createHarness, ownsCall, type ArtifactChange, type ArtifactReport, type Harness, type HarnessArtifact, type HarnessDaemonCalls, type HarnessDaemonPeer, type HarnessDaemonStopResult, type HarnessOptions, type HarnessRuntimeCalls, type OpenRequest, type SampleOptions, type SampleRound, type SampleRoundResult, type SampleRunContext, type WakeAnswer, } from './harness.js';
|
|
17
|
+
/** The shapes of `sample.create` (a page's model round answered by the app's own model). */
|
|
18
|
+
export type { AdapterSampleCaps, HarnessSampleCancel, HarnessSampleCreateParams, HarnessSampleCreateResult, HarnessSampleDelta, SampleRoundStop, SampleTokenUsage, SampleToolCall, SampleToolSpec, SampleTurn } from '@openartifactsai/protocol';
|
|
19
|
+
export type { RuntimeStatus, RuntimeUpdateResult } from '@openartifactsai/protocol';
|
|
20
|
+
export { MCP_REFUSAL_CODES, type McpCallContext, type McpOptions } from './mcp.js';
|
|
21
|
+
export type { HarnessMcpCallToolParams, HarnessMcpListToolsParams, HarnessMcpListToolsResult, HarnessMcpServer, PageMcpToolResult } from '@openartifactsai/protocol';
|
|
22
|
+
/** The shapes of `session.start` and `session.models` (a new session of the app, and the models it can run on). */
|
|
23
|
+
export type { SessionModelChoice, SessionModelEffort, SessionModelsResult, SessionStartParams, SessionStartResult } from '@openartifactsai/protocol';
|
|
24
|
+
/** A wake's structured copy: `source.requests[]` carry `userText` and `selectionSnapshot` (`wake.request.parts`). */
|
|
25
|
+
export type { SelectionSnapshot, SelectionSnapshotItem, WakeSource, WakeSourceRequest } from '@openartifactsai/protocol';
|
|
26
|
+
export { remoteGate, remotePolicyOf, type AllowRemote, type RemotePage, type RemotePagePolicy, type RemotePageRequest } from './embed/remote.js';
|
|
27
|
+
export { CONTEXT_HEADER, MAX_CONTEXT_CHARS, contextBlock, readContext, type ArtifactContext } from './context.js';
|
|
28
|
+
export { commands, installSkill, keepSkillInstalled, localSkill, renderSkill, type InstallSkillOptions, type InstallSkillResult } from './skill.js';
|
package/src/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@openartifactsai/harness-kit`: how an agent app connects to Open Artifacts.
|
|
3
|
+
*
|
|
4
|
+
* `createHarness` is the whole adapter for most apps: it finds or starts the daemon, keeps the Harness API
|
|
5
|
+
* connection, hands messages to sessions and pages to the app's UI. `HarnessClient` is the connection under it, for an
|
|
6
|
+
* app that wants the calls themselves; `ensureDaemon`, `readDaemon` and `api` find the daemon and call its Library API.
|
|
7
|
+
*
|
|
8
|
+
* Entry points: `.` (this file), `./testing` (a fake daemon for an adapter's tests), `./embed` (browser code that
|
|
9
|
+
* puts a Shell page or the home page into the app's own UI: `embedArtifact`, `embedLibrary`) and `./legacy` (the
|
|
10
|
+
* names before 0.23 that are still read: `adoptLegacyEnv`, `resolveHome`; also exported here).
|
|
11
|
+
*/
|
|
12
|
+
export { api, daemonHealth, daemonStartPlan, defaultDaemonBin, ensureDaemon, isOlderVersion, openArtifactsHome, readDaemon, restartDaemon, startDaemonProcess, stopDaemon } from "./daemon.js";
|
|
13
|
+
export { LEGACY_PROTOCOLS, LEGACY_RUNTIME, LEGACY_RUNTIME_VARIABLES, RUNTIME_ENTRY, compareVersions, isPrerelease, missingRuntimes, packageProtocols, parseVersion, protocolRangeOf, rangesMeet, rankRuntimes, readRuntimePin, readRuntimesFile, runtimeCandidates, runtimeEnv, runtimeInfo, runtimesFileOf, satisfies, selectRuntime, sharedRuntimes, sharedRuntimesOf, validRange, } from "./runtimes.js";
|
|
14
|
+
export { DEFAULT_HOME, DEFAULT_HOME_WORKSPACE, ENV_PREFIX, LEGACY_ENV_PREFIX, LEGACY_HOME, LEGACY_HOME_WORKSPACE, adoptLegacyEnv, defaultHomeWorkspace, envValue, expandUserHome, homeFromEnv, legacyEnvName, resolveHome, resolveHomeDetail, withLegacyEnv, } from "./legacy.js";
|
|
15
|
+
export { HarnessClient, NO_REPLY } from "./client.js";
|
|
16
|
+
export { KIT, SAMPLE_REFUSAL_CODES, createHarness, ownsCall, } from "./harness.js";
|
|
17
|
+
export { MCP_REFUSAL_CODES } from "./mcp.js";
|
|
18
|
+
export { remoteGate, remotePolicyOf } from "./embed/remote.js";
|
|
19
|
+
export { CONTEXT_HEADER, MAX_CONTEXT_CHARS, contextBlock, readContext } from "./context.js";
|
|
20
|
+
export { commands, installSkill, keepSkillInstalled, localSkill, renderSkill } from "./skill.js";
|
package/src/legacy.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The names Open Artifacts had before 0.23, when it was "Open Artifact", where they still turn up on a person's
|
|
3
|
+
* machine: environment variables (`OPEN_ARTIFACT_*`, set by adapters, plugins, launchers and shell profiles written for
|
|
4
|
+
* 0.22 and older), the home folder (`~/.agents/open-artifact`, where every install before 0.23 keeps its library) and
|
|
5
|
+
* the folder new artifacts go to (`~/OpenArtifact`). The new names are the only ones written; the old ones are read
|
|
6
|
+
* here, and only here, so they can go away together once no install uses them.
|
|
7
|
+
*
|
|
8
|
+
* Every process entry point that reads our variables calls {@link adoptLegacyEnv} first, so the rest of the code reads
|
|
9
|
+
* the new names only. A child process gets both spellings ({@link withLegacyEnv}): it may be a runtime, a type server
|
|
10
|
+
* or a tool of an older version. The home is found with {@link resolveHome}, which moves an old home to the new place
|
|
11
|
+
* once.
|
|
12
|
+
*/
|
|
13
|
+
/** The prefix of our environment variables. */
|
|
14
|
+
export declare const ENV_PREFIX = "OPEN_ARTIFACTS_";
|
|
15
|
+
/** The prefix before 0.23: adapters, launchers and shell profiles written for 0.22 and older still set it. */
|
|
16
|
+
export declare const LEGACY_ENV_PREFIX = "OPEN_ARTIFACT_";
|
|
17
|
+
/** The Open Artifacts home when none is named. */
|
|
18
|
+
export declare const DEFAULT_HOME = "~/.agents/open-artifacts";
|
|
19
|
+
/**
|
|
20
|
+
* The home before 0.23. An old install's library is there until a new version moves it ({@link resolveHome}); an old
|
|
21
|
+
* adapter names it explicitly, and an old runtime uses it when none is named.
|
|
22
|
+
*/
|
|
23
|
+
export declare const LEGACY_HOME = "~/.agents/open-artifact";
|
|
24
|
+
/** The person's Open Artifacts folder (`homeWorkspace`) when nothing is saved. */
|
|
25
|
+
export declare const DEFAULT_HOME_WORKSPACE = "~/OpenArtifacts";
|
|
26
|
+
/** That folder before 0.23: a person who already has it keeps it ({@link defaultHomeWorkspace}). */
|
|
27
|
+
export declare const LEGACY_HOME_WORKSPACE = "~/OpenArtifact";
|
|
28
|
+
/** The old name of one of our variables (`OPEN_ARTIFACTS_HOME` → `OPEN_ARTIFACT_HOME`); `undefined` for any other name. */
|
|
29
|
+
export declare function legacyEnvName(name: string): string | undefined;
|
|
30
|
+
/** The value of one of our variables in `env` that may not have adopted the old names: the new name's, else the old one's. */
|
|
31
|
+
export declare function envValue(env: NodeJS.ProcessEnv | undefined, name: string): string | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Gives every old variable that is set its new name, when the new name is not set (`''` counts as set: it is how a
|
|
34
|
+
* variable is cleared for a child). Changes `env` in place and returns the new names it set. Call it first thing in a
|
|
35
|
+
* process entry point, before any module reads a variable (an ES module reads its imports first: put the call in a
|
|
36
|
+
* module of its own and import that first).
|
|
37
|
+
*/
|
|
38
|
+
export declare function adoptLegacyEnv(env?: NodeJS.ProcessEnv): string[];
|
|
39
|
+
/**
|
|
40
|
+
* The environment for a child process: a copy of `env` in which each of our variables also has its old name, for a
|
|
41
|
+
* runtime, type server or tool of a version before 0.23. The new names decide: an old name whose new one is not set is
|
|
42
|
+
* dropped (so a variable deleted for the child, by its new name, is gone in both spellings). Adopt the old names of
|
|
43
|
+
* the source first (`adoptLegacyEnv` on a copy) when it may have only those.
|
|
44
|
+
*/
|
|
45
|
+
export declare function withLegacyEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
46
|
+
/** The home named in `env` (`OPEN_ARTIFACTS_HOME`, else the old `OPEN_ARTIFACT_HOME`); `undefined` when neither is set. */
|
|
47
|
+
export declare function homeFromEnv(env?: NodeJS.ProcessEnv): string | undefined;
|
|
48
|
+
/** `path` with a leading `~` (`~/`, or `~\` on Windows) as the folder `userHome`. */
|
|
49
|
+
export declare function expandUserHome(path: string, userHome?: string): string;
|
|
50
|
+
/** How {@link resolveHome} chose the home. */
|
|
51
|
+
export type HomeChoice =
|
|
52
|
+
/** A home other than the two default ones was named: used as it is. */
|
|
53
|
+
'explicit'
|
|
54
|
+
/** The default home: it was there, or no home was (it is made when needed). */
|
|
55
|
+
| 'new'
|
|
56
|
+
/** The old home was moved to the default place just now, and a link to it left where it was. */
|
|
57
|
+
| 'moved'
|
|
58
|
+
/** The old home and the new one are both folders: the old one is used, nothing is moved. */
|
|
59
|
+
| 'both'
|
|
60
|
+
/** The old home could not be moved: it is used this time, and the move is tried again by the next process. */
|
|
61
|
+
| 'move-failed';
|
|
62
|
+
/** What {@link resolveHomeDetail} found. */
|
|
63
|
+
export interface HomeResolution {
|
|
64
|
+
/** The home folder, absolute. */
|
|
65
|
+
path: string;
|
|
66
|
+
choice: HomeChoice;
|
|
67
|
+
/** The default home and the old one, absolute. */
|
|
68
|
+
defaultPath: string;
|
|
69
|
+
legacyPath: string;
|
|
70
|
+
/** One line for the daemon's log and for `open-artifacts doctor` when the old home is involved. */
|
|
71
|
+
note?: string;
|
|
72
|
+
/** For `both` and `move-failed`: what the person can do. */
|
|
73
|
+
fix?: string;
|
|
74
|
+
}
|
|
75
|
+
/** Options of {@link resolveHome}. */
|
|
76
|
+
export interface ResolveHomeOptions {
|
|
77
|
+
/** The home asked for (a `--home` argument, a host's option). Left out: `OPEN_ARTIFACTS_HOME` of `env` (or its old name). */
|
|
78
|
+
home?: string;
|
|
79
|
+
env?: NodeJS.ProcessEnv;
|
|
80
|
+
/** The person's home folder (`~`). Default `os.homedir()`. */
|
|
81
|
+
userHome?: string;
|
|
82
|
+
/** `false`: look again instead of using what this process found before (tests). */
|
|
83
|
+
cache?: boolean;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The Open Artifacts home, and how it was chosen (see {@link resolveHome}).
|
|
87
|
+
*/
|
|
88
|
+
export declare function resolveHomeDetail(options?: ResolveHomeOptions): HomeResolution;
|
|
89
|
+
/**
|
|
90
|
+
* The Open Artifacts home folder (absolute):
|
|
91
|
+
* - a home named (`home`, else `OPEN_ARTIFACTS_HOME`, else the old `OPEN_ARTIFACT_HOME`) is used as it is, unless it is
|
|
92
|
+
* one of the two default places, which counts as none named;
|
|
93
|
+
* - the default `~/.agents/open-artifacts` when it exists, except when the old `~/.agents/open-artifact` is a folder
|
|
94
|
+
* too (not a link): then the old one, and nothing is moved (the daemon's log and `doctor` say so);
|
|
95
|
+
* - the old home when only it exists is moved to the default place, and a link (a junction on Windows) left where it
|
|
96
|
+
* was; when that fails, the old home is used this time and the next process tries again;
|
|
97
|
+
* - neither: the default.
|
|
98
|
+
*
|
|
99
|
+
* Found once per process (the same answer every time); safe when several processes start at once.
|
|
100
|
+
*/
|
|
101
|
+
export declare function resolveHome(options?: ResolveHomeOptions): string;
|
|
102
|
+
/**
|
|
103
|
+
* The person's Open Artifacts folder when nothing is saved: `~/OpenArtifacts`, or the old `~/OpenArtifact` when only
|
|
104
|
+
* that one exists (as a `~` path, like the setting).
|
|
105
|
+
*/
|
|
106
|
+
export declare function defaultHomeWorkspace(userHome?: string): string;
|
package/src/legacy.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The names Open Artifacts had before 0.23, when it was "Open Artifact", where they still turn up on a person's
|
|
3
|
+
* machine: environment variables (`OPEN_ARTIFACT_*`, set by adapters, plugins, launchers and shell profiles written for
|
|
4
|
+
* 0.22 and older), the home folder (`~/.agents/open-artifact`, where every install before 0.23 keeps its library) and
|
|
5
|
+
* the folder new artifacts go to (`~/OpenArtifact`). The new names are the only ones written; the old ones are read
|
|
6
|
+
* here, and only here, so they can go away together once no install uses them.
|
|
7
|
+
*
|
|
8
|
+
* Every process entry point that reads our variables calls {@link adoptLegacyEnv} first, so the rest of the code reads
|
|
9
|
+
* the new names only. A child process gets both spellings ({@link withLegacyEnv}): it may be a runtime, a type server
|
|
10
|
+
* or a tool of an older version. The home is found with {@link resolveHome}, which moves an old home to the new place
|
|
11
|
+
* once.
|
|
12
|
+
*/
|
|
13
|
+
import { lstatSync, readdirSync, realpathSync, renameSync, rmdirSync, statSync, symlinkSync } from 'node:fs';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { join, resolve } from 'node:path';
|
|
16
|
+
/** The prefix of our environment variables. */
|
|
17
|
+
export const ENV_PREFIX = 'OPEN_ARTIFACTS_';
|
|
18
|
+
/** The prefix before 0.23: adapters, launchers and shell profiles written for 0.22 and older still set it. */
|
|
19
|
+
export const LEGACY_ENV_PREFIX = 'OPEN_ARTIFACT_';
|
|
20
|
+
/** The Open Artifacts home when none is named. */
|
|
21
|
+
export const DEFAULT_HOME = '~/.agents/open-artifacts';
|
|
22
|
+
/**
|
|
23
|
+
* The home before 0.23. An old install's library is there until a new version moves it ({@link resolveHome}); an old
|
|
24
|
+
* adapter names it explicitly, and an old runtime uses it when none is named.
|
|
25
|
+
*/
|
|
26
|
+
export const LEGACY_HOME = '~/.agents/open-artifact';
|
|
27
|
+
/** The person's Open Artifacts folder (`homeWorkspace`) when nothing is saved. */
|
|
28
|
+
export const DEFAULT_HOME_WORKSPACE = '~/OpenArtifacts';
|
|
29
|
+
/** That folder before 0.23: a person who already has it keeps it ({@link defaultHomeWorkspace}). */
|
|
30
|
+
export const LEGACY_HOME_WORKSPACE = '~/OpenArtifact';
|
|
31
|
+
/** The old name of one of our variables (`OPEN_ARTIFACTS_HOME` → `OPEN_ARTIFACT_HOME`); `undefined` for any other name. */
|
|
32
|
+
export function legacyEnvName(name) {
|
|
33
|
+
return name.startsWith(ENV_PREFIX) ? LEGACY_ENV_PREFIX + name.slice(ENV_PREFIX.length) : undefined;
|
|
34
|
+
}
|
|
35
|
+
/** The value of one of our variables in `env` that may not have adopted the old names: the new name's, else the old one's. */
|
|
36
|
+
export function envValue(env, name) {
|
|
37
|
+
if (!env)
|
|
38
|
+
return undefined;
|
|
39
|
+
if (env[name] !== undefined)
|
|
40
|
+
return env[name];
|
|
41
|
+
const legacy = legacyEnvName(name);
|
|
42
|
+
return legacy ? env[legacy] : undefined;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Gives every old variable that is set its new name, when the new name is not set (`''` counts as set: it is how a
|
|
46
|
+
* variable is cleared for a child). Changes `env` in place and returns the new names it set. Call it first thing in a
|
|
47
|
+
* process entry point, before any module reads a variable (an ES module reads its imports first: put the call in a
|
|
48
|
+
* module of its own and import that first).
|
|
49
|
+
*/
|
|
50
|
+
export function adoptLegacyEnv(env = process.env) {
|
|
51
|
+
const adopted = [];
|
|
52
|
+
for (const key of Object.keys(env)) {
|
|
53
|
+
if (!key.startsWith(LEGACY_ENV_PREFIX) || env[key] === undefined)
|
|
54
|
+
continue;
|
|
55
|
+
const name = ENV_PREFIX + key.slice(LEGACY_ENV_PREFIX.length);
|
|
56
|
+
if (env[name] !== undefined)
|
|
57
|
+
continue;
|
|
58
|
+
env[name] = env[key];
|
|
59
|
+
adopted.push(name);
|
|
60
|
+
}
|
|
61
|
+
return adopted;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The environment for a child process: a copy of `env` in which each of our variables also has its old name, for a
|
|
65
|
+
* runtime, type server or tool of a version before 0.23. The new names decide: an old name whose new one is not set is
|
|
66
|
+
* dropped (so a variable deleted for the child, by its new name, is gone in both spellings). Adopt the old names of
|
|
67
|
+
* the source first (`adoptLegacyEnv` on a copy) when it may have only those.
|
|
68
|
+
*/
|
|
69
|
+
export function withLegacyEnv(env) {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const [key, value] of Object.entries(env))
|
|
72
|
+
if (!key.startsWith(LEGACY_ENV_PREFIX))
|
|
73
|
+
out[key] = value;
|
|
74
|
+
for (const [key, value] of Object.entries(out)) {
|
|
75
|
+
const legacy = legacyEnvName(key);
|
|
76
|
+
if (legacy && value !== undefined)
|
|
77
|
+
out[legacy] = value;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/** The home named in `env` (`OPEN_ARTIFACTS_HOME`, else the old `OPEN_ARTIFACT_HOME`); `undefined` when neither is set. */
|
|
82
|
+
export function homeFromEnv(env = process.env) {
|
|
83
|
+
return env.OPEN_ARTIFACTS_HOME || env.OPEN_ARTIFACT_HOME || undefined;
|
|
84
|
+
}
|
|
85
|
+
/** `path` with a leading `~` (`~/`, or `~\` on Windows) as the folder `userHome`. */
|
|
86
|
+
export function expandUserHome(path, userHome = homedir()) {
|
|
87
|
+
if (path === '~')
|
|
88
|
+
return userHome;
|
|
89
|
+
if (path.startsWith('~/') || (process.platform === 'win32' && path.startsWith('~\\')))
|
|
90
|
+
return join(userHome, path.slice(2));
|
|
91
|
+
return path;
|
|
92
|
+
}
|
|
93
|
+
const resolved = new Map();
|
|
94
|
+
/** Whether two paths are the same folder by name (case aside on Windows, whose folder names ignore it). */
|
|
95
|
+
function samePath(a, b) {
|
|
96
|
+
const left = resolve(a);
|
|
97
|
+
const right = resolve(b);
|
|
98
|
+
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
99
|
+
}
|
|
100
|
+
function lstatOrNull(path) {
|
|
101
|
+
try {
|
|
102
|
+
return lstatSync(path);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function isDirectory(path) {
|
|
109
|
+
try {
|
|
110
|
+
return statSync(path).isDirectory();
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function realOrNull(path) {
|
|
117
|
+
try {
|
|
118
|
+
return realpathSync(path);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function errorText(error) {
|
|
125
|
+
return error?.code ?? error?.message ?? String(error);
|
|
126
|
+
}
|
|
127
|
+
/** A link at `at` to the folder `target` (a junction on Windows, which needs no privilege). */
|
|
128
|
+
function linkFolder(target, at) {
|
|
129
|
+
symlinkSync(target, at, process.platform === 'win32' ? 'junction' : 'dir');
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Moves the old home to the new place and leaves a link to it where it was, so an older version that still runs
|
|
133
|
+
* finds its library there. `null` when it worked; else why not, with the home back where it was when it could be.
|
|
134
|
+
*/
|
|
135
|
+
function moveHome(legacy, target) {
|
|
136
|
+
try {
|
|
137
|
+
renameSync(legacy, target);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
return { error: errorText(error), movedBack: true };
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
linkFolder(target, legacy);
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
catch (first) {
|
|
147
|
+
// A process of an older version made the old folder again between the two steps. An empty one gives way.
|
|
148
|
+
try {
|
|
149
|
+
const at = lstatSync(legacy);
|
|
150
|
+
if (at.isDirectory() && !at.isSymbolicLink() && readdirSync(legacy).length === 0) {
|
|
151
|
+
rmdirSync(legacy);
|
|
152
|
+
linkFolder(target, legacy);
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
/* moved back below */
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
renameSync(target, legacy);
|
|
161
|
+
return { error: errorText(first), movedBack: true };
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return { error: errorText(first), movedBack: false };
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function defaults(userHome) {
|
|
169
|
+
return { defaultPath: resolve(expandUserHome(DEFAULT_HOME, userHome)), legacyPath: resolve(expandUserHome(LEGACY_HOME, userHome)) };
|
|
170
|
+
}
|
|
171
|
+
/** The home named, when it is not one of the two default places; `null` otherwise. */
|
|
172
|
+
function explicitHome(given, userHome) {
|
|
173
|
+
if (!given)
|
|
174
|
+
return null;
|
|
175
|
+
const base = defaults(userHome);
|
|
176
|
+
const path = resolve(expandUserHome(given, userHome));
|
|
177
|
+
// Either default named explicitly (an older adapter names the old one; a parent process passes on what it found)
|
|
178
|
+
// is the default: every process then settles on the same folder.
|
|
179
|
+
if (samePath(path, base.defaultPath) || samePath(path, base.legacyPath))
|
|
180
|
+
return null;
|
|
181
|
+
return { path, choice: 'explicit', ...base };
|
|
182
|
+
}
|
|
183
|
+
function decide(userHome, migrate) {
|
|
184
|
+
const base = defaults(userHome);
|
|
185
|
+
const { defaultPath, legacyPath } = base;
|
|
186
|
+
// The new home first, then the old: a process that moves the old one between the two looks makes the new one appear
|
|
187
|
+
// before the old one goes, so the old one is never seen as a folder beside a new one that it has just become.
|
|
188
|
+
const defaultIsFolder = isDirectory(defaultPath);
|
|
189
|
+
const old = lstatOrNull(legacyPath);
|
|
190
|
+
const oldIsFolder = !!old && old.isDirectory() && !old.isSymbolicLink();
|
|
191
|
+
// A link at the old place that leads to a folder (the person's own) also counts as the old home, and is moved too.
|
|
192
|
+
const oldLeadsToFolder = !!old && old.isSymbolicLink() && isDirectory(legacyPath);
|
|
193
|
+
if (defaultIsFolder) {
|
|
194
|
+
if (oldIsFolder) {
|
|
195
|
+
const realDefault = realOrNull(defaultPath);
|
|
196
|
+
if (realDefault && realDefault === realOrNull(legacyPath))
|
|
197
|
+
return { path: defaultPath, choice: 'new', ...base };
|
|
198
|
+
return {
|
|
199
|
+
path: legacyPath,
|
|
200
|
+
choice: 'both',
|
|
201
|
+
...base,
|
|
202
|
+
note: `Both ${legacyPath} (the home before 0.23) and ${defaultPath} exist: using ${legacyPath} and moving nothing.`,
|
|
203
|
+
fix: `Keep one of them: move what you need from ${defaultPath} into ${legacyPath} and delete ${defaultPath} (it is then moved there on the next start), or delete ${legacyPath} to use ${defaultPath}.`,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
return { path: defaultPath, choice: 'new', ...base };
|
|
207
|
+
}
|
|
208
|
+
if (!oldIsFolder && !oldLeadsToFolder)
|
|
209
|
+
return { path: defaultPath, choice: 'new', ...base };
|
|
210
|
+
if (!migrate)
|
|
211
|
+
return { path: legacyPath, choice: 'move-failed', ...base, note: `Using the home ${legacyPath} (the home before 0.23).` };
|
|
212
|
+
const failed = moveHome(legacyPath, defaultPath);
|
|
213
|
+
if (!failed) {
|
|
214
|
+
return { path: defaultPath, choice: 'moved', ...base, note: `Moved the home ${legacyPath} to ${defaultPath}; ${legacyPath} now links to it.` };
|
|
215
|
+
}
|
|
216
|
+
if (!failed.movedBack) {
|
|
217
|
+
return {
|
|
218
|
+
path: defaultPath,
|
|
219
|
+
choice: 'moved',
|
|
220
|
+
...base,
|
|
221
|
+
note: `Moved the home ${legacyPath} to ${defaultPath}, but could not leave a link at ${legacyPath} (${failed.error}): versions before 0.23 use ${legacyPath}.`,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
// Another process may have moved it meanwhile (the default is there now): look again, without moving.
|
|
225
|
+
if (isDirectory(defaultPath))
|
|
226
|
+
return decide(userHome, false);
|
|
227
|
+
return {
|
|
228
|
+
path: legacyPath,
|
|
229
|
+
choice: 'move-failed',
|
|
230
|
+
...base,
|
|
231
|
+
note: `Could not move the home ${legacyPath} to ${defaultPath} (${failed.error}): using ${legacyPath}; the move is tried again on the next start.`,
|
|
232
|
+
fix: `Quit every app that uses Open Artifacts (its daemon: open-artifacts daemon stop), then start again.`,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The Open Artifacts home, and how it was chosen (see {@link resolveHome}).
|
|
237
|
+
*/
|
|
238
|
+
export function resolveHomeDetail(options = {}) {
|
|
239
|
+
const userHome = options.userHome ?? homedir();
|
|
240
|
+
const given = options.home || homeFromEnv(options.env ?? process.env);
|
|
241
|
+
const explicit = explicitHome(given, userHome);
|
|
242
|
+
if (explicit)
|
|
243
|
+
return explicit;
|
|
244
|
+
// The default home is looked at once per process: a home that could not be moved is tried again by the next one.
|
|
245
|
+
const key = resolve(userHome);
|
|
246
|
+
if (options.cache !== false) {
|
|
247
|
+
const known = resolved.get(key);
|
|
248
|
+
if (known)
|
|
249
|
+
return known;
|
|
250
|
+
}
|
|
251
|
+
const found = decide(userHome, true);
|
|
252
|
+
resolved.set(key, found);
|
|
253
|
+
return found;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* The Open Artifacts home folder (absolute):
|
|
257
|
+
* - a home named (`home`, else `OPEN_ARTIFACTS_HOME`, else the old `OPEN_ARTIFACT_HOME`) is used as it is, unless it is
|
|
258
|
+
* one of the two default places, which counts as none named;
|
|
259
|
+
* - the default `~/.agents/open-artifacts` when it exists, except when the old `~/.agents/open-artifact` is a folder
|
|
260
|
+
* too (not a link): then the old one, and nothing is moved (the daemon's log and `doctor` say so);
|
|
261
|
+
* - the old home when only it exists is moved to the default place, and a link (a junction on Windows) left where it
|
|
262
|
+
* was; when that fails, the old home is used this time and the next process tries again;
|
|
263
|
+
* - neither: the default.
|
|
264
|
+
*
|
|
265
|
+
* Found once per process (the same answer every time); safe when several processes start at once.
|
|
266
|
+
*/
|
|
267
|
+
export function resolveHome(options = {}) {
|
|
268
|
+
return resolveHomeDetail(options).path;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* The person's Open Artifacts folder when nothing is saved: `~/OpenArtifacts`, or the old `~/OpenArtifact` when only
|
|
272
|
+
* that one exists (as a `~` path, like the setting).
|
|
273
|
+
*/
|
|
274
|
+
export function defaultHomeWorkspace(userHome = homedir()) {
|
|
275
|
+
if (lstatOrNull(join(userHome, 'OpenArtifacts')))
|
|
276
|
+
return DEFAULT_HOME_WORKSPACE;
|
|
277
|
+
return isDirectory(join(userHome, 'OpenArtifact')) ? LEGACY_HOME_WORKSPACE : DEFAULT_HOME_WORKSPACE;
|
|
278
|
+
}
|
package/src/mcp.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `mcp` option of `createHarness`: the app lends its own MCP servers to pages (feature `mcp.proxy`). A page calls
|
|
3
|
+
* one as `host:<server>`; the daemon keeps the declaration check, the person's permission, confirmations and counts,
|
|
4
|
+
* and asks the adapter only for the list of tools and for calls the person allowed.
|
|
5
|
+
*/
|
|
6
|
+
import { type HarnessMcpCallToolParams, type HarnessMcpListToolsParams, type HarnessMcpListToolsResult, type PageMcpToolResult } from '@openartifactsai/protocol';
|
|
7
|
+
import { NO_REPLY } from './client.js';
|
|
8
|
+
/** The second argument of {@link McpOptions.callTool}. */
|
|
9
|
+
export interface McpCallContext {
|
|
10
|
+
/** Aborts when the daemon cancels the call (`mcp.cancel`: the page stopped waiting) or the connection drops. */
|
|
11
|
+
signal: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
/** The `mcp` option of `createHarness`. */
|
|
14
|
+
export interface McpOptions {
|
|
15
|
+
/**
|
|
16
|
+
* The servers the app lends and their tools (`mcp.listTools`); with `params.server`, only that one. Names are
|
|
17
|
+
* without the `host:` prefix. A server whose sign-in lapsed says `authStatus: 'needs_reauth'`.
|
|
18
|
+
*/
|
|
19
|
+
listTools(params: HarnessMcpListToolsParams): HarnessMcpListToolsResult | Promise<HarnessMcpListToolsResult>;
|
|
20
|
+
/**
|
|
21
|
+
* Runs one call the person allowed (`mcp.callTool`). A tool that ran and failed resolves a result with
|
|
22
|
+
* `isError: true`. Throw an error whose `code` is one of {@link MCP_REFUSAL_CODES} to refuse for that reason
|
|
23
|
+
* (`rate_limited` may carry `retryAfterMs`); any other throw answers `server_unavailable`.
|
|
24
|
+
*/
|
|
25
|
+
callTool(params: HarnessMcpCallToolParams, context: McpCallContext): PageMcpToolResult | Promise<PageMcpToolResult>;
|
|
26
|
+
}
|
|
27
|
+
/** The codes an `mcp.callTool` refusal may carry. */
|
|
28
|
+
export declare const MCP_REFUSAL_CODES: readonly ["rate_limited", "needs_reauth", "server_unavailable", "timeout"];
|
|
29
|
+
/** The calls running now, their handlers, and how to stop them. */
|
|
30
|
+
export declare function mcpLender(options: McpOptions, log: (line: string) => void): {
|
|
31
|
+
handlers: {
|
|
32
|
+
'mcp.listTools': (params: HarnessMcpListToolsParams) => Promise<HarnessMcpListToolsResult>;
|
|
33
|
+
'mcp.callTool': (params: HarnessMcpCallToolParams) => Promise<PageMcpToolResult | typeof NO_REPLY>;
|
|
34
|
+
};
|
|
35
|
+
/** `mcp.cancel` from the daemon. */
|
|
36
|
+
onCancel: (params: unknown) => void;
|
|
37
|
+
/** The connection dropped: no answer could reach the daemon. */
|
|
38
|
+
cancelAll: (why: string) => void;
|
|
39
|
+
};
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `mcp` option of `createHarness`: the app lends its own MCP servers to pages (feature `mcp.proxy`). A page calls
|
|
3
|
+
* one as `host:<server>`; the daemon keeps the declaration check, the person's permission, confirmations and counts,
|
|
4
|
+
* and asks the adapter only for the list of tools and for calls the person allowed.
|
|
5
|
+
*/
|
|
6
|
+
import { OpenArtifactsError, } from '@openartifactsai/protocol';
|
|
7
|
+
import { NO_REPLY } from "./client.js";
|
|
8
|
+
/** The codes an `mcp.callTool` refusal may carry. */
|
|
9
|
+
export const MCP_REFUSAL_CODES = Object.freeze(['rate_limited', 'needs_reauth', 'server_unavailable', 'timeout']);
|
|
10
|
+
/** A refusal that also says when to try again. */
|
|
11
|
+
class McpRefusal extends OpenArtifactsError {
|
|
12
|
+
retryAfterMs;
|
|
13
|
+
constructor(code, message, retryAfterMs) {
|
|
14
|
+
super(code, message);
|
|
15
|
+
this.retryAfterMs = retryAfterMs;
|
|
16
|
+
}
|
|
17
|
+
toJSON() {
|
|
18
|
+
return { ...super.toJSON(), ...(this.retryAfterMs !== undefined ? { retryAfterMs: this.retryAfterMs } : {}) };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** The calls running now, their handlers, and how to stop them. */
|
|
22
|
+
export function mcpLender(options, log) {
|
|
23
|
+
const calls = new Map();
|
|
24
|
+
const cancel = (id, why) => {
|
|
25
|
+
const controller = calls.get(id);
|
|
26
|
+
if (!controller || controller.signal.aborted)
|
|
27
|
+
return;
|
|
28
|
+
log(`open-artifacts mcp ${id}: ${why}`);
|
|
29
|
+
controller.abort();
|
|
30
|
+
};
|
|
31
|
+
const listTools = async (params) => {
|
|
32
|
+
const result = await options.listTools(params ?? {});
|
|
33
|
+
const servers = Array.isArray(result?.servers) ? result.servers : [];
|
|
34
|
+
return {
|
|
35
|
+
servers: servers
|
|
36
|
+
.filter((s) => s && typeof s.server === 'string' && s.server)
|
|
37
|
+
.map((s) => ({ ...s, tools: Array.isArray(s.tools) ? s.tools.filter((t) => t && typeof t.name === 'string' && t.name) : [] })),
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
const callTool = async (params) => {
|
|
41
|
+
const id = params?.id;
|
|
42
|
+
if (typeof id !== 'string' || !id)
|
|
43
|
+
throw new OpenArtifactsError('invalid_argument', 'mcp.callTool: id is required.');
|
|
44
|
+
if (typeof params.server !== 'string' || typeof params.tool !== 'string')
|
|
45
|
+
throw new OpenArtifactsError('invalid_argument', 'mcp.callTool: server and tool are required.');
|
|
46
|
+
if (calls.has(id))
|
|
47
|
+
throw new OpenArtifactsError('invalid_argument', `mcp.callTool: call ${id} is already running.`);
|
|
48
|
+
const controller = new AbortController();
|
|
49
|
+
calls.set(id, controller);
|
|
50
|
+
try {
|
|
51
|
+
const result = await options.callTool({ ...params, arguments: params.arguments ?? {} }, { signal: controller.signal });
|
|
52
|
+
if (controller.signal.aborted)
|
|
53
|
+
return NO_REPLY;
|
|
54
|
+
if (!result || typeof result !== 'object')
|
|
55
|
+
throw new OpenArtifactsError('server_unavailable', 'mcp.callTool: callTool resolved without a result.');
|
|
56
|
+
return { ...result, content: Array.isArray(result.content) ? result.content : [] };
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (controller.signal.aborted)
|
|
60
|
+
return NO_REPLY;
|
|
61
|
+
const e = error;
|
|
62
|
+
const message = typeof e?.message === 'string' && e.message ? e.message : String(error);
|
|
63
|
+
log(`open-artifacts mcp ${id}: ${message}`);
|
|
64
|
+
const code = typeof e?.code === 'string' && MCP_REFUSAL_CODES.includes(e.code) ? e.code : 'server_unavailable';
|
|
65
|
+
throw new McpRefusal(code, message, code === 'rate_limited' && typeof e?.retryAfterMs === 'number' ? e.retryAfterMs : undefined);
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
calls.delete(id);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
handlers: { 'mcp.listTools': listTools, 'mcp.callTool': callTool },
|
|
73
|
+
/** `mcp.cancel` from the daemon. */
|
|
74
|
+
onCancel: (params) => {
|
|
75
|
+
const id = params?.id;
|
|
76
|
+
if (typeof id === 'string')
|
|
77
|
+
cancel(id, 'The daemon cancelled the call.');
|
|
78
|
+
},
|
|
79
|
+
/** The connection dropped: no answer could reach the daemon. */
|
|
80
|
+
cancelAll: (why) => {
|
|
81
|
+
for (const id of [...calls.keys()])
|
|
82
|
+
cancel(id, why);
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|