文档 / 给集成方
@openartifactsai/harness-kit
这一页还没有中文版,下面显示的是英文原文。
The SDK an agent app uses to integrate Open Artifacts. It finds or starts the local daemon, holds a Harness API connection that reconnects by itself, gives the app's agent the tools, hands comment wakes to the app's sessions and page opens to its UI, and reports the artifacts its sessions make.
It depends only on @openartifactsai/protocol and Node built-ins (Node 22.18+, or Electron's Node), and bundles into a
single file. The guide is docs/integrating.md; this page is the summary of the package.
Use
import { createHarness } from '@openartifactsai/harness-kit';
const harness = await createHarness({
harness: 'my-app', // ^[a-z0-9][a-z0-9._-]{0,40}$
agentName: 'Assistant',
commands: ['artifact'],
runtime: { dir: '/path/to/@openartifactsai/cli', version: '0.16.1' }, // starts the daemon when none runs
// Give a message to a session: 'delivered' | 'resumed' | 'drafted' | 'queued' | 'held' (the daemon keeps it, you start
// the turn) | 'failed' (the daemon keeps it),
// or { status, session }. Only the owner's words (source.from.kind === 'owner') should become a user turn.
// source.requests[] may carry userText and selectionSnapshot (feature wake.request.parts) for the chat to show.
wake: async ({ session, text, source }) => ((await myApp.deliver(session, text, source)) ? 'delivered' : 'failed'),
// Show a page in the app's own UI; return false when it was not shown.
embed: { origins: [], mode: 'view', remote: 'ask' },
allowRemote: ({ origin, type }) => myApp.confirm(`Show a ${type} page from ${origin}?`),
open: ({ embedUrl, title }) => myApp.openTab(embedUrl, title),
});
await harness.attach({ session: 's1', workspace: '/path/to/project', title: 'Chat 1' });
const tools = await harness.tools(); // the daemon's, or the bundled definitions offline
const result = await harness.call('Artifact', args, { session: 's1', workspace: '/path/to/project' });
harness.on('artifact', ({ session, artifact, change }) => myApp.card(session, artifact, change));- The connection reconnects with backoff (1 s doubling to 30 s), says hello again and attaches every session again;
not after the person's
daemon.stop(), until they ask for the daemon again. - What waited in a session's inbox goes to
wakeon attach;attach()returns whatwakedid not take. On the kit's own attach after a reconnect, whatwakedid not take goes back to the daemon's inbox (inbox.return), so the session's nextcall()or wait has it; a daemon without that feature leaves it with the kit, which adds it to the session's nextcall(). - A
wakecallback that throws or takes longer thanwakeTimeoutMs(25 s) answersfailed.heldkeeps the message in the inbox likefailedbut tells the daemon not to run the profile's nudge, because your app starts the turn; to a daemon without the featurewake.heldthe kit sendsfailed. capsinhellofollow from the callbacks:wakeonly with awakecallback,openonly with anopencallback ({ embed, origins, remote }withembed),sessions.startonly with astartSessioncallback (andsessions.modelsonly with asessionModelsone next to it).options.capsaddstools,library,wake.resume,wake.mode.- Under
embed.remote: 'ask'(the default) a remote type's page reachesopenonly afterallowRemotesaid yes. - Check
harness.featuresby name before using anything newer than the base protocol. - Names from before the rename still work: the kit asks for the
open-artifacts-harnesssubprotocol and then the olderopen-artifact-harness, takesopen-artifact://links as its own, and./embedsends and reads both envelope keys,openArtifactsandopenArtifact, so a Shell of that time works too. A 0.22 daemon still running is found (readDaemon,daemonHealth) and called (api) at its older paths, andensureDaemonreplaces it with a newer runtime (harness API). daemon: { spawn }starts the daemon process yourself. The kit passes{ bin, args, env, logFile }(noELECTRON_RUN_AS_NODEinenv) and still chooses the runtime, waits for the daemon, checks its version and tries the next runtime; return the process (anything withonce('exit')) so a failed one is left at once. An Electron app with itsRunAsNodefuse off usesutilityProcess.fork(bin, args, { env, stdio: 'pipe' }); type servers then run in worker threads of the daemon, and the app asks the daemon to stop (child.kill(), then a bounded wait forexit) before it quits, sodaemon.jsonand the lock do not stay behind (runtime guide).
The Harness object
| Member | Does |
|---|---|
ready() |
connects now (starting the daemon unless autoStart: false) |
connected, features, client |
the state, the daemon's features, the raw HarnessClient |
attach, status, detach, rename |
sessions |
tools(), call(name, args, caller) |
the tools |
wrote(paths, caller) |
files the agent wrote with its own tools |
open(url, caller) |
shows an artifact (through your open when you show pages) |
view(url) |
the addresses to show one of this daemon's artifacts that the person opened in your app, with no session; shows nothing by itself (feature view.open; a remote page goes through allowRemote, not_granted when refused) |
owns(args) |
whether a tool call is about an open-artifacts:// link |
viewUrl(url), publicUrl(url) |
the local Shell page, and the site address when published |
embedOrigins() |
the origins a view may load (feature embed.origins) |
shellCommand(view, command) |
a host message to a top-level view's Shell (feature shell.command) |
context(url, caller), contextBlock(context) |
what the person selected on the page, as prompt text (feature view.context) |
saveThumbnail(url, jpeg) |
a thumbnail for the library |
installSkill({ dir, … }), commands() |
the skill file and the command menu (features skill.get, commands.list; rendered by the kit without them). opens (host | agent-browser | system | link) sets how the skill tells the agent to show a page; left out, host when you pass open (the daemon's rendering and, through harness.installSkill, the kit's own), else a general step; the standalone helpers take it only as given (commands and the skill) |
runtime.status(), runtime.update(version?) |
the runtimes on this computer and which starts; the person's yes to an update (feature runtime.update; update is not_granted when updates are off) |
daemon.restart() |
the person's restart of the daemon: stops it, waits for its process, starts another and connects to it; a second call waits for the same restart; answers the new daemon.json without its token. Refused (invalid_argument) for a daemon in this process |
daemon.stop(), daemon.start(), daemon.stopped |
the person's stop: stops the daemon and waits for its process, then does not start it again by itself (no reconnecting; calls that would connect fail with disconnected) until daemon.start(), daemon.restart() or ready(); on('state') gets stopped. Answers { stopped, others }: the daemon it stopped (null: none ran) and the other apps connected to it (null: unknown), which may start it again (runtime). start() starts one when none runs and connects; restart, stop and start run one after another |
on('artifact' | 'shell' | 'event' | 'state', listener) |
artifact reports, Shell messages, every daemon event, the connection state (connected, disconnected: dropped, it reconnects; stopped: daemon.stop()) |
close() |
closes the connection for good |
Answering pages' model calls
sample: { caps, run } makes the app a model source for pages' sample calls: hello declares caps.sample, and
each sample.create round goes to run(round, { onText, signal }), which resolves { text, stop, toolCalls?, model?, usage? }. onText(delta) becomes sample.delta (only with caps.stream); signal aborts on sample.cancel and when
the connection drops, and nothing is answered for a cancelled round. Throw an error whose code is rate_limited,
unavailable, not_granted, session_expired (the app's sign-in or key was rejected) or prompt_too_large to refuse
for that reason (SAMPLE_REFUSAL_CODES); anything else answers error. The
round is not a turn of the session: no history, no session tools. Without sample the method is method_not_found.
Walk-through: docs/integrating/sampling.md.
Lending the app's MCP servers to pages
mcp: { listTools, callTool } lends the app's MCP servers to pages, which name one as host:<server>: hello
declares caps.mcp (daemon feature mcp.proxy). listTools({ server?, artifactId? }) resolves { servers: [{ server, tools, authStatus? }] }, names without host:; keep each tool's annotations.readOnlyHint, since a tool without it is
confirmed before each call. callTool({ id, server, tool, arguments, artifactId }, { signal }) runs a call the person
already allowed and resolves the tool's result (content, structuredContent?, isError?; a tool that failed is a
result with isError: true). signal aborts on mcp.cancel and when the connection drops, and nothing is answered
then. Throw an error whose code is rate_limited (with retryAfterMs), needs_reauth, server_unavailable or
timeout to refuse for that reason (MCP_REFUSAL_CODES); anything else answers server_unavailable. Without mcp
the methods are method_not_found. Walk-through: docs/integrating/connectors.md.
Starting a new session for the person
startSession: ({ text, artifact }) => … lets the person start a new session of your app from an artifact's page:
hello declares caps.sessions.start (daemon feature session.start), and the Ask pane of an artifact no session
owns offers "New session" in your app, also while none of your sessions is attached. The callback gets text (the new
session's first message: what the person asked for, then how to take the artifact over; give it to the agent as it is)
and artifact ({ id, url, title, type, root }). Start the session and return within 30 s, without waiting for its
turn:
startSession: async ({ text, artifact }) => {
const session = await myApp.newSession({ title: artifact.title, firstMessage: text });
return { session: session.id, workspace: session.cwd }; // the id you will attach it with
},Return { session } when you know the new session's id at once: the daemon makes it the artifact's owner and hands it
what was sent from the artifact meanwhile. Return nothing when you do not: the session takes the artifact over itself
(text tells it to call Artifact adopt). Return false, or throw, when no session was started: the person is told.
It is only ever called because the person picked your app in the page, never by an agent. Without startSession the
method is method_not_found. Walk-through:
docs/integrating/wake.md.
sessionModels: () => ({ models, default? }) next to it lets the person pick the model, and its reasoning effort,
before the session starts: hello declares caps.sessions.models (daemon feature session.models), and the daemon
asks each time the person is about to pick your app (answer within 10 s):
sessionModels: async () => ({
models: [{ id: 'opus', label: 'Opus', group: 'Anthropic', efforts: [{ id: 'high', label: 'High' }], defaultEffort: 'high' }],
default: { model: 'opus', effort: 'high' },
}),
startSession: async ({ text, artifact, model, effort }) => { /* model and effort: the ids picked, or left out */ },models[] are { id, label, group?, efforts?, defaultEffort? } (SessionModelChoice), efforts[] are
{ id, label }, and default is what a new session runs on when nothing is picked. The picked ids come back to
startSession as model and effort, both left out when the person picked nothing. The daemon shows at most 200
models and 20 efforts a model, drops entries without a string id of at most 200 characters or with an id already
listed, and does not check the picked ids against your list again: startSession refuses a model it does not know
(false or a throw). A throw in sessionModels is logged and answered as { models: [] }: the person starts on your
default. Without startSession, sessionModels is ignored. Walk-through:
docs/integrating/wake.md.
On the raw HarnessClient, handlers answer the daemon's calls (wake.deliver, host.open, shell.event,
sample.create, mcp.listTools, mcp.callTool, session.start, session.models): a handler that throws an OpenArtifactsError answers a JSON-RPC error carrying its body (code,
message, fix, …) in error.data, any other throw a bare server error, and a handler that returns NO_REPLY sends
no answer at all (a round the daemon cancelled). onNotification takes the daemon's other notifications
(sample.cancel, mcp.cancel).
A call that needs a feature the daemon does not list throws unsupported, fix line Update the Open Artifacts runtime this computer runs.
Testing an adapter
@openartifactsai/harness-kit/testing runs a fake daemon in the test process: the Harness API over a real WebSocket on
an ephemeral port, and daemon.json in a temporary home.
import { startFakeDaemon } from '@openartifactsai/harness-kit/testing';
const fake = await startFakeDaemon(); // the real daemon's features; [] plays an older one
const harness = await createHarness({ harness: 'my-app', home: fake.home, autoStart: false, wake });
fake.queueInbox('s1', { text: 'Make it blue', source }); // handed to wake by the next attach
await fake.wake({ session: 's1', text: 'hi' }); // { status } as the adapter answered
fake.setArtifact({ id: 'art_…', title: 'Deck' }); // also what view.open answers for
fake.emit({ type: 'artifacts/changed', id: 'art_…' }); // on('artifact') reports it
fake.drop(); // the adapter reconnects and attaches again
const round = fake.sample({ turns: [{ role: 'user', content: 'Hi' }] }); // sample.create to your `sample.run`
await round.result; round.deltas; round.cancel(); // its answer, its sample.delta texts, sample.cancel
const call = fake.mcpCall({ server: 'notes', tool: 'add_note', arguments: { text: 'Hi' } }); // mcp.callTool to your `mcp.callTool`
await call.result; call.cancel(); // its answer (rejects a refusal), mcp.cancel
await fake.startSession({ text: 'Make a deck' }); // session.start to your `startSession`: { started, session? }
await fake.sessionModels(); // session.models to your `sessionModels`: { models, default? }
fake.calls; // every call it took, in order
await fake.close();It answers skill.get (the protocol's template for your caps) and commands.list (one entry per types, default
slides); onSkill and onCommands replace them, and handle answers any other method. More in
docs/integrating/testing.md.
Entry points
.:createHarness,HarnessClient,NO_REPLY,SAMPLE_REFUSAL_CODES,MCP_REFUSAL_CODES,ensureDaemon,readDaemon,daemonHealth,restartDaemon,stopDaemon,api,isOlderVersion,openArtifactsHome, the runtime choice (selectRuntime,rankRuntimes,runtimeCandidates, …),remoteGate,contextBlock,installSkill,renderSkill,commands../testing:startFakeDaemon(withsample()andsampleDeltasforsample.create,mcpCall()formcp.callTool,startSession()forsession.start, andsessionModels()forsession.models)../embed: browser code with no Node imports, for the app's renderer:embedArtifact(a Shell page in an iframe or a top-level view;switcherhides the Shell's artifact switcher,onSavedandsavedgive the page's save state,onModelUseandonModelNoticewhat the hidden Shell bar's AI mark and notice would show) andembedLibrary(the home page). Reference: docs/spec/embed.md../legacy(also exported from.): the names from before 0.23, when Open Artifacts was "Open Artifact", that installs still use.adoptLegacyEnv(env)copies eachOPEN_ARTIFACT_*variable to itsOPEN_ARTIFACTS_*name when that one is unset (call it first thing in a process's entry;ensureDaemonandcreateHarnessalso read both).resolveHome()finds the home: a named home as is; else~/.agents/open-artifacts, after renaming~/.agents/open-artifactto it and leaving a link at the old path when only the old one exists; the old one when both are folders (nothing is moved, andopen-artifacts doctorsays so).resolveHomeDetail()also says which case it was.withLegacyEnv(env)gives a child process both spellings, anddefaultHomeWorkspace()is~/OpenArtifacts, or~/OpenArtifactwhen only that one exists.