@theokit/agents 4.26.1 → 4.27.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/dist/{agent-handle-DNbFlkrw.d.ts → agent-handle-C6q7iA4u.d.ts} +26 -2
- package/dist/{bridge-entry-Bmg8lKHI.d.ts → bridge-entry-BBtYaYVe.d.ts} +1 -1
- package/dist/bridge.d.ts +1 -1
- package/dist/{chunk-M2JFE6IM.js → chunk-U6WNQ5A2.js} +113 -10
- package/dist/chunk-U6WNQ5A2.js.map +1 -0
- package/dist/client-react.d.ts +1 -1
- package/dist/client-react.js +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +3 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-M2JFE6IM.js.map +0 -1
|
@@ -84,9 +84,21 @@ interface InProcessTransportOptions {
|
|
|
84
84
|
* throws SYNCHRONOUSLY surfaces the error when the stream is READ (via `controller.error`), not from the
|
|
85
85
|
* `sendMessages` promise — whereas `HttpTransport` throws from `sendMessages` on a non-2xx response.
|
|
86
86
|
*/
|
|
87
|
+
/**
|
|
88
|
+
* Uma aprovação estacionada foi descartada porque o turno terminou sem decisão.
|
|
89
|
+
*
|
|
90
|
+
* M92 — tipado de propósito. Antes a promessa simplesmente **nunca** resolvia, e a chamada de tool do
|
|
91
|
+
* SDK pendurava; `resolve(false)` seria pior ainda, porque é indistinguível de "o usuário negou".
|
|
92
|
+
*/
|
|
93
|
+
declare class ApprovalAbortedError extends Error {
|
|
94
|
+
readonly approvalId: string;
|
|
95
|
+
constructor(approvalId: string, motivo: string);
|
|
96
|
+
}
|
|
87
97
|
declare class InProcessTransport implements AgentTransport {
|
|
88
98
|
#private;
|
|
89
99
|
constructor(options: InProcessTransportOptions);
|
|
100
|
+
/** Quantas aprovações estão estacionadas. Existe para o teste poder provar a eviction. */
|
|
101
|
+
get pendentes(): number;
|
|
90
102
|
sendMessages(options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0]): Promise<ReadableStream<UIMessageChunk>>;
|
|
91
103
|
reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null>;
|
|
92
104
|
approve(approvalId: string, decision: ApprovalDecision): Promise<void>;
|
|
@@ -168,9 +180,21 @@ interface AgentClientState {
|
|
|
168
180
|
* `useSyncExternalStore`; a standalone (no-React) client (M44) can subscribe directly. Being
|
|
169
181
|
* framework-agnostic, it is unit-tested without a DOM.
|
|
170
182
|
*/
|
|
183
|
+
/**
|
|
184
|
+
* M92 — opções do cliente. Aditivo: sem elas, o comportamento é o de sempre.
|
|
185
|
+
*/
|
|
186
|
+
interface AgentClientOptions {
|
|
187
|
+
/**
|
|
188
|
+
* Janela de coalescing em ms. `0` ou ausente = emite por delta de token (comportamento pré-M92).
|
|
189
|
+
*
|
|
190
|
+
* Opt-in de propósito: este é um pacote publicado, e mudar a frequência de emit por padrão mudaria o
|
|
191
|
+
* comportamento observável de quem conta emits ou depende da latência do primeiro token.
|
|
192
|
+
*/
|
|
193
|
+
readonly emitIntervalMs?: number;
|
|
194
|
+
}
|
|
171
195
|
declare class AgentClient<TInput = unknown> {
|
|
172
196
|
#private;
|
|
173
|
-
constructor(transport: AgentTransport, contextResolver?: () => RequestContext | undefined);
|
|
197
|
+
constructor(transport: AgentTransport, contextResolver?: () => RequestContext | undefined, options?: AgentClientOptions);
|
|
174
198
|
/** Subscribe to state changes; returns an unsubscribe fn. */
|
|
175
199
|
subscribe: (listener: () => void) => (() => void);
|
|
176
200
|
/** The current immutable snapshot (stable reference until the next emit). */
|
|
@@ -224,4 +248,4 @@ declare function agentHandle<TInput = unknown, TToolNames extends string = strin
|
|
|
224
248
|
/** Narrow an unknown binding to an {@link AgentHandle} (has a string `path`, is not a transport). */
|
|
225
249
|
declare function isAgentHandle(value: unknown): value is AgentHandle;
|
|
226
250
|
|
|
227
|
-
export { type ApprovalDecision as A, type ChannelPushSource as C, type InProcessApprovalRequestLike as I, type RequestContext as R, type UseAgentStatus as U, type AgentHandle as a, type AgentTransport as b, AgentClient as c, type
|
|
251
|
+
export { type ApprovalDecision as A, type ChannelPushSource as C, type InProcessApprovalRequestLike as I, type RequestContext as R, type UseAgentStatus as U, type AgentHandle as a, type AgentTransport as b, AgentClient as c, type AgentClientOptions as d, type AgentClientState as e, ApprovalAbortedError as f, ChannelTransport as g, type ChannelTransportOptions as h, type ChannelTurnHandlers as i, type InProcessAwaitApproval as j, type InProcessRunInput as k, type InProcessRunner as l, InProcessTransport as m, type InProcessTransportOptions as n, agentHandle as o, isAgentHandle as p };
|
|
@@ -2176,4 +2176,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
|
|
|
2176
2176
|
register(app: PluginApp): void;
|
|
2177
2177
|
};
|
|
2178
2178
|
|
|
2179
|
-
export {
|
|
2179
|
+
export { DelegationBudgetExceededError as $, type ApprovalOptions as A, type ApiErrorPolicy as B, type CompiledAgentOptions as C, type DelegationResult as D, type ApprovalRequiredEvent as E, type ArtifactChunkEvent as F, type Guardrail as G, type HumanInTheLoopOptions as H, type ArtifactStartEvent as I, type BackgroundDelegation as J, type BeforeToolCallContext as K, type LoopStrategy as L, type MainLoopMeta as M, BudgetExceededError as N, type BudgetOptions as O, type CheckpointSavedEvent as P, type CompiledContextWindow as Q, type ReflectionStrategy as R, type StreamEvent as S, type ToolOptions as T, ContextualTool as U, CostBudgetExceededError as V, DEFAULT_MAX_ITERATIONS as W, type DefineAgentConfig as X, type DefinicaoOuThunk as Y, type DelegateFn as Z, type DelegateOptions as _, type CompiledTool as a, delegate as a$, DelegationError as a0, type DoneEvent as a1, type ErrorEvent as a2, type FileEditEvent as a3, type GuardrailAction as a4, type GuardrailPhase as a5, type GuardrailResult as a6, GuardrailViolationError as a7, type HookHandlers as a8, type InferAgentInput as a9, type SkillsRequestContext as aA, type SkillsSelection as aB, type StateUpdateEvent as aC, type TextDeltaEvent as aD, type ThinkingEvent as aE, type TimeoutAction as aF, type ToolCallEvent as aG, type ToolCallVeto as aH, type ToolHooks as aI, type ToolHooksPlugin as aJ, type ToolResultEvent as aK, type ToolWalkResult as aL, type ToolboxOptions as aM, type ToolboxWalkResult as aN, agentsPlugin as aO, buildModelSelection as aP, compileAgentDefinition as aQ, compileAgentModule as aR, compileContextWindow as aS, compileProjectContext as aT, compileSkills as aU, compileTools as aV, createAgentExecutionContext as aW, createApiErrorHandler as aX, createSdkAgentStream as aY, createThinkTagExtractor as aZ, createToolHooksPlugin as a_, type InferAgentToolNames as aa, type IterationEvent as ab, type LLMCallContext as ac, type LoopFinishReason as ad, type LoopOutcome as ae, type LoopStrategyConfig as af, type MainLoopOptions as ag, type McpApprovalSpec as ah, type McpRegistryConfig as ai, type McpRequestContext as aj, type McpSelection as ak, type PartialToolCallEvent as al, type PolicyHandler as am, type ProcessInputContext as an, type ReflectionContext as ao, type ReflectionResult as ap, type ReflectionStrategyConfig as aq, type RunStartedEvent as ar, type ScoreVerdict as as, type ScoredDelegation as at, type Scorer as au, type SdkAgentHandle as av, type SdkMessage as aw, type SdkSendOptions as ax, type SdkTurnHandle as ay, type Segment as az, type ReasoningEffort as b, delegateBackground as b0, delegateWithScoring as b1, extractThinkTagStream as b2, generateAgentManifest as b3, generateAgentRoutes as b4, isAgentContext as b5, isAgentDefinition as b6, isApprovalRequired as b7, isDone as b8, isError as b9, isPartialToolCall as ba, isTextDelta as bb, isToolCall as bc, isToolResult as bd, ladderReflectionStrategy as be, loopStrategyConfigSchema as bf, mcpRegistry as bg, mcpToolApprovals as bh, noopReflectionStrategy as bi, presentUIMessageStream as bj, projectContextMetadataOnlyKnobs as bk, reflectionStrategyConfigSchema as bl, resolveEnabledSkills as bm, resolveLoopStrategy as bn, resolveMcpServers as bo, runWithApiErrorHandling as bp, streamAgentResponse as bq, toAgentFactory as br, translateSdkEvent as bs, type RoundStreamFactory as c, type ContextWindowOptions as d, type SkillsOptions as e, type AgentManifestEntry as f, type HitlDecision as g, AGENT_BRAND as h, type AfterToolCallContext as i, AgentBuilder as j, type AgentDefinition as k, AgentDefinitionError as l, type AgentExecutionContext as m, type AgentManifest as n, type AgentManifestSource as o, type AgentManifestTool as p, type AgentOptions as q, type AgentRoute as r, streamAgentUIMessages as s, type AgentRouteContext as t, type AgentRunInfo as u, type AgentStreamEvent as v, type AgentTurnMetadata as w, type AgentsPluginOptions as x, type ApiErrorContext as y, type ApiErrorDecision as z };
|
package/dist/bridge.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { h as AGENT_BRAND, i as AfterToolCallContext, j as AgentBuilder, k as AgentDefinition, l as AgentDefinitionError, m as AgentExecutionContext, n as AgentManifest, f as AgentManifestEntry, o as AgentManifestSource, p as AgentManifestTool, r as AgentRoute, t as AgentRouteContext, u as AgentRunInfo, v as AgentStreamEvent, w as AgentTurnMetadata, x as AgentsPluginOptions, y as ApiErrorContext, z as ApiErrorDecision, B as ApiErrorPolicy, E as ApprovalRequiredEvent, F as ArtifactChunkEvent, I as ArtifactStartEvent, J as BackgroundDelegation, K as BeforeToolCallContext,
|
|
1
|
+
export { h as AGENT_BRAND, i as AfterToolCallContext, j as AgentBuilder, k as AgentDefinition, l as AgentDefinitionError, m as AgentExecutionContext, n as AgentManifest, f as AgentManifestEntry, o as AgentManifestSource, p as AgentManifestTool, r as AgentRoute, t as AgentRouteContext, u as AgentRunInfo, v as AgentStreamEvent, w as AgentTurnMetadata, x as AgentsPluginOptions, y as ApiErrorContext, z as ApiErrorDecision, B as ApiErrorPolicy, E as ApprovalRequiredEvent, F as ArtifactChunkEvent, I as ArtifactStartEvent, J as BackgroundDelegation, K as BeforeToolCallContext, N as BudgetExceededError, P as CheckpointSavedEvent, C as CompiledAgentOptions, Q as CompiledContextWindow, a as CompiledTool, U as ContextualTool, X as DefineAgentConfig, Y as DefinicaoOuThunk, Z as DelegateFn, _ as DelegateOptions, $ as DelegationBudgetExceededError, a0 as DelegationError, D as DelegationResult, a1 as DoneEvent, a2 as ErrorEvent, a3 as FileEditEvent, a9 as InferAgentInput, aa as InferAgentToolNames, ab as IterationEvent, ac as LLMCallContext, ah as McpApprovalSpec, ai as McpRegistryConfig, aj as McpRequestContext, ak as McpSelection, al as PartialToolCallEvent, an as ProcessInputContext, ar as RunStartedEvent, as as ScoreVerdict, at as ScoredDelegation, au as Scorer, av as SdkAgentHandle, aw as SdkMessage, ax as SdkSendOptions, ay as SdkTurnHandle, az as Segment, aC as StateUpdateEvent, S as StreamEvent, aD as TextDeltaEvent, aE as ThinkingEvent, aG as ToolCallEvent, aH as ToolCallVeto, aI as ToolHooks, aJ as ToolHooksPlugin, aK as ToolResultEvent, aL as ToolWalkResult, aN as ToolboxWalkResult, aO as agentsPlugin, aP as buildModelSelection, aQ as compileAgentDefinition, aR as compileAgentModule, aS as compileContextWindow, aT as compileProjectContext, aU as compileSkills, aV as compileTools, aW as createAgentExecutionContext, aX as createApiErrorHandler, aY as createSdkAgentStream, aZ as createThinkTagExtractor, a_ as createToolHooksPlugin, a$ as delegate, b0 as delegateBackground, b1 as delegateWithScoring, b2 as extractThinkTagStream, b3 as generateAgentManifest, b4 as generateAgentRoutes, b5 as isAgentContext, b6 as isAgentDefinition, b7 as isApprovalRequired, b8 as isDone, b9 as isError, ba as isPartialToolCall, bb as isTextDelta, bc as isToolCall, bd as isToolResult, bg as mcpRegistry, bh as mcpToolApprovals, bj as presentUIMessageStream, bk as projectContextMetadataOnlyKnobs, bo as resolveMcpServers, bp as runWithApiErrorHandling, bq as streamAgentResponse, s as streamAgentUIMessages, br as toAgentFactory, bs as translateSdkEvent } from './bridge-entry-BBtYaYVe.js';
|
|
2
2
|
import '@theokit/http';
|
|
3
3
|
import '@theokit/sdk';
|
|
4
4
|
import 'zod';
|
|
@@ -165,13 +165,32 @@ function generatorToStream(gen) {
|
|
|
165
165
|
});
|
|
166
166
|
}
|
|
167
167
|
__name(generatorToStream, "generatorToStream");
|
|
168
|
+
var ApprovalAbortedError = class extends Error {
|
|
169
|
+
static {
|
|
170
|
+
__name(this, "ApprovalAbortedError");
|
|
171
|
+
}
|
|
172
|
+
approvalId;
|
|
173
|
+
constructor(approvalId, motivo) {
|
|
174
|
+
super(`Aprova\xE7\xE3o '${approvalId}' descartada: ${motivo}.`), this.approvalId = approvalId;
|
|
175
|
+
this.name = "ApprovalAbortedError";
|
|
176
|
+
}
|
|
177
|
+
};
|
|
168
178
|
var InProcessTransport = class {
|
|
169
179
|
static {
|
|
170
180
|
__name(this, "InProcessTransport");
|
|
171
181
|
}
|
|
172
182
|
#run;
|
|
173
|
-
/**
|
|
183
|
+
/**
|
|
184
|
+
* Aprovações inline estacionadas: `approvalId` → como resolver **ou rejeitar** a promessa parada.
|
|
185
|
+
*
|
|
186
|
+
* M92 — o `reject` entrou junto com a eviction. Antes havia só o `resolve`, e nada apagava a entrada
|
|
187
|
+
* quando o turno abortava: a promessa ficava pendente **para sempre**, e a chamada de tool do SDK
|
|
188
|
+
* pendurava com ela. Uma promessa que nunca resolve **nem** rejeita é a forma mais silenciosa de
|
|
189
|
+
* engolir um erro — nem stack trace existe (`error-handling.md § 2`).
|
|
190
|
+
*/
|
|
174
191
|
#pending = /* @__PURE__ */ new Map();
|
|
192
|
+
/** O turno corrente. Um `send()` novo incrementa e varre o anterior. */
|
|
193
|
+
#turno = 0;
|
|
175
194
|
constructor(options) {
|
|
176
195
|
this.#run = options.run;
|
|
177
196
|
}
|
|
@@ -180,10 +199,42 @@ var InProcessTransport = class {
|
|
|
180
199
|
reject(new Error(`Duplicate pending approval id '${req.approvalId}' \u2014 ids must be unique.`));
|
|
181
200
|
return;
|
|
182
201
|
}
|
|
183
|
-
this.#pending.set(req.approvalId,
|
|
202
|
+
this.#pending.set(req.approvalId, {
|
|
203
|
+
resolve,
|
|
204
|
+
reject,
|
|
205
|
+
turno: this.#turno
|
|
206
|
+
});
|
|
184
207
|
}), "#awaitApproval");
|
|
208
|
+
/**
|
|
209
|
+
* Varre as aprovações de um turno, rejeitando cada uma com erro TIPADO.
|
|
210
|
+
*
|
|
211
|
+
* Rejeitar e não `resolve(false)`: um `false` é indistinguível de *"o usuário negou"*, e a diferença
|
|
212
|
+
* importa — negar é decisão, abortar é interrupção. O SDK precisa das duas para desenrolar a chamada
|
|
213
|
+
* de tool corretamente.
|
|
214
|
+
*/
|
|
215
|
+
#varrerTurno(turno, motivo) {
|
|
216
|
+
for (const [id, entrada] of [
|
|
217
|
+
...this.#pending
|
|
218
|
+
]) {
|
|
219
|
+
if (entrada.turno !== turno) continue;
|
|
220
|
+
this.#pending.delete(id);
|
|
221
|
+
entrada.reject(new ApprovalAbortedError(id, motivo));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Quantas aprovações estão estacionadas. Existe para o teste poder provar a eviction. */
|
|
225
|
+
get pendentes() {
|
|
226
|
+
return this.#pending.size;
|
|
227
|
+
}
|
|
185
228
|
sendMessages(options) {
|
|
186
229
|
const { messages, abortSignal, metadata } = options;
|
|
230
|
+
this.#varrerTurno(this.#turno, "um turno novo come\xE7ou");
|
|
231
|
+
this.#turno += 1;
|
|
232
|
+
const turnoAtual = this.#turno;
|
|
233
|
+
abortSignal?.addEventListener("abort", () => {
|
|
234
|
+
this.#varrerTurno(turnoAtual, "o turno foi abortado");
|
|
235
|
+
}, {
|
|
236
|
+
once: true
|
|
237
|
+
});
|
|
187
238
|
const generator = this.#run({
|
|
188
239
|
message: extractLastUserText(messages),
|
|
189
240
|
signal: abortSignal ?? void 0,
|
|
@@ -197,12 +248,12 @@ var InProcessTransport = class {
|
|
|
197
248
|
return Promise.resolve(null);
|
|
198
249
|
}
|
|
199
250
|
approve(approvalId, decision) {
|
|
200
|
-
const
|
|
201
|
-
if (
|
|
251
|
+
const entrada = this.#pending.get(approvalId);
|
|
252
|
+
if (entrada === void 0) {
|
|
202
253
|
return Promise.reject(new Error(`No pending approval '${approvalId}' (unknown or already settled).`));
|
|
203
254
|
}
|
|
204
255
|
this.#pending.delete(approvalId);
|
|
205
|
-
resolve(decision);
|
|
256
|
+
entrada.resolve(decision);
|
|
206
257
|
return Promise.resolve();
|
|
207
258
|
}
|
|
208
259
|
};
|
|
@@ -343,9 +394,29 @@ var AgentClient = class {
|
|
|
343
394
|
status: "idle",
|
|
344
395
|
error: void 0
|
|
345
396
|
};
|
|
346
|
-
|
|
397
|
+
/**
|
|
398
|
+
* M92 — o prefixo commitado, materializado UMA vez por escrita em vez de por delta de token.
|
|
399
|
+
*
|
|
400
|
+
* `#committed` só muda em dois lugares (medido): no `done` de `send()` e em `reset()`. Entre deltas
|
|
401
|
+
* ele é constante, então reconstruí-lo a cada `#emit` é trabalho que a estrutura já garante inútil.
|
|
402
|
+
*
|
|
403
|
+
* Invalidação é **na escrita**, não por comparação: comparar custaria o mesmo O(C) que isto evita, e
|
|
404
|
+
* memoizar por comprimento erraria em `reset()` — comprimento igual com conteúdo diferente é
|
|
405
|
+
* possível, e o bug seria invisível.
|
|
406
|
+
*
|
|
407
|
+
* Honestidade sobre o tamanho do ganho: medido, o spread custa **0,0062 ms por delta @400 mensagens**
|
|
408
|
+
* — 3,1 ms num turno de 500 deltas. É real e é micro. A ordem de grandeza deste milestone está no
|
|
409
|
+
* coalescing abaixo, porque o que pende de cada emit (a derivação da timeline) custa **3,274 ms por
|
|
410
|
+
* chamada** no mesmo tamanho de thread (M86).
|
|
411
|
+
*/
|
|
412
|
+
#prefixo = [];
|
|
413
|
+
/** Coalescing opt-in: `0` (default) emite por delta, como sempre. */
|
|
414
|
+
#emitIntervalMs;
|
|
415
|
+
#timerDeEmit;
|
|
416
|
+
constructor(transport, contextResolver, options) {
|
|
347
417
|
this.#transport = transport;
|
|
348
418
|
this.#contextResolver = contextResolver;
|
|
419
|
+
this.#emitIntervalMs = options?.emitIntervalMs ?? 0;
|
|
349
420
|
}
|
|
350
421
|
/** Subscribe to state changes; returns an unsubscribe fn. */
|
|
351
422
|
subscribe = /* @__PURE__ */ __name((listener) => {
|
|
@@ -356,13 +427,20 @@ var AgentClient = class {
|
|
|
356
427
|
}, "subscribe");
|
|
357
428
|
/** The current immutable snapshot (stable reference until the next emit). */
|
|
358
429
|
getSnapshot = /* @__PURE__ */ __name(() => this.#snapshot, "getSnapshot");
|
|
430
|
+
/**
|
|
431
|
+
* Emite AGORA. Usado diretamente nas transições de status — ver `#agendarEmit`.
|
|
432
|
+
*/
|
|
359
433
|
#emit() {
|
|
434
|
+
if (this.#timerDeEmit !== void 0) {
|
|
435
|
+
clearTimeout(this.#timerDeEmit);
|
|
436
|
+
this.#timerDeEmit = void 0;
|
|
437
|
+
}
|
|
360
438
|
const thread = this.#currentUser ? [
|
|
361
|
-
...this.#
|
|
439
|
+
...this.#prefixo,
|
|
362
440
|
this.#currentUser,
|
|
363
441
|
...this.#messages
|
|
364
442
|
] : [
|
|
365
|
-
...this.#
|
|
443
|
+
...this.#prefixo,
|
|
366
444
|
...this.#messages
|
|
367
445
|
];
|
|
368
446
|
this.#snapshot = {
|
|
@@ -373,6 +451,28 @@ var AgentClient = class {
|
|
|
373
451
|
};
|
|
374
452
|
for (const listener of this.#listeners) listener();
|
|
375
453
|
}
|
|
454
|
+
/**
|
|
455
|
+
* Emite por JANELA quando o coalescing está ligado; imediatamente quando não está.
|
|
456
|
+
*
|
|
457
|
+
* Borda de saída: o timer emite ao **fim** da janela, com o estado mais recente. O que isto compra
|
|
458
|
+
* não é um emit mais barato — é **menos emits**, e o que pende de cada um é a derivação de 3,274 ms
|
|
459
|
+
* medida no M86.
|
|
460
|
+
*
|
|
461
|
+
* As transições de status (`done`/`error`/`abort`) NÃO passam por aqui: elas chamam `#emit` direto,
|
|
462
|
+
* porque um estado final preso num timer de 16 ms é um estado final perdido se o processo sair antes
|
|
463
|
+
* — e `exec` sai logo após o turno.
|
|
464
|
+
*/
|
|
465
|
+
#agendarEmit() {
|
|
466
|
+
if (this.#emitIntervalMs <= 0) {
|
|
467
|
+
this.#emit();
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
if (this.#timerDeEmit !== void 0) return;
|
|
471
|
+
this.#timerDeEmit = setTimeout(() => {
|
|
472
|
+
this.#timerDeEmit = void 0;
|
|
473
|
+
this.#emit();
|
|
474
|
+
}, this.#emitIntervalMs);
|
|
475
|
+
}
|
|
376
476
|
#upsert(message) {
|
|
377
477
|
const next = [
|
|
378
478
|
...this.#messages
|
|
@@ -399,7 +499,7 @@ var AgentClient = class {
|
|
|
399
499
|
id: this.#currentAssistantId
|
|
400
500
|
};
|
|
401
501
|
this.#upsert(stamped);
|
|
402
|
-
this.#
|
|
502
|
+
this.#agendarEmit();
|
|
403
503
|
});
|
|
404
504
|
if (aborted()) return;
|
|
405
505
|
this.#status = "done";
|
|
@@ -419,6 +519,7 @@ var AgentClient = class {
|
|
|
419
519
|
this.#currentUser,
|
|
420
520
|
...this.#messages
|
|
421
521
|
];
|
|
522
|
+
this.#prefixo = this.#committed;
|
|
422
523
|
}
|
|
423
524
|
this.abort();
|
|
424
525
|
const controller = new AbortController();
|
|
@@ -476,6 +577,7 @@ var AgentClient = class {
|
|
|
476
577
|
this.abort();
|
|
477
578
|
this.#messages = [];
|
|
478
579
|
this.#committed = [];
|
|
580
|
+
this.#prefixo = this.#committed;
|
|
479
581
|
this.#currentUser = void 0;
|
|
480
582
|
this.#error = void 0;
|
|
481
583
|
this.#status = "idle";
|
|
@@ -511,10 +613,11 @@ export {
|
|
|
511
613
|
consumeChunkStream,
|
|
512
614
|
HttpTransport,
|
|
513
615
|
extractLastUserText,
|
|
616
|
+
ApprovalAbortedError,
|
|
514
617
|
InProcessTransport,
|
|
515
618
|
ChannelTransport,
|
|
516
619
|
AgentClient,
|
|
517
620
|
agentHandle,
|
|
518
621
|
isAgentHandle
|
|
519
622
|
};
|
|
520
|
-
//# sourceMappingURL=chunk-
|
|
623
|
+
//# sourceMappingURL=chunk-U6WNQ5A2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/consume-ui-message-stream.ts","../src/client/http-transport.ts","../src/client/last-user-text.ts","../src/client/in-process-transport.ts","../src/client/channel-transport.ts","../src/client/agent-client.ts","../src/client/agent-handle.ts"],"sourcesContent":["import type { UIMessage, UIMessageChunk } from 'ai'\n\n/**\n * M2 (theokit-ai-first) — read a TheoKit agent endpoint's `UIMessageStream` SSE `Response`\n * into reconstructed assistant `UIMessage`s, reusing the `ai` package's own consumer\n * primitives (`parseJsonEventStream` + `readUIMessageStream`) — the exact path\n * `@ai-sdk/react`'s `useChat` runs internally. No reinvented wire parser (Rule 9).\n *\n * `ai` is an OPTIONAL peer dependency, so it is imported dynamically: an app that never\n * calls an agent never pays for it, and importing `theokit/client` does not hard-require\n * `ai` (mirrors how the agent runtime dynamically imports `@theokit/sdk`). An agent app\n * always has `ai` installed (it is the UIMessageStream consumer).\n *\n * `onMessage` is invoked on every reconstruction step with the latest snapshot of the\n * assistant message, so a caller (the `useAgent` hook) can render streaming updates.\n */\nexport async function consumeUIMessageStream(\n response: Response,\n onMessage: (message: UIMessage) => void,\n): Promise<void> {\n const chunkStream = await responseToChunkStream(response)\n await consumeChunkStream(chunkStream, onMessage)\n}\n\n/**\n * M41 (ADR-0050 D3) — the reusable middle piece: a UIMessageStream SSE `Response` →\n * `ReadableStream<UIMessageChunk>`, reusing `ai`'s own `parseJsonEventStream` (the exact primitive\n * `useChat` runs). This is precisely what a `ChatTransport.sendMessages` returns, so `HttpTransport`\n * builds on it directly (no reinvented wire parser — Rule 9). A body-less response yields an empty stream.\n */\nexport async function responseToChunkStream(\n response: Response,\n): Promise<ReadableStream<UIMessageChunk>> {\n if (response.body === null) {\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n controller.close()\n },\n })\n }\n\n const { parseJsonEventStream, uiMessageChunkSchema } = await import('ai')\n\n // ai validates each SSE JSON frame against its own strict chunk schema (the exact gate `useChat`\n // runs), then yields `{ success, value }`; forward the valid chunks.\n const parsed = parseJsonEventStream({ stream: response.body, schema: uiMessageChunkSchema })\n return new ReadableStream<UIMessageChunk>({\n async start(controller) {\n for await (const result of parsed) {\n if (result.success) controller.enqueue(result.value)\n }\n controller.close()\n },\n })\n}\n\n/**\n * M41 (ADR-0050 D6) — read a `ReadableStream<UIMessageChunk>` into reconstructed assistant\n * `UIMessage`s via `ai`'s `readUIMessageStream`. Shared by `consumeUIMessageStream` (Response path)\n * and the framework-agnostic `AgentClient` store (transport path). `onMessage` fires on every\n * reconstruction step so a caller can render streaming updates.\n */\nexport async function consumeChunkStream(\n stream: ReadableStream<UIMessageChunk>,\n onMessage: (message: UIMessage) => void,\n): Promise<void> {\n const { readUIMessageStream } = await import('ai')\n // #136 — a provider failure (401/429/5xx) arrives as a `{ type: 'error', errorText }` chunk, NOT a\n // thrown rejection (the in-process runner and the SSE path both emit it as data). With the default\n // `readUIMessageStream({ stream })` (no `onError`, `terminateOnError` off) that chunk is silently\n // swallowed — the stream ends \"clean\" and the store settles to 'done' instead of 'error'.\n // `onError` captures the error; `terminateOnError` stops reconstructing partial messages after it AND\n // (under ai@7.0.14) errors the underlying iterator — so the `for await` below rejects and\n // `AgentClient.#drive`'s existing catch surfaces it (status='error', error set). The post-loop\n // `throw` is a defensive fallback that still surfaces the captured error if a future `ai` version\n // stops rejecting under `terminateOnError`; it is dead code under ai@7.0.14 but cheap version-robustness.\n let streamError: Error | undefined\n for await (const message of readUIMessageStream({\n stream,\n onError: (err) => {\n streamError = err instanceof Error ? err : new Error(String(err))\n },\n terminateOnError: true,\n })) {\n onMessage(message)\n }\n if (streamError !== undefined) throw streamError\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { responseToChunkStream } from './consume-ui-message-stream.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** Extra request headers — a static record OR a resolver called per request (for dynamic auth). */\nexport type HeadersResolver = Record<string, string> | (() => Record<string, string> | undefined)\n\nexport interface HttpTransportOptions {\n /** Agent endpoint path or URL, e.g. `/api/agents/support`. */\n api: string\n /**\n * Extra request headers (e.g. auth). Static record OR a resolver evaluated on EVERY request — pass a\n * resolver when the value is dynamic (a rotating JWT), so a stale header is never sent. Merged UNDER\n * per-request headers.\n */\n headers?: HeadersResolver\n /** Override fetch (primarily for tests / non-browser hosts) — static; resolved once at construction. */\n fetch?: typeof fetch\n}\n\n/** Normalize `ai`'s `Record | Headers | undefined` header option into a plain record. */\nfunction toRecord(headers: Record<string, string> | Headers | undefined): Record<string, string> {\n if (headers === undefined) return {}\n if (headers instanceof Headers) return Object.fromEntries(headers.entries())\n return headers\n}\n\n/**\n * M41 (ADR-0050 D3) — `ChatTransport` over the web agent path.\n *\n * - `sendMessages`: `POST <api>` with the UIMessageStream `accept` + the `X-Theo-Action` CSRF header\n * (HTTP method + headers are identical to the pre-M41 `useAgent` fetch; the body shape is a superset —\n * `{ ...input, messages: [UIMessage] }` — which the server's dual-path parser accepts, so no\n * regression), captures the server-minted `x-theokit-run-id`, and returns `ReadableStream<UIMessageChunk>`\n * via `ai`'s own SSE parser (`responseToChunkStream`).\n * - `reconnectToStream`: `GET <api>/runs/<runId>/stream` (M37 durable transport); 404 → `null` (the run\n * completed / was evicted). A caller may pass a `Last-Event-ID` header to resume only the tail; by\n * default the server replays the run from the start and the client upserts by message id (idempotent).\n * - `approve`: `POST <api>/approve/<id>` (out-of-band HITL settle).\n *\n * Implemented directly (not by subclassing `DefaultChatTransport`) because reconnect keys on our\n * server-minted `runId` captured from a response header, which the base class does not expose — see\n * ADR-0050 D3.\n */\nexport class HttpTransport implements AgentTransport {\n readonly #api: string\n readonly #headers: HeadersResolver\n readonly #fetch: typeof fetch\n /** Server-minted id of the last run (from `x-theokit-run-id`) — the reconnect key. */\n #lastRunId: string | undefined\n\n constructor(options: HttpTransportOptions) {\n this.#api = options.api\n this.#headers = options.headers ?? {}\n // BIND the default fetch to globalThis — the native `fetch` throws `TypeError: Illegal invocation` when\n // invoked as a method (`this.#fetch(...)` would set `this` to this transport instance, not the window).\n // An injected fetch (tests / non-browser hosts) is a plain function and is used as-is.\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis)\n }\n\n /** Resolve the configured headers per request (a resolver evaluates now — dynamic auth is never stale). */\n #resolveHeaders(): Record<string, string> {\n return (typeof this.#headers === 'function' ? this.#headers() : this.#headers) ?? {}\n }\n\n async sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, headers, body, chatId } = options\n // Only spread an object body (never a primitive — that would emit char-indexed keys). `body` is typed\n // `object | undefined` (ai's `ChatRequestOptions`), so no cast is needed — the guard narrows to\n // `object`. (A runtime-`null` body, which the type forbids, spreads to `{}` — harmless.) The server\n // accepts `{ messages }` (ai shape) AND `{ ...input }` (typed input), preferring the turn text.\n const extra = typeof body === 'object' ? body : undefined\n const response = await this.#fetch(this.#api, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'text/event-stream',\n 'X-Theo-Action': '1',\n ...this.#resolveHeaders(),\n ...toRecord(headers),\n },\n // Send the stable `chatId` as the top-level `id` — the server reads it as the sessionId, so ONE\n // conversation (SDK history + session-scoped tools like `todolist`) persists across turns instead of\n // resetting on a fresh random session each request. Placed last so a session is never shadowed by an\n // `id` field inside the typed input. Undefined chatId ⇒ key omitted ⇒ server falls back (unchanged).\n body: JSON.stringify({ ...extra, messages, id: chatId }),\n signal: abortSignal,\n })\n if (!response.ok) {\n throw new Error(\n `Agent request to ${this.#api} failed: ${response.status} ${response.statusText}`,\n )\n }\n this.#lastRunId = response.headers.get('x-theokit-run-id') ?? undefined\n return responseToChunkStream(response)\n }\n\n async reconnectToStream(\n options: Parameters<ChatTransport<UIMessage>['reconnectToStream']>[0],\n ): Promise<ReadableStream<UIMessageChunk> | null> {\n if (this.#lastRunId === undefined) return null\n const response = await this.#fetch(`${this.#api}/runs/${this.#lastRunId}/stream`, {\n method: 'GET',\n headers: { ...this.#resolveHeaders(), ...toRecord(options.headers) },\n })\n if (response.status === 404) return null\n if (!response.ok) {\n throw new Error(\n `Agent reconnect to run ${this.#lastRunId} failed: ${response.status} ${response.statusText}`,\n )\n }\n return responseToChunkStream(response)\n }\n\n async approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n const response = await this.#fetch(`${this.#api}/approve/${approvalId}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'X-Theo-Action': '1',\n ...this.#resolveHeaders(),\n },\n body: JSON.stringify(decision),\n })\n if (!response.ok) {\n throw new Error(`Approve ${approvalId} failed: ${response.status} ${response.statusText}`)\n }\n }\n}\n","import type { UIMessage } from 'ai'\n\n/**\n * M41/M42 — extract the turn text from the last user message's text parts. Shared by the transports\n * that hand a plain `message` string to an in-process/push runner (`InProcessTransport`,\n * `ChannelTransport`) rather than POSTing the `messages[]` array (`HttpTransport`). One definition (G12).\n */\nexport function extractLastUserText(messages: readonly UIMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]\n if (message.role !== 'user') continue\n const text = message.parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('')\n if (text.length > 0) return text\n }\n return ''\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { extractLastUserText } from './last-user-text.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** An inline approval request handed to the transport's resolver (structural — no server import). */\nexport interface InProcessApprovalRequestLike {\n approvalId: string\n toolName: string\n opts: unknown\n}\n\n/** Resolve one gated-tool approval inline (mirrors the SDK's `boolean | HitlDecision` return). */\nexport type InProcessAwaitApproval = (\n req: InProcessApprovalRequestLike,\n) => Promise<boolean | ApprovalDecision>\n\n/** The input the injected runner receives (structurally compatible with `StreamAgentTurnInProcessInput`). */\nexport interface InProcessRunInput {\n message: string\n sessionId?: string\n signal?: AbortSignal\n awaitApproval?: InProcessAwaitApproval\n /** M43 — per-request context (from `sendMessages`'s `metadata`) — tenant / provider / auth for the runner. */\n context?: unknown\n}\n\n/**\n * The in-process turn runner. The consumer binds `streamAgentTurnInProcess(mod, apiKey, …)`:\n * `new InProcessTransport({ run: (input) => streamAgentTurnInProcess(mod, apiKey, input) })`.\n * Injecting it keeps this client module decoupled from `server/` and makes the transport testable.\n */\nexport type InProcessRunner = (input: InProcessRunInput) => AsyncGenerator<UIMessageChunk>\n\nexport interface InProcessTransportOptions {\n run: InProcessRunner\n}\n\n/** Bridge an `AsyncGenerator<UIMessageChunk>` into a pull-based `ReadableStream<UIMessageChunk>`. */\nfunction generatorToStream(gen: AsyncGenerator<UIMessageChunk>): ReadableStream<UIMessageChunk> {\n return new ReadableStream<UIMessageChunk>({\n async pull(controller) {\n try {\n const result = await gen.next()\n if (result.done === true) {\n controller.close()\n return\n }\n // After the done-guard, `result` is an IteratorYieldResult<UIMessageChunk> — value is typed.\n controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n }\n },\n async cancel() {\n await gen.return(undefined)\n },\n })\n}\n\n/**\n * M41 (ADR-0050 D4) — `ChatTransport` over the in-process seam (`streamAgentTurnInProcess`), for the\n * terminal/desktop surfaces that run client + server in ONE process (no HTTP loopback).\n *\n * - `sendMessages`: bridge the injected runner's `AsyncGenerator<UIMessageChunk>` into a\n * `ReadableStream<UIMessageChunk>` (honoring `abortSignal`, which the runner forwards to the SDK).\n * - `reconnectToStream`: always `null` — a single process has no dropped server-side stream to resume\n * (mirrors `ai`'s `DirectChatTransport`).\n * - `approve`: resolve the pending inline approval by id (the run parks on `awaitApproval`). An unknown\n * id rejects (fail-fast, Rule 8 — never a silent resolve).\n *\n * Error asymmetry vs `HttpTransport` (by design, matching the `ChatTransport` contract): a runner that\n * throws SYNCHRONOUSLY surfaces the error when the stream is READ (via `controller.error`), not from the\n * `sendMessages` promise — whereas `HttpTransport` throws from `sendMessages` on a non-2xx response.\n */\n/**\n * Uma aprovação estacionada foi descartada porque o turno terminou sem decisão.\n *\n * M92 — tipado de propósito. Antes a promessa simplesmente **nunca** resolvia, e a chamada de tool do\n * SDK pendurava; `resolve(false)` seria pior ainda, porque é indistinguível de \"o usuário negou\".\n */\nexport class ApprovalAbortedError extends Error {\n constructor(\n readonly approvalId: string,\n motivo: string,\n ) {\n super(`Aprovação '${approvalId}' descartada: ${motivo}.`)\n this.name = 'ApprovalAbortedError'\n }\n}\n\nexport class InProcessTransport implements AgentTransport {\n readonly #run: InProcessRunner\n /**\n * Aprovações inline estacionadas: `approvalId` → como resolver **ou rejeitar** a promessa parada.\n *\n * M92 — o `reject` entrou junto com a eviction. Antes havia só o `resolve`, e nada apagava a entrada\n * quando o turno abortava: a promessa ficava pendente **para sempre**, e a chamada de tool do SDK\n * pendurava com ela. Uma promessa que nunca resolve **nem** rejeita é a forma mais silenciosa de\n * engolir um erro — nem stack trace existe (`error-handling.md § 2`).\n */\n readonly #pending = new Map<\n string,\n {\n resolve: (decision: boolean | ApprovalDecision) => void\n reject: (err: Error) => void\n turno: number\n }\n >()\n\n /** O turno corrente. Um `send()` novo incrementa e varre o anterior. */\n #turno = 0\n\n constructor(options: InProcessTransportOptions) {\n this.#run = options.run\n }\n\n #awaitApproval: InProcessAwaitApproval = (req) =>\n new Promise<boolean | ApprovalDecision>((resolve, reject) => {\n // Approval ids are server-minted UUIDs — a collision means a real bug (two turns reusing an id).\n // Fail fast rather than silently overwrite the earlier turn's parked resolver (Rule 8).\n if (this.#pending.has(req.approvalId)) {\n reject(new Error(`Duplicate pending approval id '${req.approvalId}' — ids must be unique.`))\n return\n }\n this.#pending.set(req.approvalId, { resolve, reject, turno: this.#turno })\n })\n\n /**\n * Varre as aprovações de um turno, rejeitando cada uma com erro TIPADO.\n *\n * Rejeitar e não `resolve(false)`: um `false` é indistinguível de *\"o usuário negou\"*, e a diferença\n * importa — negar é decisão, abortar é interrupção. O SDK precisa das duas para desenrolar a chamada\n * de tool corretamente.\n */\n #varrerTurno(turno: number, motivo: string): void {\n for (const [id, entrada] of [...this.#pending]) {\n if (entrada.turno !== turno) continue\n this.#pending.delete(id)\n entrada.reject(new ApprovalAbortedError(id, motivo))\n }\n }\n\n /** Quantas aprovações estão estacionadas. Existe para o teste poder provar a eviction. */\n get pendentes(): number {\n return this.#pending.size\n }\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n // M92 — um `send()` novo varre o turno anterior: aprovações daquele turno nunca mais serão\n // decididas, e deixá-las no `Map` é vazamento com uma promessa pendurada em cada uma.\n this.#varrerTurno(this.#turno, 'um turno novo começou')\n this.#turno += 1\n const turnoAtual = this.#turno\n // O sinal de abort do turno é a costura que já chegava aqui e não era usada. `once` porque um\n // `AbortSignal` dispara no máximo uma vez, e reter o listener manteria o transporte vivo.\n abortSignal?.addEventListener(\n 'abort',\n () => {\n this.#varrerTurno(turnoAtual, 'o turno foi abortado')\n },\n { once: true },\n )\n const generator = this.#run({\n message: extractLastUserText(messages),\n signal: abortSignal ?? undefined,\n awaitApproval: this.#awaitApproval,\n // M43 — forward per-request context (the seam's `metadata`) to the runner.\n context: metadata,\n })\n return Promise.resolve(generatorToStream(generator))\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n return Promise.resolve(null)\n }\n\n approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n const entrada = this.#pending.get(approvalId)\n if (entrada === undefined) {\n return Promise.reject(\n new Error(`No pending approval '${approvalId}' (unknown or already settled).`),\n )\n }\n this.#pending.delete(approvalId)\n entrada.resolve(decision)\n return Promise.resolve()\n }\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { extractLastUserText } from './last-user-text.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** Handlers the transport hands to the injected push source for one turn. */\nexport interface ChannelTurnHandlers {\n /** One pushed JSONL line (a serialized `UIMessageChunk`). */\n onLine: (line: string) => void\n /** The turn ended — no more lines. */\n onClose: () => void\n /** The push source failed. */\n onError?: (err: unknown) => void\n}\n\n/**\n * The injected push source — a Tauri `Channel`/`invoke` bridge, kept STRUCTURAL so core adds no\n * `@tauri-apps/*` dependency and the transport is testable with a fake (ADR-0051 D2). The Tauri app\n * wires it: `new Channel()`, `channel.onmessage = onLine`, `invoke('run_agent', { message, channel })`,\n * returning a teardown that aborts the sidecar turn.\n */\nexport interface ChannelPushSource {\n /**\n * Start a turn; deliver each JSONL `UIMessageChunk` line to `onLine`, then `onClose`. Return a teardown.\n * `turn.context` (M43) is the per-request context (from the seam's `metadata`) — the Tauri `invoke`\n * forwards it to the sidecar. When no context is set it is present as `context: undefined` (the key is\n * NOT absent) — a sidecar that checks `'context' in turn` should treat `undefined` as \"no context\".\n */\n start(turn: { message: string; context?: unknown }, handlers: ChannelTurnHandlers): () => void\n /** Optional HITL settle (another Tauri `invoke`). */\n settle?(approvalId: string, decision: ApprovalDecision): Promise<void>\n}\n\nexport interface ChannelTransportOptions {\n source: ChannelPushSource\n}\n\n/**\n * M42 (ADR-0051) — `ChatTransport` over a Tauri-`Channel`-shaped push source, for the desktop webview.\n *\n * - `sendMessages`: start the turn via the injected source and bridge its pushed JSONL frames into a\n * `ReadableStream<UIMessageChunk>` (built in `start` — a Channel is push, so the stream's queue buffers\n * frames; ADR-0051 D3). A malformed JSONL line is SKIPPED, never fatal (ADR-0051 D4, Rule 8). `abortSignal`\n * tears down the source and closes the stream.\n * - `reconnectToStream`: always `null` — the M36 sidecar runs the turn directly (no durable server stream);\n * this is the honest parity for a single-process push surface (ADR-0051 D5; mirrors `InProcessTransport`).\n * - `approve`: routes to the injected `settle` (another Tauri `invoke`); absent `settle` → a typed error.\n *\n * The push source is INJECTED — core stays Tauri-agnostic and this transport is unit-tested with a fake.\n */\nexport class ChannelTransport implements AgentTransport {\n readonly #source: ChannelPushSource\n\n constructor(options: ChannelTransportOptions) {\n this.#source = options.source\n }\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n const message = extractLastUserText(messages)\n const source = this.#source\n\n // Per-stream teardown/abort-detach, hoisted so `cancel` (consumer stops reading) can also tear the\n // source down. `closed` makes every terminal transition idempotent (no enqueue/close after close).\n let closed = false\n let teardown: () => void = () => undefined\n let detachAbort: () => void = () => undefined\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n const finish = (settle: () => void): void => {\n if (closed) return\n closed = true\n detachAbort()\n settle()\n }\n teardown = source.start(\n { message, context: metadata },\n {\n onLine: (line) => {\n if (closed) return\n // Skip a malformed pushed line — one bad frame must never crash the webview (ADR-0051 D4).\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n return\n }\n // Discriminant guard: a `UIMessageChunk` is an object with a string `type`. The trust\n // boundary here is the LOCAL sidecar (not the network), so a discriminant check — not the\n // full `ai` schema (which isn't exposed standalone) — is proportionate: it rejects\n // structureless / wrong-shape payloads before they reach `readUIMessageStream`. Same\n // skip-not-crash policy as a parse error.\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as { type?: unknown }).type !== 'string'\n ) {\n return\n }\n controller.enqueue(parsed as UIMessageChunk)\n },\n onClose: () => {\n finish(() => {\n controller.close()\n })\n },\n onError: (err) => {\n finish(() => {\n controller.error(err)\n })\n },\n },\n )\n if (abortSignal !== undefined) {\n const onAbort = (): void => {\n finish(() => {\n teardown()\n controller.close()\n })\n }\n if (abortSignal.aborted) onAbort()\n else {\n abortSignal.addEventListener('abort', onAbort)\n detachAbort = () => {\n abortSignal.removeEventListener('abort', onAbort)\n }\n }\n }\n },\n cancel() {\n // The consumer stopped reading (reader.cancel) — abort the source turn + drop the abort listener.\n if (closed) return\n closed = true\n detachAbort()\n teardown()\n },\n })\n return Promise.resolve(stream)\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n return Promise.resolve(null)\n }\n\n async approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n if (this.#source.settle === undefined) {\n throw new Error(`This channel source has no HITL settle — cannot approve '${approvalId}'.`)\n }\n await this.#source.settle(approvalId, decision)\n }\n}\n","import type { UIMessage, UIMessageChunk } from 'ai'\n\nimport { consumeChunkStream } from './consume-ui-message-stream.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\nexport type UseAgentStatus = 'idle' | 'streaming' | 'done' | 'error'\n\n/** The observable state the store exposes (stable reference between emits — `useSyncExternalStore` contract). */\nexport interface AgentClientState {\n /** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat — unchanged since M41. */\n messages: UIMessage[]\n /**\n * M46 — the full conversation: committed turns + the current turn's user message + in-flight assistant.\n * Accumulated across sends (never reset except by `reset()`), with stable ids committed exactly once.\n * Render this instead of hand-rolling a transcript from `messages`.\n */\n thread: UIMessage[]\n status: UseAgentStatus\n error: Error | undefined\n}\n\n/** Derive the turn text from a typed input: `input.message` when present, else the serialized input. */\nfunction inputToText(input: unknown): string {\n if (\n typeof input === 'object' &&\n input !== null &&\n typeof (input as { message?: unknown }).message === 'string'\n ) {\n return (input as { message: string }).message\n }\n if (typeof input === 'string') return input\n return JSON.stringify(input)\n}\n\n/** Build a user `UIMessage` from a typed input (text from `{ message }`, else the serialized input). */\nfunction buildUserMessage(input: unknown): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: 'user',\n parts: [{ type: 'text', text: inputToText(input) }],\n }\n}\n\n/**\n * M41 (ADR-0050 D6) — the framework-agnostic agent client store.\n *\n * Holds `messages`/`status`/`error`, drives an {@link AgentTransport}, and notifies subscribers on\n * change. It is the SINGLE consolidation point: web (`HttpTransport`) and terminal/desktop\n * (`InProcessTransport`) run the SAME store. `useAgent` is a thin React binding over it via\n * `useSyncExternalStore`; a standalone (no-React) client (M44) can subscribe directly. Being\n * framework-agnostic, it is unit-tested without a DOM.\n */\n/**\n * M92 — opções do cliente. Aditivo: sem elas, o comportamento é o de sempre.\n */\nexport interface AgentClientOptions {\n /**\n * Janela de coalescing em ms. `0` ou ausente = emite por delta de token (comportamento pré-M92).\n *\n * Opt-in de propósito: este é um pacote publicado, e mudar a frequência de emit por padrão mudaria o\n * comportamento observável de quem conta emits ou depende da latência do primeiro token.\n */\n readonly emitIntervalMs?: number\n}\n\nexport class AgentClient<TInput = unknown> {\n readonly #transport: AgentTransport\n readonly #chatId = crypto.randomUUID()\n readonly #listeners = new Set<() => void>()\n /** M43 — resolves per-request context (evaluated on every send/reconnect — dynamic, never stale). */\n readonly #contextResolver: (() => RequestContext | undefined) | undefined\n\n #messages: UIMessage[] = []\n #status: UseAgentStatus = 'idle'\n #error: Error | undefined\n #controller: AbortController | null = null\n // M46 — conversation accumulation (React-free; all surfaces inherit it via the snapshot).\n /** Committed (finished) turns — user + assistant, with stable fabricated ids. */\n #committed: UIMessage[] = []\n /** The current turn's user message (in `thread` but never in `messages` — back-compat). */\n #currentUser: UIMessage | undefined\n /** A stable id for the current turn's assistant (the SDK leaves it empty — we fabricate one). */\n #currentAssistantId = ''\n #snapshot: AgentClientState = { messages: [], thread: [], status: 'idle', error: undefined }\n\n /**\n * M92 — o prefixo commitado, materializado UMA vez por escrita em vez de por delta de token.\n *\n * `#committed` só muda em dois lugares (medido): no `done` de `send()` e em `reset()`. Entre deltas\n * ele é constante, então reconstruí-lo a cada `#emit` é trabalho que a estrutura já garante inútil.\n *\n * Invalidação é **na escrita**, não por comparação: comparar custaria o mesmo O(C) que isto evita, e\n * memoizar por comprimento erraria em `reset()` — comprimento igual com conteúdo diferente é\n * possível, e o bug seria invisível.\n *\n * Honestidade sobre o tamanho do ganho: medido, o spread custa **0,0062 ms por delta @400 mensagens**\n * — 3,1 ms num turno de 500 deltas. É real e é micro. A ordem de grandeza deste milestone está no\n * coalescing abaixo, porque o que pende de cada emit (a derivação da timeline) custa **3,274 ms por\n * chamada** no mesmo tamanho de thread (M86).\n */\n #prefixo: UIMessage[] = []\n\n /** Coalescing opt-in: `0` (default) emite por delta, como sempre. */\n readonly #emitIntervalMs: number\n #timerDeEmit: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n transport: AgentTransport,\n contextResolver?: () => RequestContext | undefined,\n options?: AgentClientOptions,\n ) {\n this.#transport = transport\n this.#contextResolver = contextResolver\n this.#emitIntervalMs = options?.emitIntervalMs ?? 0\n }\n\n /** Subscribe to state changes; returns an unsubscribe fn. */\n subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener)\n return () => {\n this.#listeners.delete(listener)\n }\n }\n\n /** The current immutable snapshot (stable reference until the next emit). */\n getSnapshot = (): AgentClientState => this.#snapshot\n\n /**\n * Emite AGORA. Usado diretamente nas transições de status — ver `#agendarEmit`.\n */\n #emit(): void {\n if (this.#timerDeEmit !== undefined) {\n clearTimeout(this.#timerDeEmit)\n this.#timerDeEmit = undefined\n }\n // thread = prefixo commitado + o user deste turno + o assistant em voo (`messages`). O prefixo vem\n // materializado (`#prefixo`); só a cauda é concatenada aqui. A referência do SNAPSHOT muda só neste\n // ponto, que é o contrato que `useSyncExternalStore` exige.\n const thread = this.#currentUser\n ? [...this.#prefixo, this.#currentUser, ...this.#messages]\n : [...this.#prefixo, ...this.#messages]\n this.#snapshot = { messages: this.#messages, thread, status: this.#status, error: this.#error }\n for (const listener of this.#listeners) listener()\n }\n\n /**\n * Emite por JANELA quando o coalescing está ligado; imediatamente quando não está.\n *\n * Borda de saída: o timer emite ao **fim** da janela, com o estado mais recente. O que isto compra\n * não é um emit mais barato — é **menos emits**, e o que pende de cada um é a derivação de 3,274 ms\n * medida no M86.\n *\n * As transições de status (`done`/`error`/`abort`) NÃO passam por aqui: elas chamam `#emit` direto,\n * porque um estado final preso num timer de 16 ms é um estado final perdido se o processo sair antes\n * — e `exec` sai logo após o turno.\n */\n #agendarEmit(): void {\n if (this.#emitIntervalMs <= 0) {\n this.#emit()\n return\n }\n if (this.#timerDeEmit !== undefined) return\n this.#timerDeEmit = setTimeout(() => {\n this.#timerDeEmit = undefined\n this.#emit()\n }, this.#emitIntervalMs)\n }\n\n #upsert(message: UIMessage): void {\n const next = [...this.#messages]\n const idx = next.findIndex((existing) => existing.id === message.id)\n if (idx >= 0) next[idx] = message\n else next.push(message)\n this.#messages = next\n }\n\n async #drive(\n open: () => Promise<ReadableStream<UIMessageChunk> | null>,\n controller: AbortController,\n ): Promise<void> {\n // Read via a function (not a narrowed local) — `aborted` flips ASYNC across the awaits below, so the\n // control-flow narrowing of a direct `signal.aborted` read would be wrong. A stale drive (its\n // controller aborted because a newer send/abort took over) MUST NOT clobber the newer status.\n const aborted = (): boolean => controller.signal.aborted\n try {\n const stream = await open()\n if (aborted()) return\n if (stream === null) {\n // Nothing to resume (e.g. reconnect after the run completed). Settle without error.\n this.#status = this.#messages.length > 0 ? 'done' : 'idle'\n this.#emit()\n return\n }\n await consumeChunkStream(stream, (message) => {\n if (aborted()) return\n // The SDK leaves the assistant message id empty — fabricate a stable per-turn id so every chunk\n // upserts into the SAME message and the committed copy has a collision-free key (M46).\n const stamped = message.id ? message : { ...message, id: this.#currentAssistantId }\n this.#upsert(stamped)\n // O ÚNICO ponto por delta de token — todos os outros `#emit` deste arquivo são transições de\n // status, e essas nunca esperam timer (ADR-2).\n this.#agendarEmit()\n })\n if (aborted()) return\n this.#status = 'done'\n this.#emit()\n } catch (err) {\n if (aborted()) return\n this.#error = err instanceof Error ? err : new Error(String(err))\n this.#status = 'error'\n this.#emit()\n }\n }\n\n /** Send a typed input; opens a fresh stream (replaces prior messages). */\n send = (input: TInput): void => {\n // M46 — commit the PRIOR turn into history exactly once, but ONLY if it finished cleanly (`done`).\n // An errored or aborted turn (status !== 'done') is dropped, keeping committed history uncorrupted.\n if (this.#status === 'done' && this.#currentUser) {\n this.#committed = [...this.#committed, this.#currentUser, ...this.#messages]\n // Invalidação NA ESCRITA (ADR-3): este é um dos dois únicos pontos que mexem em `#committed`.\n this.#prefixo = this.#committed\n }\n this.abort()\n const controller = new AbortController()\n this.#controller = controller\n const userMsg = buildUserMessage(input)\n this.#currentUser = userMsg\n this.#currentAssistantId = crypto.randomUUID()\n this.#messages = []\n this.#error = undefined\n this.#status = 'streaming'\n this.#emit()\n const context = this.#contextResolver?.()\n void this.#drive(\n () =>\n this.#transport.sendMessages({\n trigger: 'submit-message',\n chatId: this.#chatId,\n messageId: undefined,\n messages: [userMsg],\n abortSignal: controller.signal,\n // Only object inputs flow as the request `body` (the turn text is always in `messages`);\n // a primitive input is carried by the user message, never spread into the body.\n body: typeof input === 'object' && input !== null ? input : undefined,\n // M43 — per-request context reaches every transport (headers → HTTP, metadata → in-process/channel).\n headers: context?.headers,\n metadata: context?.metadata,\n }),\n controller,\n )\n }\n\n /** Resume an interrupted stream via the transport's `reconnectToStream` (no-op when unavailable). */\n reconnect = (): void => {\n const controller = new AbortController()\n this.#controller = controller\n // Reconnecting before any send() (or after reset()) leaves #currentAssistantId empty — fabricate one\n // so a replayed assistant never lands in `thread` with an empty, non-unique id (M46 invariant).\n if (!this.#currentAssistantId) this.#currentAssistantId = crypto.randomUUID()\n // Reconnect means \"resume/retry\" — a stale error must not linger next to a fresh 'streaming' status.\n this.#error = undefined\n this.#status = 'streaming'\n this.#emit()\n const context = this.#contextResolver?.()\n void this.#drive(\n () =>\n this.#transport.reconnectToStream({\n chatId: this.#chatId,\n headers: context?.headers,\n metadata: context?.metadata,\n }),\n controller,\n )\n }\n\n /** Abort an in-flight stream (not an error — leaves messages as-is). */\n abort = (): void => {\n this.#controller?.abort()\n this.#controller = null\n // Finalize the status when the USER aborts an in-flight turn: the aborted `#drive` early-returns\n // without touching status (so a stale drive can't clobber a newer turn), which would otherwise leave\n // `status` stuck on 'streaming' — a lingering spinner + an unusable surface. A caller that aborts to\n // start a NEW turn (`send`/`sendMessages`) sets 'streaming' again immediately after, so this is safe.\n if (this.#status === 'streaming') {\n this.#status = this.#committed.length > 0 || this.#messages.length > 0 ? 'done' : 'idle'\n this.#emit()\n }\n }\n\n /** Clear messages + error, back to idle. */\n reset = (): void => {\n this.abort()\n this.#messages = []\n // M46 — reset means a NEW conversation: clear committed history + the current turn's user too.\n this.#committed = []\n // O outro ponto de escrita. Sem isto o `reset()` serviria o prefixo velho — e comprimento igual\n // com conteúdo diferente é exatamente o caso que uma memoização por tamanho não pegaria.\n this.#prefixo = this.#committed\n this.#currentUser = undefined\n this.#error = undefined\n this.#status = 'idle'\n this.#emit()\n }\n\n /** Settle a paused HITL approval via the transport's HITL path (HTTP POST or inline callback). */\n approve = async (approvalId: string, decision: ApprovalDecision): Promise<void> => {\n await this.#transport.approve?.(approvalId, decision)\n }\n}\n","import { ChannelTransport, type ChannelPushSource } from './channel-transport.js'\nimport { InProcessTransport, type InProcessRunner } from './in-process-transport.js'\n\n/**\n * M47 (ADR-M47-2) — a typed, client-safe handle for an exposed agent.\n *\n * It carries ONLY the HTTP `path` at runtime plus phantom `input`/`toolNames` types (never populated) — so\n * `useAgent(chat)` / `createAgentClient(chat…)` bind with NO magic string (the path is generated from the\n * `@Expose` exposure, not hand-typed) and NO duplicated input type (the input type flows through the phantom\n * generic, inferred from the agent's `.input()`). This mirrors tRPC/Hono's type-only handle: the client\n * pulls the agent's TYPE via `import type`, never its server runtime. The generated `@theo/agents` module\n * emits one `export const <name> = agentHandle('/api/agents/<name>')` per agent, typed with the phantoms.\n */\nexport interface AgentHandle<TInput = unknown, TToolNames extends string = string> {\n /** The agent's HTTP endpoint path (e.g. `/api/agents/chat`). The only serializable/runtime-bearing field. */\n readonly path: string\n /**\n * M47 — bind this agent in-process (TUI / single-process): wraps the app's runner in an\n * {@link InProcessTransport}. `useAgent(chat.inProcess(run))` drives the SAME agent without HTTP.\n */\n inProcess(run: InProcessRunner): InProcessTransport\n /**\n * M47 — bind this agent over a push channel (Tauri desktop webview): wraps the source in a\n * {@link ChannelTransport}. `createAgentClient(chat.channel(source))` drives the SAME agent.\n */\n channel(source: ChannelPushSource): ChannelTransport\n /** Phantom — the agent's `input` type, carried for `useAgent(handle).send` inference. Never populated. */\n readonly __input?: TInput\n /** Phantom — the agent's tool-name union, carried end-to-end. Never populated. */\n readonly __toolNames?: TToolNames\n}\n\n/**\n * Build an {@link AgentHandle} from an agent's HTTP path. Types are supplied by the caller/codegen. The\n * `inProcess`/`channel` binders are methods (dropped by `JSON.stringify`, so the `{ path }` core stays\n * serializable + client-safe) that produce the M41 transports for the non-web surfaces.\n */\nexport function agentHandle<TInput = unknown, TToolNames extends string = string>(\n path: string,\n): AgentHandle<TInput, TToolNames> {\n return {\n path,\n inProcess: (run) => new InProcessTransport({ run }),\n channel: (source) => new ChannelTransport({ source }),\n }\n}\n\n/** Narrow an unknown binding to an {@link AgentHandle} (has a string `path`, is not a transport). */\nexport function isAgentHandle(value: unknown): value is AgentHandle {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { path?: unknown }).path === 'string' &&\n typeof (value as { sendMessages?: unknown }).sendMessages !== 'function'\n )\n}\n"],"mappings":";;;;;AAgBA,eAAsBA,uBACpBC,UACAC,WAAuC;AAEvC,QAAMC,cAAc,MAAMC,sBAAsBH,QAAAA;AAChD,QAAMI,mBAAmBF,aAAaD,SAAAA;AACxC;AANsBF;AActB,eAAsBI,sBACpBH,UAAkB;AAElB,MAAIA,SAASK,SAAS,MAAM;AAC1B,WAAO,IAAIC,eAA+B;MACxCC,MAAMC,YAAU;AACdA,mBAAWC,MAAK;MAClB;IACF,CAAA;EACF;AAEA,QAAM,EAAEC,sBAAsBC,qBAAoB,IAAK,MAAM,OAAO,IAAA;AAIpE,QAAMC,SAASF,qBAAqB;IAAEG,QAAQb,SAASK;IAAMS,QAAQH;EAAqB,CAAA;AAC1F,SAAO,IAAIL,eAA+B;IACxC,MAAMC,MAAMC,YAAU;AACpB,uBAAiBO,UAAUH,QAAQ;AACjC,YAAIG,OAAOC,QAASR,YAAWS,QAAQF,OAAOG,KAAK;MACrD;AACAV,iBAAWC,MAAK;IAClB;EACF,CAAA;AACF;AAxBsBN;AAgCtB,eAAsBC,mBACpBS,QACAZ,WAAuC;AAEvC,QAAM,EAAEkB,oBAAmB,IAAK,MAAM,OAAO,IAAA;AAU7C,MAAIC;AACJ,mBAAiBC,WAAWF,oBAAoB;IAC9CN;IACAS,SAAS,wBAACC,QAAAA;AACRH,oBAAcG,eAAeC,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A;EAEJ,GApBY;;EAuBZW,QAAQ,6BAAA;AACN,SAAK,aAAaA,MAAAA;AAClB,SAAK,cAAc;AAKnB,QAAI,KAAK,YAAY,aAAa;AAChC,WAAK,UAAU,KAAK,WAAWP,SAAS,KAAK,KAAK,UAAUA,SAAS,IAAI,SAAS;AAClF,WAAK,MAAK;IACZ;EACF,GAXQ;;EAcRqB,QAAQ,6BAAA;AACN,SAAKd,MAAK;AACV,SAAK,YAAY,CAAA;AAEjB,SAAK,aAAa,CAAA;AAGlB,SAAK,WAAW,KAAK;AACrB,SAAK,eAAe7B;AACpB,SAAK,SAASA;AACd,SAAK,UAAU;AACf,SAAK,MAAK;EACZ,GAZQ;;EAeR4C,UAAU,8BAAOC,YAAoBC,aAAAA;AACnC,UAAM,KAAK,WAAWF,UAAUC,YAAYC,QAAAA;EAC9C,GAFU;AAGZ;;;AChRO,SAASC,YACdC,MAAY;AAEZ,SAAO;IACLA;IACAC,WAAW,wBAACC,QAAQ,IAAIC,mBAAmB;MAAED;IAAI,CAAA,GAAtC;IACXE,SAAS,wBAACC,WAAW,IAAIC,iBAAiB;MAAED;IAAO,CAAA,GAA1C;EACX;AACF;AARgBN;AAWT,SAASQ,cAAcC,OAAc;AAC1C,SACE,OAAOA,UAAU,YACjBA,UAAU,QACV,OAAQA,MAA6BR,SAAS,YAC9C,OAAQQ,MAAqCC,iBAAiB;AAElE;AAPgBF;","names":["consumeUIMessageStream","response","onMessage","chunkStream","responseToChunkStream","consumeChunkStream","body","ReadableStream","start","controller","close","parseJsonEventStream","uiMessageChunkSchema","parsed","stream","schema","result","success","enqueue","value","readUIMessageStream","streamError","message","onError","err","Error","String","terminateOnError","undefined","toRecord","headers","undefined","Headers","Object","fromEntries","entries","HttpTransport","options","api","fetch","globalThis","bind","sendMessages","messages","abortSignal","body","chatId","extra","response","method","accept","JSON","stringify","id","signal","ok","Error","status","statusText","get","responseToChunkStream","reconnectToStream","approve","approvalId","decision","extractLastUserText","messages","i","length","message","role","text","parts","filter","part","type","map","join","generatorToStream","gen","ReadableStream","pull","controller","result","next","done","close","enqueue","value","err","error","cancel","return","undefined","ApprovalAbortedError","Error","approvalId","motivo","name","InProcessTransport","Map","options","run","req","Promise","resolve","reject","has","set","turno","id","entrada","delete","pendentes","size","sendMessages","messages","abortSignal","metadata","turnoAtual","addEventListener","once","generator","message","extractLastUserText","signal","awaitApproval","context","reconnectToStream","approve","decision","get","ChannelTransport","options","source","sendMessages","messages","abortSignal","metadata","message","extractLastUserText","closed","teardown","undefined","detachAbort","stream","ReadableStream","start","controller","finish","settle","context","onLine","line","parsed","JSON","parse","type","enqueue","onClose","close","onError","err","error","onAbort","aborted","addEventListener","removeEventListener","cancel","Promise","resolve","reconnectToStream","approve","approvalId","decision","Error","inputToText","input","message","JSON","stringify","buildUserMessage","id","crypto","randomUUID","role","parts","type","text","AgentClient","Set","messages","thread","status","error","undefined","transport","contextResolver","options","emitIntervalMs","subscribe","listener","add","delete","getSnapshot","clearTimeout","setTimeout","next","idx","findIndex","existing","push","open","controller","aborted","signal","stream","length","consumeChunkStream","stamped","err","Error","String","send","abort","AbortController","userMsg","context","sendMessages","trigger","chatId","messageId","abortSignal","body","headers","metadata","reconnect","reconnectToStream","reset","approve","approvalId","decision","agentHandle","path","inProcess","run","InProcessTransport","channel","source","ChannelTransport","isAgentHandle","value","sendMessages"]}
|
package/dist/client-react.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { UIMessage } from 'ai';
|
|
2
|
-
import { R as RequestContext, U as UseAgentStatus, A as ApprovalDecision, a as AgentHandle, b as AgentTransport } from './agent-handle-
|
|
2
|
+
import { R as RequestContext, U as UseAgentStatus, A as ApprovalDecision, a as AgentHandle, b as AgentTransport } from './agent-handle-C6q7iA4u.js';
|
|
3
3
|
|
|
4
4
|
interface UseAgentReturn<TInput = unknown, TToolNames extends string = string> {
|
|
5
5
|
/** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat since M41. */
|
package/dist/client-react.js
CHANGED
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as AgentTransport, A as ApprovalDecision } from './agent-handle-
|
|
2
|
-
export { c as AgentClient, d as AgentClientState, a as AgentHandle, C as ChannelPushSource,
|
|
1
|
+
import { b as AgentTransport, A as ApprovalDecision } from './agent-handle-C6q7iA4u.js';
|
|
2
|
+
export { c as AgentClient, d as AgentClientOptions, e as AgentClientState, a as AgentHandle, f as ApprovalAbortedError, C as ChannelPushSource, g as ChannelTransport, h as ChannelTransportOptions, i as ChannelTurnHandlers, I as InProcessApprovalRequestLike, j as InProcessAwaitApproval, k as InProcessRunInput, l as InProcessRunner, m as InProcessTransport, n as InProcessTransportOptions, R as RequestContext, U as UseAgentStatus, o as agentHandle, p as isAgentHandle } from './agent-handle-C6q7iA4u.js';
|
|
3
3
|
import { ChatTransport, UIMessage, UIMessageChunk } from 'ai';
|
|
4
4
|
|
|
5
5
|
/** Extra request headers — a static record OR a resolver called per request (for dynamic auth). */
|
package/dist/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AgentClient,
|
|
3
|
+
ApprovalAbortedError,
|
|
3
4
|
ChannelTransport,
|
|
4
5
|
HttpTransport,
|
|
5
6
|
InProcessTransport,
|
|
@@ -9,10 +10,11 @@ import {
|
|
|
9
10
|
extractLastUserText,
|
|
10
11
|
isAgentHandle,
|
|
11
12
|
responseToChunkStream
|
|
12
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-U6WNQ5A2.js";
|
|
13
14
|
import "./chunk-7QVYU63E.js";
|
|
14
15
|
export {
|
|
15
16
|
AgentClient,
|
|
17
|
+
ApprovalAbortedError,
|
|
16
18
|
ChannelTransport,
|
|
17
19
|
HttpTransport,
|
|
18
20
|
InProcessTransport,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { G as Guardrail, L as LoopStrategy, R as ReflectionStrategy, C as CompiledAgentOptions, M as MainLoopMeta, a as CompiledTool, b as ReasoningEffort, c as RoundStreamFactory, S as StreamEvent, D as DelegationResult, d as ContextWindowOptions, e as SkillsOptions, T as ToolOptions, A as ApprovalOptions, H as HumanInTheLoopOptions, f as AgentManifestEntry, g as HitlDecision, s as streamAgentUIMessages } from './bridge-entry-
|
|
2
|
-
export { h as AGENT_BRAND, i as AfterToolCallContext, j as AgentBuilder, k as AgentDefinition, l as AgentDefinitionError, m as AgentExecutionContext, n as AgentManifest, o as AgentManifestSource, p as AgentManifestTool, q as AgentOptions, r as AgentRoute, t as AgentRouteContext, u as AgentRunInfo, v as AgentStreamEvent, w as AgentTurnMetadata, x as AgentsPluginOptions, y as ApiErrorContext, z as ApiErrorDecision, B as ApiErrorPolicy, E as ApprovalRequiredEvent, F as ArtifactChunkEvent, I as ArtifactStartEvent, J as BackgroundDelegation, K as BeforeToolCallContext, N as
|
|
1
|
+
import { G as Guardrail, L as LoopStrategy, R as ReflectionStrategy, C as CompiledAgentOptions, M as MainLoopMeta, a as CompiledTool, b as ReasoningEffort, c as RoundStreamFactory, S as StreamEvent, D as DelegationResult, d as ContextWindowOptions, e as SkillsOptions, T as ToolOptions, A as ApprovalOptions, H as HumanInTheLoopOptions, f as AgentManifestEntry, g as HitlDecision, s as streamAgentUIMessages } from './bridge-entry-BBtYaYVe.js';
|
|
2
|
+
export { h as AGENT_BRAND, i as AfterToolCallContext, j as AgentBuilder, k as AgentDefinition, l as AgentDefinitionError, m as AgentExecutionContext, n as AgentManifest, o as AgentManifestSource, p as AgentManifestTool, q as AgentOptions, r as AgentRoute, t as AgentRouteContext, u as AgentRunInfo, v as AgentStreamEvent, w as AgentTurnMetadata, x as AgentsPluginOptions, y as ApiErrorContext, z as ApiErrorDecision, B as ApiErrorPolicy, E as ApprovalRequiredEvent, F as ArtifactChunkEvent, I as ArtifactStartEvent, J as BackgroundDelegation, K as BeforeToolCallContext, N as BudgetExceededError, O as BudgetOptions, P as CheckpointSavedEvent, Q as CompiledContextWindow, U as ContextualTool, V as CostBudgetExceededError, W as DEFAULT_MAX_ITERATIONS, X as DefineAgentConfig, Y as DefinicaoOuThunk, Z as DelegateFn, _ as DelegateOptions, $ as DelegationBudgetExceededError, a0 as DelegationError, a1 as DoneEvent, a2 as ErrorEvent, a3 as FileEditEvent, a4 as GuardrailAction, a5 as GuardrailPhase, a6 as GuardrailResult, a7 as GuardrailViolationError, a8 as HookHandlers, a9 as InferAgentInput, aa as InferAgentToolNames, ab as IterationEvent, ac as LLMCallContext, ad as LoopFinishReason, ae as LoopOutcome, af as LoopStrategyConfig, ag as MainLoopOptions, ah as McpApprovalSpec, ai as McpRegistryConfig, aj as McpRequestContext, ak as McpSelection, al as PartialToolCallEvent, am as PolicyHandler, an as ProcessInputContext, ao as ReflectionContext, ap as ReflectionResult, aq as ReflectionStrategyConfig, ar as RunStartedEvent, as as ScoreVerdict, at as ScoredDelegation, au as Scorer, av as SdkAgentHandle, aw as SdkMessage, ax as SdkSendOptions, ay as SdkTurnHandle, az as Segment, aA as SkillsRequestContext, aB as SkillsSelection, aC as StateUpdateEvent, aD as TextDeltaEvent, aE as ThinkingEvent, aF as TimeoutAction, aG as ToolCallEvent, aH as ToolCallVeto, aI as ToolHooks, aJ as ToolHooksPlugin, aK as ToolResultEvent, aL as ToolWalkResult, aM as ToolboxOptions, aN as ToolboxWalkResult, aO as agentsPlugin, aP as buildModelSelection, aQ as compileAgentDefinition, aR as compileAgentModule, aS as compileContextWindow, aT as compileProjectContext, aU as compileSkills, aV as compileTools, aW as createAgentExecutionContext, aX as createApiErrorHandler, aY as createSdkAgentStream, aZ as createThinkTagExtractor, a_ as createToolHooksPlugin, a$ as delegate, b0 as delegateBackground, b1 as delegateWithScoring, b2 as extractThinkTagStream, b3 as generateAgentManifest, b4 as generateAgentRoutes, b5 as isAgentContext, b6 as isAgentDefinition, b7 as isApprovalRequired, b8 as isDone, b9 as isError, ba as isPartialToolCall, bb as isTextDelta, bc as isToolCall, bd as isToolResult, be as ladderReflectionStrategy, bf as loopStrategyConfigSchema, bg as mcpRegistry, bh as mcpToolApprovals, bi as noopReflectionStrategy, bj as presentUIMessageStream, bk as projectContextMetadataOnlyKnobs, bl as reflectionStrategyConfigSchema, bm as resolveEnabledSkills, bn as resolveLoopStrategy, bo as resolveMcpServers, bp as runWithApiErrorHandling, bq as streamAgentResponse, br as toAgentFactory, bs as translateSdkEvent } from './bridge-entry-BBtYaYVe.js';
|
|
3
3
|
export * from '@theokit/sdk/errors';
|
|
4
|
-
export {
|
|
4
|
+
export { ConfigurationError, BudgetExceededError as WindowBudgetExceededError } from '@theokit/sdk/errors';
|
|
5
5
|
import { PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool, GoalLoopAgent, GoalOptions, runGoalLoop, GoalEvent, GoalResult, InlineSkill } from '@theokit/sdk';
|
|
6
6
|
export { Agent, CustomTool, GoalEvent, GoalLoopAgent, GoalOptions, GoalResult, JudgeCredentialError, JudgeResult, Provider, SDKAgent, SessionRecord, Squad, Tool, Verdict } from '@theokit/sdk';
|
|
7
7
|
import { RetryOptions } from '@theokit/sdk/retry';
|
package/dist/index.js
CHANGED
|
@@ -1009,7 +1009,7 @@ export {
|
|
|
1009
1009
|
AgentDefinitionError,
|
|
1010
1010
|
AgentRunner,
|
|
1011
1011
|
AgentRunnerBuilder,
|
|
1012
|
-
|
|
1012
|
+
BudgetExceededError,
|
|
1013
1013
|
CONTEXT_WINDOW_FLOOR,
|
|
1014
1014
|
CONTEXT_WINDOW_MARGIN,
|
|
1015
1015
|
CapabilityConflictError,
|
|
@@ -1024,7 +1024,6 @@ export {
|
|
|
1024
1024
|
DEFAULT_KEEP_TOKENS,
|
|
1025
1025
|
DEFAULT_MAX_ITERATIONS,
|
|
1026
1026
|
DelegationBudgetExceededError,
|
|
1027
|
-
BudgetExceededError as DelegationBudgetExceededErrorAlias,
|
|
1028
1027
|
DelegationError,
|
|
1029
1028
|
FieldCapability,
|
|
1030
1029
|
GoalRunner,
|
|
@@ -1055,6 +1054,7 @@ export {
|
|
|
1055
1054
|
Toolset,
|
|
1056
1055
|
ToolsetError,
|
|
1057
1056
|
UnknownCapabilityError,
|
|
1057
|
+
BudgetExceededError2 as WindowBudgetExceededError,
|
|
1058
1058
|
agentsPlugin,
|
|
1059
1059
|
applyCapabilities,
|
|
1060
1060
|
assertNoSymlinkEscape,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/capability/capability.ts","../src/capability/capabilities.ts","../src/capability/registry.ts","../src/capability/agent-capabilities.ts","../src/capability/toolbox.ts","../src/capability/toolset.ts","../src/a2a/agent-card.ts","../src/a2a/mcp-server-manifest.ts","../src/a2a/a2a-client.ts","../src/conversation-scope.ts","../src/skills-resolver.ts","../src/acp/protocol.ts","../src/acp/client.ts","../src/index.ts","../src/in-process-turn.ts"],"sourcesContent":["import { isDeepStrictEqual } from 'node:util'\n\nimport type { CompiledAgentOptions } from '../bridge/agent-compiler.js'\n\n/**\n * M52 — the capability layer: object-oriented, composable authoring that produces the EXISTING narrow\n * waist (`CompiledAgentOptions`), which `assembleM8CreateOptions` already turns into `Agent.create`\n * options. No new spec and no new adapter were invented (ADR-1/ADR-2) — a third representation would be\n * the very duplication this initiative removes.\n */\n\n/** Which capability contributed which fields — makes the wiring inspectable as DATA. */\nexport interface ProvenanceEntry {\n readonly capability: string\n readonly contributed: readonly string[]\n}\n\n/** The mutable draft a capability enriches. `tools`/`agents` are pre-seeded (required in the waist). */\nexport interface CompiledAgentOptionsDraft extends Partial<\n Omit<CompiledAgentOptions, 'tools' | 'agents'>\n> {\n tools: CompiledAgentOptions['tools']\n agents: CompiledAgentOptions['agents']\n readonly provenance: ProvenanceEntry[]\n}\n\n/**\n * **Strategy + value-level Decorator.** N independent ways to enrich an agent (model, tools, skills,\n * MCP, HITL…), added or removed without touching the builder — a central `switch` would violate OCP.\n */\nexport interface Capability {\n /** Stable identity — used for provenance and conflict messages. */\n readonly name: string\n apply(draft: CompiledAgentOptionsDraft): void\n}\n\n/** Two capabilities set the same scalar field to different values — a composition bug, never last-wins. */\nexport class CapabilityConflictError extends Error {\n override readonly name = 'CapabilityConflictError'\n constructor(field: string, previous: unknown, next: unknown, capability: string) {\n super(\n // NUNCA ecoa os valores: um draft montado a partir de arquivo de config pode carregar\n // token de MCP, header de auth, credencial de memória. Reporta a FORMA, como a validação\n // de fronteira das capabilities já faz.\n `capability \"${capability}\": campo \"${field}\" já declarado (${shapeOf(previous)}) ` +\n `e redeclarado com valor diferente (${shapeOf(next)}) — declare uma vez só.`,\n )\n }\n}\n\n/** Type/shape of a value for diagnostics — never its content. */\nfunction shapeOf(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return `array(${value.length})`\n if (typeof value === 'object') {\n return `object{${Object.keys(value)\n .sort((a, b) => a.localeCompare(b))\n .join(',')}}`\n }\n return typeof value\n}\n\n/**\n * A fresh draft. `stream` is deliberately NOT seeded: a pre-seeded value would make\n * `setOnce(draft, 'stream', false, …)` throw a conflict against a default nobody declared, so\n * `stream: false` would be structurally unreachable. The default is applied at finalize instead.\n */\nexport function createDraft(): CompiledAgentOptionsDraft {\n return { tools: [], agents: {}, provenance: [] }\n}\n\n/** A draft that has been finalized — the waist's required `stream` is settled. */\nexport type FinalizedDraft = CompiledAgentOptionsDraft & { stream: boolean }\n\n/** Apply capabilities in declaration order (deterministic) and return the draft. */\nexport function applyCapabilities(\n capabilities: readonly Capability[],\n draft: CompiledAgentOptionsDraft = createDraft(),\n): FinalizedDraft {\n for (const c of capabilities) c.apply(draft)\n draft.stream ??= true // same default the reference compiler emits\n return draft as FinalizedDraft\n}\n\n/** Set a scalar exactly once — fail-fast on a conflicting redeclaration (Rule 8). */\nexport function setOnce<K extends keyof CompiledAgentOptionsDraft>(\n draft: CompiledAgentOptionsDraft,\n field: K,\n value: CompiledAgentOptionsDraft[K],\n capability: string,\n): void {\n if (value === undefined) return // nothing to declare — never consume the slot with a hole\n const previous = draft[field]\n // DEEP equality, never reference identity: two capabilities may legitimately build the SAME\n // logical value in separate objects (`compileSkillsSelection` returns a fresh object per call),\n // and `previous !== value` would report those as a conflict that does not exist. CAVEAT, stated\n // because it is not obvious: `isDeepStrictEqual` compares FUNCTIONS by identity, so a field whose\n // value carries functions (resolvers, guardrail methods) stays identity-idempotent, not\n // value-idempotent. Fail-fast is the safe side of that asymmetry.\n if (previous !== undefined && !isDeepStrictEqual(previous, value)) {\n throw new CapabilityConflictError(field, previous, value, capability)\n }\n draft[field] = value\n draft.provenance.push({ capability, contributed: [field] })\n}\n","import type { InlineSkill } from '@theokit/sdk'\n\nimport type { CompiledTool } from '../bridge/agent-compiler.js'\nimport { compileSkillsSelection } from '../bridge/define-agent.js'\nimport { ConfigurationError } from '../errors.js'\n\nimport { type Capability, type CompiledAgentOptionsDraft, setOnce } from './capability.js'\n\n/**\n * M52 — three real capabilities proving the contract against genuine variation: one that VALIDATES and\n * can conflict (model), one that ACCUMULATES (tools), and one that is pure DATA (skills — a plain\n * factory, because a class with no behavior would be ceremony: KISS).\n */\n\n// `ConfigurationError` lives in `../errors.js` and is imported above. The M55 compatibility\n// re-export from this module is GONE (M56): a second import path for one class is exactly the kind\n// of concession that keeps dead surface alive. Import it from where it is defined.\n\n/** Human-readable type of a rejected value — never its content (config files may hold secrets). */\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n return Array.isArray(value) ? 'array' : typeof value\n}\n\n/** Sets the model id (and optional reasoning effort). CLASS: it validates and can conflict. */\nexport class ModelCapability implements Capability {\n readonly name = 'model'\n constructor(\n private readonly id: string,\n private readonly reasoningEffort?: CompiledAgentOptionsDraft['reasoningEffort'],\n ) {\n // Boundary validation: the registry hands `unknown` straight from a config FILE, so a wrong\n // type must fail here, typed and named — not as a raw `id.trim is not a function` three frames\n // deep (rules/error-handling.md § 2: validate at the boundary, fail typed).\n if (typeof id !== 'string') {\n throw new ConfigurationError(`model: esperava string, recebi ${describe(id)}`)\n }\n if (id.trim().length === 0) throw new ConfigurationError('model: id não pode ser vazio')\n }\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, 'model', this.id, this.name)\n if (this.reasoningEffort !== undefined) {\n setOnce(draft, 'reasoningEffort', this.reasoningEffort, this.name)\n }\n }\n}\n\n/** Adds tools. CLASS: it ACCUMULATES (never overwrites), which is behavior worth owning. */\nexport class ToolsCapability implements Capability {\n readonly name = 'tools'\n readonly #tools: readonly CompiledTool[]\n constructor(tools: readonly CompiledTool[]) {\n this.#tools = tools\n }\n apply(draft: CompiledAgentOptionsDraft): void {\n draft.tools.push(...this.#tools)\n draft.provenance.push({ capability: this.name, contributed: ['tools'] })\n }\n}\n\n/**\n * Enables skills by name (or inline). M57: a CLASS now (was a factory function). Validation moves to\n * the constructor — fail-fast at authoring, the same place `ModelCapability`/`AgentConfigCapability`\n * validate. The `apply` body (delegate + merge) is unchanged, so the compiled output is identical.\n */\nexport class SkillsCapability implements Capability {\n readonly name = 'skills'\n readonly #entries: readonly (string | InlineSkill)[]\n\n constructor(entries: readonly (string | InlineSkill)[]) {\n // Boundary validation BEFORE anything spreads: a config file carrying `skills: \"code-review\"`\n // would otherwise spread into eleven single-character skill names and reach Agent.create with no\n // error at all — silent corruption, the worst failure mode for file-based authoring.\n if (!Array.isArray(entries)) {\n throw new ConfigurationError(`skills: esperava array de nomes, recebi ${describe(entries)}`)\n }\n for (const e of entries) {\n // The reference compiler accepts `string | InlineSkill` (define-agent.ts § compileSkillsSelection),\n // so inline skills must be accepted here too — rejecting them outright would make this layer less\n // expressive than the path it claims equivalence with.\n //\n // ONE deliberate asymmetry, stated rather than glossed over: an inline skill with an empty\n // `instructions` compiles through `defineAgent` but is REJECTED here. That object's body is\n // unreachable at runtime (`SkillsManager.get` would fall back to `readFile(source)`, and a\n // hand-rolled inline has no real `source`), so this rejects a broken agent at authoring time\n // instead of at prompt-assembly time. It is an input rejection, never an output divergence.\n if (typeof e === 'string') {\n if (e.trim().length === 0) {\n throw new ConfigurationError('skills: nome vazio — use um nome de skill não vazio')\n }\n continue\n }\n if (typeof e !== 'object' || e === null || Array.isArray(e)) {\n throw new ConfigurationError(\n `skills: entrada inválida (${describe(e)}) — use um nome ou um skill inline`,\n )\n }\n // An inline skill reaches the `<skills>` system-prompt block. Accepting `{ name }` alone lets a\n // malformed skill through with `undefined` description/instructions — the same silent\n // corruption this boundary exists to stop, one level down. `InlineSkill extends Skill` requires\n // all three (`@theokit/sdk` create-skill.d.ts + discover-skills.d.ts).\n for (const field of ['name', 'description', 'instructions'] as const) {\n const value = (e as Record<string, unknown>)[field]\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ConfigurationError(\n `skills: skill inline sem \\`${field}\\` válido (${describe(value)}) — ` +\n 'name, description e instructions são obrigatórios',\n )\n }\n }\n }\n this.#entries = entries\n }\n\n apply(draft: CompiledAgentOptionsDraft): void {\n // DELEGA ao compilador canônico (não reimplementa): `autoInject`, skills inline e o caminho\n // resolver vivem numa fonte só — reimplementar aqui divergiria (foi o que a prova de\n // equivalência pegou).\n const compiled = compileSkillsSelection(this.#entries.slice())\n if (compiled.skills === undefined) return\n // ACCUMULATES, never setOnce: skills is a merge-semantics field in the reference compiler\n // (`defineAgent({skills:['a','b']})` → `['a','b']`). With setOnce a preset's baseline skills\n // could never be extended at the call site — defeating the whole point of the Composite.\n //\n // CONCAT, never dedupe. The capability list IS the authoring list: `skills(['a']) +\n // skills(['a'])` corresponds to authoring `['a','a']`, which the reference compiler maps to\n // `['a','a']`. A dedupe here looks tidier but makes the merge path the ONLY place in this\n // layer that diverges from the reference — the exact thing the milestone exists to prevent.\n const previous = draft.skills\n draft.skills =\n previous === undefined\n ? compiled.skills\n : {\n // The spread is exhaustive only because `compileSkillsSelection` emits a FIXED 3-key\n // shape (`enabled`, `autoInject: true`, and `inline` iff non-empty) — `enabled` and\n // `inline` are both re-derived below, and `autoInject` is the same literal on both\n // sides. TRAP for the future: if a capability ever authors `autoInject: false`, this\n // spread would silently normalize it back to `true`. Unreachable today (no capability\n // and no reference array form can express it) — revisit when one can.\n ...previous,\n ...compiled.skills,\n enabled: [...(previous.enabled ?? []), ...(compiled.skills.enabled ?? [])],\n ...(previous.inline !== undefined || compiled.skills.inline !== undefined\n ? { inline: [...(previous.inline ?? []), ...(compiled.skills.inline ?? [])] }\n : {}),\n }\n draft.provenance.push({ capability: this.name, contributed: ['skills'] })\n }\n}\n","import type { Capability, CompiledAgentOptionsDraft } from './capability.js'\n\n/**\n * M52 — resolution + composition. The registry is what unlocks FILE-BASED authoring (a config lists\n * capability names): resolving name → capability without a switch that grows per feature (OCP).\n */\n\n/** Fail-fast with the known set — never `undefined` leaking into the pipeline. */\nexport class UnknownCapabilityError extends Error {\n override readonly name = 'UnknownCapabilityError'\n constructor(requested: string, known: readonly string[]) {\n super(\n `capability \"${requested}\" não registrada. Conhecidas: ${known.join(', ') || '(nenhuma)'}.`,\n )\n }\n}\n\n/** **Registry + Factory Method.** */\nexport class CapabilityRegistry {\n readonly #factories = new Map<string, (arg: unknown) => Capability>()\n\n register(name: string, factory: (arg: unknown) => Capability): this {\n this.#factories.set(name, factory)\n return this\n }\n\n has(name: string): boolean {\n return this.#factories.has(name)\n }\n\n names(): string[] {\n return [...this.#factories.keys()]\n }\n\n resolve(name: string, arg?: unknown): Capability {\n const factory = this.#factories.get(name)\n if (factory === undefined) throw new UnknownCapabilityError(name, this.names())\n return factory(arg)\n }\n}\n\n/**\n * **Composite** — a preset behaves like ONE capability, so a caller says `codingAgent()` instead of\n * spreading an array at the call site. Members apply in declaration order (deterministic).\n */\nexport class CapabilityPreset implements Capability {\n readonly #members: readonly Capability[]\n constructor(\n readonly name: string,\n members: readonly Capability[],\n ) {\n this.#members = members\n }\n apply(draft: CompiledAgentOptionsDraft): void {\n for (const member of this.#members) member.apply(draft)\n }\n}\n","import type { CompiledAgentOptions } from '../bridge/agent-compiler.js'\nimport {\n compileContextWindow,\n type ContextWindowOptions,\n} from '../bridge/compile-context-window.js'\nimport { compileSkills, type SkillsOptions } from '../bridge/compile-skills.js'\nimport { ConfigurationError } from '../errors.js'\n\nimport { type Capability, type CompiledAgentOptionsDraft, setOnce } from './capability.js'\n\n/**\n * M53 — the capabilities that replace the waist-bound agent decorators, one per field the decorator\n * pipeline produces today (`docs/agents/decorator-to-capability.md` § A).\n *\n * M57 reverses ADR 0001 § 4 (which kept the pure-assignment ones as a factory function to avoid\n * \"13 near-identical classes\"): the authoring surface is now 100% classes, aligned with the SDK's\n * `X.create()`/class shape. The `FieldCapability` base keeps the assignment ones DRY (one line each);\n * the behaviour-carrying ones are written out. Rationale in ADR 0005.\n */\n\n/**\n * Base for a capability whose only job is to assign one waist field — no validation, no merge, no\n * precedence. M57: this replaces the `fieldCapability(name, field)` factory function with a class, so\n * the authoring surface is 100% classes (aligned with the SDK's `X.create()` and the existing\n * `ModelCapability`). The subclasses below are one line each; the shared `apply` lives here (DRY).\n * NOT the Template-Method the ADR-0001 refused — that was inheritance of variable *behaviour*\n * (`shouldContinue`); here the base carries *data* (name/field) and `apply` is identical for all.\n */\nexport abstract class FieldCapability<\n K extends keyof CompiledAgentOptionsDraft,\n> implements Capability {\n abstract readonly name: string\n protected abstract readonly field: K\n constructor(private readonly value: NonNullable<CompiledAgentOptionsDraft[K]>) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, this.field, this.value as CompiledAgentOptionsDraft[K], this.name)\n }\n}\n\n/** `@Memory` → `memory`. */\nexport class MemoryCapability extends FieldCapability<'memory'> {\n readonly name = 'memory'\n protected readonly field = 'memory' as const\n}\n/**\n * `@ContextWindow` → `context`. DELEGATES to `compileContextWindow`, which is the canonical\n * `ContextWindowOptions → ContextSettings` conversion (it also reports the metadata-only knobs).\n * Taking a pre-converted value here would duplicate that knowledge — the exact divergence the M52\n * zero-behavior proof caught in `skills`.\n */\nexport class ContextWindowCapability implements Capability {\n readonly name = 'context-window'\n constructor(private readonly options: ContextWindowOptions) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, 'context', compileContextWindow(this.options).context, this.name)\n }\n}\n/** `@ProjectContext` → `projectContext`. */\nexport class ProjectContextCapability extends FieldCapability<'projectContext'> {\n readonly name = 'project-context'\n protected readonly field = 'projectContext' as const\n}\n/** `@MCP` → `mcpServers`. */\nexport class McpServersCapability extends FieldCapability<'mcpServers'> {\n readonly name = 'mcp'\n protected readonly field = 'mcpServers' as const\n}\n/** `@Guardrails` → `guardrails`. */\nexport class GuardrailsCapability extends FieldCapability<'guardrails'> {\n readonly name = 'guardrails'\n protected readonly field = 'guardrails' as const\n}\n/**\n * `@Checkpoint` → `checkpoint`. Carries the non-durable WARNING the metadata walk used to emit: only\n * `'filesystem'` selects the SDK's durable store, so any other storage cannot resume across\n * requests. The warning moves WITH the feature — a declared checkpoint that silently cannot resume\n * is exactly the kind of no-op this project refuses to ship.\n */\nexport class CheckpointCapability implements Capability {\n readonly name = 'checkpoint'\n constructor(private readonly options: CompiledAgentOptions['checkpoint']) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n if (this.options !== undefined && this.options.storage !== 'filesystem') {\n console.warn(\n `[THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY] checkpoint({ storage: '${this.options.storage ?? 'memory'}' }) ` +\n `does NOT resume across requests — only 'filesystem' selects the SDK's durable conversation ` +\n `store. Use checkpoint({ storage: 'filesystem' }) for cross-request resume.`,\n )\n }\n setOnce(draft, 'checkpoint', this.options, this.name)\n }\n}\n/**\n * `@HumanInTheLoop` → `hitl`, keyed `\"<namespace>_<tool>\"` — the same key `compileHitlGates` mints\n * via `toolRuntimeName`. The separator is `_`, not `.`: the dot is outside the charset the SDK\n * accepts, and a gate keyed with a dot silently failed to match its tool (theokit#145).\n */\nexport class HumanInTheLoopCapability extends FieldCapability<'hitl'> {\n readonly name = 'human-in-the-loop'\n protected readonly field = 'hitl' as const\n}\n/**\n * `@SubAgents` → `agents`. MERGES instead of `setOnce`: `agents` is a pre-seeded collection on the\n * draft (`createDraft` gives it `{}`), so a `setOnce` would conflict against the seed itself — the\n * same trap the pre-seeded `stream` sprang in M52. Merging also lets a preset declare a baseline\n * child set that a call site extends.\n */\nexport class SubAgentsCapability implements Capability {\n readonly name = 'sub-agents'\n constructor(private readonly children: CompiledAgentOptions['agents']) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n for (const [name, child] of Object.entries(this.children)) {\n if (name in draft.agents && draft.agents[name] !== child) {\n throw new ConfigurationError(\n `sub-agents: filho \"${name}\" declarado duas vezes com definições diferentes`,\n )\n }\n draft.agents[name] = child\n }\n draft.provenance.push({ capability: this.name, contributed: ['agents'] })\n }\n}\n/**\n * `@Skills({ include, autoDiscover })` → `skills`. Delegates to `compileSkills` (same reason as\n * `contextWindow`). Distinct from the M52 `skills([...])`, which takes the plain name/inline list.\n */\nexport class SkillsOptionsCapability implements Capability {\n readonly name = 'skills'\n constructor(private readonly options: SkillsOptions) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, 'skills', compileSkills(this.options), this.name)\n }\n}\n\n/** Functional-path fields that had no decorator source — closing the gap list, not adding surface. */\nexport class SettingSourcesCapability extends FieldCapability<'settingSources'> {\n readonly name = 'setting-sources'\n protected readonly field = 'settingSources' as const\n}\nexport class PluginsCapability extends FieldCapability<'plugins'> {\n readonly name = 'plugins'\n protected readonly field = 'plugins' as const\n}\nexport class RunContextCapability extends FieldCapability<'runContext'> {\n readonly name = 'run-context'\n protected readonly field = 'runContext' as const\n}\nexport class SkillsResolverCapability extends FieldCapability<'skillsResolver'> {\n readonly name = 'skills-resolver'\n protected readonly field = 'skillsResolver' as const\n}\n\n/** The scalar agent config (name/route are HTTP concerns, never agent config). */\nexport interface AgentConfig {\n readonly systemPrompt?: CompiledAgentOptions['systemPrompt']\n readonly parseThinkTags?: boolean\n readonly stripToolDialect?: boolean\n readonly recoverLeakedToolCalls?: boolean\n readonly stream?: boolean\n readonly maxIterations?: number\n readonly timeoutMs?: number\n}\n\n/**\n * Scalar waist fields (formerly the `@Agent` options). CLASS, not a factory: it validates, and it is the one\n * capability that writes fields another capability may legitimately override (see\n * {@link MainLoopCapability}).\n */\nexport class AgentConfigCapability implements Capability {\n readonly name = 'agent-config'\n constructor(private readonly config: AgentConfig) {\n // The registry hands this `unknown` straight from a config file, so the guard is real at\n // runtime even though the declared type makes it look redundant to the compiler.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- boundary check: the value may not be an object at runtime\n if (typeof config !== 'object' || config === null) {\n throw new ConfigurationError('agent-config: esperava um objeto de configuração')\n }\n for (const field of ['maxIterations', 'timeoutMs'] as const) {\n const value = config[field]\n if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {\n throw new ConfigurationError(`agent-config: \\`${field}\\` deve ser um número positivo`)\n }\n }\n }\n\n apply(draft: CompiledAgentOptionsDraft): void {\n // `maxIterations`/`timeoutMs` are the two fields `main-loop` outranks (see MainLoopCapability).\n // Skipping them when main-loop already contributed makes the precedence ORDER-INDEPENDENT while\n // still letting two agent-config declarations conflict with each other.\n const claimedByMainLoop = (field: string): boolean =>\n draft.provenance.some((p) => p.capability === 'main-loop' && p.contributed.includes(field))\n if (!claimedByMainLoop('maxIterations')) {\n setOnce(draft, 'maxIterations', this.config.maxIterations, this.name)\n }\n if (!claimedByMainLoop('timeoutMs')) {\n setOnce(draft, 'timeoutMs', this.config.timeoutMs, this.name)\n }\n setOnce(draft, 'systemPrompt', this.config.systemPrompt, this.name)\n setOnce(draft, 'parseThinkTags', this.config.parseThinkTags, this.name)\n setOnce(draft, 'stripToolDialect', this.config.stripToolDialect, this.name)\n setOnce(draft, 'recoverLeakedToolCalls', this.config.recoverLeakedToolCalls, this.name)\n setOnce(draft, 'stream', this.config.stream, this.name)\n }\n}\n\n/**\n * `@MainLoop({ maxIterations, timeoutMs })` → the same two fields `@Agent` can write.\n *\n * PRECEDENCE, preserved deliberately: `compileAgent` resolves these as\n * `mainLoop.x ?? agentConfig.x` — the main-loop declaration WINS when both are present. A plain\n * `setOnce` would raise a conflict where the pipeline has a defined winner, so this capability\n * OVERRIDES instead. That is the one place in the layer where a later write beats an earlier one,\n * and it exists to keep behavior identical, not for convenience.\n */\nexport class MainLoopCapability implements Capability {\n readonly name = 'main-loop'\n constructor(private readonly config: { maxIterations?: number; timeoutMs?: number }) {}\n\n apply(draft: CompiledAgentOptionsDraft): void {\n const contributed: string[] = []\n if (this.config.maxIterations !== undefined) {\n draft.maxIterations = this.config.maxIterations\n contributed.push('maxIterations')\n }\n if (this.config.timeoutMs !== undefined) {\n draft.timeoutMs = this.config.timeoutMs\n contributed.push('timeoutMs')\n }\n if (contributed.length > 0) draft.provenance.push({ capability: this.name, contributed })\n }\n}\n","import {\n compileHitlGates,\n compileTools,\n toolRuntimeName,\n type ClassToken,\n type ToolboxWalkResult,\n} from '../bridge/agent-compiler.js'\nimport { ConfigurationError } from '../errors.js'\nimport type { ApprovalOptions, HumanInTheLoopOptions, ToolOptions } from '../types.js'\n\nimport type { Capability, CompiledAgentOptionsDraft } from './capability.js'\n\n/**\n * M53 — tools without `@Toolbox`/`@Tool`.\n *\n * A toolbox class declares its tools as DATA (`static tools`) and keeps its handlers as ordinary\n * methods; the capability takes an INSTANCE. That preserves what the decorators actually bought —\n * grouping under a namespace and handlers bound to the instance (so a toolbox can hold state and\n * injected dependencies) — with no metadata reflection at all.\n *\n * The compilation itself is NOT reimplemented: it delegates to `compileTools`, the same function the\n * decorator path calls, so namespacing (`toolRuntimeName`), handler binding and the fail-fast checks\n * stay in one place.\n *\n * @example\n * ```ts\n * class SupportTools {\n * static tools: ToolDeclaration[] = [\n * { name: 'search', description: 'Search tickets', input: z.object({ q: z.string() }), method: 'search' },\n * ]\n * async search({ q }: { q: string }): Promise<string> { return `found ${q}` }\n * }\n *\n * const agent = applyCapabilities([\n * new ModelCapability('openai/gpt-5.4'),\n * new ToolboxCapability(new SupportTools(), { namespace: 'support' }),\n * ])\n * ```\n */\nexport interface ToolDeclaration extends ToolOptions {\n /** Method on the toolbox instance that implements this tool. */\n readonly method: string\n /** Require human approval before the tool runs (surfaced in the manifest). */\n readonly approval?: ApprovalOptions\n /** Gate the tool behind human-in-the-loop (M4). */\n readonly hitl?: HumanInTheLoopOptions\n /** Manifest-only observability flags. */\n readonly trace?: boolean\n readonly audit?: boolean\n}\n\n/** A toolbox instance whose class declares its tools. */\nexport interface ToolboxSource {\n readonly constructor: { tools?: readonly ToolDeclaration[] }\n}\n\nexport interface ToolboxOptions {\n /**\n * Prefix for every tool name (`\"<namespace>_<tool>\"`), as `@Toolbox({ namespace })` did.\n * The separator is `_`, not `.` — the dot is outside the charset the SDK accepts (theokit#145).\n */\n readonly namespace?: string\n /** Declarations, when they are not on the class as `static tools`. */\n readonly tools?: readonly ToolDeclaration[]\n}\n\nexport class ToolboxCapability implements Capability {\n readonly name = 'toolbox'\n readonly #instance: object\n readonly #declarations: readonly ToolDeclaration[]\n readonly #namespace: string\n\n constructor(instance: object, options: ToolboxOptions = {}) {\n // Boundary check: the registry hands this `unknown` straight from a config file, so the guard is\n // real at runtime even though the declared type makes it look redundant to the compiler.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- may not be an object at runtime\n if (typeof instance !== 'object' || instance === null) {\n throw new ConfigurationError('toolbox: esperava uma instância de toolbox')\n }\n const declared =\n options.tools ?? (instance.constructor as { tools?: readonly ToolDeclaration[] }).tools\n if (declared === undefined || declared.length === 0) {\n throw new ConfigurationError(\n `toolbox: ${instance.constructor.name} não declara tools — use \\`static tools = [...]\\` ou a opção \\`tools\\``,\n )\n }\n for (const tool of declared) {\n // Validate here rather than at call time: a missing method only surfaces when the model\n // decides to call the tool, which is the worst moment to discover a typo.\n if (typeof (instance as Record<string, unknown>)[tool.method] !== 'function') {\n throw new ConfigurationError(\n `toolbox: ${instance.constructor.name}.${tool.method} não é um método (tool \"${tool.name}\")`,\n )\n }\n }\n this.#instance = instance\n this.#declarations = declared\n this.#namespace = options.namespace ?? ''\n // Fail at AUTHORING, not when the model finally calls the tool: a namespace/tool pair that\n // cannot mint a name the SDK accepts is a broken agent, and `Agent.create` would only say so\n // at runtime (theokit#145).\n //\n // The CALL is the validation (M55): `toolRuntimeName` validates what it mints, so this loop no\n // longer knows the name format — one module owns that rule. Re-testing it here would be the\n // very duplication that let the gate key and the tool name drift apart in #145. The minted\n // value is intentionally discarded; `compile()` mints again when it actually needs it.\n for (const tool of declared) toolRuntimeName(this.#namespace, tool.name)\n }\n\n /**\n * The single derivation of this toolbox (M55). Both compilers below consume THIS object, so the\n * tool registry and the HITL gate map cannot disagree on a name — the property is structural, not\n * a convention repeated in two loops. That repetition is precisely how the two drifted apart in\n * #145: the tool became `ns_tool` while its gate stayed `ns.tool`, silently ungating it.\n *\n * Same technique the `opencode` harness uses for the analogous tool↔permission coupling, where\n * `Permission.visibleTools` filters the tool record itself rather than keeping a parallel map\n * (\"so the two cannot drift\" — `permission/index.ts`).\n */\n #walk(): ToolboxWalkResult {\n return {\n // `constructor` is typed `Function` by lib.d.ts; here it is used purely as an IDENTITY key\n // into the instances map, which is what `ClassToken` models.\n class: this.#instance.constructor as ClassToken,\n namespace: this.#namespace,\n guards: [],\n tools: this.#declarations.map((tool) => ({\n propertyKey: tool.method,\n config: tool,\n guards: [],\n approval: tool.approval,\n trace: tool.trace ?? false,\n audit: tool.audit ?? false,\n ...(tool.hitl !== undefined ? { hitl: tool.hitl } : {}),\n })),\n }\n }\n\n /**\n * M56 — the public `compile()` is GONE. It had zero callers anywhere in the monorepo and was kept\n * only because deleting a public method is breaking; that concession is exactly the dead surface\n * M55 set out to remove, preserved inside the milestone that removed it. `apply()` is the one path.\n */\n apply(draft: CompiledAgentOptionsDraft): void {\n const walk = this.#walk()\n\n // ACCUMULATES: several toolboxes compose into one agent, exactly as several `@Toolbox` classes did.\n draft.tools.push(...compileTools([walk], new Map([[walk.class, this.#instance]])))\n draft.provenance.push({ capability: this.name, contributed: ['tools'] })\n\n const gates = compileHitlGates([walk])\n // The early return comes BEFORE `??=`, deliberately: `agent-compiler.ts` documents that an\n // empty gate map means \"no gated tools ⇒ the non-HITL stream path (M2, byte-unchanged)\".\n // Creating an empty Map here would flip that branch for every agent that has no HITL at all.\n if (gates.size === 0) return\n draft.hitl ??= new Map()\n for (const [key, options] of gates) draft.hitl.set(key, options)\n draft.provenance.push({ capability: this.name, contributed: ['hitl'] })\n }\n}\n","/**\n * M91 — `Toolset`: coleção nomeada e imutável de tools, com política de resolução que falha alto.\n *\n * ## Por que na camada\n *\n * A camada já publica as costuras de `sandbox` e `interactive`; esta é a contraparte que faltava. Sem\n * ela, o consumidor escreveu a sua — `agents/tools/registry.ts` do agent-builder, 170 LoC — e a\n * política que importa (falhar alto em nome desconhecido **e** duplicado) ficou fora do framework,\n * onde o próximo consumidor teria de redescobri-la.\n *\n * ## O que ela NÃO faz, e por quê\n *\n * **Não prefixa namespace.** Foi isso que desqualificou o `ToolboxCapability` deste mesmo diretório\n * para este papel: o nome de uma tool é **contrato com o modelo**, e prefixar muda o que o modelo vê.\n *\n * **Não constrói tools.** Quais tools, com quais opções e sob qual escopo é decisão do consumidor —\n * a camada não sabe o `projectRoot` nem a postura de sandbox de ninguém. O `Toolset` recebe as\n * entradas já construídas e é dono só da **política de resolução**. É a divisão que impede a\n * primitiva de virar uma segunda cópia do registry do consumidor.\n *\n * ## Por que falhar alto nos dois casos\n *\n * Nome **desconhecido**: um role que declara `run_shell` numa whitelist e recebe silêncio fica sem a\n * tool sem ninguém notar. Nome **duplicado**: registra a mesma tool duas vezes no `Agent.create`, sem\n * sinal nenhum. Nos dois, o resultado é uma mudança de autoridade **não observável** — que é\n * exatamente o que uma whitelist existe para impedir.\n */\n\n/** O mínimo que o `Toolset` precisa saber de uma tool: que ela tem nome. */\nexport interface ToolComNome {\n readonly name: string\n}\n\nexport class ToolsetError extends Error {\n constructor(\n message: string,\n readonly code: 'unknown_tool' | 'duplicate_tool',\n ) {\n super(message)\n this.name = 'ToolsetError'\n }\n}\n\nexport class Toolset<T extends ToolComNome> {\n readonly #porNome: ReadonlyMap<string, T>\n\n private constructor(porNome: ReadonlyMap<string, T>) {\n this.#porNome = porNome\n Object.freeze(this)\n }\n\n /**\n * Constrói a partir das tools já instanciadas. Falha alto em nome duplicado **na construção** — não\n * na resolução: um descritor com duas tools de mesmo nome está errado no momento em que é escrito, e\n * adiar o erro para o primeiro `resolve` esconde metade dos casos.\n */\n static from<T extends ToolComNome>(tools: readonly T[]): Toolset<T> {\n const porNome = new Map<string, T>()\n for (const tool of tools) {\n if (porNome.has(tool.name)) {\n throw new ToolsetError(`duplicate tool \"${tool.name}\" in toolset`, 'duplicate_tool')\n }\n porNome.set(tool.name, tool)\n }\n return new Toolset(porNome)\n }\n\n /** Uma tool pelo nome. Lança com o nome no erro — nunca devolve `undefined` em silêncio. */\n get(name: string): T {\n const tool = this.#porNome.get(name)\n if (tool === undefined) {\n throw new ToolsetError(`unknown tool \"${name}\"`, 'unknown_tool')\n }\n return tool\n }\n\n /**\n * Resolve uma whitelist. Falha alto em desconhecido **e** em duplicado dentro da própria lista:\n * um time nunca concede em silêncio uma tool que o role não declarou, nem descarta em silêncio uma\n * que declarou.\n */\n resolve(names: readonly string[]): readonly T[] {\n const vistos = new Set<string>()\n return names.map((name) => {\n if (vistos.has(name)) {\n throw new ToolsetError(`duplicate tool \"${name}\" in a whitelist`, 'duplicate_tool')\n }\n vistos.add(name)\n return this.get(name)\n })\n }\n\n /** Os nomes conhecidos, na ordem de registro. */\n names(): readonly string[] {\n return [...this.#porNome.keys()]\n }\n\n /** Todas as tools, na ordem de registro. */\n all(): readonly T[] {\n return [...this.#porNome.values()]\n }\n}\n","/**\n * M15 (theokit-ai-first) — A2A agent card generation (ADR-0040 § D2, home/discovery concern).\n *\n * Produces an [A2A](https://github.com/google/A2A)-spec Agent Card from the framework's\n * `AgentManifestEntry`, so other systems can discover a TheoKit agent's capabilities over HTTP at\n * `/.well-known/<name>/agent-card.json`. Pure data transform — no LLM, no runtime (G2).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** A single capability exposed by an A2A agent (maps from a TheoKit tool). */\nexport interface A2ASkill {\n id: string\n name: string\n description: string\n}\n\n/** A2A agent-card capabilities block. */\nexport interface A2ACapabilities {\n streaming: boolean\n pushNotifications: boolean\n stateTransitionHistory: boolean\n}\n\n/** An A2A-spec Agent Card (the subset TheoKit advertises). */\nexport interface AgentCard {\n name: string\n description: string\n url: string\n version: string\n capabilities: A2ACapabilities\n defaultInputModes: string[]\n defaultOutputModes: string[]\n skills: A2ASkill[]\n}\n\nexport interface BuildAgentCardOptions {\n /** Absolute base URL of the deployment (e.g. `https://app.example.com`). A trailing slash is trimmed. */\n baseUrl: string\n /** Human description of the agent. Defaults to a generated sentence when omitted (spec requires non-empty). */\n description?: string\n}\n\n/** Strip a single trailing slash so `${baseUrl}${route}` never doubles the separator. */\nfunction trimTrailingSlash(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url\n}\n\n/** Build an A2A agent card from a manifest entry. */\nexport function buildAgentCard(entry: AgentManifestEntry, options: BuildAgentCardOptions): AgentCard {\n const base = trimTrailingSlash(options.baseUrl)\n return {\n name: entry.name,\n description: options.description ?? `TheoKit agent \"${entry.name}\".`,\n url: `${base}${entry.route}`,\n version: '1.0',\n capabilities: {\n streaming: entry.stream,\n pushNotifications: false,\n stateTransitionHistory: false,\n },\n defaultInputModes: ['text'],\n defaultOutputModes: ['text'],\n skills: entry.tools.map((t) => ({ id: t.name, name: t.name, description: t.description })),\n }\n}\n\n/** The A2A discovery path for an agent: `/.well-known/<name>/agent-card.json`. */\nexport function wellKnownCardPath(agentName: string): string {\n return `/.well-known/${agentName}/agent-card.json`\n}\n","/**\n * M16 (theokit-ai-first) — MCP server manifest generation (ADR-0040 § D2, home concern).\n *\n * Exposes a TheoKit agent's tools to external MCP clients as `tools/list` descriptors, so the app\n * can advertise its agents over its OWN HTTP routes. Pure data transform — no LLM, no runtime, and\n * NO stdio transport (that stays SDK-side per sdk-runtime.md). Serving these over `GET /mcp` and the\n * JSON-RPC envelope are follow-ups (mount path).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** The MCP protocol revision these descriptors target. */\nexport const MCP_PROTOCOL_VERSION = '2024-11-05'\n\n/** A JSON-schema object (the shape MCP expects for a tool's `inputSchema`). */\nexport interface McpJsonSchema {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n}\n\n/** An MCP `tools/list` tool descriptor. */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: McpJsonSchema\n}\n\n/** MCP `initialize` server info. */\nexport interface McpServerInfo {\n name: string\n version: string\n protocolVersion: string\n}\n\n/**\n * Map an agent's tools to MCP tool descriptors. The manifest tool carries name + description; the\n * per-tool JSON schema is not retained in the manifest, so a permissive empty-object schema is\n * emitted (MCP clients accept it and pass through arbitrary args). Wiring the real per-tool schema\n * is a follow-up once the manifest carries it.\n */\nexport function buildMcpToolDescriptors(entry: AgentManifestEntry): McpToolDescriptor[] {\n return entry.tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: { type: 'object', properties: {} },\n }))\n}\n\n/** Build the MCP `initialize` server-info block for an agent. */\nexport function mcpServerInfo(entry: AgentManifestEntry): McpServerInfo {\n return { name: entry.name, version: '1.0', protocolVersion: MCP_PROTOCOL_VERSION }\n}\n","/**\n * M15 (theokit-ai-first) — A2A client: call a remote A2A agent as a tool (ADR-0040 § D2).\n *\n * `createA2ATool` returns a `CustomTool` whose handler POSTs the input message to a remote agent's\n * HTTP endpoint and returns its text response — cross-network delegation. Uses `fetch` (Web\n * Standards, G8). The target is a remote AGENT endpoint, not an LLM provider, so the G2 grep guard\n * (`openrouter.ai|api.openai.com|api.anthropic.com`) is unaffected. `fetchImpl` is injectable for tests.\n */\nimport type { CustomTool } from '@theokit/sdk'\n\n/** How to authenticate to the remote agent. */\nexport interface A2AAuth {\n /** Bearer token → `Authorization: Bearer <token>`. */\n bearer?: string\n /** API-key header pair → `<name>: <value>` (e.g. `x-api-key`). */\n apiKey?: { header: string; value: string }\n}\n\nexport interface A2AToolConfig {\n /** Remote agent endpoint URL (POST target). */\n url: string\n /** Tool name the model calls. */\n name: string\n /** Tool description surfaced to the model. */\n description: string\n /** Static headers merged into every request. */\n headers?: Record<string, string>\n /** Auth applied to every request. */\n auth?: A2AAuth\n /** Injected fetch (defaults to the global). Narrowed to the call shape this client uses. */\n fetchImpl?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/** Build the request headers from static headers + auth. */\nfunction buildHeaders(config: A2AToolConfig): Record<string, string> {\n const headers: Record<string, string> = { 'content-type': 'application/json', ...config.headers }\n if (config.auth?.bearer) headers.authorization = `Bearer ${config.auth.bearer}`\n if (config.auth?.apiKey) headers[config.auth.apiKey.header] = config.auth.apiKey.value\n return headers\n}\n\n/**\n * Create a tool that delegates to a remote A2A agent. The remote is expected to answer a\n * `{ message }` POST with a JSON body carrying a `response` (or `text`) string.\n */\nexport function createA2ATool(config: A2AToolConfig): CustomTool {\n const doFetch = config.fetchImpl ?? fetch\n return {\n name: config.name,\n description: config.description,\n inputSchema: {\n type: 'object',\n properties: { message: { type: 'string', description: 'The message to send to the remote agent.' } },\n required: ['message'],\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n // The input schema requires `message: string`; narrow defensively (never base-to-string).\n const message = typeof input.message === 'string' ? input.message : ''\n const res = await doFetch(config.url, {\n method: 'POST',\n headers: buildHeaders(config),\n body: JSON.stringify({ message }),\n })\n if (!res.ok) {\n throw new Error(`A2A call to \"${config.name}\" failed: ${res.status} ${res.statusText}`)\n }\n const data = (await res.json()) as { response?: string; text?: string }\n return data.response ?? data.text ?? ''\n },\n }\n}\n","/**\n * M11 (theokit-ai-first) — {resource, thread} conversation scoping (ADR-0040 § D2, home concern).\n *\n * Maps a request's (resource, thread) pair to a deterministic, collision-safe conversation id so\n * multi-tenant apps isolate history without hand-building `user-${id}-thread-${id}` strings. This\n * is the app's request→conversation mapping — NOT the SDK's storage engine (which the derived id is\n * simply handed to). Background compression of long histories stays SDK-side.\n *\n * Encoding: each component is `encodeURIComponent`-escaped and joined with `/`. Since\n * `encodeURIComponent` escapes a raw `/` to `%2F`, the separator is unambiguous — `('a/b','c')` and\n * `('a','b/c')` derive DIFFERENT ids (collision-safe). Reversible via {@link parseConversationId}.\n */\n\nconst SEPARATOR = '/'\n\n/** Derive a deterministic conversation id from a (resource, thread) pair. Fails fast on empty input. */\nexport function deriveConversationId(resource: string, thread: string): string {\n if (!resource) throw new Error('[@theokit/agents] deriveConversationId: resource must be non-empty')\n if (!thread) throw new Error('[@theokit/agents] deriveConversationId: thread must be non-empty')\n return `${encodeURIComponent(resource)}${SEPARATOR}${encodeURIComponent(thread)}`\n}\n\n/**\n * Reverse a derived conversation id back to its (resource, thread). Returns `null` for a value that\n * is not a derived scope id (no separator, or an empty component) — callers treat that as \"opaque id,\n * not scoped\".\n */\nexport function parseConversationId(id: string): { resource: string; thread: string } | null {\n const idx = id.indexOf(SEPARATOR)\n if (idx <= 0 || idx >= id.length - 1) return null\n const resource = decodeURIComponent(id.slice(0, idx))\n const thread = decodeURIComponent(id.slice(idx + 1))\n if (!resource || !thread) return null\n return { resource, thread }\n}\n","/**\n * M13 (theokit-ai-first) — per-request skills resolution (ADR-0040 § D2, home/boundary concern).\n *\n * The static `skills.enabled` filter already works (`compile-skills` maps `include` → the SDK's\n * `enabled`). This adds a PER-REQUEST resolver so multi-tenant apps expose different skill sets to\n * different users. A selection is either a static list or a function of the request context (the M7\n * run-context). Discovery + injection stay in the SDK; this only CHOOSES the enabled set per call.\n */\n\nimport type { InlineSkill } from '@theokit/sdk'\n\n/** The request context handed to a skills resolver (the M7 run-context — opaque per-request data). */\nexport type SkillsRequestContext = Record<string, unknown>\n\n/**\n * How the skill set is chosen:\n * - a static array of `string` (filesystem skill NAMES → `skills.enabled`) and/or `InlineSkill`\n * objects from `createSkill` (code-defined skills → `skills.inline`, injected into the `<skills>`\n * block). A mixed list is split at compile time.\n * - a function — resolved per request from the {@link SkillsRequestContext} (sync or async). The\n * resolver returns filesystem skill NAMES (inline skills are static — declared on the agent).\n */\nexport type SkillsSelection =\n | readonly (string | InlineSkill)[]\n | ((ctx: SkillsRequestContext) => readonly string[] | Promise<readonly string[]>)\n\n/**\n * Resolve the enabled skill names for a request. Returns `undefined` when no selection is given (the\n * SDK then enables every discovered skill). Fails fast if a resolver returns a non-array. The static\n * array is compiled ahead of time (see `compileSkillsSelection`), so this is exercised for the\n * resolver form; a static array is defensively narrowed to its string (name) members.\n */\nexport async function resolveEnabledSkills(\n selection: SkillsSelection | undefined,\n ctx: SkillsRequestContext,\n): Promise<string[] | undefined> {\n if (selection === undefined) return undefined\n if (typeof selection !== 'function') {\n return selection.filter((s): s is string => typeof s === 'string')\n }\n const resolved: unknown = await selection(ctx)\n if (!Array.isArray(resolved)) {\n throw new Error('[@theokit/agents] skills resolver must return an array of skill names')\n }\n // The resolver is USER code, so the array's ITEMS are validated too — previously only the array\n // shape was checked and a `[42, null]` would have reached `Agent.create` as \"skill names\".\n const names = resolved as readonly unknown[]\n if (!names.every((n): n is string => typeof n === 'string' && n.trim().length > 0)) {\n throw new Error('[@theokit/agents] skills resolver must return non-empty skill NAME strings')\n }\n return [...names]\n}\n","/**\n * M17 (theokit-ai-first) — ACP (Agent Client Protocol) stdio framing.\n *\n * ACP talks to a coding agent (Claude Code, Amp, Codex) over stdio as newline-delimited JSON. This\n * is the transport-agnostic CORE: encode a message to a line, and decode a byte/char stream that may\n * split a message across chunks. Pure — no subprocess, no Node API. The subprocess spawn lives in the\n * adapter layer (G8) / SDK; `createACPTool` (wrapping this codec + an injected transport) is a\n * follow-up once the adapter ships.\n */\n\n/** Serialize a message to a single newline-terminated JSON line. */\nexport function encodeAcpMessage(message: unknown): string {\n return `${JSON.stringify(message)}\\n`\n}\n\n/**\n * Incremental decoder for newline-delimited JSON. Feed it chunks with {@link push}; it buffers a\n * partial trailing line across calls and returns every WHOLE message parsed so far. Blank lines are\n * skipped. A completed non-JSON line fails fast with a typed error (error-handling.md) — a corrupt\n * frame must never be silently dropped.\n */\nexport class AcpMessageDecoder {\n private buffer = ''\n\n /** Feed a chunk; returns the messages completed by this chunk (possibly empty). */\n push(chunk: string): unknown[] {\n this.buffer += chunk\n const messages: unknown[] = []\n let newlineIndex = this.buffer.indexOf('\\n')\n while (newlineIndex !== -1) {\n const line = this.buffer.slice(0, newlineIndex).trim()\n this.buffer = this.buffer.slice(newlineIndex + 1)\n if (line.length > 0) {\n try {\n messages.push(JSON.parse(line))\n } catch (cause) {\n throw new Error(`[@theokit/agents] ACP decode failed on line: ${line}`, { cause })\n }\n }\n newlineIndex = this.buffer.indexOf('\\n')\n }\n return messages\n }\n}\n","/**\n * M17 (theokit-ai-first) — ACP client: JSON-RPC over the stdio framing.\n *\n * Drives a coding agent (Claude Code, Amp, Codex) over an INJECTED {@link AcpTransport}. The\n * subprocess spawn is a Node API and lives in the adapter layer (G8); this client is transport-\n * agnostic and testable. It correlates responses to requests by `id`, and dispatches server→client\n * requests (e.g. `session/request_permission`) to a registered handler, replying with its decision.\n */\nimport { AcpMessageDecoder, encodeAcpMessage } from './protocol.js'\n\n/** The stdio channel to the coding-agent subprocess (abstracted for testability + G8). */\nexport interface AcpTransport {\n /** Write one already-encoded (newline-terminated) line to the agent's stdin. */\n send(line: string): void\n /** Subscribe to raw lines/chunks from the agent's stdout. */\n subscribe(onData: (chunk: string) => void): void\n}\n\ninterface JsonRpcResponse {\n id: number\n result?: unknown\n error?: { code: number; message: string }\n}\ninterface JsonRpcServerRequest {\n id: number\n method: string\n params?: unknown\n}\n\ninterface Pending {\n resolve: (value: unknown) => void\n reject: (err: Error) => void\n}\n/** Return a value or a Promise — `unknown` already includes `Promise<unknown>`; `await` handles both. */\ntype ServerRequestHandler = (params: unknown) => unknown\n\nfunction isResponse(m: Record<string, unknown>): m is JsonRpcResponse & Record<string, unknown> {\n return typeof m.id === 'number' && (('result' in m) || ('error' in m)) && !('method' in m)\n}\nfunction isServerRequest(m: Record<string, unknown>): m is JsonRpcServerRequest & Record<string, unknown> {\n return typeof m.method === 'string' && typeof m.id === 'number'\n}\n\nexport class AcpClient {\n private nextId = 1\n private readonly pending = new Map<number, Pending>()\n private readonly handlers = new Map<string, ServerRequestHandler>()\n private readonly decoder = new AcpMessageDecoder()\n\n constructor(private readonly transport: AcpTransport) {\n transport.subscribe((chunk) => {\n for (const message of this.decoder.push(chunk)) {\n this.dispatch(message as Record<string, unknown>)\n }\n })\n }\n\n /** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n request(method: string, params: unknown): Promise<unknown> {\n const id = this.nextId++\n return new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { resolve, reject })\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id, method, params }))\n })\n }\n\n /** Register a handler for a server→client request method (e.g. `session/request_permission`). */\n onRequest(method: string, handler: ServerRequestHandler): void {\n this.handlers.set(method, handler)\n }\n\n private dispatch(message: Record<string, unknown>): void {\n if (isResponse(message)) {\n const entry = this.pending.get(message.id)\n if (!entry) return\n this.pending.delete(message.id)\n if (message.error) entry.reject(new Error(message.error.message))\n else entry.resolve(message.result)\n return\n }\n if (isServerRequest(message)) {\n void this.handleServerRequest(message)\n }\n }\n\n private async handleServerRequest(req: JsonRpcServerRequest): Promise<void> {\n const handler = this.handlers.get(req.method)\n if (!handler) {\n this.transport.send(\n encodeAcpMessage({ jsonrpc: '2.0', id: req.id, error: { code: -32601, message: `No handler: ${req.method}` } }),\n )\n return\n }\n try {\n const result = await handler(req.params)\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id: req.id, result }))\n } catch (err) {\n this.transport.send(\n encodeAcpMessage({\n jsonrpc: '2.0',\n id: req.id,\n error: { code: -32603, message: err instanceof Error ? err.message : 'handler failed' },\n }),\n )\n }\n }\n}\n","// M31 builder-only: the `@Agent/@Tool/@Toolbox/@HumanInTheLoop/@Guardrails/@Skills/@MainLoop/\n// @SubAgents/@Checkpoint/@Mixin/…` decorators are removed from the public API (ADR-0043 D1/D2). The\n// `AgentBuilder.create()` / `tool()` builders are the single authoring surface. The decorator implementations +\n// their metadata getters remain internal (the compiler reads them via source-path imports).\n// The decorator OPTION TYPES stay public (the framework + consumers annotate with them — e.g. the\n// HITL `TimeoutAction` used by the approval-registry and the `AgentBuilder.create().approval(...)` options).\nexport type { HumanInTheLoopOptions, TimeoutAction } from './types.js'\n// M35 — the settled HITL decision type is part of the public approval contract: an `awaitApproval`\n// resolver (the HTTP registry or the in-process seam) may return a bare boolean OR this structured value.\nexport type { HitlDecision } from './bridge/hitl-plugin.js'\n// `ConfigurationError` is part of the public contract — consumers `catch` it. It used to reach the\n// barrel via a compat re-export inside `capability/capabilities.ts` (removed in M56); export it here\n// from its home module so removing that internal re-export does not drop it from the package API.\nexport { ConfigurationError } from './errors.js'\nexport * from './capability/index.js'\nexport * from './bridge/index.js'\nexport * from './loop/index.js'\nexport * from './guardrails/index.js'\nexport * from './a2a/agent-card.js'\nexport * from './a2a/mcp-server-manifest.js'\nexport * from './a2a/a2a-client.js'\nexport * from './conversation-scope.js'\nexport * from './skills-resolver.js'\nexport * from './acp/protocol.js'\nexport * from './acp/client.js'\nexport * from './manifest/agent-manifest.js'\nexport { agentsPlugin, type AgentsPluginOptions } from './theokit-plugin.js'\nexport type {\n AgentOptions,\n MainLoopOptions,\n MainLoopMeta,\n ToolboxOptions,\n ToolOptions,\n BudgetOptions,\n ApprovalOptions,\n PolicyHandler,\n ReasoningEffort,\n} from './types.js'\n\n// M58 — layered boundary `SDK → Theokit → AgentBuilder`: the consumer imports the SDK's already-OO\n// core primitives from `@theokit/agents`, not from `@theokit/sdk` directly. PASS-THROUGH, never a\n// wrapper (parsimony-ladder Rung 9): `Agent.create()` / `Tool.create()` / `Provider` are already the\n// target OO shape, so wrapping them would be ceremony without value. The domains with their own\n// infra surface (sandbox / persistence / interactive / pty) live on matching subpaths that mirror the\n// SDK's own subpath split (`@theokit/agents/{sandbox,persistence,interactive,pty}`).\nexport { Agent, Squad, Tool, Provider } from '@theokit/sdk'\nexport type { SDKAgent, CustomTool, SessionRecord } from '@theokit/sdk'\n\n// M63 — closing the layered boundary so the consumer imports ZERO `@theokit/sdk*` directly. Same\n// PASS-THROUGH doctrine as the M58 core above (Rung 9): these are already the target shape.\n// - `SubAgent` (a2a delegation primitive): `SubAgent.create()` is already OO; wrapping it adds nothing.\n// - the path-safety helpers are pure functions — a class would be ceremony (parsimony-ladder Rung 5).\nexport { SubAgent } from '@theokit/sdk/a2a'\nexport { assertNoSymlinkEscape, isForbiddenPath, safePathJoin } from '@theokit/sdk/path-safety'\n\n// M77 — the context-window resolver, so a surface can render a budget meter against the REAL window\n// instead of a constant. Same PASS-THROUGH doctrine (Rung 9): `resolveEffectiveContextWindow` is a\n// pure function and `CONTEXT_WINDOW_*` are constants — wrapping them in a class would be ceremony.\n//\n// The consumer needs this because its TUI hardcoded `contextWindow: 400_000`, decoupled from the\n// configured model: change the model and the meter silently lies. A meter that lies is worse than no\n// meter, because it is trusted.\nexport {\n CONTEXT_WINDOW_FLOOR,\n CONTEXT_WINDOW_MARGIN,\n ContextWindowMarginError,\n resolveEffectiveContextWindow,\n} from '@theokit/sdk/compaction'\nexport type { ContextWindowSource, EffectiveContextWindow } from '@theokit/sdk/compaction'\n\n// M78 — a política de cobertura declarada. Antes deste milestone o barril crescia de forma REATIVA\n// (símbolo a símbolo, sob pressão de bug) e cobria 9 dos 28 subpaths do SDK, sem nada avisar quando\n// um subpath novo aparecia. `tests/unit/subpath-coverage.test.ts` agora exige veredito para TODOS os\n// 28 — `in` (verificado) ou `out` (com razão escrita).\n//\n// Mesma doutrina de PASS-THROUGH do M58/M63 (Rung 9): estes já são a forma alvo — a hierarquia de\n// erro é OO, `Retry`/`Semaphore` são classes, e as de `/messages` e `/models` são funções puras.\n// Envolver qualquer uma seria cerimônia sem nada dentro.\n//\n// `/errors` é o eixo do milestone: o consumidor tem como regra INQUEBRÁVEL erro tipado, e sem acesso\n// a esta hierarquia a única saída legal era criar uma PARALELA — foi o que aconteceu, cinco classes\n// estendendo `Error` nu. E como `isTransientError` exige `TheokitAgentError`, o predicado que separa\n// recuperável de irrecuperável era inútil lá por construção.\n// `export *` e não uma lista curada, de propósito. A primeira versão re-exportava quatro classes\n// escolhidas a dedo e `RateLimitError` — que o refresh OAuth precisa para reconhecer um 429 — ficou\n// de fora sem nada acusar. Uma hierarquia de erro PELA METADE é exatamente o defeito que este\n// milestone fecha: o consumidor voltaria a criar a classe que falta.\n//\n// O mesmo vale para os outros quatro: são subpaths pequenos e coesos, onde \"parte do domínio\" não é\n// uma unidade que faça sentido. `tests/unit/subpath-coverage.test.ts` verifica a cobertura TOTAL\n// destes, não uma amostra.\nexport * from '@theokit/sdk/errors'\nexport * from '@theokit/sdk/retry'\nexport * from '@theokit/sdk/concurrency'\nexport * from '@theokit/sdk/messages'\nexport * from '@theokit/sdk/models'\n// M81 — o loader de subagents em disco. A assimetria oposta (skills com porta pública, subagents\n// sem) é o que fez o consumidor escrever um SEGUNDO parser de `.md` — e depois um teste cuja única\n// função era vigiar a divergência entre os dois. O que atravessa é a config PARSEADA, nunca o\n// formato de arquivo: exportar o formato congelaria um detalhe interno como API pública.\nexport { discoverSubagents, loadSubagentDefinition } from '@theokit/sdk/subagents-loader'\n\n// COLISÃO DE NOME RESOLVIDA no M91 — era declarada e agora está paga.\n//\n// `@theokit/sdk/errors` e `./bridge/index.js` exportavam ambos `BudgetExceededError`, e NÃO eram a\n// mesma coisa: a do SDK é orçamento por JANELA (`budgetName`, `window`, `spentUsd`, `mode`); a da\n// camada é orçamento por DELEGAÇÃO (`agentName`, `actualCost`, `budgetLimit`).\n//\n// Como o consumidor tem regra inquebrável de nunca importar `@theokit/sdk` direto, ele **nunca\n// alcançava a do SDK** pelo barril — e um `instanceof` casava com o domínio errado em silêncio. O\n// comentário anterior registrava isso como lacuna conhecida e dizia que renomear era breaking, fora\n// do escopo do M78. O M91 renomeou, com alias `@deprecated` por uma major.\n//\n// Agora as duas atravessam: `DelegationBudgetExceededError` daqui, `BudgetExceededError` do SDK.\nexport {\n DelegationBudgetExceededError,\n /** @deprecated Use `DelegationBudgetExceededError` — mesma classe, alias por uma major. */\n BudgetExceededError as DelegationBudgetExceededErrorAlias,\n} from './bridge/delegation-types.js'\nexport { BudgetExceededError } from '@theokit/sdk/errors'\n\n// M82 — o tipo público dos handlers de `.hooks()`. Publicado porque a alternativa é o consumidor\n// declarar o seu (foi o que o agent-builder fez, com `ctx: unknown` em quatro de cinco handlers).\nexport type { HookHandlers } from './bridge/hook-handlers.js'\n\n// M84 — o transporte in-process veio do pacote CLI, onde era folha. Fica na barra principal (e não\n// num subpath novo) porque \"rodar um turn de agente\" é exatamente o que a barra principal faz;\n// separá-lo multiplicaria superfície sem separar nada. O CLI passa a re-exportar daqui.\nexport { streamAgentTurnInProcess, InProcessApprovalRequiredError } from './in-process-turn.js'\nexport type {\n StreamAgentTurnInProcessInput,\n StreamAgentTurnDeps,\n InProcessApprovalRequest,\n InProcessAwaitApproval,\n} from './in-process-turn.js'\n","/**\n * M35 (multi-surface) — the in-process agent-turn seam (Model A).\n *\n * The FRAMEWORK-owned sibling of the HTTP `mountAgent` and the stdout `runAgentInTerminal`: it runs a\n * compiled agent with the SAME `compileAgentModule` + SAME `streamAgentUIMessages` (G2 — reuses the\n * SDK runtime, reimplements nothing), but returns the raw `UIMessageChunk` generator so ANY consumer\n * drives it directly — the Ink TUI (M35), a Tauri window (M36), or a test — in a SINGLE process with\n * NO HTTP loopback, NO port, and NO CSRF (there is no network boundary to defend).\n *\n * The ONLY difference from the HTTP mount is HITL resolution: the mount pauses the run and resolves\n * the approval via a SECOND HTTP request to `/approve/:id` (the approval registry). In-process there\n * is no second request — the caller resolves the approval INLINE via `awaitApproval` (e.g. the Ink\n * TUI's y/n prompt). The gated-tool map is `compiled.hitl` verbatim, so the pause semantics are\n * byte-identical to the HTTP path; only the resolver differs. Parity with the mount is by\n * construction: both compile the module, resolve function-form skills, and call `streamAgentUIMessages`\n * with the same `{ message, sessionId, hitl }`.\n *\n * Consumers WILL still receive `tool-approval-request` chunks from the returned generator — they are\n * INFORMATIONAL (render them or ignore them). The authoritative human gate is `awaitApproval`, which\n * the SDK awaits BEFORE the gated tool runs; the chunk is not the gate.\n */\nimport type { UIMessageChunk } from 'ai'\n\nimport { compileAgentModule, streamAgentUIMessages } from './bridge/agent-endpoint.js'\nimport type { HitlDecision } from './bridge/hitl-plugin.js'\nimport { resolveEnabledSkills } from './skills-resolver.js'\nimport type { HumanInTheLoopOptions } from './types.js'\n\n/** An inline approval request handed to the caller's `awaitApproval` (the Ink/Tauri prompt). */\nexport interface InProcessApprovalRequest {\n approvalId: string\n toolName: string\n opts: HumanInTheLoopOptions\n}\n\n/** Resolve one gated-tool approval inline (approve/deny, or a structured {@link HitlDecision}). */\nexport type InProcessAwaitApproval = (\n req: InProcessApprovalRequest,\n) => Promise<boolean | HitlDecision>\n\nexport interface StreamAgentTurnInProcessInput {\n message: string\n /**\n * M35 (multimodal) — images to send alongside the text. Threaded to the SDK's structured\n * `SDKUserMessage { text, images }` send form. Absent ⇒ the string send path is byte-unchanged.\n */\n images?: Parameters<typeof streamAgentUIMessages>[2]['images']\n /** Resume key; a fresh id per run when omitted. */\n sessionId?: string\n /**\n * Inline HITL resolver — required IFF the agent has `@HumanInTheLoop`-gated tools. Omitting it for a\n * gated agent is a fail-fast error, never a silent bypass (Rule 8, the #99 lesson).\n */\n awaitApproval?: InProcessAwaitApproval\n /** Labels a fail-fast `AgentDefinitionError` (the file path). */\n source?: string\n /** Abort signal forwarded to the SDK stream (client disconnect / window close). */\n signal?: AbortSignal\n}\n\n/** Injectable stream fn (defaults to the real SDK bridge) — lets tests drive a deterministic stream. */\nexport interface StreamAgentTurnDeps {\n stream: typeof streamAgentUIMessages\n}\n\n/**\n * Thrown when a gated agent is run in-process without an `awaitApproval` resolver. Refusing loudly is\n * the correct posture: silently running a `@HumanInTheLoop`-gated tool with no human gate is exactly\n * the #99 class of bug. Typed so callers can catch it distinctly.\n */\nexport class InProcessApprovalRequiredError extends Error {\n constructor(toolNames: readonly string[]) {\n super(\n `Agent has HITL-gated tool(s) [${toolNames.join(', ')}] but no \\`awaitApproval\\` resolver was ` +\n `supplied to streamAgentTurnInProcess. In-process runs must resolve approvals inline — pass ` +\n `awaitApproval, or remove the gate. Refused (fail-closed).`,\n )\n this.name = 'InProcessApprovalRequiredError'\n }\n}\n\n/**\n * Run a compiled agent in-process and return its `UIMessageChunk` stream. `apiKey` is resolved by the\n * caller (same contract as the HTTP mount). Validation + compile happen SYNCHRONOUSLY (so a gated\n * agent without a resolver throws at call time, not lazily on first iteration); the returned value is\n * the SDK's `streamAgentUIMessages` generator.\n */\nexport function streamAgentTurnInProcess(\n mod: unknown,\n apiKey: string,\n input: StreamAgentTurnInProcessInput,\n deps: StreamAgentTurnDeps = { stream: streamAgentUIMessages },\n): AsyncGenerator<UIMessageChunk> {\n const compiled = compileAgentModule(mod, input.source)\n const gated = compiled.hitl\n\n // Fail-fast BEFORE building the stream: a gated agent with no inline resolver would silently bypass\n // the human gate (the #99 class of bug). Refuse loudly (Rule 8, fail-closed).\n if (gated && gated.size > 0 && !input.awaitApproval) {\n throw new InProcessApprovalRequiredError([...gated.keys()])\n }\n const resolve = input.awaitApproval\n\n // Mirror mount-agent's HITL wiring cast-free (structural inference); absent gate ⇒ the non-HITL\n // stream path (M2), unchanged. The SDK calls (approvalId, opts, toolName); route to the caller.\n const hitl =\n gated && gated.size > 0 && resolve\n ? {\n gated,\n awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) =>\n resolve({ approvalId, toolName, opts }),\n }\n : undefined\n\n const sessionId = input.sessionId ?? crypto.randomUUID()\n\n // Resolve function-form skills (`defineAgent({ skills: (ctx) => [...] })`) BEFORE streaming — exact\n // parity with mount-agent. Done INSIDE the returned generator so the synchronous fail-fast above is\n // preserved (the caller still gets a plain `AsyncGenerator`, no `await` at the call site). A static\n // skill list leaves `skillsResolver` undefined and this is a no-op.\n return (async function* () {\n if (compiled.skillsResolver) {\n const enabled = await resolveEnabledSkills(compiled.skillsResolver, compiled.runContext ?? {})\n if (enabled !== undefined) compiled.skills = { enabled, autoInject: true }\n }\n yield* deps.stream(compiled, apiKey, {\n message: input.message,\n // M35 — pass images through so the SDK send uses the structured `{ text, images }` form.\n ...(input.images !== undefined ? { images: input.images } : {}),\n sessionId,\n hitl,\n signal: input.signal,\n })\n })()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,yBAAyB;AAqC3B,IAAMC,0BAAN,cAAsCC,MAAAA;EArC7C,OAqC6CA;;;EACzBC,OAAO;EACzB,YAAYC,OAAeC,UAAmBC,MAAeC,YAAoB;AAC/E;;;;MAIE,eAAeA,UAAAA,aAAuBH,KAAAA,sBAAwBI,QAAQH,QAAAA,CAAAA,wCAC9BG,QAAQF,IAAAA,CAAAA;IAA8B;EAElF;AACF;AAGA,SAASE,QAAQC,OAAc;AAC7B,MAAIA,UAAU,KAAM,QAAO;AAC3B,MAAIC,MAAMC,QAAQF,KAAAA,EAAQ,QAAO,SAASA,MAAMG,MAAM;AACtD,MAAI,OAAOH,UAAU,UAAU;AAC7B,WAAO,UAAUI,OAAOC,KAAKL,KAAAA,EAC1BM,KAAK,CAACC,GAAGC,MAAMD,EAAEE,cAAcD,CAAAA,CAAAA,EAC/BE,KAAK,GAAA,CAAA;EACV;AACA,SAAO,OAAOV;AAChB;AATSD;AAgBF,SAASY,cAAAA;AACd,SAAO;IAAEC,OAAO,CAAA;IAAIC,QAAQ,CAAC;IAAGC,YAAY,CAAA;EAAG;AACjD;AAFgBH;AAQT,SAASI,kBACdC,cACAC,QAAmCN,YAAAA,GAAa;AAEhD,aAAWO,KAAKF,aAAcE,GAAEC,MAAMF,KAAAA;AACtCA,QAAMG,WAAW;AACjB,SAAOH;AACT;AAPgBF;AAUT,SAASM,QACdJ,OACAtB,OACAK,OACAF,YAAkB;AAElB,MAAIE,UAAUsB,OAAW;AACzB,QAAM1B,WAAWqB,MA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","CapabilityConflictError","Error","name","field","previous","next","capability","shapeOf","value","Array","isArray","length","Object","keys","sort","a","b","localeCompare","join","createDraft","tools","agents","provenance","applyCapabilities","capabilities","draft","c","apply","stream","setOnce","undefined","isDeepStrictEqual","push","contributed","describe","value","Array","isArray","ModelCapability","name","id","reasoningEffort","ConfigurationError","trim","length","apply","draft","setOnce","undefined","ToolsCapability","tools","push","provenance","capability","contributed","SkillsCapability","entries","e","field","compiled","compileSkillsSelection","slice","skills","previous","enabled","inline","UnknownCapabilityError","Error","name","requested","known","join","CapabilityRegistry","Map","register","factory","set","has","names","keys","resolve","arg","get","undefined","CapabilityPreset","members","apply","draft","member","FieldCapability","value","apply","draft","setOnce","field","name","MemoryCapability","ContextWindowCapability","options","compileContextWindow","context","ProjectContextCapability","McpServersCapability","GuardrailsCapability","CheckpointCapability","undefined","storage","console","warn","HumanInTheLoopCapability","SubAgentsCapability","children","child","Object","entries","agents","ConfigurationError","provenance","push","capability","contributed","SkillsOptionsCapability","compileSkills","SettingSourcesCapability","PluginsCapability","RunContextCapability","SkillsResolverCapability","AgentConfigCapability","config","Number","isFinite","claimedByMainLoop","some","p","includes","maxIterations","timeoutMs","systemPrompt","parseThinkTags","stripToolDialect","recoverLeakedToolCalls","stream","MainLoopCapability","length","ToolboxCapability","name","instance","options","ConfigurationError","declared","tools","undefined","length","tool","method","namespace","toolRuntimeName","class","guards","map","propertyKey","config","approval","trace","audit","hitl","apply","draft","walk","push","compileTools","Map","provenance","capability","contributed","gates","compileHitlGates","size","key","set","ToolsetError","Error","message","code","name","Toolset","porNome","Object","freeze","from","tools","Map","tool","has","set","get","undefined","resolve","names","vistos","Set","map","add","keys","all","values","trimTrailingSlash","url","endsWith","slice","buildAgentCard","entry","options","base","baseUrl","name","description","route","version","capabilities","streaming","stream","pushNotifications","stateTransitionHistory","defaultInputModes","defaultOutputModes","skills","tools","map","t","id","wellKnownCardPath","agentName","MCP_PROTOCOL_VERSION","buildMcpToolDescriptors","entry","tools","map","t","name","description","inputSchema","type","properties","mcpServerInfo","version","protocolVersion","buildHeaders","config","headers","auth","bearer","authorization","apiKey","header","value","createA2ATool","doFetch","fetchImpl","fetch","name","description","inputSchema","type","properties","message","required","handler","input","res","url","method","body","JSON","stringify","ok","Error","status","statusText","data","json","response","text","SEPARATOR","deriveConversationId","resource","thread","Error","encodeURIComponent","parseConversationId","id","idx","indexOf","length","decodeURIComponent","slice","resolveEnabledSkills","selection","ctx","undefined","filter","s","resolved","Array","isArray","Error","names","every","n","trim","length","encodeAcpMessage","message","JSON","stringify","AcpMessageDecoder","buffer","push","chunk","messages","newlineIndex","indexOf","line","slice","trim","length","parse","cause","Error","isResponse","m","id","isServerRequest","method","AcpClient","nextId","pending","Map","handlers","decoder","AcpMessageDecoder","transport","subscribe","chunk","message","push","dispatch","request","params","Promise","resolve","reject","set","send","encodeAcpMessage","jsonrpc","onRequest","handler","entry","get","delete","error","Error","result","handleServerRequest","req","code","err","Agent","Squad","Tool","Provider","SubAgent","assertNoSymlinkEscape","isForbiddenPath","safePathJoin","CONTEXT_WINDOW_FLOOR","CONTEXT_WINDOW_MARGIN","ContextWindowMarginError","resolveEffectiveContextWindow","discoverSubagents","loadSubagentDefinition","BudgetExceededError","InProcessApprovalRequiredError","Error","toolNames","join","name","streamAgentTurnInProcess","mod","apiKey","input","deps","stream","streamAgentUIMessages","compiled","compileAgentModule","source","gated","hitl","size","awaitApproval","keys","resolve","approvalId","opts","toolName","undefined","sessionId","crypto","randomUUID","skillsResolver","enabled","resolveEnabledSkills","runContext","skills","autoInject","message","images","signal"]}
|
|
1
|
+
{"version":3,"sources":["../src/capability/capability.ts","../src/capability/capabilities.ts","../src/capability/registry.ts","../src/capability/agent-capabilities.ts","../src/capability/toolbox.ts","../src/capability/toolset.ts","../src/a2a/agent-card.ts","../src/a2a/mcp-server-manifest.ts","../src/a2a/a2a-client.ts","../src/conversation-scope.ts","../src/skills-resolver.ts","../src/acp/protocol.ts","../src/acp/client.ts","../src/index.ts","../src/in-process-turn.ts"],"sourcesContent":["import { isDeepStrictEqual } from 'node:util'\n\nimport type { CompiledAgentOptions } from '../bridge/agent-compiler.js'\n\n/**\n * M52 — the capability layer: object-oriented, composable authoring that produces the EXISTING narrow\n * waist (`CompiledAgentOptions`), which `assembleM8CreateOptions` already turns into `Agent.create`\n * options. No new spec and no new adapter were invented (ADR-1/ADR-2) — a third representation would be\n * the very duplication this initiative removes.\n */\n\n/** Which capability contributed which fields — makes the wiring inspectable as DATA. */\nexport interface ProvenanceEntry {\n readonly capability: string\n readonly contributed: readonly string[]\n}\n\n/** The mutable draft a capability enriches. `tools`/`agents` are pre-seeded (required in the waist). */\nexport interface CompiledAgentOptionsDraft extends Partial<\n Omit<CompiledAgentOptions, 'tools' | 'agents'>\n> {\n tools: CompiledAgentOptions['tools']\n agents: CompiledAgentOptions['agents']\n readonly provenance: ProvenanceEntry[]\n}\n\n/**\n * **Strategy + value-level Decorator.** N independent ways to enrich an agent (model, tools, skills,\n * MCP, HITL…), added or removed without touching the builder — a central `switch` would violate OCP.\n */\nexport interface Capability {\n /** Stable identity — used for provenance and conflict messages. */\n readonly name: string\n apply(draft: CompiledAgentOptionsDraft): void\n}\n\n/** Two capabilities set the same scalar field to different values — a composition bug, never last-wins. */\nexport class CapabilityConflictError extends Error {\n override readonly name = 'CapabilityConflictError'\n constructor(field: string, previous: unknown, next: unknown, capability: string) {\n super(\n // NUNCA ecoa os valores: um draft montado a partir de arquivo de config pode carregar\n // token de MCP, header de auth, credencial de memória. Reporta a FORMA, como a validação\n // de fronteira das capabilities já faz.\n `capability \"${capability}\": campo \"${field}\" já declarado (${shapeOf(previous)}) ` +\n `e redeclarado com valor diferente (${shapeOf(next)}) — declare uma vez só.`,\n )\n }\n}\n\n/** Type/shape of a value for diagnostics — never its content. */\nfunction shapeOf(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return `array(${value.length})`\n if (typeof value === 'object') {\n return `object{${Object.keys(value)\n .sort((a, b) => a.localeCompare(b))\n .join(',')}}`\n }\n return typeof value\n}\n\n/**\n * A fresh draft. `stream` is deliberately NOT seeded: a pre-seeded value would make\n * `setOnce(draft, 'stream', false, …)` throw a conflict against a default nobody declared, so\n * `stream: false` would be structurally unreachable. The default is applied at finalize instead.\n */\nexport function createDraft(): CompiledAgentOptionsDraft {\n return { tools: [], agents: {}, provenance: [] }\n}\n\n/** A draft that has been finalized — the waist's required `stream` is settled. */\nexport type FinalizedDraft = CompiledAgentOptionsDraft & { stream: boolean }\n\n/** Apply capabilities in declaration order (deterministic) and return the draft. */\nexport function applyCapabilities(\n capabilities: readonly Capability[],\n draft: CompiledAgentOptionsDraft = createDraft(),\n): FinalizedDraft {\n for (const c of capabilities) c.apply(draft)\n draft.stream ??= true // same default the reference compiler emits\n return draft as FinalizedDraft\n}\n\n/** Set a scalar exactly once — fail-fast on a conflicting redeclaration (Rule 8). */\nexport function setOnce<K extends keyof CompiledAgentOptionsDraft>(\n draft: CompiledAgentOptionsDraft,\n field: K,\n value: CompiledAgentOptionsDraft[K],\n capability: string,\n): void {\n if (value === undefined) return // nothing to declare — never consume the slot with a hole\n const previous = draft[field]\n // DEEP equality, never reference identity: two capabilities may legitimately build the SAME\n // logical value in separate objects (`compileSkillsSelection` returns a fresh object per call),\n // and `previous !== value` would report those as a conflict that does not exist. CAVEAT, stated\n // because it is not obvious: `isDeepStrictEqual` compares FUNCTIONS by identity, so a field whose\n // value carries functions (resolvers, guardrail methods) stays identity-idempotent, not\n // value-idempotent. Fail-fast is the safe side of that asymmetry.\n if (previous !== undefined && !isDeepStrictEqual(previous, value)) {\n throw new CapabilityConflictError(field, previous, value, capability)\n }\n draft[field] = value\n draft.provenance.push({ capability, contributed: [field] })\n}\n","import type { InlineSkill } from '@theokit/sdk'\n\nimport type { CompiledTool } from '../bridge/agent-compiler.js'\nimport { compileSkillsSelection } from '../bridge/define-agent.js'\nimport { ConfigurationError } from '../errors.js'\n\nimport { type Capability, type CompiledAgentOptionsDraft, setOnce } from './capability.js'\n\n/**\n * M52 — three real capabilities proving the contract against genuine variation: one that VALIDATES and\n * can conflict (model), one that ACCUMULATES (tools), and one that is pure DATA (skills — a plain\n * factory, because a class with no behavior would be ceremony: KISS).\n */\n\n// `ConfigurationError` lives in `../errors.js` and is imported above. The M55 compatibility\n// re-export from this module is GONE (M56): a second import path for one class is exactly the kind\n// of concession that keeps dead surface alive. Import it from where it is defined.\n\n/** Human-readable type of a rejected value — never its content (config files may hold secrets). */\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n return Array.isArray(value) ? 'array' : typeof value\n}\n\n/** Sets the model id (and optional reasoning effort). CLASS: it validates and can conflict. */\nexport class ModelCapability implements Capability {\n readonly name = 'model'\n constructor(\n private readonly id: string,\n private readonly reasoningEffort?: CompiledAgentOptionsDraft['reasoningEffort'],\n ) {\n // Boundary validation: the registry hands `unknown` straight from a config FILE, so a wrong\n // type must fail here, typed and named — not as a raw `id.trim is not a function` three frames\n // deep (rules/error-handling.md § 2: validate at the boundary, fail typed).\n if (typeof id !== 'string') {\n throw new ConfigurationError(`model: esperava string, recebi ${describe(id)}`)\n }\n if (id.trim().length === 0) throw new ConfigurationError('model: id não pode ser vazio')\n }\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, 'model', this.id, this.name)\n if (this.reasoningEffort !== undefined) {\n setOnce(draft, 'reasoningEffort', this.reasoningEffort, this.name)\n }\n }\n}\n\n/** Adds tools. CLASS: it ACCUMULATES (never overwrites), which is behavior worth owning. */\nexport class ToolsCapability implements Capability {\n readonly name = 'tools'\n readonly #tools: readonly CompiledTool[]\n constructor(tools: readonly CompiledTool[]) {\n this.#tools = tools\n }\n apply(draft: CompiledAgentOptionsDraft): void {\n draft.tools.push(...this.#tools)\n draft.provenance.push({ capability: this.name, contributed: ['tools'] })\n }\n}\n\n/**\n * Enables skills by name (or inline). M57: a CLASS now (was a factory function). Validation moves to\n * the constructor — fail-fast at authoring, the same place `ModelCapability`/`AgentConfigCapability`\n * validate. The `apply` body (delegate + merge) is unchanged, so the compiled output is identical.\n */\nexport class SkillsCapability implements Capability {\n readonly name = 'skills'\n readonly #entries: readonly (string | InlineSkill)[]\n\n constructor(entries: readonly (string | InlineSkill)[]) {\n // Boundary validation BEFORE anything spreads: a config file carrying `skills: \"code-review\"`\n // would otherwise spread into eleven single-character skill names and reach Agent.create with no\n // error at all — silent corruption, the worst failure mode for file-based authoring.\n if (!Array.isArray(entries)) {\n throw new ConfigurationError(`skills: esperava array de nomes, recebi ${describe(entries)}`)\n }\n for (const e of entries) {\n // The reference compiler accepts `string | InlineSkill` (define-agent.ts § compileSkillsSelection),\n // so inline skills must be accepted here too — rejecting them outright would make this layer less\n // expressive than the path it claims equivalence with.\n //\n // ONE deliberate asymmetry, stated rather than glossed over: an inline skill with an empty\n // `instructions` compiles through `defineAgent` but is REJECTED here. That object's body is\n // unreachable at runtime (`SkillsManager.get` would fall back to `readFile(source)`, and a\n // hand-rolled inline has no real `source`), so this rejects a broken agent at authoring time\n // instead of at prompt-assembly time. It is an input rejection, never an output divergence.\n if (typeof e === 'string') {\n if (e.trim().length === 0) {\n throw new ConfigurationError('skills: nome vazio — use um nome de skill não vazio')\n }\n continue\n }\n if (typeof e !== 'object' || e === null || Array.isArray(e)) {\n throw new ConfigurationError(\n `skills: entrada inválida (${describe(e)}) — use um nome ou um skill inline`,\n )\n }\n // An inline skill reaches the `<skills>` system-prompt block. Accepting `{ name }` alone lets a\n // malformed skill through with `undefined` description/instructions — the same silent\n // corruption this boundary exists to stop, one level down. `InlineSkill extends Skill` requires\n // all three (`@theokit/sdk` create-skill.d.ts + discover-skills.d.ts).\n for (const field of ['name', 'description', 'instructions'] as const) {\n const value = (e as Record<string, unknown>)[field]\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ConfigurationError(\n `skills: skill inline sem \\`${field}\\` válido (${describe(value)}) — ` +\n 'name, description e instructions são obrigatórios',\n )\n }\n }\n }\n this.#entries = entries\n }\n\n apply(draft: CompiledAgentOptionsDraft): void {\n // DELEGA ao compilador canônico (não reimplementa): `autoInject`, skills inline e o caminho\n // resolver vivem numa fonte só — reimplementar aqui divergiria (foi o que a prova de\n // equivalência pegou).\n const compiled = compileSkillsSelection(this.#entries.slice())\n if (compiled.skills === undefined) return\n // ACCUMULATES, never setOnce: skills is a merge-semantics field in the reference compiler\n // (`defineAgent({skills:['a','b']})` → `['a','b']`). With setOnce a preset's baseline skills\n // could never be extended at the call site — defeating the whole point of the Composite.\n //\n // CONCAT, never dedupe. The capability list IS the authoring list: `skills(['a']) +\n // skills(['a'])` corresponds to authoring `['a','a']`, which the reference compiler maps to\n // `['a','a']`. A dedupe here looks tidier but makes the merge path the ONLY place in this\n // layer that diverges from the reference — the exact thing the milestone exists to prevent.\n const previous = draft.skills\n draft.skills =\n previous === undefined\n ? compiled.skills\n : {\n // The spread is exhaustive only because `compileSkillsSelection` emits a FIXED 3-key\n // shape (`enabled`, `autoInject: true`, and `inline` iff non-empty) — `enabled` and\n // `inline` are both re-derived below, and `autoInject` is the same literal on both\n // sides. TRAP for the future: if a capability ever authors `autoInject: false`, this\n // spread would silently normalize it back to `true`. Unreachable today (no capability\n // and no reference array form can express it) — revisit when one can.\n ...previous,\n ...compiled.skills,\n enabled: [...(previous.enabled ?? []), ...(compiled.skills.enabled ?? [])],\n ...(previous.inline !== undefined || compiled.skills.inline !== undefined\n ? { inline: [...(previous.inline ?? []), ...(compiled.skills.inline ?? [])] }\n : {}),\n }\n draft.provenance.push({ capability: this.name, contributed: ['skills'] })\n }\n}\n","import type { Capability, CompiledAgentOptionsDraft } from './capability.js'\n\n/**\n * M52 — resolution + composition. The registry is what unlocks FILE-BASED authoring (a config lists\n * capability names): resolving name → capability without a switch that grows per feature (OCP).\n */\n\n/** Fail-fast with the known set — never `undefined` leaking into the pipeline. */\nexport class UnknownCapabilityError extends Error {\n override readonly name = 'UnknownCapabilityError'\n constructor(requested: string, known: readonly string[]) {\n super(\n `capability \"${requested}\" não registrada. Conhecidas: ${known.join(', ') || '(nenhuma)'}.`,\n )\n }\n}\n\n/** **Registry + Factory Method.** */\nexport class CapabilityRegistry {\n readonly #factories = new Map<string, (arg: unknown) => Capability>()\n\n register(name: string, factory: (arg: unknown) => Capability): this {\n this.#factories.set(name, factory)\n return this\n }\n\n has(name: string): boolean {\n return this.#factories.has(name)\n }\n\n names(): string[] {\n return [...this.#factories.keys()]\n }\n\n resolve(name: string, arg?: unknown): Capability {\n const factory = this.#factories.get(name)\n if (factory === undefined) throw new UnknownCapabilityError(name, this.names())\n return factory(arg)\n }\n}\n\n/**\n * **Composite** — a preset behaves like ONE capability, so a caller says `codingAgent()` instead of\n * spreading an array at the call site. Members apply in declaration order (deterministic).\n */\nexport class CapabilityPreset implements Capability {\n readonly #members: readonly Capability[]\n constructor(\n readonly name: string,\n members: readonly Capability[],\n ) {\n this.#members = members\n }\n apply(draft: CompiledAgentOptionsDraft): void {\n for (const member of this.#members) member.apply(draft)\n }\n}\n","import type { CompiledAgentOptions } from '../bridge/agent-compiler.js'\nimport {\n compileContextWindow,\n type ContextWindowOptions,\n} from '../bridge/compile-context-window.js'\nimport { compileSkills, type SkillsOptions } from '../bridge/compile-skills.js'\nimport { ConfigurationError } from '../errors.js'\n\nimport { type Capability, type CompiledAgentOptionsDraft, setOnce } from './capability.js'\n\n/**\n * M53 — the capabilities that replace the waist-bound agent decorators, one per field the decorator\n * pipeline produces today (`docs/agents/decorator-to-capability.md` § A).\n *\n * M57 reverses ADR 0001 § 4 (which kept the pure-assignment ones as a factory function to avoid\n * \"13 near-identical classes\"): the authoring surface is now 100% classes, aligned with the SDK's\n * `X.create()`/class shape. The `FieldCapability` base keeps the assignment ones DRY (one line each);\n * the behaviour-carrying ones are written out. Rationale in ADR 0005.\n */\n\n/**\n * Base for a capability whose only job is to assign one waist field — no validation, no merge, no\n * precedence. M57: this replaces the `fieldCapability(name, field)` factory function with a class, so\n * the authoring surface is 100% classes (aligned with the SDK's `X.create()` and the existing\n * `ModelCapability`). The subclasses below are one line each; the shared `apply` lives here (DRY).\n * NOT the Template-Method the ADR-0001 refused — that was inheritance of variable *behaviour*\n * (`shouldContinue`); here the base carries *data* (name/field) and `apply` is identical for all.\n */\nexport abstract class FieldCapability<\n K extends keyof CompiledAgentOptionsDraft,\n> implements Capability {\n abstract readonly name: string\n protected abstract readonly field: K\n constructor(private readonly value: NonNullable<CompiledAgentOptionsDraft[K]>) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, this.field, this.value as CompiledAgentOptionsDraft[K], this.name)\n }\n}\n\n/** `@Memory` → `memory`. */\nexport class MemoryCapability extends FieldCapability<'memory'> {\n readonly name = 'memory'\n protected readonly field = 'memory' as const\n}\n/**\n * `@ContextWindow` → `context`. DELEGATES to `compileContextWindow`, which is the canonical\n * `ContextWindowOptions → ContextSettings` conversion (it also reports the metadata-only knobs).\n * Taking a pre-converted value here would duplicate that knowledge — the exact divergence the M52\n * zero-behavior proof caught in `skills`.\n */\nexport class ContextWindowCapability implements Capability {\n readonly name = 'context-window'\n constructor(private readonly options: ContextWindowOptions) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, 'context', compileContextWindow(this.options).context, this.name)\n }\n}\n/** `@ProjectContext` → `projectContext`. */\nexport class ProjectContextCapability extends FieldCapability<'projectContext'> {\n readonly name = 'project-context'\n protected readonly field = 'projectContext' as const\n}\n/** `@MCP` → `mcpServers`. */\nexport class McpServersCapability extends FieldCapability<'mcpServers'> {\n readonly name = 'mcp'\n protected readonly field = 'mcpServers' as const\n}\n/** `@Guardrails` → `guardrails`. */\nexport class GuardrailsCapability extends FieldCapability<'guardrails'> {\n readonly name = 'guardrails'\n protected readonly field = 'guardrails' as const\n}\n/**\n * `@Checkpoint` → `checkpoint`. Carries the non-durable WARNING the metadata walk used to emit: only\n * `'filesystem'` selects the SDK's durable store, so any other storage cannot resume across\n * requests. The warning moves WITH the feature — a declared checkpoint that silently cannot resume\n * is exactly the kind of no-op this project refuses to ship.\n */\nexport class CheckpointCapability implements Capability {\n readonly name = 'checkpoint'\n constructor(private readonly options: CompiledAgentOptions['checkpoint']) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n if (this.options !== undefined && this.options.storage !== 'filesystem') {\n console.warn(\n `[THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY] checkpoint({ storage: '${this.options.storage ?? 'memory'}' }) ` +\n `does NOT resume across requests — only 'filesystem' selects the SDK's durable conversation ` +\n `store. Use checkpoint({ storage: 'filesystem' }) for cross-request resume.`,\n )\n }\n setOnce(draft, 'checkpoint', this.options, this.name)\n }\n}\n/**\n * `@HumanInTheLoop` → `hitl`, keyed `\"<namespace>_<tool>\"` — the same key `compileHitlGates` mints\n * via `toolRuntimeName`. The separator is `_`, not `.`: the dot is outside the charset the SDK\n * accepts, and a gate keyed with a dot silently failed to match its tool (theokit#145).\n */\nexport class HumanInTheLoopCapability extends FieldCapability<'hitl'> {\n readonly name = 'human-in-the-loop'\n protected readonly field = 'hitl' as const\n}\n/**\n * `@SubAgents` → `agents`. MERGES instead of `setOnce`: `agents` is a pre-seeded collection on the\n * draft (`createDraft` gives it `{}`), so a `setOnce` would conflict against the seed itself — the\n * same trap the pre-seeded `stream` sprang in M52. Merging also lets a preset declare a baseline\n * child set that a call site extends.\n */\nexport class SubAgentsCapability implements Capability {\n readonly name = 'sub-agents'\n constructor(private readonly children: CompiledAgentOptions['agents']) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n for (const [name, child] of Object.entries(this.children)) {\n if (name in draft.agents && draft.agents[name] !== child) {\n throw new ConfigurationError(\n `sub-agents: filho \"${name}\" declarado duas vezes com definições diferentes`,\n )\n }\n draft.agents[name] = child\n }\n draft.provenance.push({ capability: this.name, contributed: ['agents'] })\n }\n}\n/**\n * `@Skills({ include, autoDiscover })` → `skills`. Delegates to `compileSkills` (same reason as\n * `contextWindow`). Distinct from the M52 `skills([...])`, which takes the plain name/inline list.\n */\nexport class SkillsOptionsCapability implements Capability {\n readonly name = 'skills'\n constructor(private readonly options: SkillsOptions) {}\n apply(draft: CompiledAgentOptionsDraft): void {\n setOnce(draft, 'skills', compileSkills(this.options), this.name)\n }\n}\n\n/** Functional-path fields that had no decorator source — closing the gap list, not adding surface. */\nexport class SettingSourcesCapability extends FieldCapability<'settingSources'> {\n readonly name = 'setting-sources'\n protected readonly field = 'settingSources' as const\n}\nexport class PluginsCapability extends FieldCapability<'plugins'> {\n readonly name = 'plugins'\n protected readonly field = 'plugins' as const\n}\nexport class RunContextCapability extends FieldCapability<'runContext'> {\n readonly name = 'run-context'\n protected readonly field = 'runContext' as const\n}\nexport class SkillsResolverCapability extends FieldCapability<'skillsResolver'> {\n readonly name = 'skills-resolver'\n protected readonly field = 'skillsResolver' as const\n}\n\n/** The scalar agent config (name/route are HTTP concerns, never agent config). */\nexport interface AgentConfig {\n readonly systemPrompt?: CompiledAgentOptions['systemPrompt']\n readonly parseThinkTags?: boolean\n readonly stripToolDialect?: boolean\n readonly recoverLeakedToolCalls?: boolean\n readonly stream?: boolean\n readonly maxIterations?: number\n readonly timeoutMs?: number\n}\n\n/**\n * Scalar waist fields (formerly the `@Agent` options). CLASS, not a factory: it validates, and it is the one\n * capability that writes fields another capability may legitimately override (see\n * {@link MainLoopCapability}).\n */\nexport class AgentConfigCapability implements Capability {\n readonly name = 'agent-config'\n constructor(private readonly config: AgentConfig) {\n // The registry hands this `unknown` straight from a config file, so the guard is real at\n // runtime even though the declared type makes it look redundant to the compiler.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- boundary check: the value may not be an object at runtime\n if (typeof config !== 'object' || config === null) {\n throw new ConfigurationError('agent-config: esperava um objeto de configuração')\n }\n for (const field of ['maxIterations', 'timeoutMs'] as const) {\n const value = config[field]\n if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {\n throw new ConfigurationError(`agent-config: \\`${field}\\` deve ser um número positivo`)\n }\n }\n }\n\n apply(draft: CompiledAgentOptionsDraft): void {\n // `maxIterations`/`timeoutMs` are the two fields `main-loop` outranks (see MainLoopCapability).\n // Skipping them when main-loop already contributed makes the precedence ORDER-INDEPENDENT while\n // still letting two agent-config declarations conflict with each other.\n const claimedByMainLoop = (field: string): boolean =>\n draft.provenance.some((p) => p.capability === 'main-loop' && p.contributed.includes(field))\n if (!claimedByMainLoop('maxIterations')) {\n setOnce(draft, 'maxIterations', this.config.maxIterations, this.name)\n }\n if (!claimedByMainLoop('timeoutMs')) {\n setOnce(draft, 'timeoutMs', this.config.timeoutMs, this.name)\n }\n setOnce(draft, 'systemPrompt', this.config.systemPrompt, this.name)\n setOnce(draft, 'parseThinkTags', this.config.parseThinkTags, this.name)\n setOnce(draft, 'stripToolDialect', this.config.stripToolDialect, this.name)\n setOnce(draft, 'recoverLeakedToolCalls', this.config.recoverLeakedToolCalls, this.name)\n setOnce(draft, 'stream', this.config.stream, this.name)\n }\n}\n\n/**\n * `@MainLoop({ maxIterations, timeoutMs })` → the same two fields `@Agent` can write.\n *\n * PRECEDENCE, preserved deliberately: `compileAgent` resolves these as\n * `mainLoop.x ?? agentConfig.x` — the main-loop declaration WINS when both are present. A plain\n * `setOnce` would raise a conflict where the pipeline has a defined winner, so this capability\n * OVERRIDES instead. That is the one place in the layer where a later write beats an earlier one,\n * and it exists to keep behavior identical, not for convenience.\n */\nexport class MainLoopCapability implements Capability {\n readonly name = 'main-loop'\n constructor(private readonly config: { maxIterations?: number; timeoutMs?: number }) {}\n\n apply(draft: CompiledAgentOptionsDraft): void {\n const contributed: string[] = []\n if (this.config.maxIterations !== undefined) {\n draft.maxIterations = this.config.maxIterations\n contributed.push('maxIterations')\n }\n if (this.config.timeoutMs !== undefined) {\n draft.timeoutMs = this.config.timeoutMs\n contributed.push('timeoutMs')\n }\n if (contributed.length > 0) draft.provenance.push({ capability: this.name, contributed })\n }\n}\n","import {\n compileHitlGates,\n compileTools,\n toolRuntimeName,\n type ClassToken,\n type ToolboxWalkResult,\n} from '../bridge/agent-compiler.js'\nimport { ConfigurationError } from '../errors.js'\nimport type { ApprovalOptions, HumanInTheLoopOptions, ToolOptions } from '../types.js'\n\nimport type { Capability, CompiledAgentOptionsDraft } from './capability.js'\n\n/**\n * M53 — tools without `@Toolbox`/`@Tool`.\n *\n * A toolbox class declares its tools as DATA (`static tools`) and keeps its handlers as ordinary\n * methods; the capability takes an INSTANCE. That preserves what the decorators actually bought —\n * grouping under a namespace and handlers bound to the instance (so a toolbox can hold state and\n * injected dependencies) — with no metadata reflection at all.\n *\n * The compilation itself is NOT reimplemented: it delegates to `compileTools`, the same function the\n * decorator path calls, so namespacing (`toolRuntimeName`), handler binding and the fail-fast checks\n * stay in one place.\n *\n * @example\n * ```ts\n * class SupportTools {\n * static tools: ToolDeclaration[] = [\n * { name: 'search', description: 'Search tickets', input: z.object({ q: z.string() }), method: 'search' },\n * ]\n * async search({ q }: { q: string }): Promise<string> { return `found ${q}` }\n * }\n *\n * const agent = applyCapabilities([\n * new ModelCapability('openai/gpt-5.4'),\n * new ToolboxCapability(new SupportTools(), { namespace: 'support' }),\n * ])\n * ```\n */\nexport interface ToolDeclaration extends ToolOptions {\n /** Method on the toolbox instance that implements this tool. */\n readonly method: string\n /** Require human approval before the tool runs (surfaced in the manifest). */\n readonly approval?: ApprovalOptions\n /** Gate the tool behind human-in-the-loop (M4). */\n readonly hitl?: HumanInTheLoopOptions\n /** Manifest-only observability flags. */\n readonly trace?: boolean\n readonly audit?: boolean\n}\n\n/** A toolbox instance whose class declares its tools. */\nexport interface ToolboxSource {\n readonly constructor: { tools?: readonly ToolDeclaration[] }\n}\n\nexport interface ToolboxOptions {\n /**\n * Prefix for every tool name (`\"<namespace>_<tool>\"`), as `@Toolbox({ namespace })` did.\n * The separator is `_`, not `.` — the dot is outside the charset the SDK accepts (theokit#145).\n */\n readonly namespace?: string\n /** Declarations, when they are not on the class as `static tools`. */\n readonly tools?: readonly ToolDeclaration[]\n}\n\nexport class ToolboxCapability implements Capability {\n readonly name = 'toolbox'\n readonly #instance: object\n readonly #declarations: readonly ToolDeclaration[]\n readonly #namespace: string\n\n constructor(instance: object, options: ToolboxOptions = {}) {\n // Boundary check: the registry hands this `unknown` straight from a config file, so the guard is\n // real at runtime even though the declared type makes it look redundant to the compiler.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- may not be an object at runtime\n if (typeof instance !== 'object' || instance === null) {\n throw new ConfigurationError('toolbox: esperava uma instância de toolbox')\n }\n const declared =\n options.tools ?? (instance.constructor as { tools?: readonly ToolDeclaration[] }).tools\n if (declared === undefined || declared.length === 0) {\n throw new ConfigurationError(\n `toolbox: ${instance.constructor.name} não declara tools — use \\`static tools = [...]\\` ou a opção \\`tools\\``,\n )\n }\n for (const tool of declared) {\n // Validate here rather than at call time: a missing method only surfaces when the model\n // decides to call the tool, which is the worst moment to discover a typo.\n if (typeof (instance as Record<string, unknown>)[tool.method] !== 'function') {\n throw new ConfigurationError(\n `toolbox: ${instance.constructor.name}.${tool.method} não é um método (tool \"${tool.name}\")`,\n )\n }\n }\n this.#instance = instance\n this.#declarations = declared\n this.#namespace = options.namespace ?? ''\n // Fail at AUTHORING, not when the model finally calls the tool: a namespace/tool pair that\n // cannot mint a name the SDK accepts is a broken agent, and `Agent.create` would only say so\n // at runtime (theokit#145).\n //\n // The CALL is the validation (M55): `toolRuntimeName` validates what it mints, so this loop no\n // longer knows the name format — one module owns that rule. Re-testing it here would be the\n // very duplication that let the gate key and the tool name drift apart in #145. The minted\n // value is intentionally discarded; `compile()` mints again when it actually needs it.\n for (const tool of declared) toolRuntimeName(this.#namespace, tool.name)\n }\n\n /**\n * The single derivation of this toolbox (M55). Both compilers below consume THIS object, so the\n * tool registry and the HITL gate map cannot disagree on a name — the property is structural, not\n * a convention repeated in two loops. That repetition is precisely how the two drifted apart in\n * #145: the tool became `ns_tool` while its gate stayed `ns.tool`, silently ungating it.\n *\n * Same technique the `opencode` harness uses for the analogous tool↔permission coupling, where\n * `Permission.visibleTools` filters the tool record itself rather than keeping a parallel map\n * (\"so the two cannot drift\" — `permission/index.ts`).\n */\n #walk(): ToolboxWalkResult {\n return {\n // `constructor` is typed `Function` by lib.d.ts; here it is used purely as an IDENTITY key\n // into the instances map, which is what `ClassToken` models.\n class: this.#instance.constructor as ClassToken,\n namespace: this.#namespace,\n guards: [],\n tools: this.#declarations.map((tool) => ({\n propertyKey: tool.method,\n config: tool,\n guards: [],\n approval: tool.approval,\n trace: tool.trace ?? false,\n audit: tool.audit ?? false,\n ...(tool.hitl !== undefined ? { hitl: tool.hitl } : {}),\n })),\n }\n }\n\n /**\n * M56 — the public `compile()` is GONE. It had zero callers anywhere in the monorepo and was kept\n * only because deleting a public method is breaking; that concession is exactly the dead surface\n * M55 set out to remove, preserved inside the milestone that removed it. `apply()` is the one path.\n */\n apply(draft: CompiledAgentOptionsDraft): void {\n const walk = this.#walk()\n\n // ACCUMULATES: several toolboxes compose into one agent, exactly as several `@Toolbox` classes did.\n draft.tools.push(...compileTools([walk], new Map([[walk.class, this.#instance]])))\n draft.provenance.push({ capability: this.name, contributed: ['tools'] })\n\n const gates = compileHitlGates([walk])\n // The early return comes BEFORE `??=`, deliberately: `agent-compiler.ts` documents that an\n // empty gate map means \"no gated tools ⇒ the non-HITL stream path (M2, byte-unchanged)\".\n // Creating an empty Map here would flip that branch for every agent that has no HITL at all.\n if (gates.size === 0) return\n draft.hitl ??= new Map()\n for (const [key, options] of gates) draft.hitl.set(key, options)\n draft.provenance.push({ capability: this.name, contributed: ['hitl'] })\n }\n}\n","/**\n * M91 — `Toolset`: coleção nomeada e imutável de tools, com política de resolução que falha alto.\n *\n * ## Por que na camada\n *\n * A camada já publica as costuras de `sandbox` e `interactive`; esta é a contraparte que faltava. Sem\n * ela, o consumidor escreveu a sua — `agents/tools/registry.ts` do agent-builder, 170 LoC — e a\n * política que importa (falhar alto em nome desconhecido **e** duplicado) ficou fora do framework,\n * onde o próximo consumidor teria de redescobri-la.\n *\n * ## O que ela NÃO faz, e por quê\n *\n * **Não prefixa namespace.** Foi isso que desqualificou o `ToolboxCapability` deste mesmo diretório\n * para este papel: o nome de uma tool é **contrato com o modelo**, e prefixar muda o que o modelo vê.\n *\n * **Não constrói tools.** Quais tools, com quais opções e sob qual escopo é decisão do consumidor —\n * a camada não sabe o `projectRoot` nem a postura de sandbox de ninguém. O `Toolset` recebe as\n * entradas já construídas e é dono só da **política de resolução**. É a divisão que impede a\n * primitiva de virar uma segunda cópia do registry do consumidor.\n *\n * ## Por que falhar alto nos dois casos\n *\n * Nome **desconhecido**: um role que declara `run_shell` numa whitelist e recebe silêncio fica sem a\n * tool sem ninguém notar. Nome **duplicado**: registra a mesma tool duas vezes no `Agent.create`, sem\n * sinal nenhum. Nos dois, o resultado é uma mudança de autoridade **não observável** — que é\n * exatamente o que uma whitelist existe para impedir.\n */\n\n/** O mínimo que o `Toolset` precisa saber de uma tool: que ela tem nome. */\nexport interface ToolComNome {\n readonly name: string\n}\n\nexport class ToolsetError extends Error {\n constructor(\n message: string,\n readonly code: 'unknown_tool' | 'duplicate_tool',\n ) {\n super(message)\n this.name = 'ToolsetError'\n }\n}\n\nexport class Toolset<T extends ToolComNome> {\n readonly #porNome: ReadonlyMap<string, T>\n\n private constructor(porNome: ReadonlyMap<string, T>) {\n this.#porNome = porNome\n Object.freeze(this)\n }\n\n /**\n * Constrói a partir das tools já instanciadas. Falha alto em nome duplicado **na construção** — não\n * na resolução: um descritor com duas tools de mesmo nome está errado no momento em que é escrito, e\n * adiar o erro para o primeiro `resolve` esconde metade dos casos.\n */\n static from<T extends ToolComNome>(tools: readonly T[]): Toolset<T> {\n const porNome = new Map<string, T>()\n for (const tool of tools) {\n if (porNome.has(tool.name)) {\n throw new ToolsetError(`duplicate tool \"${tool.name}\" in toolset`, 'duplicate_tool')\n }\n porNome.set(tool.name, tool)\n }\n return new Toolset(porNome)\n }\n\n /** Uma tool pelo nome. Lança com o nome no erro — nunca devolve `undefined` em silêncio. */\n get(name: string): T {\n const tool = this.#porNome.get(name)\n if (tool === undefined) {\n throw new ToolsetError(`unknown tool \"${name}\"`, 'unknown_tool')\n }\n return tool\n }\n\n /**\n * Resolve uma whitelist. Falha alto em desconhecido **e** em duplicado dentro da própria lista:\n * um time nunca concede em silêncio uma tool que o role não declarou, nem descarta em silêncio uma\n * que declarou.\n */\n resolve(names: readonly string[]): readonly T[] {\n const vistos = new Set<string>()\n return names.map((name) => {\n if (vistos.has(name)) {\n throw new ToolsetError(`duplicate tool \"${name}\" in a whitelist`, 'duplicate_tool')\n }\n vistos.add(name)\n return this.get(name)\n })\n }\n\n /** Os nomes conhecidos, na ordem de registro. */\n names(): readonly string[] {\n return [...this.#porNome.keys()]\n }\n\n /** Todas as tools, na ordem de registro. */\n all(): readonly T[] {\n return [...this.#porNome.values()]\n }\n}\n","/**\n * M15 (theokit-ai-first) — A2A agent card generation (ADR-0040 § D2, home/discovery concern).\n *\n * Produces an [A2A](https://github.com/google/A2A)-spec Agent Card from the framework's\n * `AgentManifestEntry`, so other systems can discover a TheoKit agent's capabilities over HTTP at\n * `/.well-known/<name>/agent-card.json`. Pure data transform — no LLM, no runtime (G2).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** A single capability exposed by an A2A agent (maps from a TheoKit tool). */\nexport interface A2ASkill {\n id: string\n name: string\n description: string\n}\n\n/** A2A agent-card capabilities block. */\nexport interface A2ACapabilities {\n streaming: boolean\n pushNotifications: boolean\n stateTransitionHistory: boolean\n}\n\n/** An A2A-spec Agent Card (the subset TheoKit advertises). */\nexport interface AgentCard {\n name: string\n description: string\n url: string\n version: string\n capabilities: A2ACapabilities\n defaultInputModes: string[]\n defaultOutputModes: string[]\n skills: A2ASkill[]\n}\n\nexport interface BuildAgentCardOptions {\n /** Absolute base URL of the deployment (e.g. `https://app.example.com`). A trailing slash is trimmed. */\n baseUrl: string\n /** Human description of the agent. Defaults to a generated sentence when omitted (spec requires non-empty). */\n description?: string\n}\n\n/** Strip a single trailing slash so `${baseUrl}${route}` never doubles the separator. */\nfunction trimTrailingSlash(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url\n}\n\n/** Build an A2A agent card from a manifest entry. */\nexport function buildAgentCard(entry: AgentManifestEntry, options: BuildAgentCardOptions): AgentCard {\n const base = trimTrailingSlash(options.baseUrl)\n return {\n name: entry.name,\n description: options.description ?? `TheoKit agent \"${entry.name}\".`,\n url: `${base}${entry.route}`,\n version: '1.0',\n capabilities: {\n streaming: entry.stream,\n pushNotifications: false,\n stateTransitionHistory: false,\n },\n defaultInputModes: ['text'],\n defaultOutputModes: ['text'],\n skills: entry.tools.map((t) => ({ id: t.name, name: t.name, description: t.description })),\n }\n}\n\n/** The A2A discovery path for an agent: `/.well-known/<name>/agent-card.json`. */\nexport function wellKnownCardPath(agentName: string): string {\n return `/.well-known/${agentName}/agent-card.json`\n}\n","/**\n * M16 (theokit-ai-first) — MCP server manifest generation (ADR-0040 § D2, home concern).\n *\n * Exposes a TheoKit agent's tools to external MCP clients as `tools/list` descriptors, so the app\n * can advertise its agents over its OWN HTTP routes. Pure data transform — no LLM, no runtime, and\n * NO stdio transport (that stays SDK-side per sdk-runtime.md). Serving these over `GET /mcp` and the\n * JSON-RPC envelope are follow-ups (mount path).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** The MCP protocol revision these descriptors target. */\nexport const MCP_PROTOCOL_VERSION = '2024-11-05'\n\n/** A JSON-schema object (the shape MCP expects for a tool's `inputSchema`). */\nexport interface McpJsonSchema {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n}\n\n/** An MCP `tools/list` tool descriptor. */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: McpJsonSchema\n}\n\n/** MCP `initialize` server info. */\nexport interface McpServerInfo {\n name: string\n version: string\n protocolVersion: string\n}\n\n/**\n * Map an agent's tools to MCP tool descriptors. The manifest tool carries name + description; the\n * per-tool JSON schema is not retained in the manifest, so a permissive empty-object schema is\n * emitted (MCP clients accept it and pass through arbitrary args). Wiring the real per-tool schema\n * is a follow-up once the manifest carries it.\n */\nexport function buildMcpToolDescriptors(entry: AgentManifestEntry): McpToolDescriptor[] {\n return entry.tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: { type: 'object', properties: {} },\n }))\n}\n\n/** Build the MCP `initialize` server-info block for an agent. */\nexport function mcpServerInfo(entry: AgentManifestEntry): McpServerInfo {\n return { name: entry.name, version: '1.0', protocolVersion: MCP_PROTOCOL_VERSION }\n}\n","/**\n * M15 (theokit-ai-first) — A2A client: call a remote A2A agent as a tool (ADR-0040 § D2).\n *\n * `createA2ATool` returns a `CustomTool` whose handler POSTs the input message to a remote agent's\n * HTTP endpoint and returns its text response — cross-network delegation. Uses `fetch` (Web\n * Standards, G8). The target is a remote AGENT endpoint, not an LLM provider, so the G2 grep guard\n * (`openrouter.ai|api.openai.com|api.anthropic.com`) is unaffected. `fetchImpl` is injectable for tests.\n */\nimport type { CustomTool } from '@theokit/sdk'\n\n/** How to authenticate to the remote agent. */\nexport interface A2AAuth {\n /** Bearer token → `Authorization: Bearer <token>`. */\n bearer?: string\n /** API-key header pair → `<name>: <value>` (e.g. `x-api-key`). */\n apiKey?: { header: string; value: string }\n}\n\nexport interface A2AToolConfig {\n /** Remote agent endpoint URL (POST target). */\n url: string\n /** Tool name the model calls. */\n name: string\n /** Tool description surfaced to the model. */\n description: string\n /** Static headers merged into every request. */\n headers?: Record<string, string>\n /** Auth applied to every request. */\n auth?: A2AAuth\n /** Injected fetch (defaults to the global). Narrowed to the call shape this client uses. */\n fetchImpl?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/** Build the request headers from static headers + auth. */\nfunction buildHeaders(config: A2AToolConfig): Record<string, string> {\n const headers: Record<string, string> = { 'content-type': 'application/json', ...config.headers }\n if (config.auth?.bearer) headers.authorization = `Bearer ${config.auth.bearer}`\n if (config.auth?.apiKey) headers[config.auth.apiKey.header] = config.auth.apiKey.value\n return headers\n}\n\n/**\n * Create a tool that delegates to a remote A2A agent. The remote is expected to answer a\n * `{ message }` POST with a JSON body carrying a `response` (or `text`) string.\n */\nexport function createA2ATool(config: A2AToolConfig): CustomTool {\n const doFetch = config.fetchImpl ?? fetch\n return {\n name: config.name,\n description: config.description,\n inputSchema: {\n type: 'object',\n properties: { message: { type: 'string', description: 'The message to send to the remote agent.' } },\n required: ['message'],\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n // The input schema requires `message: string`; narrow defensively (never base-to-string).\n const message = typeof input.message === 'string' ? input.message : ''\n const res = await doFetch(config.url, {\n method: 'POST',\n headers: buildHeaders(config),\n body: JSON.stringify({ message }),\n })\n if (!res.ok) {\n throw new Error(`A2A call to \"${config.name}\" failed: ${res.status} ${res.statusText}`)\n }\n const data = (await res.json()) as { response?: string; text?: string }\n return data.response ?? data.text ?? ''\n },\n }\n}\n","/**\n * M11 (theokit-ai-first) — {resource, thread} conversation scoping (ADR-0040 § D2, home concern).\n *\n * Maps a request's (resource, thread) pair to a deterministic, collision-safe conversation id so\n * multi-tenant apps isolate history without hand-building `user-${id}-thread-${id}` strings. This\n * is the app's request→conversation mapping — NOT the SDK's storage engine (which the derived id is\n * simply handed to). Background compression of long histories stays SDK-side.\n *\n * Encoding: each component is `encodeURIComponent`-escaped and joined with `/`. Since\n * `encodeURIComponent` escapes a raw `/` to `%2F`, the separator is unambiguous — `('a/b','c')` and\n * `('a','b/c')` derive DIFFERENT ids (collision-safe). Reversible via {@link parseConversationId}.\n */\n\nconst SEPARATOR = '/'\n\n/** Derive a deterministic conversation id from a (resource, thread) pair. Fails fast on empty input. */\nexport function deriveConversationId(resource: string, thread: string): string {\n if (!resource) throw new Error('[@theokit/agents] deriveConversationId: resource must be non-empty')\n if (!thread) throw new Error('[@theokit/agents] deriveConversationId: thread must be non-empty')\n return `${encodeURIComponent(resource)}${SEPARATOR}${encodeURIComponent(thread)}`\n}\n\n/**\n * Reverse a derived conversation id back to its (resource, thread). Returns `null` for a value that\n * is not a derived scope id (no separator, or an empty component) — callers treat that as \"opaque id,\n * not scoped\".\n */\nexport function parseConversationId(id: string): { resource: string; thread: string } | null {\n const idx = id.indexOf(SEPARATOR)\n if (idx <= 0 || idx >= id.length - 1) return null\n const resource = decodeURIComponent(id.slice(0, idx))\n const thread = decodeURIComponent(id.slice(idx + 1))\n if (!resource || !thread) return null\n return { resource, thread }\n}\n","/**\n * M13 (theokit-ai-first) — per-request skills resolution (ADR-0040 § D2, home/boundary concern).\n *\n * The static `skills.enabled` filter already works (`compile-skills` maps `include` → the SDK's\n * `enabled`). This adds a PER-REQUEST resolver so multi-tenant apps expose different skill sets to\n * different users. A selection is either a static list or a function of the request context (the M7\n * run-context). Discovery + injection stay in the SDK; this only CHOOSES the enabled set per call.\n */\n\nimport type { InlineSkill } from '@theokit/sdk'\n\n/** The request context handed to a skills resolver (the M7 run-context — opaque per-request data). */\nexport type SkillsRequestContext = Record<string, unknown>\n\n/**\n * How the skill set is chosen:\n * - a static array of `string` (filesystem skill NAMES → `skills.enabled`) and/or `InlineSkill`\n * objects from `createSkill` (code-defined skills → `skills.inline`, injected into the `<skills>`\n * block). A mixed list is split at compile time.\n * - a function — resolved per request from the {@link SkillsRequestContext} (sync or async). The\n * resolver returns filesystem skill NAMES (inline skills are static — declared on the agent).\n */\nexport type SkillsSelection =\n | readonly (string | InlineSkill)[]\n | ((ctx: SkillsRequestContext) => readonly string[] | Promise<readonly string[]>)\n\n/**\n * Resolve the enabled skill names for a request. Returns `undefined` when no selection is given (the\n * SDK then enables every discovered skill). Fails fast if a resolver returns a non-array. The static\n * array is compiled ahead of time (see `compileSkillsSelection`), so this is exercised for the\n * resolver form; a static array is defensively narrowed to its string (name) members.\n */\nexport async function resolveEnabledSkills(\n selection: SkillsSelection | undefined,\n ctx: SkillsRequestContext,\n): Promise<string[] | undefined> {\n if (selection === undefined) return undefined\n if (typeof selection !== 'function') {\n return selection.filter((s): s is string => typeof s === 'string')\n }\n const resolved: unknown = await selection(ctx)\n if (!Array.isArray(resolved)) {\n throw new Error('[@theokit/agents] skills resolver must return an array of skill names')\n }\n // The resolver is USER code, so the array's ITEMS are validated too — previously only the array\n // shape was checked and a `[42, null]` would have reached `Agent.create` as \"skill names\".\n const names = resolved as readonly unknown[]\n if (!names.every((n): n is string => typeof n === 'string' && n.trim().length > 0)) {\n throw new Error('[@theokit/agents] skills resolver must return non-empty skill NAME strings')\n }\n return [...names]\n}\n","/**\n * M17 (theokit-ai-first) — ACP (Agent Client Protocol) stdio framing.\n *\n * ACP talks to a coding agent (Claude Code, Amp, Codex) over stdio as newline-delimited JSON. This\n * is the transport-agnostic CORE: encode a message to a line, and decode a byte/char stream that may\n * split a message across chunks. Pure — no subprocess, no Node API. The subprocess spawn lives in the\n * adapter layer (G8) / SDK; `createACPTool` (wrapping this codec + an injected transport) is a\n * follow-up once the adapter ships.\n */\n\n/** Serialize a message to a single newline-terminated JSON line. */\nexport function encodeAcpMessage(message: unknown): string {\n return `${JSON.stringify(message)}\\n`\n}\n\n/**\n * Incremental decoder for newline-delimited JSON. Feed it chunks with {@link push}; it buffers a\n * partial trailing line across calls and returns every WHOLE message parsed so far. Blank lines are\n * skipped. A completed non-JSON line fails fast with a typed error (error-handling.md) — a corrupt\n * frame must never be silently dropped.\n */\nexport class AcpMessageDecoder {\n private buffer = ''\n\n /** Feed a chunk; returns the messages completed by this chunk (possibly empty). */\n push(chunk: string): unknown[] {\n this.buffer += chunk\n const messages: unknown[] = []\n let newlineIndex = this.buffer.indexOf('\\n')\n while (newlineIndex !== -1) {\n const line = this.buffer.slice(0, newlineIndex).trim()\n this.buffer = this.buffer.slice(newlineIndex + 1)\n if (line.length > 0) {\n try {\n messages.push(JSON.parse(line))\n } catch (cause) {\n throw new Error(`[@theokit/agents] ACP decode failed on line: ${line}`, { cause })\n }\n }\n newlineIndex = this.buffer.indexOf('\\n')\n }\n return messages\n }\n}\n","/**\n * M17 (theokit-ai-first) — ACP client: JSON-RPC over the stdio framing.\n *\n * Drives a coding agent (Claude Code, Amp, Codex) over an INJECTED {@link AcpTransport}. The\n * subprocess spawn is a Node API and lives in the adapter layer (G8); this client is transport-\n * agnostic and testable. It correlates responses to requests by `id`, and dispatches server→client\n * requests (e.g. `session/request_permission`) to a registered handler, replying with its decision.\n */\nimport { AcpMessageDecoder, encodeAcpMessage } from './protocol.js'\n\n/** The stdio channel to the coding-agent subprocess (abstracted for testability + G8). */\nexport interface AcpTransport {\n /** Write one already-encoded (newline-terminated) line to the agent's stdin. */\n send(line: string): void\n /** Subscribe to raw lines/chunks from the agent's stdout. */\n subscribe(onData: (chunk: string) => void): void\n}\n\ninterface JsonRpcResponse {\n id: number\n result?: unknown\n error?: { code: number; message: string }\n}\ninterface JsonRpcServerRequest {\n id: number\n method: string\n params?: unknown\n}\n\ninterface Pending {\n resolve: (value: unknown) => void\n reject: (err: Error) => void\n}\n/** Return a value or a Promise — `unknown` already includes `Promise<unknown>`; `await` handles both. */\ntype ServerRequestHandler = (params: unknown) => unknown\n\nfunction isResponse(m: Record<string, unknown>): m is JsonRpcResponse & Record<string, unknown> {\n return typeof m.id === 'number' && (('result' in m) || ('error' in m)) && !('method' in m)\n}\nfunction isServerRequest(m: Record<string, unknown>): m is JsonRpcServerRequest & Record<string, unknown> {\n return typeof m.method === 'string' && typeof m.id === 'number'\n}\n\nexport class AcpClient {\n private nextId = 1\n private readonly pending = new Map<number, Pending>()\n private readonly handlers = new Map<string, ServerRequestHandler>()\n private readonly decoder = new AcpMessageDecoder()\n\n constructor(private readonly transport: AcpTransport) {\n transport.subscribe((chunk) => {\n for (const message of this.decoder.push(chunk)) {\n this.dispatch(message as Record<string, unknown>)\n }\n })\n }\n\n /** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n request(method: string, params: unknown): Promise<unknown> {\n const id = this.nextId++\n return new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { resolve, reject })\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id, method, params }))\n })\n }\n\n /** Register a handler for a server→client request method (e.g. `session/request_permission`). */\n onRequest(method: string, handler: ServerRequestHandler): void {\n this.handlers.set(method, handler)\n }\n\n private dispatch(message: Record<string, unknown>): void {\n if (isResponse(message)) {\n const entry = this.pending.get(message.id)\n if (!entry) return\n this.pending.delete(message.id)\n if (message.error) entry.reject(new Error(message.error.message))\n else entry.resolve(message.result)\n return\n }\n if (isServerRequest(message)) {\n void this.handleServerRequest(message)\n }\n }\n\n private async handleServerRequest(req: JsonRpcServerRequest): Promise<void> {\n const handler = this.handlers.get(req.method)\n if (!handler) {\n this.transport.send(\n encodeAcpMessage({ jsonrpc: '2.0', id: req.id, error: { code: -32601, message: `No handler: ${req.method}` } }),\n )\n return\n }\n try {\n const result = await handler(req.params)\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id: req.id, result }))\n } catch (err) {\n this.transport.send(\n encodeAcpMessage({\n jsonrpc: '2.0',\n id: req.id,\n error: { code: -32603, message: err instanceof Error ? err.message : 'handler failed' },\n }),\n )\n }\n }\n}\n","// M31 builder-only: the `@Agent/@Tool/@Toolbox/@HumanInTheLoop/@Guardrails/@Skills/@MainLoop/\n// @SubAgents/@Checkpoint/@Mixin/…` decorators are removed from the public API (ADR-0043 D1/D2). The\n// `AgentBuilder.create()` / `tool()` builders are the single authoring surface. The decorator implementations +\n// their metadata getters remain internal (the compiler reads them via source-path imports).\n// The decorator OPTION TYPES stay public (the framework + consumers annotate with them — e.g. the\n// HITL `TimeoutAction` used by the approval-registry and the `AgentBuilder.create().approval(...)` options).\nexport type { HumanInTheLoopOptions, TimeoutAction } from './types.js'\n// M35 — the settled HITL decision type is part of the public approval contract: an `awaitApproval`\n// resolver (the HTTP registry or the in-process seam) may return a bare boolean OR this structured value.\nexport type { HitlDecision } from './bridge/hitl-plugin.js'\n// `ConfigurationError` is part of the public contract — consumers `catch` it. It used to reach the\n// barrel via a compat re-export inside `capability/capabilities.ts` (removed in M56); export it here\n// from its home module so removing that internal re-export does not drop it from the package API.\nexport { ConfigurationError } from './errors.js'\nexport * from './capability/index.js'\nexport * from './bridge/index.js'\nexport * from './loop/index.js'\nexport * from './guardrails/index.js'\nexport * from './a2a/agent-card.js'\nexport * from './a2a/mcp-server-manifest.js'\nexport * from './a2a/a2a-client.js'\nexport * from './conversation-scope.js'\nexport * from './skills-resolver.js'\nexport * from './acp/protocol.js'\nexport * from './acp/client.js'\nexport * from './manifest/agent-manifest.js'\nexport { agentsPlugin, type AgentsPluginOptions } from './theokit-plugin.js'\nexport type {\n AgentOptions,\n MainLoopOptions,\n MainLoopMeta,\n ToolboxOptions,\n ToolOptions,\n BudgetOptions,\n ApprovalOptions,\n PolicyHandler,\n ReasoningEffort,\n} from './types.js'\n\n// M58 — layered boundary `SDK → Theokit → AgentBuilder`: the consumer imports the SDK's already-OO\n// core primitives from `@theokit/agents`, not from `@theokit/sdk` directly. PASS-THROUGH, never a\n// wrapper (parsimony-ladder Rung 9): `Agent.create()` / `Tool.create()` / `Provider` are already the\n// target OO shape, so wrapping them would be ceremony without value. The domains with their own\n// infra surface (sandbox / persistence / interactive / pty) live on matching subpaths that mirror the\n// SDK's own subpath split (`@theokit/agents/{sandbox,persistence,interactive,pty}`).\nexport { Agent, Squad, Tool, Provider } from '@theokit/sdk'\nexport type { SDKAgent, CustomTool, SessionRecord } from '@theokit/sdk'\n\n// M63 — closing the layered boundary so the consumer imports ZERO `@theokit/sdk*` directly. Same\n// PASS-THROUGH doctrine as the M58 core above (Rung 9): these are already the target shape.\n// - `SubAgent` (a2a delegation primitive): `SubAgent.create()` is already OO; wrapping it adds nothing.\n// - the path-safety helpers are pure functions — a class would be ceremony (parsimony-ladder Rung 5).\nexport { SubAgent } from '@theokit/sdk/a2a'\nexport { assertNoSymlinkEscape, isForbiddenPath, safePathJoin } from '@theokit/sdk/path-safety'\n\n// M77 — the context-window resolver, so a surface can render a budget meter against the REAL window\n// instead of a constant. Same PASS-THROUGH doctrine (Rung 9): `resolveEffectiveContextWindow` is a\n// pure function and `CONTEXT_WINDOW_*` are constants — wrapping them in a class would be ceremony.\n//\n// The consumer needs this because its TUI hardcoded `contextWindow: 400_000`, decoupled from the\n// configured model: change the model and the meter silently lies. A meter that lies is worse than no\n// meter, because it is trusted.\nexport {\n CONTEXT_WINDOW_FLOOR,\n CONTEXT_WINDOW_MARGIN,\n ContextWindowMarginError,\n resolveEffectiveContextWindow,\n} from '@theokit/sdk/compaction'\nexport type { ContextWindowSource, EffectiveContextWindow } from '@theokit/sdk/compaction'\n\n// M78 — a política de cobertura declarada. Antes deste milestone o barril crescia de forma REATIVA\n// (símbolo a símbolo, sob pressão de bug) e cobria 9 dos 28 subpaths do SDK, sem nada avisar quando\n// um subpath novo aparecia. `tests/unit/subpath-coverage.test.ts` agora exige veredito para TODOS os\n// 28 — `in` (verificado) ou `out` (com razão escrita).\n//\n// Mesma doutrina de PASS-THROUGH do M58/M63 (Rung 9): estes já são a forma alvo — a hierarquia de\n// erro é OO, `Retry`/`Semaphore` são classes, e as de `/messages` e `/models` são funções puras.\n// Envolver qualquer uma seria cerimônia sem nada dentro.\n//\n// `/errors` é o eixo do milestone: o consumidor tem como regra INQUEBRÁVEL erro tipado, e sem acesso\n// a esta hierarquia a única saída legal era criar uma PARALELA — foi o que aconteceu, cinco classes\n// estendendo `Error` nu. E como `isTransientError` exige `TheokitAgentError`, o predicado que separa\n// recuperável de irrecuperável era inútil lá por construção.\n// `export *` e não uma lista curada, de propósito. A primeira versão re-exportava quatro classes\n// escolhidas a dedo e `RateLimitError` — que o refresh OAuth precisa para reconhecer um 429 — ficou\n// de fora sem nada acusar. Uma hierarquia de erro PELA METADE é exatamente o defeito que este\n// milestone fecha: o consumidor voltaria a criar a classe que falta.\n//\n// O mesmo vale para os outros quatro: são subpaths pequenos e coesos, onde \"parte do domínio\" não é\n// uma unidade que faça sentido. `tests/unit/subpath-coverage.test.ts` verifica a cobertura TOTAL\n// destes, não uma amostra.\nexport * from '@theokit/sdk/errors'\nexport * from '@theokit/sdk/retry'\nexport * from '@theokit/sdk/concurrency'\nexport * from '@theokit/sdk/messages'\nexport * from '@theokit/sdk/models'\n// M81 — o loader de subagents em disco. A assimetria oposta (skills com porta pública, subagents\n// sem) é o que fez o consumidor escrever um SEGUNDO parser de `.md` — e depois um teste cuja única\n// função era vigiar a divergência entre os dois. O que atravessa é a config PARSEADA, nunca o\n// formato de arquivo: exportar o formato congelaria um detalhe interno como API pública.\nexport { discoverSubagents, loadSubagentDefinition } from '@theokit/sdk/subagents-loader'\n\n// COLISÃO DE NOME RESOLVIDA no M91 — e a PRIMEIRA tentativa estava errada.\n//\n// `@theokit/sdk/errors` e `./bridge/index.js` exportavam ambos `BudgetExceededError`, e NÃO eram a\n// mesma coisa: a do SDK é orçamento por JANELA (`budgetName`, `window`, `spentUsd`, `mode`); a da\n// camada é orçamento por DELEGAÇÃO (`agentName`, `actualCost`, `budgetLimit`). Como o consumidor tem\n// regra inquebrável de nunca importar `@theokit/sdk` direto, ele nunca alcançava a do SDK — e um\n// `instanceof` casava com o domínio errado em silêncio.\n//\n// ## O que o `4.26.0` fez de errado, medido\n//\n// Ele **reaproveitou** o nome: o barril passou a exportar a classe do SDK sob `BudgetExceededError`.\n// Para um consumidor em `^4.25` que fazia `catch (e) { if (e instanceof BudgetExceededError) … }`, o\n// ramo de orçamento de delegação **deixou de casar, em silêncio** — exatamente o modo de falha que\n// este milestone existe para matar, em espelho. E foi publicado como MINOR.\n//\n// ## A correção\n//\n// O nome antigo volta a ser a classe de DELEGAÇÃO — é o alias `@deprecated` que o DoD pediu, mesma\n// identidade referencial de sempre, zero quebra para quem está em `^4.25`. A classe do SDK atravessa\n// sob um nome que não colide, o que fecha a lacuna original sem reaproveitar nome de ninguém:\n// \"enriquecer nunca reduz\" (M73) vale também para não redefinir o que um nome significa.\nexport { DelegationBudgetExceededError } from './bridge/delegation-types.js'\nexport {\n // O alias EXISTE para ser deprecado; re-exportá-lo é o contrato de compatibilidade, não descuido.\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n BudgetExceededError,\n} from './bridge/delegation-types.js'\nexport { BudgetExceededError as WindowBudgetExceededError } from '@theokit/sdk/errors'\n\n// M82 — o tipo público dos handlers de `.hooks()`. Publicado porque a alternativa é o consumidor\n// declarar o seu (foi o que o agent-builder fez, com `ctx: unknown` em quatro de cinco handlers).\nexport type { HookHandlers } from './bridge/hook-handlers.js'\n\n// M84 — o transporte in-process veio do pacote CLI, onde era folha. Fica na barra principal (e não\n// num subpath novo) porque \"rodar um turn de agente\" é exatamente o que a barra principal faz;\n// separá-lo multiplicaria superfície sem separar nada. O CLI passa a re-exportar daqui.\nexport { streamAgentTurnInProcess, InProcessApprovalRequiredError } from './in-process-turn.js'\nexport type {\n StreamAgentTurnInProcessInput,\n StreamAgentTurnDeps,\n InProcessApprovalRequest,\n InProcessAwaitApproval,\n} from './in-process-turn.js'\n","/**\n * M35 (multi-surface) — the in-process agent-turn seam (Model A).\n *\n * The FRAMEWORK-owned sibling of the HTTP `mountAgent` and the stdout `runAgentInTerminal`: it runs a\n * compiled agent with the SAME `compileAgentModule` + SAME `streamAgentUIMessages` (G2 — reuses the\n * SDK runtime, reimplements nothing), but returns the raw `UIMessageChunk` generator so ANY consumer\n * drives it directly — the Ink TUI (M35), a Tauri window (M36), or a test — in a SINGLE process with\n * NO HTTP loopback, NO port, and NO CSRF (there is no network boundary to defend).\n *\n * The ONLY difference from the HTTP mount is HITL resolution: the mount pauses the run and resolves\n * the approval via a SECOND HTTP request to `/approve/:id` (the approval registry). In-process there\n * is no second request — the caller resolves the approval INLINE via `awaitApproval` (e.g. the Ink\n * TUI's y/n prompt). The gated-tool map is `compiled.hitl` verbatim, so the pause semantics are\n * byte-identical to the HTTP path; only the resolver differs. Parity with the mount is by\n * construction: both compile the module, resolve function-form skills, and call `streamAgentUIMessages`\n * with the same `{ message, sessionId, hitl }`.\n *\n * Consumers WILL still receive `tool-approval-request` chunks from the returned generator — they are\n * INFORMATIONAL (render them or ignore them). The authoritative human gate is `awaitApproval`, which\n * the SDK awaits BEFORE the gated tool runs; the chunk is not the gate.\n */\nimport type { UIMessageChunk } from 'ai'\n\nimport { compileAgentModule, streamAgentUIMessages } from './bridge/agent-endpoint.js'\nimport type { HitlDecision } from './bridge/hitl-plugin.js'\nimport { resolveEnabledSkills } from './skills-resolver.js'\nimport type { HumanInTheLoopOptions } from './types.js'\n\n/** An inline approval request handed to the caller's `awaitApproval` (the Ink/Tauri prompt). */\nexport interface InProcessApprovalRequest {\n approvalId: string\n toolName: string\n opts: HumanInTheLoopOptions\n}\n\n/** Resolve one gated-tool approval inline (approve/deny, or a structured {@link HitlDecision}). */\nexport type InProcessAwaitApproval = (\n req: InProcessApprovalRequest,\n) => Promise<boolean | HitlDecision>\n\nexport interface StreamAgentTurnInProcessInput {\n message: string\n /**\n * M35 (multimodal) — images to send alongside the text. Threaded to the SDK's structured\n * `SDKUserMessage { text, images }` send form. Absent ⇒ the string send path is byte-unchanged.\n */\n images?: Parameters<typeof streamAgentUIMessages>[2]['images']\n /** Resume key; a fresh id per run when omitted. */\n sessionId?: string\n /**\n * Inline HITL resolver — required IFF the agent has `@HumanInTheLoop`-gated tools. Omitting it for a\n * gated agent is a fail-fast error, never a silent bypass (Rule 8, the #99 lesson).\n */\n awaitApproval?: InProcessAwaitApproval\n /** Labels a fail-fast `AgentDefinitionError` (the file path). */\n source?: string\n /** Abort signal forwarded to the SDK stream (client disconnect / window close). */\n signal?: AbortSignal\n}\n\n/** Injectable stream fn (defaults to the real SDK bridge) — lets tests drive a deterministic stream. */\nexport interface StreamAgentTurnDeps {\n stream: typeof streamAgentUIMessages\n}\n\n/**\n * Thrown when a gated agent is run in-process without an `awaitApproval` resolver. Refusing loudly is\n * the correct posture: silently running a `@HumanInTheLoop`-gated tool with no human gate is exactly\n * the #99 class of bug. Typed so callers can catch it distinctly.\n */\nexport class InProcessApprovalRequiredError extends Error {\n constructor(toolNames: readonly string[]) {\n super(\n `Agent has HITL-gated tool(s) [${toolNames.join(', ')}] but no \\`awaitApproval\\` resolver was ` +\n `supplied to streamAgentTurnInProcess. In-process runs must resolve approvals inline — pass ` +\n `awaitApproval, or remove the gate. Refused (fail-closed).`,\n )\n this.name = 'InProcessApprovalRequiredError'\n }\n}\n\n/**\n * Run a compiled agent in-process and return its `UIMessageChunk` stream. `apiKey` is resolved by the\n * caller (same contract as the HTTP mount). Validation + compile happen SYNCHRONOUSLY (so a gated\n * agent without a resolver throws at call time, not lazily on first iteration); the returned value is\n * the SDK's `streamAgentUIMessages` generator.\n */\nexport function streamAgentTurnInProcess(\n mod: unknown,\n apiKey: string,\n input: StreamAgentTurnInProcessInput,\n deps: StreamAgentTurnDeps = { stream: streamAgentUIMessages },\n): AsyncGenerator<UIMessageChunk> {\n const compiled = compileAgentModule(mod, input.source)\n const gated = compiled.hitl\n\n // Fail-fast BEFORE building the stream: a gated agent with no inline resolver would silently bypass\n // the human gate (the #99 class of bug). Refuse loudly (Rule 8, fail-closed).\n if (gated && gated.size > 0 && !input.awaitApproval) {\n throw new InProcessApprovalRequiredError([...gated.keys()])\n }\n const resolve = input.awaitApproval\n\n // Mirror mount-agent's HITL wiring cast-free (structural inference); absent gate ⇒ the non-HITL\n // stream path (M2), unchanged. The SDK calls (approvalId, opts, toolName); route to the caller.\n const hitl =\n gated && gated.size > 0 && resolve\n ? {\n gated,\n awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) =>\n resolve({ approvalId, toolName, opts }),\n }\n : undefined\n\n const sessionId = input.sessionId ?? crypto.randomUUID()\n\n // Resolve function-form skills (`defineAgent({ skills: (ctx) => [...] })`) BEFORE streaming — exact\n // parity with mount-agent. Done INSIDE the returned generator so the synchronous fail-fast above is\n // preserved (the caller still gets a plain `AsyncGenerator`, no `await` at the call site). A static\n // skill list leaves `skillsResolver` undefined and this is a no-op.\n return (async function* () {\n if (compiled.skillsResolver) {\n const enabled = await resolveEnabledSkills(compiled.skillsResolver, compiled.runContext ?? {})\n if (enabled !== undefined) compiled.skills = { enabled, autoInject: true }\n }\n yield* deps.stream(compiled, apiKey, {\n message: input.message,\n // M35 — pass images through so the SDK send uses the structured `{ text, images }` form.\n ...(input.images !== undefined ? { images: input.images } : {}),\n sessionId,\n hitl,\n signal: input.signal,\n })\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ClD,YAAYC,WAA8B;AACxC,UACE,iCAAiCA,UAAUC,KAAK,IAAA,CAAA,mMAEa;AAE/D,SAAKC,OAAO;EACd;AACF;AAQO,SAASC,yBACdC,KACAC,QACAC,OACAC,OAA4B;EAAEC,QAAQC;AAAsB,GAAC;AAE7D,QAAMC,WAAWC,mBAAmBP,KAAKE,MAAMM,MAAM;AACrD,QAAMC,QAAQH,SAASI;AAIvB,MAAID,SAASA,MAAME,OAAO,KAAK,CAACT,MAAMU,eAAe;AACnD,UAAM,IAAIlB,+BAA+B;SAAIe,MAAMI,KAAI;KAAG;EAC5D;AACA,QAAMC,UAAUZ,MAAMU;AAItB,QAAMF,OACJD,SAASA,MAAME,OAAO,KAAKG,UACvB;IACEL;IACAG,eAAe,wBAACG,YAAoBC,MAA6BC,aAC/DH,QAAQ;MAAEC;MAAYE;MAAUD;IAAK,CAAA,GADxB;EAEjB,IACAE;AAEN,QAAMC,YAAYjB,MAAMiB,aAAaC,OAAOC,WAAU;AAMtD,UAAQ,mBAAA;AACN,QAAIf,SAASgB,gBAAgB;AAC3B,YAAMC,UAAU,MAAMC,qBAAqBlB,SAASgB,gBAAgBhB,SAASmB,cAAc,CAAC,CAAA;AAC5F,UAAIF,YAAYL,OAAWZ,UAASoB,SAAS;QAAEH;QAASI,YAAY;MAAK;IAC3E;AACA,WAAOxB,KAAKC,OAAOE,UAAUL,QAAQ;MACnC2B,SAAS1B,MAAM0B;;MAEf,GAAI1B,MAAM2B,WAAWX,SAAY;QAAEW,QAAQ3B,MAAM2B;MAAO,IAAI,CAAC;MAC7DV;MACAT;MACAoB,QAAQ5B,MAAM4B;IAChB,CAAA;EACF,GAAA;AACF;AA/CgB/B;","names":["isDeepStrictEqual","CapabilityConflictError","Error","name","field","previous","next","capability","shapeOf","value","Array","isArray","length","Object","keys","sort","a","b","localeCompare","join","createDraft","tools","agents","provenance","applyCapabilities","capabilities","draft","c","apply","stream","setOnce","undefined","isDeepStrictEqual","push","contributed","describe","value","Array","isArray","ModelCapability","name","id","reasoningEffort","ConfigurationError","trim","length","apply","draft","setOnce","undefined","ToolsCapability","tools","push","provenance","capability","contributed","SkillsCapability","entries","e","field","compiled","compileSkillsSelection","slice","skills","previous","enabled","inline","UnknownCapabilityError","Error","name","requested","known","join","CapabilityRegistry","Map","register","factory","set","has","names","keys","resolve","arg","get","undefined","CapabilityPreset","members","apply","draft","member","FieldCapability","value","apply","draft","setOnce","field","name","MemoryCapability","ContextWindowCapability","options","compileContextWindow","context","ProjectContextCapability","McpServersCapability","GuardrailsCapability","CheckpointCapability","undefined","storage","console","warn","HumanInTheLoopCapability","SubAgentsCapability","children","child","Object","entries","agents","ConfigurationError","provenance","push","capability","contributed","SkillsOptionsCapability","compileSkills","SettingSourcesCapability","PluginsCapability","RunContextCapability","SkillsResolverCapability","AgentConfigCapability","config","Number","isFinite","claimedByMainLoop","some","p","includes","maxIterations","timeoutMs","systemPrompt","parseThinkTags","stripToolDialect","recoverLeakedToolCalls","stream","MainLoopCapability","length","ToolboxCapability","name","instance","options","ConfigurationError","declared","tools","undefined","length","tool","method","namespace","toolRuntimeName","class","guards","map","propertyKey","config","approval","trace","audit","hitl","apply","draft","walk","push","compileTools","Map","provenance","capability","contributed","gates","compileHitlGates","size","key","set","ToolsetError","Error","message","code","name","Toolset","porNome","Object","freeze","from","tools","Map","tool","has","set","get","undefined","resolve","names","vistos","Set","map","add","keys","all","values","trimTrailingSlash","url","endsWith","slice","buildAgentCard","entry","options","base","baseUrl","name","description","route","version","capabilities","streaming","stream","pushNotifications","stateTransitionHistory","defaultInputModes","defaultOutputModes","skills","tools","map","t","id","wellKnownCardPath","agentName","MCP_PROTOCOL_VERSION","buildMcpToolDescriptors","entry","tools","map","t","name","description","inputSchema","type","properties","mcpServerInfo","version","protocolVersion","buildHeaders","config","headers","auth","bearer","authorization","apiKey","header","value","createA2ATool","doFetch","fetchImpl","fetch","name","description","inputSchema","type","properties","message","required","handler","input","res","url","method","body","JSON","stringify","ok","Error","status","statusText","data","json","response","text","SEPARATOR","deriveConversationId","resource","thread","Error","encodeURIComponent","parseConversationId","id","idx","indexOf","length","decodeURIComponent","slice","resolveEnabledSkills","selection","ctx","undefined","filter","s","resolved","Array","isArray","Error","names","every","n","trim","length","encodeAcpMessage","message","JSON","stringify","AcpMessageDecoder","buffer","push","chunk","messages","newlineIndex","indexOf","line","slice","trim","length","parse","cause","Error","isResponse","m","id","isServerRequest","method","AcpClient","nextId","pending","Map","handlers","decoder","AcpMessageDecoder","transport","subscribe","chunk","message","push","dispatch","request","params","Promise","resolve","reject","set","send","encodeAcpMessage","jsonrpc","onRequest","handler","entry","get","delete","error","Error","result","handleServerRequest","req","code","err","Agent","Squad","Tool","Provider","SubAgent","assertNoSymlinkEscape","isForbiddenPath","safePathJoin","CONTEXT_WINDOW_FLOOR","CONTEXT_WINDOW_MARGIN","ContextWindowMarginError","resolveEffectiveContextWindow","discoverSubagents","loadSubagentDefinition","WindowBudgetExceededError","BudgetExceededError","InProcessApprovalRequiredError","Error","toolNames","join","name","streamAgentTurnInProcess","mod","apiKey","input","deps","stream","streamAgentUIMessages","compiled","compileAgentModule","source","gated","hitl","size","awaitApproval","keys","resolve","approvalId","opts","toolName","undefined","sessionId","crypto","randomUUID","skillsResolver","enabled","resolveEnabledSkills","runContext","skills","autoInject","message","images","signal"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/agents",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.27.0",
|
|
4
4
|
"description": "AI agents as first-class citizens of the TheoKit pipeline. The fluent agent()/tool() builders compile to SDK Agent.create() (M31 builder-only authoring API).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/consume-ui-message-stream.ts","../src/client/http-transport.ts","../src/client/last-user-text.ts","../src/client/in-process-transport.ts","../src/client/channel-transport.ts","../src/client/agent-client.ts","../src/client/agent-handle.ts"],"sourcesContent":["import type { UIMessage, UIMessageChunk } from 'ai'\n\n/**\n * M2 (theokit-ai-first) — read a TheoKit agent endpoint's `UIMessageStream` SSE `Response`\n * into reconstructed assistant `UIMessage`s, reusing the `ai` package's own consumer\n * primitives (`parseJsonEventStream` + `readUIMessageStream`) — the exact path\n * `@ai-sdk/react`'s `useChat` runs internally. No reinvented wire parser (Rule 9).\n *\n * `ai` is an OPTIONAL peer dependency, so it is imported dynamically: an app that never\n * calls an agent never pays for it, and importing `theokit/client` does not hard-require\n * `ai` (mirrors how the agent runtime dynamically imports `@theokit/sdk`). An agent app\n * always has `ai` installed (it is the UIMessageStream consumer).\n *\n * `onMessage` is invoked on every reconstruction step with the latest snapshot of the\n * assistant message, so a caller (the `useAgent` hook) can render streaming updates.\n */\nexport async function consumeUIMessageStream(\n response: Response,\n onMessage: (message: UIMessage) => void,\n): Promise<void> {\n const chunkStream = await responseToChunkStream(response)\n await consumeChunkStream(chunkStream, onMessage)\n}\n\n/**\n * M41 (ADR-0050 D3) — the reusable middle piece: a UIMessageStream SSE `Response` →\n * `ReadableStream<UIMessageChunk>`, reusing `ai`'s own `parseJsonEventStream` (the exact primitive\n * `useChat` runs). This is precisely what a `ChatTransport.sendMessages` returns, so `HttpTransport`\n * builds on it directly (no reinvented wire parser — Rule 9). A body-less response yields an empty stream.\n */\nexport async function responseToChunkStream(\n response: Response,\n): Promise<ReadableStream<UIMessageChunk>> {\n if (response.body === null) {\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n controller.close()\n },\n })\n }\n\n const { parseJsonEventStream, uiMessageChunkSchema } = await import('ai')\n\n // ai validates each SSE JSON frame against its own strict chunk schema (the exact gate `useChat`\n // runs), then yields `{ success, value }`; forward the valid chunks.\n const parsed = parseJsonEventStream({ stream: response.body, schema: uiMessageChunkSchema })\n return new ReadableStream<UIMessageChunk>({\n async start(controller) {\n for await (const result of parsed) {\n if (result.success) controller.enqueue(result.value)\n }\n controller.close()\n },\n })\n}\n\n/**\n * M41 (ADR-0050 D6) — read a `ReadableStream<UIMessageChunk>` into reconstructed assistant\n * `UIMessage`s via `ai`'s `readUIMessageStream`. Shared by `consumeUIMessageStream` (Response path)\n * and the framework-agnostic `AgentClient` store (transport path). `onMessage` fires on every\n * reconstruction step so a caller can render streaming updates.\n */\nexport async function consumeChunkStream(\n stream: ReadableStream<UIMessageChunk>,\n onMessage: (message: UIMessage) => void,\n): Promise<void> {\n const { readUIMessageStream } = await import('ai')\n // #136 — a provider failure (401/429/5xx) arrives as a `{ type: 'error', errorText }` chunk, NOT a\n // thrown rejection (the in-process runner and the SSE path both emit it as data). With the default\n // `readUIMessageStream({ stream })` (no `onError`, `terminateOnError` off) that chunk is silently\n // swallowed — the stream ends \"clean\" and the store settles to 'done' instead of 'error'.\n // `onError` captures the error; `terminateOnError` stops reconstructing partial messages after it AND\n // (under ai@7.0.14) errors the underlying iterator — so the `for await` below rejects and\n // `AgentClient.#drive`'s existing catch surfaces it (status='error', error set). The post-loop\n // `throw` is a defensive fallback that still surfaces the captured error if a future `ai` version\n // stops rejecting under `terminateOnError`; it is dead code under ai@7.0.14 but cheap version-robustness.\n let streamError: Error | undefined\n for await (const message of readUIMessageStream({\n stream,\n onError: (err) => {\n streamError = err instanceof Error ? err : new Error(String(err))\n },\n terminateOnError: true,\n })) {\n onMessage(message)\n }\n if (streamError !== undefined) throw streamError\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { responseToChunkStream } from './consume-ui-message-stream.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** Extra request headers — a static record OR a resolver called per request (for dynamic auth). */\nexport type HeadersResolver = Record<string, string> | (() => Record<string, string> | undefined)\n\nexport interface HttpTransportOptions {\n /** Agent endpoint path or URL, e.g. `/api/agents/support`. */\n api: string\n /**\n * Extra request headers (e.g. auth). Static record OR a resolver evaluated on EVERY request — pass a\n * resolver when the value is dynamic (a rotating JWT), so a stale header is never sent. Merged UNDER\n * per-request headers.\n */\n headers?: HeadersResolver\n /** Override fetch (primarily for tests / non-browser hosts) — static; resolved once at construction. */\n fetch?: typeof fetch\n}\n\n/** Normalize `ai`'s `Record | Headers | undefined` header option into a plain record. */\nfunction toRecord(headers: Record<string, string> | Headers | undefined): Record<string, string> {\n if (headers === undefined) return {}\n if (headers instanceof Headers) return Object.fromEntries(headers.entries())\n return headers\n}\n\n/**\n * M41 (ADR-0050 D3) — `ChatTransport` over the web agent path.\n *\n * - `sendMessages`: `POST <api>` with the UIMessageStream `accept` + the `X-Theo-Action` CSRF header\n * (HTTP method + headers are identical to the pre-M41 `useAgent` fetch; the body shape is a superset —\n * `{ ...input, messages: [UIMessage] }` — which the server's dual-path parser accepts, so no\n * regression), captures the server-minted `x-theokit-run-id`, and returns `ReadableStream<UIMessageChunk>`\n * via `ai`'s own SSE parser (`responseToChunkStream`).\n * - `reconnectToStream`: `GET <api>/runs/<runId>/stream` (M37 durable transport); 404 → `null` (the run\n * completed / was evicted). A caller may pass a `Last-Event-ID` header to resume only the tail; by\n * default the server replays the run from the start and the client upserts by message id (idempotent).\n * - `approve`: `POST <api>/approve/<id>` (out-of-band HITL settle).\n *\n * Implemented directly (not by subclassing `DefaultChatTransport`) because reconnect keys on our\n * server-minted `runId` captured from a response header, which the base class does not expose — see\n * ADR-0050 D3.\n */\nexport class HttpTransport implements AgentTransport {\n readonly #api: string\n readonly #headers: HeadersResolver\n readonly #fetch: typeof fetch\n /** Server-minted id of the last run (from `x-theokit-run-id`) — the reconnect key. */\n #lastRunId: string | undefined\n\n constructor(options: HttpTransportOptions) {\n this.#api = options.api\n this.#headers = options.headers ?? {}\n // BIND the default fetch to globalThis — the native `fetch` throws `TypeError: Illegal invocation` when\n // invoked as a method (`this.#fetch(...)` would set `this` to this transport instance, not the window).\n // An injected fetch (tests / non-browser hosts) is a plain function and is used as-is.\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis)\n }\n\n /** Resolve the configured headers per request (a resolver evaluates now — dynamic auth is never stale). */\n #resolveHeaders(): Record<string, string> {\n return (typeof this.#headers === 'function' ? this.#headers() : this.#headers) ?? {}\n }\n\n async sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, headers, body, chatId } = options\n // Only spread an object body (never a primitive — that would emit char-indexed keys). `body` is typed\n // `object | undefined` (ai's `ChatRequestOptions`), so no cast is needed — the guard narrows to\n // `object`. (A runtime-`null` body, which the type forbids, spreads to `{}` — harmless.) The server\n // accepts `{ messages }` (ai shape) AND `{ ...input }` (typed input), preferring the turn text.\n const extra = typeof body === 'object' ? body : undefined\n const response = await this.#fetch(this.#api, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'text/event-stream',\n 'X-Theo-Action': '1',\n ...this.#resolveHeaders(),\n ...toRecord(headers),\n },\n // Send the stable `chatId` as the top-level `id` — the server reads it as the sessionId, so ONE\n // conversation (SDK history + session-scoped tools like `todolist`) persists across turns instead of\n // resetting on a fresh random session each request. Placed last so a session is never shadowed by an\n // `id` field inside the typed input. Undefined chatId ⇒ key omitted ⇒ server falls back (unchanged).\n body: JSON.stringify({ ...extra, messages, id: chatId }),\n signal: abortSignal,\n })\n if (!response.ok) {\n throw new Error(\n `Agent request to ${this.#api} failed: ${response.status} ${response.statusText}`,\n )\n }\n this.#lastRunId = response.headers.get('x-theokit-run-id') ?? undefined\n return responseToChunkStream(response)\n }\n\n async reconnectToStream(\n options: Parameters<ChatTransport<UIMessage>['reconnectToStream']>[0],\n ): Promise<ReadableStream<UIMessageChunk> | null> {\n if (this.#lastRunId === undefined) return null\n const response = await this.#fetch(`${this.#api}/runs/${this.#lastRunId}/stream`, {\n method: 'GET',\n headers: { ...this.#resolveHeaders(), ...toRecord(options.headers) },\n })\n if (response.status === 404) return null\n if (!response.ok) {\n throw new Error(\n `Agent reconnect to run ${this.#lastRunId} failed: ${response.status} ${response.statusText}`,\n )\n }\n return responseToChunkStream(response)\n }\n\n async approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n const response = await this.#fetch(`${this.#api}/approve/${approvalId}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'X-Theo-Action': '1',\n ...this.#resolveHeaders(),\n },\n body: JSON.stringify(decision),\n })\n if (!response.ok) {\n throw new Error(`Approve ${approvalId} failed: ${response.status} ${response.statusText}`)\n }\n }\n}\n","import type { UIMessage } from 'ai'\n\n/**\n * M41/M42 — extract the turn text from the last user message's text parts. Shared by the transports\n * that hand a plain `message` string to an in-process/push runner (`InProcessTransport`,\n * `ChannelTransport`) rather than POSTing the `messages[]` array (`HttpTransport`). One definition (G12).\n */\nexport function extractLastUserText(messages: readonly UIMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]\n if (message.role !== 'user') continue\n const text = message.parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('')\n if (text.length > 0) return text\n }\n return ''\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { extractLastUserText } from './last-user-text.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** An inline approval request handed to the transport's resolver (structural — no server import). */\nexport interface InProcessApprovalRequestLike {\n approvalId: string\n toolName: string\n opts: unknown\n}\n\n/** Resolve one gated-tool approval inline (mirrors the SDK's `boolean | HitlDecision` return). */\nexport type InProcessAwaitApproval = (\n req: InProcessApprovalRequestLike,\n) => Promise<boolean | ApprovalDecision>\n\n/** The input the injected runner receives (structurally compatible with `StreamAgentTurnInProcessInput`). */\nexport interface InProcessRunInput {\n message: string\n sessionId?: string\n signal?: AbortSignal\n awaitApproval?: InProcessAwaitApproval\n /** M43 — per-request context (from `sendMessages`'s `metadata`) — tenant / provider / auth for the runner. */\n context?: unknown\n}\n\n/**\n * The in-process turn runner. The consumer binds `streamAgentTurnInProcess(mod, apiKey, …)`:\n * `new InProcessTransport({ run: (input) => streamAgentTurnInProcess(mod, apiKey, input) })`.\n * Injecting it keeps this client module decoupled from `server/` and makes the transport testable.\n */\nexport type InProcessRunner = (input: InProcessRunInput) => AsyncGenerator<UIMessageChunk>\n\nexport interface InProcessTransportOptions {\n run: InProcessRunner\n}\n\n/** Bridge an `AsyncGenerator<UIMessageChunk>` into a pull-based `ReadableStream<UIMessageChunk>`. */\nfunction generatorToStream(gen: AsyncGenerator<UIMessageChunk>): ReadableStream<UIMessageChunk> {\n return new ReadableStream<UIMessageChunk>({\n async pull(controller) {\n try {\n const result = await gen.next()\n if (result.done === true) {\n controller.close()\n return\n }\n // After the done-guard, `result` is an IteratorYieldResult<UIMessageChunk> — value is typed.\n controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n }\n },\n async cancel() {\n await gen.return(undefined)\n },\n })\n}\n\n/**\n * M41 (ADR-0050 D4) — `ChatTransport` over the in-process seam (`streamAgentTurnInProcess`), for the\n * terminal/desktop surfaces that run client + server in ONE process (no HTTP loopback).\n *\n * - `sendMessages`: bridge the injected runner's `AsyncGenerator<UIMessageChunk>` into a\n * `ReadableStream<UIMessageChunk>` (honoring `abortSignal`, which the runner forwards to the SDK).\n * - `reconnectToStream`: always `null` — a single process has no dropped server-side stream to resume\n * (mirrors `ai`'s `DirectChatTransport`).\n * - `approve`: resolve the pending inline approval by id (the run parks on `awaitApproval`). An unknown\n * id rejects (fail-fast, Rule 8 — never a silent resolve).\n *\n * Error asymmetry vs `HttpTransport` (by design, matching the `ChatTransport` contract): a runner that\n * throws SYNCHRONOUSLY surfaces the error when the stream is READ (via `controller.error`), not from the\n * `sendMessages` promise — whereas `HttpTransport` throws from `sendMessages` on a non-2xx response.\n */\nexport class InProcessTransport implements AgentTransport {\n readonly #run: InProcessRunner\n /** Pending inline approvals: approvalId → resolver of the parked `awaitApproval` promise. */\n readonly #pending = new Map<string, (decision: boolean | ApprovalDecision) => void>()\n\n constructor(options: InProcessTransportOptions) {\n this.#run = options.run\n }\n\n #awaitApproval: InProcessAwaitApproval = (req) =>\n new Promise<boolean | ApprovalDecision>((resolve, reject) => {\n // Approval ids are server-minted UUIDs — a collision means a real bug (two turns reusing an id).\n // Fail fast rather than silently overwrite the earlier turn's parked resolver (Rule 8).\n if (this.#pending.has(req.approvalId)) {\n reject(new Error(`Duplicate pending approval id '${req.approvalId}' — ids must be unique.`))\n return\n }\n this.#pending.set(req.approvalId, resolve)\n })\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n const generator = this.#run({\n message: extractLastUserText(messages),\n signal: abortSignal ?? undefined,\n awaitApproval: this.#awaitApproval,\n // M43 — forward per-request context (the seam's `metadata`) to the runner.\n context: metadata,\n })\n return Promise.resolve(generatorToStream(generator))\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n return Promise.resolve(null)\n }\n\n approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n const resolve = this.#pending.get(approvalId)\n if (resolve === undefined) {\n return Promise.reject(\n new Error(`No pending approval '${approvalId}' (unknown or already settled).`),\n )\n }\n this.#pending.delete(approvalId)\n resolve(decision)\n return Promise.resolve()\n }\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { extractLastUserText } from './last-user-text.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** Handlers the transport hands to the injected push source for one turn. */\nexport interface ChannelTurnHandlers {\n /** One pushed JSONL line (a serialized `UIMessageChunk`). */\n onLine: (line: string) => void\n /** The turn ended — no more lines. */\n onClose: () => void\n /** The push source failed. */\n onError?: (err: unknown) => void\n}\n\n/**\n * The injected push source — a Tauri `Channel`/`invoke` bridge, kept STRUCTURAL so core adds no\n * `@tauri-apps/*` dependency and the transport is testable with a fake (ADR-0051 D2). The Tauri app\n * wires it: `new Channel()`, `channel.onmessage = onLine`, `invoke('run_agent', { message, channel })`,\n * returning a teardown that aborts the sidecar turn.\n */\nexport interface ChannelPushSource {\n /**\n * Start a turn; deliver each JSONL `UIMessageChunk` line to `onLine`, then `onClose`. Return a teardown.\n * `turn.context` (M43) is the per-request context (from the seam's `metadata`) — the Tauri `invoke`\n * forwards it to the sidecar. When no context is set it is present as `context: undefined` (the key is\n * NOT absent) — a sidecar that checks `'context' in turn` should treat `undefined` as \"no context\".\n */\n start(turn: { message: string; context?: unknown }, handlers: ChannelTurnHandlers): () => void\n /** Optional HITL settle (another Tauri `invoke`). */\n settle?(approvalId: string, decision: ApprovalDecision): Promise<void>\n}\n\nexport interface ChannelTransportOptions {\n source: ChannelPushSource\n}\n\n/**\n * M42 (ADR-0051) — `ChatTransport` over a Tauri-`Channel`-shaped push source, for the desktop webview.\n *\n * - `sendMessages`: start the turn via the injected source and bridge its pushed JSONL frames into a\n * `ReadableStream<UIMessageChunk>` (built in `start` — a Channel is push, so the stream's queue buffers\n * frames; ADR-0051 D3). A malformed JSONL line is SKIPPED, never fatal (ADR-0051 D4, Rule 8). `abortSignal`\n * tears down the source and closes the stream.\n * - `reconnectToStream`: always `null` — the M36 sidecar runs the turn directly (no durable server stream);\n * this is the honest parity for a single-process push surface (ADR-0051 D5; mirrors `InProcessTransport`).\n * - `approve`: routes to the injected `settle` (another Tauri `invoke`); absent `settle` → a typed error.\n *\n * The push source is INJECTED — core stays Tauri-agnostic and this transport is unit-tested with a fake.\n */\nexport class ChannelTransport implements AgentTransport {\n readonly #source: ChannelPushSource\n\n constructor(options: ChannelTransportOptions) {\n this.#source = options.source\n }\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n const message = extractLastUserText(messages)\n const source = this.#source\n\n // Per-stream teardown/abort-detach, hoisted so `cancel` (consumer stops reading) can also tear the\n // source down. `closed` makes every terminal transition idempotent (no enqueue/close after close).\n let closed = false\n let teardown: () => void = () => undefined\n let detachAbort: () => void = () => undefined\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n const finish = (settle: () => void): void => {\n if (closed) return\n closed = true\n detachAbort()\n settle()\n }\n teardown = source.start(\n { message, context: metadata },\n {\n onLine: (line) => {\n if (closed) return\n // Skip a malformed pushed line — one bad frame must never crash the webview (ADR-0051 D4).\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n return\n }\n // Discriminant guard: a `UIMessageChunk` is an object with a string `type`. The trust\n // boundary here is the LOCAL sidecar (not the network), so a discriminant check — not the\n // full `ai` schema (which isn't exposed standalone) — is proportionate: it rejects\n // structureless / wrong-shape payloads before they reach `readUIMessageStream`. Same\n // skip-not-crash policy as a parse error.\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as { type?: unknown }).type !== 'string'\n ) {\n return\n }\n controller.enqueue(parsed as UIMessageChunk)\n },\n onClose: () => {\n finish(() => {\n controller.close()\n })\n },\n onError: (err) => {\n finish(() => {\n controller.error(err)\n })\n },\n },\n )\n if (abortSignal !== undefined) {\n const onAbort = (): void => {\n finish(() => {\n teardown()\n controller.close()\n })\n }\n if (abortSignal.aborted) onAbort()\n else {\n abortSignal.addEventListener('abort', onAbort)\n detachAbort = () => {\n abortSignal.removeEventListener('abort', onAbort)\n }\n }\n }\n },\n cancel() {\n // The consumer stopped reading (reader.cancel) — abort the source turn + drop the abort listener.\n if (closed) return\n closed = true\n detachAbort()\n teardown()\n },\n })\n return Promise.resolve(stream)\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n return Promise.resolve(null)\n }\n\n async approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n if (this.#source.settle === undefined) {\n throw new Error(`This channel source has no HITL settle — cannot approve '${approvalId}'.`)\n }\n await this.#source.settle(approvalId, decision)\n }\n}\n","import type { UIMessage, UIMessageChunk } from 'ai'\n\nimport { consumeChunkStream } from './consume-ui-message-stream.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\nexport type UseAgentStatus = 'idle' | 'streaming' | 'done' | 'error'\n\n/** The observable state the store exposes (stable reference between emits — `useSyncExternalStore` contract). */\nexport interface AgentClientState {\n /** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat — unchanged since M41. */\n messages: UIMessage[]\n /**\n * M46 — the full conversation: committed turns + the current turn's user message + in-flight assistant.\n * Accumulated across sends (never reset except by `reset()`), with stable ids committed exactly once.\n * Render this instead of hand-rolling a transcript from `messages`.\n */\n thread: UIMessage[]\n status: UseAgentStatus\n error: Error | undefined\n}\n\n/** Derive the turn text from a typed input: `input.message` when present, else the serialized input. */\nfunction inputToText(input: unknown): string {\n if (\n typeof input === 'object' &&\n input !== null &&\n typeof (input as { message?: unknown }).message === 'string'\n ) {\n return (input as { message: string }).message\n }\n if (typeof input === 'string') return input\n return JSON.stringify(input)\n}\n\n/** Build a user `UIMessage` from a typed input (text from `{ message }`, else the serialized input). */\nfunction buildUserMessage(input: unknown): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: 'user',\n parts: [{ type: 'text', text: inputToText(input) }],\n }\n}\n\n/**\n * M41 (ADR-0050 D6) — the framework-agnostic agent client store.\n *\n * Holds `messages`/`status`/`error`, drives an {@link AgentTransport}, and notifies subscribers on\n * change. It is the SINGLE consolidation point: web (`HttpTransport`) and terminal/desktop\n * (`InProcessTransport`) run the SAME store. `useAgent` is a thin React binding over it via\n * `useSyncExternalStore`; a standalone (no-React) client (M44) can subscribe directly. Being\n * framework-agnostic, it is unit-tested without a DOM.\n */\nexport class AgentClient<TInput = unknown> {\n readonly #transport: AgentTransport\n readonly #chatId = crypto.randomUUID()\n readonly #listeners = new Set<() => void>()\n /** M43 — resolves per-request context (evaluated on every send/reconnect — dynamic, never stale). */\n readonly #contextResolver: (() => RequestContext | undefined) | undefined\n\n #messages: UIMessage[] = []\n #status: UseAgentStatus = 'idle'\n #error: Error | undefined\n #controller: AbortController | null = null\n // M46 — conversation accumulation (React-free; all surfaces inherit it via the snapshot).\n /** Committed (finished) turns — user + assistant, with stable fabricated ids. */\n #committed: UIMessage[] = []\n /** The current turn's user message (in `thread` but never in `messages` — back-compat). */\n #currentUser: UIMessage | undefined\n /** A stable id for the current turn's assistant (the SDK leaves it empty — we fabricate one). */\n #currentAssistantId = ''\n #snapshot: AgentClientState = { messages: [], thread: [], status: 'idle', error: undefined }\n\n constructor(transport: AgentTransport, contextResolver?: () => RequestContext | undefined) {\n this.#transport = transport\n this.#contextResolver = contextResolver\n }\n\n /** Subscribe to state changes; returns an unsubscribe fn. */\n subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener)\n return () => {\n this.#listeners.delete(listener)\n }\n }\n\n /** The current immutable snapshot (stable reference until the next emit). */\n getSnapshot = (): AgentClientState => this.#snapshot\n\n #emit(): void {\n // thread = committed turns + this turn's user + the in-flight assistant (`messages`). New array per\n // emit is fine — the SNAPSHOT reference only changes here, satisfying useSyncExternalStore.\n const thread = this.#currentUser\n ? [...this.#committed, this.#currentUser, ...this.#messages]\n : [...this.#committed, ...this.#messages]\n this.#snapshot = { messages: this.#messages, thread, status: this.#status, error: this.#error }\n for (const listener of this.#listeners) listener()\n }\n\n #upsert(message: UIMessage): void {\n const next = [...this.#messages]\n const idx = next.findIndex((existing) => existing.id === message.id)\n if (idx >= 0) next[idx] = message\n else next.push(message)\n this.#messages = next\n }\n\n async #drive(\n open: () => Promise<ReadableStream<UIMessageChunk> | null>,\n controller: AbortController,\n ): Promise<void> {\n // Read via a function (not a narrowed local) — `aborted` flips ASYNC across the awaits below, so the\n // control-flow narrowing of a direct `signal.aborted` read would be wrong. A stale drive (its\n // controller aborted because a newer send/abort took over) MUST NOT clobber the newer status.\n const aborted = (): boolean => controller.signal.aborted\n try {\n const stream = await open()\n if (aborted()) return\n if (stream === null) {\n // Nothing to resume (e.g. reconnect after the run completed). Settle without error.\n this.#status = this.#messages.length > 0 ? 'done' : 'idle'\n this.#emit()\n return\n }\n await consumeChunkStream(stream, (message) => {\n if (aborted()) return\n // The SDK leaves the assistant message id empty — fabricate a stable per-turn id so every chunk\n // upserts into the SAME message and the committed copy has a collision-free key (M46).\n const stamped = message.id ? message : { ...message, id: this.#currentAssistantId }\n this.#upsert(stamped)\n this.#emit()\n })\n if (aborted()) return\n this.#status = 'done'\n this.#emit()\n } catch (err) {\n if (aborted()) return\n this.#error = err instanceof Error ? err : new Error(String(err))\n this.#status = 'error'\n this.#emit()\n }\n }\n\n /** Send a typed input; opens a fresh stream (replaces prior messages). */\n send = (input: TInput): void => {\n // M46 — commit the PRIOR turn into history exactly once, but ONLY if it finished cleanly (`done`).\n // An errored or aborted turn (status !== 'done') is dropped, keeping committed history uncorrupted.\n if (this.#status === 'done' && this.#currentUser) {\n this.#committed = [...this.#committed, this.#currentUser, ...this.#messages]\n }\n this.abort()\n const controller = new AbortController()\n this.#controller = controller\n const userMsg = buildUserMessage(input)\n this.#currentUser = userMsg\n this.#currentAssistantId = crypto.randomUUID()\n this.#messages = []\n this.#error = undefined\n this.#status = 'streaming'\n this.#emit()\n const context = this.#contextResolver?.()\n void this.#drive(\n () =>\n this.#transport.sendMessages({\n trigger: 'submit-message',\n chatId: this.#chatId,\n messageId: undefined,\n messages: [userMsg],\n abortSignal: controller.signal,\n // Only object inputs flow as the request `body` (the turn text is always in `messages`);\n // a primitive input is carried by the user message, never spread into the body.\n body: typeof input === 'object' && input !== null ? input : undefined,\n // M43 — per-request context reaches every transport (headers → HTTP, metadata → in-process/channel).\n headers: context?.headers,\n metadata: context?.metadata,\n }),\n controller,\n )\n }\n\n /** Resume an interrupted stream via the transport's `reconnectToStream` (no-op when unavailable). */\n reconnect = (): void => {\n const controller = new AbortController()\n this.#controller = controller\n // Reconnecting before any send() (or after reset()) leaves #currentAssistantId empty — fabricate one\n // so a replayed assistant never lands in `thread` with an empty, non-unique id (M46 invariant).\n if (!this.#currentAssistantId) this.#currentAssistantId = crypto.randomUUID()\n // Reconnect means \"resume/retry\" — a stale error must not linger next to a fresh 'streaming' status.\n this.#error = undefined\n this.#status = 'streaming'\n this.#emit()\n const context = this.#contextResolver?.()\n void this.#drive(\n () =>\n this.#transport.reconnectToStream({\n chatId: this.#chatId,\n headers: context?.headers,\n metadata: context?.metadata,\n }),\n controller,\n )\n }\n\n /** Abort an in-flight stream (not an error — leaves messages as-is). */\n abort = (): void => {\n this.#controller?.abort()\n this.#controller = null\n // Finalize the status when the USER aborts an in-flight turn: the aborted `#drive` early-returns\n // without touching status (so a stale drive can't clobber a newer turn), which would otherwise leave\n // `status` stuck on 'streaming' — a lingering spinner + an unusable surface. A caller that aborts to\n // start a NEW turn (`send`/`sendMessages`) sets 'streaming' again immediately after, so this is safe.\n if (this.#status === 'streaming') {\n this.#status = this.#committed.length > 0 || this.#messages.length > 0 ? 'done' : 'idle'\n this.#emit()\n }\n }\n\n /** Clear messages + error, back to idle. */\n reset = (): void => {\n this.abort()\n this.#messages = []\n // M46 — reset means a NEW conversation: clear committed history + the current turn's user too.\n this.#committed = []\n this.#currentUser = undefined\n this.#error = undefined\n this.#status = 'idle'\n this.#emit()\n }\n\n /** Settle a paused HITL approval via the transport's HITL path (HTTP POST or inline callback). */\n approve = async (approvalId: string, decision: ApprovalDecision): Promise<void> => {\n await this.#transport.approve?.(approvalId, decision)\n }\n}\n","import { ChannelTransport, type ChannelPushSource } from './channel-transport.js'\nimport { InProcessTransport, type InProcessRunner } from './in-process-transport.js'\n\n/**\n * M47 (ADR-M47-2) — a typed, client-safe handle for an exposed agent.\n *\n * It carries ONLY the HTTP `path` at runtime plus phantom `input`/`toolNames` types (never populated) — so\n * `useAgent(chat)` / `createAgentClient(chat…)` bind with NO magic string (the path is generated from the\n * `@Expose` exposure, not hand-typed) and NO duplicated input type (the input type flows through the phantom\n * generic, inferred from the agent's `.input()`). This mirrors tRPC/Hono's type-only handle: the client\n * pulls the agent's TYPE via `import type`, never its server runtime. The generated `@theo/agents` module\n * emits one `export const <name> = agentHandle('/api/agents/<name>')` per agent, typed with the phantoms.\n */\nexport interface AgentHandle<TInput = unknown, TToolNames extends string = string> {\n /** The agent's HTTP endpoint path (e.g. `/api/agents/chat`). The only serializable/runtime-bearing field. */\n readonly path: string\n /**\n * M47 — bind this agent in-process (TUI / single-process): wraps the app's runner in an\n * {@link InProcessTransport}. `useAgent(chat.inProcess(run))` drives the SAME agent without HTTP.\n */\n inProcess(run: InProcessRunner): InProcessTransport\n /**\n * M47 — bind this agent over a push channel (Tauri desktop webview): wraps the source in a\n * {@link ChannelTransport}. `createAgentClient(chat.channel(source))` drives the SAME agent.\n */\n channel(source: ChannelPushSource): ChannelTransport\n /** Phantom — the agent's `input` type, carried for `useAgent(handle).send` inference. Never populated. */\n readonly __input?: TInput\n /** Phantom — the agent's tool-name union, carried end-to-end. Never populated. */\n readonly __toolNames?: TToolNames\n}\n\n/**\n * Build an {@link AgentHandle} from an agent's HTTP path. Types are supplied by the caller/codegen. The\n * `inProcess`/`channel` binders are methods (dropped by `JSON.stringify`, so the `{ path }` core stays\n * serializable + client-safe) that produce the M41 transports for the non-web surfaces.\n */\nexport function agentHandle<TInput = unknown, TToolNames extends string = string>(\n path: string,\n): AgentHandle<TInput, TToolNames> {\n return {\n path,\n inProcess: (run) => new InProcessTransport({ run }),\n channel: (source) => new ChannelTransport({ source }),\n }\n}\n\n/** Narrow an unknown binding to an {@link AgentHandle} (has a string `path`, is not a transport). */\nexport function isAgentHandle(value: unknown): value is AgentHandle {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { path?: unknown }).path === 'string' &&\n typeof (value as { sendMessages?: unknown }).sendMessages !== 'function'\n )\n}\n"],"mappings":";;;;;AAgBA,eAAsBA,uBACpBC,UACAC,WAAuC;AAEvC,QAAMC,cAAc,MAAMC,sBAAsBH,QAAAA;AAChD,QAAMI,mBAAmBF,aAAaD,SAAAA;AACxC;AANsBF;AActB,eAAsBI,sBACpBH,UAAkB;AAElB,MAAIA,SAASK,SAAS,MAAM;AAC1B,WAAO,IAAIC,eAA+B;MACxCC,MAAMC,YAAU;AACdA,mBAAWC,MAAK;MAClB;IACF,CAAA;EACF;AAEA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;IACXE,SAAS,wBAACC,WAAW,IAAIC,iBAAiB;MAAED;IAAO,CAAA,GAA1C;EACX;AACF;AARgBN;AAWT,SAASQ,cAAcC,OAAc;AAC1C,SACE,OAAOA,UAAU,YACjBA,UAAU,QACV,OAAQA,MAA6BR,SAAS,YAC9C,OAAQQ,MAAqCC,iBAAiB;AAElE;AAPgBF;","names":["consumeUIMessageStream","response","onMessage","chunkStream","responseToChunkStream","consumeChunkStream","body","ReadableStream","start","controller","close","parseJsonEventStream","uiMessageChunkSchema","parsed","stream","schema","result","success","enqueue","value","readUIMessageStream","streamError","message","onError","err","Error","String","terminateOnError","undefined","toRecord","headers","undefined","Headers","Object","fromEntries","entries","HttpTransport","options","api","fetch","globalThis","bind","sendMessages","messages","abortSignal","body","chatId","extra","response","method","accept","JSON","stringify","id","signal","ok","Error","status","statusText","get","responseToChunkStream","reconnectToStream","approve","approvalId","decision","extractLastUserText","messages","i","length","message","role","text","parts","filter","part","type","map","join","generatorToStream","gen","ReadableStream","pull","controller","result","next","done","close","enqueue","value","err","error","cancel","return","undefined","InProcessTransport","Map","options","run","req","Promise","resolve","reject","has","approvalId","Error","set","sendMessages","messages","abortSignal","metadata","generator","message","extractLastUserText","signal","awaitApproval","context","reconnectToStream","approve","decision","get","delete","ChannelTransport","options","source","sendMessages","messages","abortSignal","metadata","message","extractLastUserText","closed","teardown","undefined","detachAbort","stream","ReadableStream","start","controller","finish","settle","context","onLine","line","parsed","JSON","parse","type","enqueue","onClose","close","onError","err","error","onAbort","aborted","addEventListener","removeEventListener","cancel","Promise","resolve","reconnectToStream","approve","approvalId","decision","Error","inputToText","input","message","JSON","stringify","buildUserMessage","id","crypto","randomUUID","role","parts","type","text","AgentClient","Set","messages","thread","status","error","undefined","transport","contextResolver","subscribe","listener","add","delete","getSnapshot","next","idx","findIndex","existing","push","open","controller","aborted","signal","stream","length","consumeChunkStream","stamped","err","Error","String","send","abort","AbortController","userMsg","context","sendMessages","trigger","chatId","messageId","abortSignal","body","headers","metadata","reconnect","reconnectToStream","reset","approve","approvalId","decision","agentHandle","path","inProcess","run","InProcessTransport","channel","source","ChannelTransport","isAgentHandle","value","sendMessages"]}
|