# @openartifactsai/harness-kit

The SDK an agent app uses to integrate [Open Artifacts](https://github.com/openartifactsai/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](../../docs/integrating.md); this page is the summary of the package.

## Use

```ts
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 `wake` on attach; `attach()` returns what `wake` did not take. On the
  kit's own attach after a reconnect, what `wake` did not take goes back to the daemon's inbox (`inbox.return`), so
  the session's next `call()` or wait has it; a daemon without that feature leaves it with the kit, which adds it to
  the session's next `call()`.
- A `wake` callback that throws or takes longer than `wakeTimeoutMs` (25 s) answers `failed`. `held` keeps the message
  in the inbox like `failed` but tells the daemon not to run the profile's nudge, because your app starts the turn; to a
  daemon without the feature `wake.held` the kit sends `failed`.
- `caps` in `hello` follow from the callbacks: `wake` only with a `wake` callback, `open` only with an `open` callback
  (`{ embed, origins, remote }` with `embed`), `sessions.start` only with a `startSession` callback (and
  `sessions.models` only with a `sessionModels` one next to it). `options.caps` adds `tools`, `library`, `wake.resume`,
  `wake.mode`.
- Under `embed.remote: 'ask'` (the default) a remote type's page reaches `open` only after `allowRemote` said yes.
- Check `harness.features` by name before using anything newer than the base protocol.
- Names from before the rename still work: the kit asks for the `open-artifacts-harness` subprotocol and then the older
  `open-artifact-harness`, takes `open-artifact://` links as its own, and `./embed` sends and reads both envelope keys,
  `openArtifacts` and `openArtifact`, 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, and `ensureDaemon` replaces it with a newer
  runtime ([harness API](../../docs/spec/harness-api.md#names-from-before-the-rename)).
- `daemon: { spawn }` starts the daemon process yourself. The kit passes `{ bin, args, env, logFile }` (no
  `ELECTRON_RUN_AS_NODE` in `env`) and still chooses the runtime, waits for the daemon, checks its version and tries
  the next runtime; return the process (anything with `once('exit')`) so a failed one is left at once. An Electron app
  with its `RunAsNode` fuse off uses `utilityProcess.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 for
  `exit`) before it quits, so `daemon.json` and the lock do not stay behind
  ([runtime guide](../../docs/integrating/runtime.md#electron-apps-with-the-runasnode-fuse-off)).

## 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](../../docs/integrating.md#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](../../docs/integrating/runtime.md)). `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](https://github.com/openartifactsai/open-artifacts/blob/main/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](https://github.com/openartifactsai/open-artifacts/blob/main/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:

```ts
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](../../docs/integrating/wake.md#starting-a-new-session).

`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):

```ts
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](../../docs/integrating/wake.md#letting-the-person-pick-the-model).

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.

```ts
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](../../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` (with `sample()` and `sampleDeltas` for `sample.create`, `mcpCall()` for `mcp.callTool`, `startSession()` for `session.start`, and `sessionModels()` for `session.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; `switcher` hides the Shell's artifact switcher, `onSaved` and `saved` give the page's save state,
  `onModelUse` and `onModelNotice` what the hidden Shell bar's AI mark and notice would show) and
  `embedLibrary` (the home page). Reference: [docs/spec/embed.md](../../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 each `OPEN_ARTIFACT_*` variable to its `OPEN_ARTIFACTS_*` name when
  that one is unset (call it first thing in a process's entry; `ensureDaemon` and `createHarness` also read both).
  `resolveHome()` finds the home: a named home as is; else `~/.agents/open-artifacts`, after renaming
  `~/.agents/open-artifact` to 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, and `open-artifacts doctor` says so). `resolveHomeDetail()` also says which
  case it was. `withLegacyEnv(env)` gives a child process both spellings, and `defaultHomeWorkspace()` is
  `~/OpenArtifacts`, or `~/OpenArtifact` when only that one exists.
