@anureo/sdk 0.0.0-stage → 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.
Files changed (76) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +185 -2
  3. package/package.json +66 -4
  4. package/src/adapter/identity.d.ts +41 -0
  5. package/src/adapter/identity.js +71 -0
  6. package/src/client-options.d.ts +71 -0
  7. package/src/client-options.js +0 -0
  8. package/src/client.d.ts +106 -0
  9. package/src/client.js +254 -0
  10. package/src/diagnostics/errors.d.ts +15 -0
  11. package/src/diagnostics/errors.js +59 -0
  12. package/src/diagnostics/events.d.ts +46 -0
  13. package/src/diagnostics/events.js +47 -0
  14. package/src/diagnostics.d.ts +20 -0
  15. package/src/diagnostics.js +56 -0
  16. package/src/errors.d.ts +48 -0
  17. package/src/errors.js +63 -0
  18. package/src/index.d.ts +27 -0
  19. package/src/index.js +23 -0
  20. package/src/lifecycle/approval.d.ts +16 -0
  21. package/src/lifecycle/approval.js +18 -0
  22. package/src/lifecycle/deferred.d.ts +10 -0
  23. package/src/lifecycle/deferred.js +12 -0
  24. package/src/lifecycle/errors.d.ts +18 -0
  25. package/src/lifecycle/errors.js +45 -0
  26. package/src/lifecycle/events.d.ts +35 -0
  27. package/src/lifecycle/events.js +141 -0
  28. package/src/lifecycle/execution-observation.d.ts +33 -0
  29. package/src/lifecycle/execution-observation.js +0 -0
  30. package/src/lifecycle/immutable.d.ts +12 -0
  31. package/src/lifecycle/immutable.js +28 -0
  32. package/src/lifecycle/input.d.ts +9 -0
  33. package/src/lifecycle/input.js +19 -0
  34. package/src/lifecycle/interactions.d.ts +129 -0
  35. package/src/lifecycle/interactions.js +282 -0
  36. package/src/lifecycle/limits.d.ts +7 -0
  37. package/src/lifecycle/limits.js +13 -0
  38. package/src/lifecycle/result.d.ts +77 -0
  39. package/src/lifecycle/result.js +213 -0
  40. package/src/lifecycle/value.d.ts +4 -0
  41. package/src/lifecycle/value.js +5 -0
  42. package/src/ports.d.ts +224 -0
  43. package/src/ports.js +0 -0
  44. package/src/privacy/file-change-limits.d.ts +20 -0
  45. package/src/privacy/file-change-limits.js +124 -0
  46. package/src/privacy/secrets.d.ts +205 -0
  47. package/src/privacy/secrets.js +564 -0
  48. package/src/process.d.ts +92 -0
  49. package/src/process.js +331 -0
  50. package/src/queue.d.ts +143 -0
  51. package/src/queue.js +266 -0
  52. package/src/request.d.ts +28 -0
  53. package/src/request.js +81 -0
  54. package/src/requests/guard.d.ts +15 -0
  55. package/src/requests/guard.js +93 -0
  56. package/src/session.d.ts +459 -0
  57. package/src/session.js +1135 -0
  58. package/src/structured-output/adapter.d.ts +8 -0
  59. package/src/structured-output/adapter.js +54 -0
  60. package/src/structured-output/bridge.d.ts +81 -0
  61. package/src/structured-output/bridge.js +274 -0
  62. package/src/structured-output/errors.d.ts +17 -0
  63. package/src/structured-output/errors.js +31 -0
  64. package/src/structured-output/limits.d.ts +19 -0
  65. package/src/structured-output/limits.js +0 -0
  66. package/src/structured-output/schema.d.ts +20 -0
  67. package/src/structured-output/schema.js +122 -0
  68. package/src/structured-output/session.d.ts +329 -0
  69. package/src/structured-output/session.js +846 -0
  70. package/src/structured-output/stdio.mjs +83 -0
  71. package/src/structured-output/tool.d.ts +38 -0
  72. package/src/structured-output/tool.js +34 -0
  73. package/src/turn.d.ts +75 -0
  74. package/src/turn.js +95 -0
  75. package/src/types.d.ts +62 -0
  76. package/src/types.js +0 -0
@@ -0,0 +1,329 @@
1
+ import { type AhpRequestMap, type AhpResultMap, type Capabilities, type SessionOpenParams, type SessionState } from '@anureo/protocol';
2
+ import type { BackendSession, HarnessAdapter, SessionEventSink, SessionMethod } from "../ports.js";
3
+ import type { OutputBridgeManager } from "./bridge.js";
4
+ import type { OutputLimits } from "./limits.js";
5
+ /**
6
+ * Internal BackendSession implementation constructed and tracked by withStructuredOutput's
7
+ * openSession port. Client.attachSession gives this wrapper to Session, which reads attachment state,
8
+ * dispatches through execute and releases it through disposeBackend. Owns one native session's output
9
+ * associations, fallback lane and serialized commitment. Hosts observe receipts independently of
10
+ * final events, and caller wait cancellation leaves native work and lane ownership alive.
11
+ */
12
+ export declare class OutputSession implements BackendSession {
13
+ /**
14
+ * withStructuredOutput's openSession port constructs this wrapper before tracking and opening it.
15
+ * Capture dependencies without I/O. The wrapper must await open before attachment and dispose on
16
+ * setup failure. dispose invokes forget after release attempts so adapter ownership can be removed.
17
+ */
18
+ constructor(input: {
19
+ params: SessionOpenParams;
20
+ sink: SessionEventSink;
21
+ manager: OutputBridgeManager;
22
+ limits: OutputLimits;
23
+ forget: () => void;
24
+ });
25
+ /** Session.attach reads the native binding after open. validateEnvelope uses the requested identity until the native backend is available. */
26
+ get binding(): import("@anureo/protocol").SessionBinding;
27
+ /** Session.attach adopts this capability projection. The native tool or MCP lease can supply schema support without mutating backend capabilities. */
28
+ get capabilities(): Capabilities;
29
+ /** Session.attach restores this optional projected native state. Return a credential-redacted snapshot with the fallback capability revision applied. */
30
+ get state(): SessionState | undefined;
31
+ /**
32
+ * withStructuredOutput's openSession port awaits this before Client.attachSession receives the
33
+ * wrapper. Prepare an optional bridge before native open, then adopt the backend and its active
34
+ * turns. A reserved bridge name, lease cleanup failure or warning publication failure rejects
35
+ * setup. Other bridge preparation failures warn and continue. If disposal wins the open race,
36
+ * await native release and reject with its failure or SESSION_CLOSED.
37
+ * nativeOutput is the initialization negotiation result, used only to decide bridge preparation;
38
+ * per-session capabilities decide submission mode. Native-open and release failures reject to the
39
+ * adapter wrapper, which owns setup cleanup.
40
+ */
41
+ open({ adapter, nativeOutput }: {
42
+ adapter: HarnessAdapter;
43
+ nativeOutput: boolean;
44
+ }): Promise<this>;
45
+ /**
46
+ * Session.invokeRequest invokes this BackendSession port; Session.executeRequest validates and
47
+ * projects its result. Prepare output policy, check the transformed request against native
48
+ * capabilities, and dispatch once. Bind any receipt turn before returning. A native close
49
+ * receipt revokes output admission before the wrapper returns to Session. Failures
50
+ * reclaim only definitely rejected, unbound submissions and preserve safe cleanup diagnostics.
51
+ * Session owns request replay, caller wait cancellation and native-result validation. These waits
52
+ * never release a live output lane.
53
+ */
54
+ execute<M extends SessionMethod>(method: M, original: AhpRequestMap[M]): Promise<AhpResultMap[M]>;
55
+ /**
56
+ * withStructuredOutput's setup-failure/dispose paths and Session.disposeBackend await this shared
57
+ * cleanup promise. Close admission immediately, release output resources, then attempt backend
58
+ * disposal even after release rejection. Remove adapter ownership after both stages and propagate
59
+ * classified cleanup failures. open separately releases a backend that arrives after this teardown.
60
+ */
61
+ dispose(): Promise<void>;
62
+ private backend?;
63
+ private lease?;
64
+ private disposed;
65
+ private disposal?;
66
+ private chain;
67
+ private queuedBytes;
68
+ private queuedEvents;
69
+ private heldBytes;
70
+ private heldCount;
71
+ private outputBytes;
72
+ private readonly pending;
73
+ private readonly outputs;
74
+ private readonly byTurn;
75
+ private readonly unresolved;
76
+ private readonly active;
77
+ private readonly terminalVersions;
78
+ private terminalVersion;
79
+ private locked?;
80
+ private readonly privateStrings;
81
+ private readonly params;
82
+ private readonly sink;
83
+ private readonly manager;
84
+ private readonly limits;
85
+ private readonly forget;
86
+ /**
87
+ * execute calls this after preparing the request. Validate its frame size, protocol shape and
88
+ * native binding and capabilities before dispatch. Return the native promise directly so the close
89
+ * continuation can revoke output admission as soon as its receipt arrives.
90
+ */
91
+ private dispatch;
92
+ /**
93
+ * open awaits this only for an attested MCP transport. Retain a lease and its private credentials
94
+ * before returning augmented native-open params. A reserved name rejects before allocation; other
95
+ * setup failures release any lease and publish a warning before returning the original params.
96
+ * Cleanup or warning-publication failures reject open, whose adapter caller owns session disposal.
97
+ */
98
+ private prepareBridge;
99
+ /**
100
+ * open supplies these callbacks to the native adapter, which may invoke them before attachment.
101
+ * Route events and bindings through serialized output policy. Session handles interactions and
102
+ * direct failure reports. tryEmit returns false when admission throws and forwards both immediate
103
+ * and asynchronous failures to Session.fail.
104
+ */
105
+ private nativeSink;
106
+ /**
107
+ * execute returns this rejection after preparation, dispatch or result projection fails. Reclaim
108
+ * only definite submission failures; reject leaves already-bound work alive until its terminal.
109
+ * Preserve the original cause unless cleanup fails, then attach safe cleanup diagnostics without
110
+ * replacing the dispatch error code or outcome. Unknown acceptance retains its output lane.
111
+ */
112
+ private rejectDispatch;
113
+ /**
114
+ * The capabilities getter and projectState return this projection to Session attachment
115
+ * and state observers. Prefer the native tool extension over the MCP extension when both exist,
116
+ * retaining native schema support and suppressing fallback advertisement after disposal.
117
+ */
118
+ private projectCapabilities;
119
+ /**
120
+ * The state getter, routeEarlyEvent and execute call this before exposing native state to
121
+ * Session. Return a new state with projected capabilities and the fallback revision offset so
122
+ * observers can distinguish synthetic support. Other state fields remain shared until redaction.
123
+ */
124
+ private projectState;
125
+ /**
126
+ * emit queues acceptance here, prepareBridge and prepareOutput register callbacks that queue
127
+ * candidates here, and execute queues receipt binding. Run work after earlier queued work,
128
+ * returning its result/rejection while preserving the chain for later operations. Callers still own
129
+ * failure publication and cleanup.
130
+ */
131
+ private enqueue;
132
+ /**
133
+ * nativeSink's emit, tryEmit and bindSubmission callbacks invoke this for native events.
134
+ * Reserve queue capacity and clone the envelope before serialized accept. Serialization, cloning
135
+ * and capacity failures throw synchronously. Processing failures await Session.fail before rejecting,
136
+ * and settlement releases queue counters. Adapters await the returned promise for publication order.
137
+ */
138
+ private emit;
139
+ /**
140
+ * routeEarlyEvent awaits this after publishing submission/bound, while execute queues it
141
+ * for a receipt containing turnId. Associate the output and replay held events in order before the
142
+ * caller advances. Conflicting/earlier-execution bindings throw PROTOCOL_ERROR. Replay failures
143
+ * reject to emit or execute, whose failure paths still own observation teardown and cleanup.
144
+ */
145
+ private bind;
146
+ /**
147
+ * bind uses this decision before replaying held events. A late binding from an input admitted
148
+ * before the terminal can share that ended execution and is reclaimed immediately. Binding a
149
+ * newer input to an ended execution or changing an existing binding throws PROTOCOL_ERROR.
150
+ * Record competing schemas on the first output so a native success reports the conflict.
151
+ */
152
+ private associateOutput;
153
+ /**
154
+ * The state getter, accept, routeEarlyEvent, publishOutput and execute project values
155
+ * here before exposing them to Session. Recursively replace output IDs and retained bridge secrets
156
+ * in string values, preserving object keys and leaving retained source data untouched. Session
157
+ * still owns projection of marked user secrets and any host history policy.
158
+ */
159
+ private redact;
160
+ /**
161
+ * rememberText, projectItemSnapshot, submitCandidate and admitOutput reserve or replace retained
162
+ * data here. Apply a signed byte delta to session/output accounting or throw RESULT_BUDGET_EXCEEDED
163
+ * before mutation. Callers commit the corresponding value only after this succeeds and drop/release
164
+ * later reclaim its accounting.
165
+ */
166
+ private retain;
167
+ /**
168
+ * projectItemSnapshot and projectItemDelta store text here for outputValue's terminal assembly.
169
+ * Replace one item's text with signed byte accounting. Distinct-item or byte overflow throws
170
+ * RESULT_BUDGET_EXCEEDED before replacing text, propagating through accept to observation failure.
171
+ */
172
+ private rememberText;
173
+ /**
174
+ * bind reclaims late terminal associations here, and completeTurn/reject reclaim finished or
175
+ * rejected submissions. Remove the submission and subtract its retained bytes. These callers still
176
+ * own turn associations, unresolved IDs and exclusive-lane release.
177
+ */
178
+ private drop;
179
+ /**
180
+ * emit queues this work and bind replays held envelopes through it. Validate and route an envelope,
181
+ * then project its items and commit a terminal before publishing it to Session. A held or suppressed
182
+ * event resolves without publication. Protocol, budget, cleanup and sink failures reject the caller,
183
+ * while candidate-validation failures become failed terminals through publishOutput.
184
+ */
185
+ private accept;
186
+ /**
187
+ * accept calls this before routing or retaining an envelope. Assert its protocol shape using the
188
+ * current binding and validation-only stream metadata. Assertion failures reject acceptance before
189
+ * association state changes, including for envelopes that would otherwise be held.
190
+ */
191
+ private validateEnvelope;
192
+ /**
193
+ * accept awaits this before execution projection. Publish binding before replaying held events,
194
+ * reclaim definite rejections, and publish projected session state. Return true only when publication
195
+ * is complete here. Binding, cleanup or sink failures reject accept. Rejected-status events continue
196
+ * through accept for their normal publication after reclamation.
197
+ */
198
+ private routeEarlyEvent;
199
+ /**
200
+ * accept uses this pure lookup for output association, buffering and terminal projection. Prefer
201
+ * scope.turnId, then lifecycle payload identity, returning undefined for unscoped non-lifecycle events.
202
+ */
203
+ private eventTurnId;
204
+ /**
205
+ * accept uses this predicate to forward lifecycle events for already-terminal turns directly to
206
+ * Session. Return whether the event bypasses output bookkeeping so duplicate starts/completions
207
+ * cannot reopen completed output state. Session still validates its own lifecycle observations.
208
+ */
209
+ private isLateTerminal;
210
+ /**
211
+ * accept returns early when this retains an item/terminal envelope for a possible late binding.
212
+ * Reserve held counters and preserve per-turn order while any output is unbound. bind later replays
213
+ * these envelopes and releases counters. emit already checked combined queued/held capacity.
214
+ */
215
+ private holdForBinding;
216
+ /**
217
+ * accept routes output-associated events through this projection before publication. Retain
218
+ * snapshots/deltas under the output budget and return other events unchanged. undefined means
219
+ * a native final was withheld until terminal validation. Retention failures reject accept.
220
+ */
221
+ private projectItemEvent;
222
+ /**
223
+ * projectItemEvent retains message snapshots and downgrades visible messages to commentary.
224
+ * Withhold completed native finals until terminal validation so accepted output can preserve the
225
+ * identity used by authoritative history. Budget failures throw before publication to accept.
226
+ */
227
+ private projectItemSnapshot;
228
+ /**
229
+ * projectItemEvent assembles streamed text and agent-message patches here for terminal parsing.
230
+ * Preserve final identities but expose patches as commentary until commitment. Budget failures
231
+ * throw through accept; unrelated deltas pass through unchanged.
232
+ */
233
+ private projectItemDelta;
234
+ /**
235
+ * accept awaits this for a real turn/completed event and then publishes the returned terminal.
236
+ * Close candidate admission, disable the direct tool, publish accepted output or withheld commentary,
237
+ * then reclaim associations and release the fallback lane. Validation can replace success with a
238
+ * failed terminal. Tool/sink failures reject before remaining cleanup, leaving disposal to reclaim
239
+ * resources. Host result timeouts never enter this terminal path.
240
+ */
241
+ private completeTurn;
242
+ /**
243
+ * completeTurn records the native terminal after tool cleanup and item publication succeed.
244
+ * Bound the terminal markers used by late binding and reclaim the associated submissions and lane.
245
+ * Use the payload ID for active, terminal and turn-index records. Match retained candidates and
246
+ * the lane using the envelope's resolved association ID.
247
+ */
248
+ private recordTerminal;
249
+ /**
250
+ * completeTurn awaits this only for native success with output state. Convert validation failures
251
+ * into a failed terminal, or publish commentary followed by one accepted final before returning
252
+ * success. Reuse the sole completed native final's identity when available. Sink publication failures
253
+ * reject completeTurn directly, preserving their infrastructure-failure semantics.
254
+ */
255
+ private publishOutput;
256
+ /**
257
+ * publishOutput obtains its candidate here before final schema/privacy checks. Parse the
258
+ * joined native final texts, or return the first retained tool/MCP value. Missing values throw
259
+ * STRUCTURED_OUTPUT_MISSING or STRUCTURED_OUTPUT_INVALID according to prior schema attempts.
260
+ */
261
+ private outputValue;
262
+ /**
263
+ * completeTurn awaits this for non-success terminals, including failures from final validation.
264
+ * Emit retained native items as commentary in insertion order. Publication failures reject before
265
+ * completeTurn records the terminal and reclaims its associations.
266
+ */
267
+ private publishCommentaryFinals;
268
+ /**
269
+ * publishOutput and publishCommentaryFinals await Session.emit directly. Preserve the native
270
+ * item identity while emitting commentary, and let publication failure halt the terminal path.
271
+ */
272
+ private emitCommentaryFinal;
273
+ /**
274
+ * prepareBridge registers a queued handler with OutputBridgeManager.create. The manager's MCP
275
+ * CallTool handler awaits this result. Check the active MCP output, envelope and exact outputId
276
+ * before submitCandidate, returning an MCP acceptance or safe retry guidance. Envelope/ID failures
277
+ * consume no schema attempts. Infrastructure failures reject the registered MCP handler.
278
+ */
279
+ private submitValue;
280
+ /**
281
+ * submitValue formats this decision for MCP. prepareOutput supplies the native tool port with a
282
+ * queued callback capturing the exact Output. Pi's createOutputTool awaits it and translates
283
+ * acceptance into a termination request or returns an error for correction. A structurally equal
284
+ * retry is accepted without storing a second value. The third schema mismatch before acceptance
285
+ * exhausts retries. Return policy failures as decisions, while clone failure rejects the callback.
286
+ * Acceptance remains provisional until publishOutput revalidates the projected result.
287
+ */
288
+ private submitCandidate;
289
+ /** submitCandidate reports either byte-budget failure immediately and retains it for later calls and terminal validation. */
290
+ private rejectCandidateBudget;
291
+ /**
292
+ * routeEarlyEvent calls this for rejected status, and rejectDispatch calls after a definite request
293
+ * failure. Remove unresolved admission, then finish/reclaim an unbound output and release its lane.
294
+ * Bound execution remains owned until its terminal. Tool-disable failures reject before reclamation,
295
+ * allowing the caller to report cleanup failure and later disposal to attempt release.
296
+ */
297
+ private reject;
298
+ /**
299
+ * execute awaits this after checking backend attachment and before native frame/capability checks.
300
+ * Transform schema-bearing input and record the captured input/review ID as unresolved only
301
+ * after preparation succeeds. Return params for native validation and dispatch. Setup
302
+ * failures reject execute, which still knows the original submission ID for definite-failure cleanup.
303
+ */
304
+ private prepareSubmission;
305
+ /**
306
+ * prepareSubmission awaits this for schema-bearing input using the attached backend. Compile the
307
+ * schema, enforce mode-specific admission and reserve retention, then return native params or
308
+ * configure the locked fallback before returning transformed input. The native tool callback is registered here
309
+ * and captures this exact Output. Capacity, schema, exclusivity and registration failures reject to
310
+ * execute's recovery path, which reclaims definite failures. Dispatch and result observation remain
311
+ * with execute and Session.
312
+ */
313
+ private prepareOutput;
314
+ /**
315
+ * prepareOutput calls this after capacity checking and schema compilation, before fallback setup.
316
+ * Prefer native schemas, then a direct tool, then MCP; reject unavailable or conflicting lanes
317
+ * before reserving schema bytes and storing the submission. execute has established backend
318
+ * attachment. Its definite-failure path owns reclaiming state if later setup or dispatch rejects.
319
+ */
320
+ private admitOutput;
321
+ /**
322
+ * execute awaits this after a native close receipt and dispose awaits it before backend
323
+ * disposal. Clear retention, associations and held-event accounting, detach the lease, then attempt
324
+ * lease disposal and native tool disabling together. Clear the lane before invoking either so
325
+ * queued candidates expire at receipt time. Classify promise rejections after both settle.
326
+ * Session still owns observation closure, and OutputSession.dispose owns backend release.
327
+ */
328
+ private release;
329
+ }