Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,54 @@
# Migration Guide

## Migrating from 0.10.0 to 0.11.0

### 1. Upgrade the package

```bash
npm install @factory/droid-sdk@^0.11.0
```

Applications that use `run()`, `createSession()`, `resumeSession()`, or
`connectToDaemon()` sessions need no changes. Two unstable daemon resources
lost methods.

### 2. Remove Software Factory calls

`droid.unstable.softwareFactory` is gone, with its `workstreams`, `signals`,
`changes`, `activities`, and `events` resources and their types
(`SoftwareFactoryResource`, `SoftwareFactoryWorkstreamsResource`,
`SoftwareFactorySignalsResource`, `SoftwareFactoryChangesResource`,
`SoftwareFactoryActivitiesResource`, `SoftwareFactoryEventsResource`, and
`SoftwareFactoryWorkstreamEntry`). Daemons no longer serve them.

### 3. Remove held cron sessions

`droid.unstable.crons.holdSession()` and `resumeSession()` are gone, with the
`CronOperationsResource` type. A loop tick now reaches its session as a steering
message, so there is no held state to set or clear. `list`, `create`, `update`,
and `delete` are unchanged.

### 4. New in 0.11.0

- `droid.unstable.workstreams` starts, lists, and updates workstreams on a
daemon. See
[`examples/node/start-workstream.ts`](./examples/node/start-workstream.ts).
- `@factory/droid-sdk/api` exports a client generated from the public Factory
API spec. See [`examples/node/rest-api.ts`](./examples/node/rest-api.ts).
- The root entry point adds `listEnvironments`, `listRemoteSessionElicitations`,
and `answerRemoteSessionElicitation`.
- `@factory/droid-sdk/node` adds `DroidConnectionEndedError`,
`RequestCancelledError`, and `isDroidConnectionEnded`.

### 5. Verify the migration

```bash
npm run typecheck
npm run lint
npm run format:check
npx tsx examples/node/list-sessions.ts
```

## Migrating from 0.9.x to 0.10.0

### 1. Upgrade the package
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ Run Node examples with `npx tsx examples/node/<file>.ts`. To connect a Node
application to a running daemon with an API key, run
`FACTORY_API_KEY=... npx tsx examples/node/daemon-session.ts`.
To start a mission with orchestrator and worker progress, run
`npx tsx examples/node/mission.ts`.
`npx tsx examples/node/mission.ts`. To start a workstream on a running daemon
and leave it running, run
`DROID_DAEMON_URL=... FACTORY_API_KEY=... npx tsx examples/node/start-workstream.ts "<goal>"`.

For browser examples, start a local daemon and run
`npm run serve:browser-example`, then open `http://127.0.0.1:8420/`. The
Expand Down
75 changes: 50 additions & 25 deletions docs/typescript-sdk-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ The namespaced daemon facade normalizes common collection results:
- `sessions.getMessages()` returns the message array directly.
- Collection methods such as `customModels.list()`, `terminals.list()`,
`mcp.listRegistry()`, `mcp.listTools()`, `commands.list()`, and the plugin,
marketplace, automation, and Software Factory list methods return arrays.
marketplace, and automation list methods return arrays.
- Methods whose protocol result includes additional metadata retain the result
object. This includes `sessions.search()`, `mcp.listServers()`, and
`skills.list()`.
Expand Down Expand Up @@ -1095,22 +1095,44 @@ different Factory API host.
| Resource | Functions |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Machine templates | `listMachineTemplates`, `getMachineTemplate` |
| Environments | `listEnvironments` |
| Computers | `listComputers`, `getComputer`, `getComputerByName`, `createComputer`, `updateComputer`, `deleteComputer`, `restartComputer`, `refreshComputer` |
| Computer operations | `getComputerMetrics`, `retryInstallDeps` |
| Remote sessions | `listRemoteSessions` |
| Remote sessions | `listRemoteSessions`, `listRemoteSessionElicitations`, `answerRemoteSessionElicitation` |

The `@factory/droid-sdk/api` entry point exports a client generated from the
public Factory API spec, with one function per operation. Each operation takes
`{ client }` from `createFactoryClient()` and resolves `{ data, error }`,
where `error` holds the body of an HTTP error response. A network failure, an
abort, or a response that cannot be parsed rejects the call instead, and
`throwOnError: true` makes HTTP errors reject too. Several names, such as
`listComputers`, exist on both entry points with different contracts, so a
file that imports both should alias the shared names.

```ts
import { createFactoryClient, listComputers } from '@factory/droid-sdk/api';

const client = createFactoryClient({ apiKey: process.env.FACTORY_API_KEY! });
const { data, error } = await listComputers({ client });
```

See [`examples/node/rest-api.ts`](../examples/node/rest-api.ts).

### Unstable daemon resources

APIs under `droid.unstable` may change between SDK releases.

| Namespace | Main methods or resources |
| ----------------- | ------------------------------------------------------------------------- |
| `crons` | `list`, `create`, `update`, `delete`, `holdSession`, `resumeSession` |
| `missions` | `inspectReadiness`, `acknowledgeReadinessWarning` |
| `semanticDiff` | `getCache`, `saveCache`, `generate` |
| `fileTransfers` | `push`, `pull` |
| `proxy` | `getToken` |
| `softwareFactory` | `workstreams`, `signals`, `changes`, `activities`, and `events` resources |
| Namespace | Main methods or resources |
| --------------- | ------------------------------------------------- |
| `crons` | `list`, `create`, `update`, `delete` |
| `missions` | `inspectReadiness`, `acknowledgeReadinessWarning` |
| `workstreams` | `start`, `list`, `updateSettings` |
| `semanticDiff` | `getCache`, `saveCache`, `generate` |
| `fileTransfers` | `push`, `pull` |
| `proxy` | `getToken` |

See [`examples/node/start-workstream.ts`](../examples/node/start-workstream.ts)
for `workstreams.start()`.

Keep unstable API use behind an application-owned adapter.

Expand Down Expand Up @@ -1317,15 +1339,15 @@ switch (result.subtype) {
- Daemon replacement locking does not coordinate separate clients.
- Browser daemon authentication currently requires an API key.
- New-session spec handoff IDs require raw notification inspection.
- REST remote-session support currently provides listing only.

## Runnable examples

The package includes runnable examples for one-shot runs, streaming, partial
events, sessions, resume, model selection, permissions, AskUser, image and
document attachments, structured output, SDK and external MCP tools, skills,
hooks, observability, spec mode, replacement lifecycle, daemon sessions,
concurrent browser sessions, daemon lifecycle operations, and missions.
concurrent browser sessions, daemon lifecycle operations, missions,
workstreams, and the Factory REST API.

All examples are under:

Expand All @@ -1352,26 +1374,29 @@ Some examples need additional input:
- `document-input.ts`: optionally pass a text or PDF path.
- `external-mcp.ts`: set `MCP_SERVER_URL` and, if necessary, `MCP_SERVER_TOKEN`.
- `daemon-session.ts`: start a daemon first. Set `DROID_DAEMON_URL` for a non-default address.
- `start-workstream.ts`: pass the workstream goal, and set `DROID_DAEMON_URL` for a running daemon whose account has access to workstreams.
- `rest-api.ts`: optionally pass the API base URL.

Use compatible SDK and CLI versions. SDK 0.9.1 and earlier can reject newer
protocol messages, including model providers and Script permission requests.
Use SDK 0.10.0 or later with current CLI releases.
A successful result without assistant text does not prove that streaming works.
Do not remove permission checks to bypass a protocol mismatch.

| Topic | Node examples |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Runs and results | `run.ts`, `result-metadata.ts` |
| Sessions | `multi-turn-session.ts`, `resume-session.ts`, `list-sessions.ts`, `rename-session.ts`, `init-metadata.ts`, `session-settings.ts` |
| Streaming and cancellation | `session-stream.ts`, `partial-stream.ts`, `abort-session-stream.ts`, `interrupt-session.ts` |
| Models | `model-discovery.ts`, `model-selection.ts` |
| Inputs and outputs | `image-attachment.ts`, `document-input.ts`, `structured-output.ts` |
| Permissions and user input | `permission-handler.ts`, `ask-user-elicitation.ts`, `tool-controls.ts` |
| Extensions | `sdk-mcp-tool.ts`, `external-mcp.ts`, `skills.ts`, `hook-execution.ts` |
| Session lifecycle | `fork-session.ts`, `compact-session.ts`, `rewind-session.ts` |
| Spec mode | `enter-spec-mode.ts`, `spec-mode-same-session.ts`, `spec-mode-new-session.ts` |
| Daemon and missions | `daemon-session.ts`, `mission.ts` |
| Observability | `observability.ts` |
| Topic | Node examples |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Runs and results | `run.ts`, `result-metadata.ts` |
| Sessions | `multi-turn-session.ts`, `resume-session.ts`, `list-sessions.ts`, `rename-session.ts`, `init-metadata.ts`, `session-settings.ts` |
| Streaming and cancellation | `session-stream.ts`, `partial-stream.ts`, `abort-session-stream.ts`, `interrupt-session.ts` |
| Models | `model-discovery.ts`, `model-selection.ts` |
| Inputs and outputs | `image-attachment.ts`, `document-input.ts`, `structured-output.ts` |
| Permissions and user input | `permission-handler.ts`, `ask-user-elicitation.ts`, `tool-controls.ts` |
| Extensions | `sdk-mcp-tool.ts`, `external-mcp.ts`, `skills.ts`, `hook-execution.ts` |
| Session lifecycle | `fork-session.ts`, `compact-session.ts`, `rewind-session.ts` |
| Spec mode | `enter-spec-mode.ts`, `spec-mode-same-session.ts`, `spec-mode-new-session.ts` |
| Daemon, missions, and workstreams | `daemon-session.ts`, `mission.ts`, `start-workstream.ts` |
| Factory REST API | `rest-api.ts` |
| Observability | `observability.ts` |

Start a mission in a test project and print orchestrator and worker progress.
`interactionMode: DroidInteractionMode.Mission` alone does not give the session
Expand Down
56 changes: 56 additions & 0 deletions examples/node/rest-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Factory REST API example.
*
* Lists the Computers and remote sessions an API key can see, using the
* client generated from the public Factory API spec. Listing sessions works
* only for organizations that have that feature enabled.
*
* These operations take `{ client }` from `createFactoryClient({ apiKey, baseUrl })`
* and resolve `{ data, error }`. The root `@factory/droid-sdk` REST helpers
* take `{ apiKey, baseUrl }` and resolve the response body. Several names
* exist on both with different contracts, so a file that imports both should
* alias the shared names or import this entry under a namespace. A root
* options object cannot be passed here: generated operations require a
* `client` created with `createFactoryClient`.
*
* Usage:
* FACTORY_API_KEY=... npx tsx examples/node/rest-api.ts [baseUrl]
*/

import {
createFactoryClient,
listComputers,
listSessions,
} from '@factory/droid-sdk/api';

const apiKey = process.env.FACTORY_API_KEY;
if (!apiKey) {
throw new Error('Set FACTORY_API_KEY.');
}

const client = createFactoryClient({
apiKey,
baseUrl: process.argv[2],
});

const computers = await listComputers({ client });
if (computers.error !== undefined) {
throw new Error(
`Listing Computers failed: ${JSON.stringify(computers.error)}`
);
}
console.log(`Computers (${computers.data.computers.length}):`);
for (const computer of computers.data.computers) {
console.log(` ${computer.id} ${computer.name} ${computer.status ?? ''}`);
}

const sessions = await listSessions({ client, query: { limit: 5 } });
if (sessions.error !== undefined) {
throw new Error(`Listing sessions failed: ${JSON.stringify(sessions.error)}`);
}
console.log(`Recent sessions (${sessions.data.sessions.length}):`);
for (const session of sessions.data.sessions) {
console.log(
` ${session.sessionId} ${session.status} ${session.messageCount} messages`
);
}
76 changes: 76 additions & 0 deletions examples/node/start-workstream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Start a workstream on a running daemon and leave it running.
*
* The orchestrator plans the goal and runs agents in the daemon, which keeps
* the workstream going after this script exits. Without an `askUserHandler`,
* any question the orchestrator asks is declined (see ask-user-elicitation.ts).
* An agent's questions and permission prompts are answered only by a client
* that attaches that agent with handlers (`droid.sessions.resume(agentId, ...)`).
*
* Set DROID_DAEMON_URL and FACTORY_API_KEY for an existing daemon whose account
* has access to workstreams. Set DROID_WORKSTREAM_COMPUTER_ID to let agents also run
* on that computer instead of only on this daemon's machine.
* Usage: npx tsx examples/node/start-workstream.ts "<goal>" [cwd]
*/

import {
AutonomyLevel,
DroidMessageType,
ReasoningEffort,
WorkstreamMachineTargetKind,
connectToDaemon,
} from '@factory/droid-sdk';

const url = process.env.DROID_DAEMON_URL;
const apiKey = process.env.FACTORY_API_KEY;
const computerId = process.env.DROID_WORKSTREAM_COMPUTER_ID;
if (!url || !apiKey) {
throw new Error('Set DROID_DAEMON_URL and FACTORY_API_KEY.');
}

const [goal, cwd = process.cwd()] = process.argv.slice(2);
if (!goal) {
throw new Error('Pass the workstream goal as the first argument.');
}

const droid = await connectToDaemon({ url, auth: { apiKey } });
try {
// Agents on another machine reach this daemon through its relay.
if (computerId) await droid.relay.start();
const orchestrator = await droid.unstable.workstreams.start({
cwd,
title: goal.slice(0, 80),
// Agents inherit the orchestrator's autonomy; below High they stop to ask.
autonomyLevel: AutonomyLevel.High,
agentReasoningEffort: ReasoningEffort.High,
...(computerId
? {
machines: [
{
label: 'remote',
target: {
kind: WorkstreamMachineTargetKind.Computer,
computerId,
},
},
],
defaultMachineLabel: 'remote',
}
: {}),
});
console.log(`Workstream ${orchestrator.id} started.`);

for await (const msg of orchestrator.stream(goal)) {
if (msg.type === DroidMessageType.Assistant) {
process.stdout.write(msg.text);
} else if (msg.type === DroidMessageType.Result && !msg.success) {
throw new Error(msg.error?.message ?? `Turn ended: ${msg.subtype}`);
}
}

// Detach, not close: closing would end the workstream in the daemon.
await orchestrator.detach();
console.log(`\nWorkstream ${orchestrator.id} keeps running in the daemon.`);
} finally {
droid.disconnect();
}
Loading
Loading