@anureo/sdk 0.2.0 → 0.3.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/README.md +162 -65
- package/package.json +29 -24
- package/src/adapter/identity.d.ts +41 -0
- package/src/adapter/identity.js +71 -0
- package/src/client-options.d.ts +71 -0
- package/src/client-options.js +0 -0
- package/src/client.d.ts +106 -0
- package/src/client.js +254 -0
- package/src/diagnostics/errors.d.ts +15 -0
- package/src/diagnostics/errors.js +59 -0
- package/src/diagnostics/events.d.ts +46 -0
- package/src/diagnostics/events.js +47 -0
- package/src/diagnostics.d.ts +20 -0
- package/src/diagnostics.js +56 -0
- package/src/errors.d.ts +48 -0
- package/src/errors.js +63 -0
- package/src/index.d.ts +27 -0
- package/src/index.js +23 -0
- package/src/lifecycle/approval.d.ts +16 -0
- package/src/lifecycle/approval.js +18 -0
- package/src/lifecycle/deferred.d.ts +10 -0
- package/src/lifecycle/deferred.js +12 -0
- package/src/lifecycle/errors.d.ts +18 -0
- package/src/lifecycle/errors.js +45 -0
- package/src/lifecycle/events.d.ts +35 -0
- package/src/lifecycle/events.js +141 -0
- package/src/lifecycle/execution-observation.d.ts +33 -0
- package/src/lifecycle/execution-observation.js +0 -0
- package/src/lifecycle/immutable.d.ts +12 -0
- package/src/lifecycle/immutable.js +28 -0
- package/src/lifecycle/input.d.ts +9 -0
- package/src/lifecycle/input.js +19 -0
- package/src/lifecycle/interactions.d.ts +129 -0
- package/src/lifecycle/interactions.js +282 -0
- package/src/lifecycle/limits.d.ts +7 -0
- package/src/lifecycle/limits.js +13 -0
- package/src/lifecycle/result.d.ts +77 -0
- package/src/lifecycle/result.js +213 -0
- package/src/lifecycle/value.d.ts +4 -0
- package/src/lifecycle/value.js +5 -0
- package/src/ports.d.ts +224 -0
- package/src/ports.js +0 -0
- package/src/privacy/file-change-limits.d.ts +20 -0
- package/src/privacy/file-change-limits.js +124 -0
- package/src/privacy/secrets.d.ts +205 -0
- package/src/privacy/secrets.js +564 -0
- package/src/process.d.ts +92 -0
- package/src/process.js +331 -0
- package/src/queue.d.ts +143 -0
- package/src/queue.js +266 -0
- package/src/request.d.ts +28 -0
- package/src/request.js +81 -0
- package/src/requests/guard.d.ts +15 -0
- package/src/requests/guard.js +93 -0
- package/src/session.d.ts +459 -0
- package/src/session.js +1135 -0
- package/src/structured-output/adapter.d.ts +8 -0
- package/src/structured-output/adapter.js +54 -0
- package/src/structured-output/bridge.d.ts +81 -0
- package/src/structured-output/bridge.js +274 -0
- package/src/structured-output/errors.d.ts +17 -0
- package/src/structured-output/errors.js +31 -0
- package/src/structured-output/limits.d.ts +19 -0
- package/src/structured-output/limits.js +0 -0
- package/src/structured-output/schema.d.ts +20 -0
- package/src/structured-output/schema.js +122 -0
- package/src/structured-output/session.d.ts +329 -0
- package/src/structured-output/session.js +846 -0
- package/src/structured-output/stdio.mjs +83 -0
- package/src/structured-output/tool.d.ts +38 -0
- package/src/structured-output/tool.js +34 -0
- package/src/turn.d.ts +75 -0
- package/src/turn.js +95 -0
- package/src/types.d.ts +62 -0
- package/src/types.js +0 -0
- package/dist/diagnostics.d.ts +0 -15
- package/dist/diagnostics.js +0 -34
- package/dist/errors.d.ts +0 -15
- package/dist/file-change-limits.d.ts +0 -5
- package/dist/identity.d.ts +0 -13
- package/dist/index.d.ts +0 -8
- package/dist/index.js +0 -1474
- package/dist/interactions.d.ts +0 -20
- package/dist/ports.d.ts +0 -66
- package/dist/process.d.ts +0 -34
- package/dist/process.js +0 -191
- package/dist/queue.d.ts +0 -36
- package/dist/queue.js +0 -166
- package/dist/runtime.d.ts +0 -85
- package/dist/secrets.d.ts +0 -28
package/README.md
CHANGED
|
@@ -1,79 +1,177 @@
|
|
|
1
1
|
# @anureo/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@anureo/sdk` runs agent sessions through a harness adapter. Applications use it
|
|
4
|
+
to submit input, stream events, collect results, and control native executions.
|
|
5
|
+
The SDK validates AHP requests and events, tracks which execution handles each
|
|
6
|
+
submission, and owns session observation and cleanup. The adapter provides the
|
|
7
|
+
native execution and reports its progress.
|
|
4
8
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
- Per-method request caching, waiting timeouts, typed errors, and recovery state
|
|
9
|
-
- Secret redaction for events, histories, and file-change materials marked as secret
|
|
9
|
+
This guide describes the revised workspace API. The published 0.2.0 release has a
|
|
10
|
+
different lifecycle API. See the [workspace guide](../../README.md) and the
|
|
11
|
+
[lifecycle migration notes](../../draft/docs/native-harness-lifecycle.md).
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
## Quick start
|
|
12
14
|
|
|
13
|
-
|
|
15
|
+
This example requires an authenticated Codex CLI on PATH and the
|
|
16
|
+
[Codex adapter](../adapter/codex/README.md). For a streaming version, run
|
|
17
|
+
`bun run example` from the workspace root or read the
|
|
18
|
+
[greeting example](../../examples/greeting.ts).
|
|
14
19
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
| `@anureo/sdk/process` | `spawnHarnessProcess` — child-process helper used by the stdio adapters |
|
|
19
|
-
| `@anureo/sdk/queue` | The bounded event queue used for host consumption and stream buffering |
|
|
20
|
-
| `@anureo/sdk/diagnostics` | `catalogPhase` and helpers for progress-reporting probes (model catalog sessions) |
|
|
20
|
+
```typescript
|
|
21
|
+
import { createClient } from '@anureo/sdk'
|
|
22
|
+
import { createCodexAdapter } from '@anureo/adapter-codex'
|
|
21
23
|
|
|
22
|
-
|
|
24
|
+
const client = await createClient({
|
|
25
|
+
adapter: createCodexAdapter({ command: 'codex' }),
|
|
26
|
+
identity: { adapterId: 'codex', runtimeConfigId: 'local' },
|
|
27
|
+
})
|
|
23
28
|
|
|
24
|
-
|
|
29
|
+
try {
|
|
30
|
+
const session = await client.sessions.create({ cwd: process.cwd() })
|
|
31
|
+
const turn = await session.submit({ input: 'Say hello in one sentence.' })
|
|
32
|
+
const result = await turn.result()
|
|
25
33
|
|
|
26
|
-
|
|
34
|
+
if (result.status === 'failed') throw new Error(result.error.message)
|
|
35
|
+
if (result.status === 'interrupted') throw new Error('Turn interrupted')
|
|
36
|
+
console.log(result.text)
|
|
27
37
|
|
|
28
|
-
```typescript
|
|
29
|
-
import { createHarnessRuntime } from '@anureo/sdk'
|
|
30
|
-
import { createScriptedAdapter } from '@anureo/conformance'
|
|
31
|
-
|
|
32
|
-
const runtime = createHarnessRuntime(createScriptedAdapter())
|
|
33
|
-
try {
|
|
34
|
-
await runtime.initialize({
|
|
35
|
-
protocolVersions: [1],
|
|
36
|
-
clientInfo: { name: 'my-host', version: '0.1.0' },
|
|
37
|
-
})
|
|
38
|
-
const session = await runtime.openSession({
|
|
39
|
-
requestId: 'open', mode: 'new', cwd: process.cwd(),
|
|
40
|
-
binding: { sessionId: 's1', adapterId: 'scripted', runtimeConfigId: 'local' },
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
// Start consuming events before submitting input: the queue is bounded.
|
|
44
|
-
const consume = (async () => {
|
|
45
|
-
for await (const event of session.events()) {
|
|
46
|
-
if (event.type === 'item/completed' && event.payload.item.type === 'agentMessage') {
|
|
47
|
-
console.log(event.payload.item.text)
|
|
48
|
-
}
|
|
49
|
-
if (event.type === 'turn/completed') return
|
|
50
|
-
}
|
|
51
|
-
})()
|
|
52
|
-
void consume.catch(() => {})
|
|
53
|
-
|
|
54
|
-
await session.startTurn({
|
|
55
|
-
requestId: 'start', sessionId: session.binding.sessionId, turnId: 't1',
|
|
56
|
-
input: [{ type: 'text', text: 'Hello' }],
|
|
57
|
-
})
|
|
58
|
-
await consume
|
|
59
38
|
await session.close()
|
|
60
39
|
} finally {
|
|
61
|
-
await
|
|
40
|
+
await client.dispose()
|
|
62
41
|
}
|
|
63
42
|
```
|
|
64
43
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
44
|
+
## Application API
|
|
45
|
+
|
|
46
|
+
Import the application API and its types from `@anureo/sdk`.
|
|
47
|
+
|
|
48
|
+
### Client
|
|
49
|
+
|
|
50
|
+
| API | Purpose |
|
|
51
|
+
| --- | --- |
|
|
52
|
+
| `createClient(options, wait?)` | Initialize an adapter and return a `Client` ready to open sessions. |
|
|
53
|
+
| `new Client(options)`, `client.initialize(wait?)` | Construct a client without I/O, then negotiate adapter capabilities explicitly. |
|
|
54
|
+
| `client.identity` | Read the adapter and runtime configuration IDs used to validate session bindings. |
|
|
55
|
+
| `client.sessions.create(options, wait?)` | Open a new session with a fresh binding. |
|
|
56
|
+
| `client.sessions.resume(reference, wait?)` | Reopen the session identified by a saved `session.reference`, when supported. |
|
|
57
|
+
| `client.sessions.fork(reference, { boundary }, wait?)` | Open a new session from a specified boundary in an existing session, when supported. |
|
|
58
|
+
| `client.openSession(params, wait?)` | Open a session with explicit AHP open parameters and binding. |
|
|
59
|
+
| `client.dispose()` | Release the client's sessions and adapter. Call it in `finally`. |
|
|
60
|
+
|
|
61
|
+
[`ClientOptions`](src/client-options.ts) configures the adapter, client identity,
|
|
62
|
+
runtime hooks, interaction handlers, and retention limits.
|
|
63
|
+
[`RuntimeOptions`](src/ports.ts) configures timeouts, resource budgets, and host
|
|
64
|
+
hooks such as ID generation and history redaction.
|
|
65
|
+
|
|
66
|
+
### Session
|
|
67
|
+
|
|
68
|
+
A `Session` represents a conversation opened through the client.
|
|
69
|
+
|
|
70
|
+
| API | Purpose |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `session.submit(options, wait?)` | Send input and return a `Turn` once the adapter associates the input with an execution. |
|
|
73
|
+
| `session.review({ target }, wait?)` | Start a supported native review and return its associated `Turn`. |
|
|
74
|
+
| `session.events(options?)` | Subscribe to future session events, including submission progress and interaction requests. Subscribe before submitting to observe those events. |
|
|
75
|
+
| `session.id`, `session.binding`, `session.reference` | Read the session ID, its adapter binding, or a reference for resuming or forking it. |
|
|
76
|
+
| `session.capabilities`, `session.snapshot` | Check the session's current capabilities or read its current privacy-filtered state. |
|
|
77
|
+
| `session.interrupt(options?, wait?)` | Request a session-wide interrupt. Pass `cancelQueued` only when supported. An acknowledgement alone cannot establish that execution stopped or that queued input was withdrawn. |
|
|
78
|
+
| `session.request(method, params, wait?)` | Send a typed, lower-level AHP session request for operations such as history reads or manual interaction responses. |
|
|
79
|
+
| `session.close(wait?)` | Request native close and release observation and backend resources after the receipt. The receipt reports `observationClosed` and `executionStopped` separately. |
|
|
80
|
+
| `session.dispose()` | Release local observation and backend resources without asserting that native execution stopped. |
|
|
81
|
+
|
|
82
|
+
`Input` accepts a string or an array of AHP input blocks. [`SubmitOptions`](src/client-options.ts)
|
|
83
|
+
also accepts capability-gated `delivery`, `overrides`, and `outputSchema`.
|
|
84
|
+
Delivery defaults to `native`, so a backend can queue input or merge it into an
|
|
85
|
+
existing execution. Two submissions can return handles with the same `turn.id`.
|
|
86
|
+
Count the execution and its usage once. Use `delivery: 'afterTurn'` when
|
|
87
|
+
`session.capabilities.input?.delivery` includes `afterTurn`.
|
|
88
|
+
The SDK tracks submission IDs internally. `submit()` waits for an execution
|
|
89
|
+
association, which can arrive before an acceptance receipt or after the execution
|
|
90
|
+
has already ended.
|
|
91
|
+
|
|
92
|
+
Pass a JSON Schema as `outputSchema` when `session.capabilities.turn?.outputSchema`
|
|
93
|
+
is enabled. A successful result carries JSON in `result.text`. The SDK uses native
|
|
94
|
+
schemas where available, a direct output tool on Pi, or a session-scoped MCP bridge
|
|
95
|
+
on supported ACP and Hermes sessions. The [structured output example](../../examples/structured-output.ts)
|
|
96
|
+
shows how to submit and parse a result.
|
|
97
|
+
|
|
98
|
+
Configure supported interactions through `ClientOptions.interactions`.
|
|
99
|
+
An `InteractionHandlers` function handles its kind automatically. An explicit
|
|
100
|
+
key with value `undefined` enables manual responses through session events and
|
|
101
|
+
`session.request('interaction/respond', params)`. An omitted kind is unsupported.
|
|
102
|
+
|
|
103
|
+
### Turn
|
|
104
|
+
|
|
105
|
+
| API | Purpose |
|
|
106
|
+
| --- | --- |
|
|
107
|
+
| `turn.id` | Read the execution ID shared by all handles observing that execution. |
|
|
108
|
+
| `turn.result(wait?)` | Wait for the execution's terminal result or read it if already retained. |
|
|
109
|
+
| `turn.events(options?)` | Subscribe to future events for this execution. |
|
|
110
|
+
| `turn.steer({ input }, wait?)` | Wait for native confirmation that input was appended to this exact execution. Requires `session.capabilities.input?.steer?.atomicMatch` and rejects stale targets. |
|
|
111
|
+
| `turn.interrupt(wait?)` | Request interruption of this exact execution when supported. Use `result()` to observe its terminal status. |
|
|
112
|
+
| `turn.observe()` | Create an independent handle for the same execution. |
|
|
113
|
+
| `turn.dispose()` | Stop this handle's waits and subscriptions. Native execution and other handles can continue. |
|
|
114
|
+
|
|
115
|
+
[`TurnResult`](src/types.ts) is an immutable snapshot with text, items,
|
|
116
|
+
and any available usage. Its status is `completed`, `interrupted`, or `failed`.
|
|
117
|
+
An interrupted result can carry a native error reason.
|
|
118
|
+
|
|
119
|
+
[`RequestOptions`](src/types.ts) sets a caller's wait deadline and abort signal.
|
|
120
|
+
A timeout after dispatch can leave the native outcome unknown. Check
|
|
121
|
+
`HarnessSdkError.outcomeUnknown` before retrying to avoid duplicate work.
|
|
122
|
+
[`EventSubscriptionOptions`](src/types.ts) controls cancellation and
|
|
123
|
+
per-subscription queue limits.
|
|
124
|
+
|
|
125
|
+
## Adapter API
|
|
126
|
+
|
|
127
|
+
Adapters import their contracts from `@anureo/sdk` and use the types in
|
|
128
|
+
[`@anureo/protocol`](../protocol/README.md) for AHP requests, results, and events.
|
|
129
|
+
|
|
130
|
+
| Contract | Who implements and calls it |
|
|
131
|
+
| --- | --- |
|
|
132
|
+
| `HarnessAdapter` | The adapter implements `initialize()`, `openSession()`, and `dispose()`. The client calls them to negotiate capabilities, open native sessions, and release client-wide resources. |
|
|
133
|
+
| `BackendSession` | The adapter returns this from `openSession()`. Core reads its binding, capabilities, and optional state, and calls `execute()` and `dispose()` for native requests and cleanup. `SessionMethod` identifies requests routed through an open session. |
|
|
134
|
+
| `SessionEventSink` | Core supplies this to the adapter at open. The adapter calls `emit()` or `tryEmit()` to publish events, `bindSubmission()` to associate input with an execution, and `fail()` to report observation failure. `EventScope` supplies turn or item context for an event. |
|
|
135
|
+
| `NativeInteractionResponder` | The adapter supplies this callback to `sink.requestInteraction()`. Core calls it to deliver a response or request cancellation. The adapter calls `sink.resolveInteraction()` when the native peer has already settled a request. |
|
|
136
|
+
| `StructuredOutputToolPort`, `StructuredOutputToolDefinition`, `StructuredOutputToolResult` | An adapter can expose a tool port on `BackendSession`. Core calls `configure()` to install or disable the tool. The adapter presents the definition and calls its `execute()` to validate a candidate. |
|
|
137
|
+
|
|
138
|
+
`HarnessAdapter.outputBridgeTransport()` lets an adapter opt into the session MCP
|
|
139
|
+
bridge. `SessionEventSink.projectOutput()` is an optional hook for privacy-filtering
|
|
140
|
+
output before final schema validation. See [the port definitions](src/ports.ts)
|
|
141
|
+
for ordering, failure, and ownership contracts.
|
|
142
|
+
|
|
143
|
+
## Supporting exports
|
|
144
|
+
|
|
145
|
+
| Purpose | Import path | Exports |
|
|
146
|
+
| --- | --- | --- |
|
|
147
|
+
| Errors and caller waits | `@anureo/sdk` | `HarnessSdkError` carries a safe code and outcome metadata. `sdkError()` normalizes a failure. `waitForRequest()` applies a caller-scoped wait using `RequestOptions`. |
|
|
148
|
+
| Unattended approvals | `@anureo/sdk` | `approveWithNarrowestScope()` can be explicitly registered as `interactions.approval`. It chooses allow-once, then session, then rule grants, and rejects when none is offered. Clients never enable it automatically. |
|
|
149
|
+
| Host logging | `@anureo/sdk` | LogTape's `configure`, `configureSync`, `getLogger`, `drain`, `dispose`, `disposeSync`, `reset`, and `resetSync`, plus `Config`, `LogLevel`, `LogRecord`, `Logger`, and `Sink`. The application configures logging sinks. |
|
|
150
|
+
| Native subprocesses | `@anureo/sdk/process` or `@anureo/sdk` | `spawnHarnessProcess()` launches and owns stdio subprocess I/O and cleanup. The module also exports `ProcessPortError`, `ProcessExit`, `HarnessProcess`, and `HarnessProcessOptions`. |
|
|
151
|
+
| Bounded buffering | `@anureo/sdk/queue` or `@anureo/sdk` | `BoundedEventQueue` provides a bounded, single-reader async queue. `QueueLimits` configures its budgets. |
|
|
152
|
+
| Model catalog diagnostics | `@anureo/sdk/diagnostics` | `catalogPhase()` reports probe timing and outcomes. `emitCatalogPhase()` publishes a diagnostic, and `safeCatalogErrorCode()` projects an error to a safe code. `CatalogProbeOptions` and `CatalogProbeEvent` describe observers and their events. |
|
|
153
|
+
|
|
154
|
+
### Implementation helpers
|
|
155
|
+
|
|
156
|
+
The root currently exports `NativeIdentityMap` for native-to-SDK ID mapping,
|
|
157
|
+
`InteractionRegistry` for tracking native interaction responses, and
|
|
158
|
+
`SecretRedactor` for filtering marked secrets.
|
|
159
|
+
`@anureo/sdk/structured-output-stdio` is an internal package entry that core
|
|
160
|
+
resolves to launch the stdio bridge subprocess.
|
|
161
|
+
|
|
162
|
+
## Code structure
|
|
163
|
+
|
|
164
|
+
| Source | Responsibility |
|
|
165
|
+
| --- | --- |
|
|
166
|
+
| [`package.json`](package.json), [`src/index.ts`](src/index.ts) | Define the package entry points and assemble the root exports. |
|
|
167
|
+
| [`src/client.ts`](src/client.ts), [`src/session.ts`](src/session.ts), [`src/turn.ts`](src/turn.ts) | Implement the application API for opening sessions, dispatching requests, and observing and controlling executions. |
|
|
168
|
+
| [`src/client-options.ts`](src/client-options.ts), [`src/types.ts`](src/types.ts), [`src/ports.ts`](src/ports.ts) | Define public configuration, input, result, and observation types, plus adapter contracts. |
|
|
169
|
+
| [`src/errors.ts`](src/errors.ts), [`src/request.ts`](src/request.ts) | Provide SDK errors, failure normalization, and caller-scoped waits. |
|
|
170
|
+
| [`src/lifecycle/`](src/lifecycle/) | Supports the application API with event subscriptions, result accumulation, and interaction settlement. |
|
|
171
|
+
| [`src/adapter/`](src/adapter/), [`src/requests/`](src/requests/) | Provide native-to-SDK ID mapping and request validation against session bindings and capabilities. |
|
|
172
|
+
| [`src/privacy/`](src/privacy/) | Redacts marked secrets from observed data and bounds retained file change content. |
|
|
173
|
+
| [`src/structured-output/`](src/structured-output/) | Wraps adapters for schema validation and manages the direct-tool and MCP fallback paths. |
|
|
174
|
+
| [`src/process.ts`](src/process.ts), [`src/queue.ts`](src/queue.ts), [`src/diagnostics.ts`](src/diagnostics.ts) | Implement the subprocess, bounded queue, and model catalog diagnostics subpaths. |
|
|
77
175
|
|
|
78
176
|
## Development
|
|
79
177
|
|
|
@@ -83,7 +181,6 @@ bun run typecheck
|
|
|
83
181
|
bun test src
|
|
84
182
|
```
|
|
85
183
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
- [AHP v1 protocol](../../spec/ahp-v1.md)
|
|
184
|
+
See the [architecture notes](../../draft/docs/architecture.md) for package
|
|
185
|
+
responsibilities and the [AHP v1 schema](../protocol/schema/v1/ahp.schema.json)
|
|
186
|
+
for wire contracts.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anureo/sdk",
|
|
3
|
-
"version": "0.2.0",
|
|
4
3
|
"description": "Runtime core of the Anureo SDK: unified HarnessRuntime and HarnessSession over any adapter, enforcing AHP semantics",
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"anureo",
|
|
@@ -26,38 +26,43 @@
|
|
|
26
26
|
"type": "module",
|
|
27
27
|
"exports": {
|
|
28
28
|
".": {
|
|
29
|
-
"types": "./
|
|
30
|
-
"import": "./
|
|
31
|
-
"default": "./
|
|
29
|
+
"types": "./src/index.d.ts",
|
|
30
|
+
"import": "./src/index.js",
|
|
31
|
+
"default": "./src/index.js"
|
|
32
32
|
},
|
|
33
33
|
"./process": {
|
|
34
|
-
"types": "./
|
|
35
|
-
"import": "./
|
|
36
|
-
"default": "./
|
|
34
|
+
"types": "./src/process.d.ts",
|
|
35
|
+
"import": "./src/process.js",
|
|
36
|
+
"default": "./src/process.js"
|
|
37
37
|
},
|
|
38
38
|
"./queue": {
|
|
39
|
-
"types": "./
|
|
40
|
-
"import": "./
|
|
41
|
-
"default": "./
|
|
39
|
+
"types": "./src/queue.d.ts",
|
|
40
|
+
"import": "./src/queue.js",
|
|
41
|
+
"default": "./src/queue.js"
|
|
42
42
|
},
|
|
43
43
|
"./diagnostics": {
|
|
44
|
-
"types": "./
|
|
45
|
-
"import": "./
|
|
46
|
-
"default": "./
|
|
47
|
-
}
|
|
44
|
+
"types": "./src/diagnostics.d.ts",
|
|
45
|
+
"import": "./src/diagnostics.js",
|
|
46
|
+
"default": "./src/diagnostics.js"
|
|
47
|
+
},
|
|
48
|
+
"./structured-output-stdio": "./src/structured-output/stdio.mjs"
|
|
48
49
|
},
|
|
49
|
-
"files": [
|
|
50
|
-
"dist",
|
|
51
|
-
"schema",
|
|
52
|
-
"protocol",
|
|
53
|
-
"examples",
|
|
54
|
-
"README.md",
|
|
55
|
-
"LICENSE"
|
|
56
|
-
],
|
|
57
50
|
"dependencies": {
|
|
58
|
-
"@anureo/protocol": "0.
|
|
51
|
+
"@anureo/protocol": "0.3.0",
|
|
52
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
53
|
+
"ajv": "8.20.0"
|
|
59
54
|
},
|
|
60
55
|
"engines": {
|
|
61
56
|
"node": ">=22"
|
|
62
|
-
}
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"@logtape/logtape": ">=2.0.0 <3"
|
|
60
|
+
},
|
|
61
|
+
"files": [
|
|
62
|
+
"src",
|
|
63
|
+
"bin",
|
|
64
|
+
"schema",
|
|
65
|
+
"protocol",
|
|
66
|
+
"examples"
|
|
67
|
+
]
|
|
63
68
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Translate opaque native turn and item IDs when implementing an adapter. Keep one
|
|
3
|
+
* map per native session and use it for events that share those identities. The
|
|
4
|
+
* adapter owns event ordering, failure handling and clearing the map once its
|
|
5
|
+
* identities are no longer needed.
|
|
6
|
+
*/
|
|
7
|
+
export declare class NativeIdentityMap {
|
|
8
|
+
private readonly createId;
|
|
9
|
+
/**
|
|
10
|
+
* Supply an allocator that returns unique, nonempty SDK item IDs. item() invokes it
|
|
11
|
+
* synchronously on a cache miss and propagates failures. The allocator owns uniqueness.
|
|
12
|
+
*/
|
|
13
|
+
constructor(createId: () => string);
|
|
14
|
+
/**
|
|
15
|
+
* Record a turn pair before translating it through turn() or nativeTurn(). Rebinding
|
|
16
|
+
* the same pair is harmless. A conflicting nonempty stored ID throws HarnessSdkError
|
|
17
|
+
* with code PROTOCOL_ERROR before either lookup changes. Empty stored values permit
|
|
18
|
+
* rebinding, which writes only the supplied pair. The adapter handles conflicts.
|
|
19
|
+
*/
|
|
20
|
+
bindTurn(turnId: string, nativeTurnId: string): void;
|
|
21
|
+
/** Adapters translate a native turn ID to its stored SDK ID, or undefined, without mutation or allocation. */
|
|
22
|
+
turn(nativeTurnId: string): string | undefined;
|
|
23
|
+
/** Adapters translate an SDK turn ID to its stored native ID, or undefined, without mutation or allocation. */
|
|
24
|
+
nativeTurn(turnId: string): string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Reuse the SDK item ID for a native item within an SDK turn. The turn can be unbound.
|
|
27
|
+
* The allocator runs synchronously when the pair has no nonempty cached ID. An empty
|
|
28
|
+
* result is returned and triggers another allocation on the next lookup. Allocator
|
|
29
|
+
* failures propagate unchanged and leave the adapter free to retry.
|
|
30
|
+
*/
|
|
31
|
+
item(turnId: string, nativeItemId: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* Forget both turn directions and all cached item IDs once pending events no longer
|
|
34
|
+
* need them. Later calls can bind and allocate again with the same allocator.
|
|
35
|
+
* Repeated clears are harmless. The adapter remains responsible for native cleanup.
|
|
36
|
+
*/
|
|
37
|
+
clear(): void;
|
|
38
|
+
private readonly turnIdsByNativeTurnId;
|
|
39
|
+
private readonly nativeTurnIdsByTurnId;
|
|
40
|
+
private readonly items;
|
|
41
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Maps opaque native identities to SDK identities within an adapter-owned session.
|
|
2
|
+
import { HarnessSdkError } from "../errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Translate opaque native turn and item IDs when implementing an adapter. Keep one
|
|
5
|
+
* map per native session and use it for events that share those identities. The
|
|
6
|
+
* adapter owns event ordering, failure handling and clearing the map once its
|
|
7
|
+
* identities are no longer needed.
|
|
8
|
+
*/
|
|
9
|
+
export class NativeIdentityMap {
|
|
10
|
+
createId;
|
|
11
|
+
/**
|
|
12
|
+
* Supply an allocator that returns unique, nonempty SDK item IDs. item() invokes it
|
|
13
|
+
* synchronously on a cache miss and propagates failures. The allocator owns uniqueness.
|
|
14
|
+
*/
|
|
15
|
+
constructor(createId) {
|
|
16
|
+
this.createId = createId;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Record a turn pair before translating it through turn() or nativeTurn(). Rebinding
|
|
20
|
+
* the same pair is harmless. A conflicting nonempty stored ID throws HarnessSdkError
|
|
21
|
+
* with code PROTOCOL_ERROR before either lookup changes. Empty stored values permit
|
|
22
|
+
* rebinding, which writes only the supplied pair. The adapter handles conflicts.
|
|
23
|
+
*/
|
|
24
|
+
bindTurn(turnId, nativeTurnId) {
|
|
25
|
+
const existingTurnId = this.turnIdsByNativeTurnId.get(nativeTurnId);
|
|
26
|
+
const existingNativeTurnId = this.nativeTurnIdsByTurnId.get(turnId);
|
|
27
|
+
if ((existingTurnId && existingTurnId !== turnId) ||
|
|
28
|
+
(existingNativeTurnId && existingNativeTurnId !== nativeTurnId)) {
|
|
29
|
+
throw new HarnessSdkError("PROTOCOL_ERROR", "Conflicting native turn identity");
|
|
30
|
+
}
|
|
31
|
+
this.turnIdsByNativeTurnId.set(nativeTurnId, turnId);
|
|
32
|
+
this.nativeTurnIdsByTurnId.set(turnId, nativeTurnId);
|
|
33
|
+
}
|
|
34
|
+
/** Adapters translate a native turn ID to its stored SDK ID, or undefined, without mutation or allocation. */
|
|
35
|
+
turn(nativeTurnId) {
|
|
36
|
+
return this.turnIdsByNativeTurnId.get(nativeTurnId);
|
|
37
|
+
}
|
|
38
|
+
/** Adapters translate an SDK turn ID to its stored native ID, or undefined, without mutation or allocation. */
|
|
39
|
+
nativeTurn(turnId) {
|
|
40
|
+
return this.nativeTurnIdsByTurnId.get(turnId);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Reuse the SDK item ID for a native item within an SDK turn. The turn can be unbound.
|
|
44
|
+
* The allocator runs synchronously when the pair has no nonempty cached ID. An empty
|
|
45
|
+
* result is returned and triggers another allocation on the next lookup. Allocator
|
|
46
|
+
* failures propagate unchanged and leave the adapter free to retry.
|
|
47
|
+
*/
|
|
48
|
+
item(turnId, nativeItemId) {
|
|
49
|
+
// Encode the pair so delimiter characters inside opaque IDs cannot alias another pair.
|
|
50
|
+
const key = JSON.stringify([turnId, nativeItemId]);
|
|
51
|
+
let itemId = this.items.get(key);
|
|
52
|
+
if (!itemId) {
|
|
53
|
+
itemId = this.createId();
|
|
54
|
+
this.items.set(key, itemId);
|
|
55
|
+
}
|
|
56
|
+
return itemId;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Forget both turn directions and all cached item IDs once pending events no longer
|
|
60
|
+
* need them. Later calls can bind and allocate again with the same allocator.
|
|
61
|
+
* Repeated clears are harmless. The adapter remains responsible for native cleanup.
|
|
62
|
+
*/
|
|
63
|
+
clear() {
|
|
64
|
+
this.turnIdsByNativeTurnId.clear();
|
|
65
|
+
this.nativeTurnIdsByTurnId.clear();
|
|
66
|
+
this.items.clear();
|
|
67
|
+
}
|
|
68
|
+
turnIdsByNativeTurnId = new Map();
|
|
69
|
+
nativeTurnIdsByTurnId = new Map();
|
|
70
|
+
items = new Map();
|
|
71
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { AhpRequestMap, InteractionRequested, InteractionResponse, SessionBinding } from '@anureo/protocol';
|
|
2
|
+
import type { HarnessAdapter, RuntimeOptions } from "./ports.js";
|
|
3
|
+
import type { Input } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Register automatic interaction handlers in ClientOptions.interactions. An enumerable own key
|
|
6
|
+
* with value undefined advertises manual handling through interaction/requested events and
|
|
7
|
+
* Session.request('interaction/respond', ...). Omit a kind to leave it unsupported.
|
|
8
|
+
*
|
|
9
|
+
* Session.requestInteraction publishes interaction/requested before scheduling a handler with a
|
|
10
|
+
* detached native request, including any private fields needed to answer it. Resolve an answer
|
|
11
|
+
* matching the request kind for native delivery. Rejection triggers cancellation while actionable.
|
|
12
|
+
* Stop host work when the signal aborts on settlement or teardown. The SDK ignores late answers
|
|
13
|
+
* and holds the handler slot until the handler's promise settles.
|
|
14
|
+
*/
|
|
15
|
+
export type InteractionHandlers = {
|
|
16
|
+
[K in InteractionRequested['kind']]?: (request: Extract<InteractionRequested, {
|
|
17
|
+
kind: K;
|
|
18
|
+
}>, context: {
|
|
19
|
+
signal: AbortSignal;
|
|
20
|
+
}) => Promise<Extract<InteractionResponse, {
|
|
21
|
+
kind: K;
|
|
22
|
+
}>>;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Configure an SDK client and transfer adapter cleanup to it when construction succeeds.
|
|
26
|
+
* Client validates identity, interaction registrations and retention limits before native setup.
|
|
27
|
+
* Await Client.dispose to release owned resources. Host callbacks retain responsibility for their
|
|
28
|
+
* own effects and cleanup.
|
|
29
|
+
*/
|
|
30
|
+
export interface ClientOptions {
|
|
31
|
+
/** Client-owned native integration, initialized before opens and disposed after owned sessions. */
|
|
32
|
+
adapter: HarnessAdapter;
|
|
33
|
+
/** Nonblank adapter and runtime configuration IDs that every session binding must match. */
|
|
34
|
+
identity: Pick<SessionBinding, 'adapterId' | 'runtimeConfigId'>;
|
|
35
|
+
/** Host hooks and resource budgets used by this client and each opened session. */
|
|
36
|
+
runtime?: RuntimeOptions;
|
|
37
|
+
/** Interaction kinds and automatic handlers to advertise during initialization. */
|
|
38
|
+
interactions?: InteractionHandlers;
|
|
39
|
+
/** Positive safe-integer retention budgets; capacity checks reject rather than evict unresolved work. */
|
|
40
|
+
limits?: {
|
|
41
|
+
/** Maximum tracked executions per session, including active executions and pinned results. Defaults to 128. */
|
|
42
|
+
maxExecutions?: number;
|
|
43
|
+
/** Maximum retained submission/association records per session; defaults to 1024. */
|
|
44
|
+
maxSubmissions?: number;
|
|
45
|
+
/**
|
|
46
|
+
* Budget for retained execution item snapshots in serialized UTF-8 bytes. Defaults to 16 MiB.
|
|
47
|
+
* Applies within each execution and across the session. Structured output uses a separate
|
|
48
|
+
* retention budget of the same size.
|
|
49
|
+
*/
|
|
50
|
+
maxResultBytes?: number;
|
|
51
|
+
/** Maximum distinct retained items per execution; defaults to 2048. */
|
|
52
|
+
maxItems?: number;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Supply input and per-submission policy to Session.submit. It validates the request before dispatch
|
|
57
|
+
* and resolves with a Turn when it observes the native execution association, which can precede
|
|
58
|
+
* the receipt or follow completion. Invalid input, unsupported policy and wait failures reject.
|
|
59
|
+
* Dispatch failure can reject an unresolved association. Use Turn.result for the terminal outcome,
|
|
60
|
+
* including structured-output validation, and dispose the Turn to release its local observations.
|
|
61
|
+
*/
|
|
62
|
+
export interface SubmitOptions {
|
|
63
|
+
/** Text or protocol blocks to detach and validate before native dispatch. */
|
|
64
|
+
input: Input;
|
|
65
|
+
/** Capability-gated delivery policy. Omission selects 'native', which can queue input or join an existing execution. */
|
|
66
|
+
delivery?: AhpRequestMap['input/submit']['delivery'];
|
|
67
|
+
/** Per-turn overrides checked against advertised capability keys. */
|
|
68
|
+
overrides?: AhpRequestMap['input/submit']['overrides'];
|
|
69
|
+
/** Require valid JSON matching this schema in the final result. Requires session.capabilities.turn.outputSchema. */
|
|
70
|
+
outputSchema?: AhpRequestMap['input/submit']['outputSchema'];
|
|
71
|
+
}
|
|
File without changes
|
package/src/client.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type AhpRequestMap, type SessionBinding, type SessionOpenParams } from '@anureo/protocol';
|
|
2
|
+
import type { RequestOptions } from "./types.js";
|
|
3
|
+
import type { ClientOptions } from "./client-options.js";
|
|
4
|
+
import { Session } from "./session.js";
|
|
5
|
+
export { Session } from "./session.js";
|
|
6
|
+
export type { ClientOptions, InteractionHandlers, SubmitOptions } from "./client-options.js";
|
|
7
|
+
/**
|
|
8
|
+
* Open and manage sessions through one adapter. Use createClient for an initialized client, or
|
|
9
|
+
* construct and initialize it explicitly. Await dispose to release owned sessions and the adapter.
|
|
10
|
+
*/
|
|
11
|
+
export declare class Client {
|
|
12
|
+
private readonly options;
|
|
13
|
+
/**
|
|
14
|
+
* Take ownership of the adapter without starting native I/O. Invalid identity, interaction
|
|
15
|
+
* registrations or retention limits throw INVALID_PARAMS. Direct callers must await initialize
|
|
16
|
+
* before opening sessions and later await dispose, including after failed initialization.
|
|
17
|
+
*/
|
|
18
|
+
constructor(options: ClientOptions);
|
|
19
|
+
/** Read a fresh copy of the adapter and runtime configuration IDs used to check session bindings. */
|
|
20
|
+
get identity(): ClientOptions['identity'];
|
|
21
|
+
/**
|
|
22
|
+
* Negotiate adapter capabilities before opening sessions. Each call invokes adapter negotiation
|
|
23
|
+
* once if admitted and stores the validated capability snapshot on success. The wait defaults to
|
|
24
|
+
* 30 seconds unless configured by runtime.requestTimeoutMs. Invalid waits, adapter or protocol
|
|
25
|
+
* failures, abort and timeout reject. A negotiation that finishes after a failed wait cannot update
|
|
26
|
+
* the client's capabilities. createClient awaits this method and handles cleanup on failure.
|
|
27
|
+
*/
|
|
28
|
+
initialize(wait?: RequestOptions): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Open with explicit request and binding IDs. Resolve with the client-owned Session after backend
|
|
31
|
+
* attachment and initial state publication. Invalid input, unsupported mode, setup or wait failure
|
|
32
|
+
* rejects. The attachment wait defaults to 120 seconds unless configured by runtime.openTimeoutMs.
|
|
33
|
+
* If the wait ends early, the SDK closes local observation and still releases a late backend.
|
|
34
|
+
*/
|
|
35
|
+
openSession(params: SessionOpenParams, wait?: RequestOptions): Promise<Session>;
|
|
36
|
+
/**
|
|
37
|
+
* Release the client and its sessions. Stop admitting opens immediately and share the disposal
|
|
38
|
+
* promise across calls. Await all owned session disposal attempts before releasing the adapter.
|
|
39
|
+
* Reject with RESOURCE_RELEASE_FAILED if release fails. Disposal ends local observation and leaves
|
|
40
|
+
* native execution stop unconfirmed. An open that delivers a backend after teardown releases it
|
|
41
|
+
* on its own attachment path.
|
|
42
|
+
*/
|
|
43
|
+
dispose(): Promise<void>;
|
|
44
|
+
private initialized?;
|
|
45
|
+
private closed;
|
|
46
|
+
private disposing?;
|
|
47
|
+
private readonly owned;
|
|
48
|
+
private readonly createId;
|
|
49
|
+
/** Open sessions using generated request IDs and the same attachment wait and ownership as openSession. */
|
|
50
|
+
readonly sessions: {
|
|
51
|
+
/** Open a new session with a fresh binding. A throwing ID generator fails the call synchronously. */
|
|
52
|
+
create: (options: Omit<SessionOpenParams, "requestId" | "binding" | "mode">, wait?: RequestOptions) => Promise<Session>;
|
|
53
|
+
/** Reopen a saved session reference when supported. Foreign bindings reject and ID-generator throws propagate synchronously. */
|
|
54
|
+
resume: (reference: {
|
|
55
|
+
binding: SessionBinding;
|
|
56
|
+
cwd: string;
|
|
57
|
+
}, wait?: RequestOptions) => Promise<Session>;
|
|
58
|
+
/** Open a fresh session at a supported boundary in the referenced session. Foreign bindings reject before ID generation, which can throw synchronously. */
|
|
59
|
+
fork: (reference: {
|
|
60
|
+
binding: SessionBinding;
|
|
61
|
+
cwd: string;
|
|
62
|
+
}, options: {
|
|
63
|
+
boundary: AhpRequestMap["session/revert"]["boundary"];
|
|
64
|
+
}, wait?: RequestOptions) => Promise<Session>;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* sessions.create and sessions.fork use this for a fresh destination after generating the request
|
|
68
|
+
* ID. Snapshot the configured identity before invoking the host's session ID generator.
|
|
69
|
+
*/
|
|
70
|
+
private newBinding;
|
|
71
|
+
/**
|
|
72
|
+
* dispose caches this release attempt. Close admission before taking the session snapshot and
|
|
73
|
+
* keep the adapter alive until all session disposals settle. Report failures in session order,
|
|
74
|
+
* followed by the adapter failure, through the shared disposal promise.
|
|
75
|
+
*/
|
|
76
|
+
private disposeOwnedResources;
|
|
77
|
+
/**
|
|
78
|
+
* openSession and sessions.create/resume/fork return this promise to hosts. Validate before
|
|
79
|
+
* allocating a Session, then own it before native callbacks or disposal can race attachment.
|
|
80
|
+
* Resolve the attached session, or remove it and await disposal before rejecting setup/wait failure
|
|
81
|
+
* (aggregated if cleanup fails). attachSession continues to release late backends after wait failure.
|
|
82
|
+
*/
|
|
83
|
+
private open;
|
|
84
|
+
/**
|
|
85
|
+
* Client.open uses the returned negotiated capabilities to construct Session. Preserve admission
|
|
86
|
+
* precedence: wait validity, abort, client state, protocol shape, binding, then mode capability.
|
|
87
|
+
* Throws before session allocation/native dispatch; open exposes that failure as its rejection.
|
|
88
|
+
*/
|
|
89
|
+
private validateOpen;
|
|
90
|
+
/**
|
|
91
|
+
* Client.open passes this operation to waitForRequest. Give the wrapped adapter a separate params
|
|
92
|
+
* clone and the Session sink, then await attachment/publication. This work outlives caller abort or
|
|
93
|
+
* timeout: OutputSession.open or Session.attach disposes a backend arriving after teardown.
|
|
94
|
+
* Native/attachment failures reject the operation and remain observed by waitForRequest.
|
|
95
|
+
*/
|
|
96
|
+
private attachSession;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Create and initialize a client before opening sessions. A pre-aborted wait rejects before the
|
|
100
|
+
* client takes ownership of the adapter. Once construction succeeds, initialization failure triggers
|
|
101
|
+
* disposal before rejection. The original cause is preserved unless disposal also fails, in which
|
|
102
|
+
* case both failures are reported as RESOURCE_RELEASE_FAILED. Await dispose on the returned client.
|
|
103
|
+
* createRefactorClient and createReviewClient return this promise to their CLI commands, which
|
|
104
|
+
* await disposal after the run and report output.
|
|
105
|
+
*/
|
|
106
|
+
export declare function createClient(options: ClientOptions, wait?: RequestOptions): Promise<Client>;
|