@theokit/agents 0.45.0 → 0.47.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/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { G as Guardrail, R as ReasoningEffort } from './types-DVA4LQsA.js';
2
2
  export { A as AgentOptions, a as ApprovalOptions, B as BudgetOptions, C as CostBudgetExceededError, b as GuardrailAction, c as GuardrailPhase, d as GuardrailResult, e as GuardrailViolationError, H as HumanInTheLoopOptions, M as MainLoopMeta, f as MainLoopOptions, P as PolicyHandler, T as TimeoutAction, g as ToolOptions, h as ToolboxOptions } from './types-DVA4LQsA.js';
3
- import { L as LoopStrategy, R as ReflectionStrategy, C as CompiledAgentOptions, a as CompiledTool, b as RoundStreamFactory, S as StreamEvent, D as DelegationResult, A as AgentManifestEntry } from './bridge-entry-DQJMvdRy.js';
4
- export { c as AGENT_BRAND, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinition, g as AgentDefinitionError, h as AgentExecutionContext, i as AgentManifest, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentWalkResult, q as AgentWarningCode, r as AgentsPluginOptions, s as ApiErrorContext, t as ApiErrorDecision, u as ApiErrorPolicy, v as ApprovalRequiredEvent, w as ArtifactChunkEvent, x as ArtifactStartEvent, B as BackgroundDelegation, y as BeforeToolCallContext, z as BudgetExceededError, E as CheckpointSavedEvent, F as CompiledContextWindow, G as ContextualTool, H as DEFAULT_MAX_ITERATIONS, I as DefineAgentConfig, J as DelegateFn, K as DelegateOptions, M as DelegationError, N as DoneEvent, O as ErrorEvent, P as FileEditEvent, Q as HitlDecision, T as InferAgentInput, U as InferAgentToolNames, V as IterationEvent, W as LLMCallContext, X as LoopFinishReason, Y as LoopOutcome, Z as LoopStrategyConfig, _ as McpApprovalSpec, $ as McpRegistryConfig, a0 as McpRequestContext, a1 as McpSelection, a2 as PartialToolCallEvent, a3 as ProcessInputContext, a4 as ReflectionContext, a5 as ReflectionResult, a6 as ReflectionStrategyConfig, a7 as RunStartedEvent, a8 as ScoreVerdict, a9 as ScoredDelegation, aa as Scorer, ab as SdkAgentHandle, ac as SdkMessage, ad as Segment, ae as SkillsRequestContext, af as SkillsSelection, ag as StateUpdateEvent, ah as TextDeltaEvent, ai as ThinkingEvent, aj as ToolCallEvent, ak as ToolCallVeto, al as ToolHooks, am as ToolHooksPlugin, an as ToolResultEvent, ao as ToolWalkResult, ap as ToolboxWalkResult, aq as agent, ar as agentsPlugin, as as buildModelSelection, at as compileAgent, au as compileAgentDefinition, av as compileAgentModule, aw as compileContextWindow, ax as compileProjectContext, ay as compileSkills, az as compileTools, aA as contextualTool, aB as createAgentExecutionContext, aC as createApiErrorHandler, aD as createSdkAgentStream, aE as createThinkTagExtractor, aF as createToolHooksPlugin, aG as delegate, aH as delegateBackground, aI as delegateWithScoring, aJ as extractThinkTagStream, aK as generateAgentManifest, aL as generateAgentRoutes, aM as isAgentContext, aN as isAgentDefinition, aO as isApprovalRequired, aP as isDone, aQ as isError, aR as isPartialToolCall, aS as isTextDelta, aT as isToolCall, aU as isToolResult, aV as ladderReflectionStrategy, aW as loopStrategyConfigSchema, aX as mcpRegistry, aY as mcpToolApprovals, aZ as noopReflectionStrategy, a_ as projectContextMetadataOnlyKnobs, a$ as reflectionStrategyConfigSchema, b0 as resolveEnabledSkills, b1 as resolveLoopStrategy, b2 as resolveMcpServers, b3 as runWithApiErrorHandling, b4 as streamAgentResponse, b5 as streamAgentUIMessages, b6 as toAgentFactory, b7 as translateSdkEvent, b8 as translateToUIMessageStream, b9 as validateUniqueRoutes, ba as walkAgentMetadata } from './bridge-entry-DQJMvdRy.js';
5
- import { PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
3
+ import { L as LoopStrategy, R as ReflectionStrategy, C as CompiledAgentOptions, a as CompiledTool, b as RoundStreamFactory, S as StreamEvent, D as DelegationResult, A as AgentManifestEntry } from './bridge-entry-BQ6UUSLZ.js';
4
+ export { c as AGENT_BRAND, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinition, g as AgentDefinitionError, h as AgentExecutionContext, i as AgentManifest, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentWalkResult, q as AgentWarningCode, r as AgentsPluginOptions, s as ApiErrorContext, t as ApiErrorDecision, u as ApiErrorPolicy, v as ApprovalRequiredEvent, w as ArtifactChunkEvent, x as ArtifactStartEvent, B as BackgroundDelegation, y as BeforeToolCallContext, z as BudgetExceededError, E as CheckpointSavedEvent, F as CompiledContextWindow, G as ContextualTool, H as DEFAULT_MAX_ITERATIONS, I as DefineAgentConfig, J as DelegateFn, K as DelegateOptions, M as DelegationError, N as DoneEvent, O as ErrorEvent, P as FileEditEvent, Q as HitlDecision, T as InferAgentInput, U as InferAgentToolNames, V as IterationEvent, W as LLMCallContext, X as LoopFinishReason, Y as LoopOutcome, Z as LoopStrategyConfig, _ as McpApprovalSpec, $ as McpRegistryConfig, a0 as McpRequestContext, a1 as McpSelection, a2 as PartialToolCallEvent, a3 as ProcessInputContext, a4 as ReflectionContext, a5 as ReflectionResult, a6 as ReflectionStrategyConfig, a7 as RunStartedEvent, a8 as ScoreVerdict, a9 as ScoredDelegation, aa as Scorer, ab as SdkAgentHandle, ac as SdkMessage, ad as Segment, ae as SkillsRequestContext, af as SkillsSelection, ag as StateUpdateEvent, ah as TextDeltaEvent, ai as ThinkingEvent, aj as ToolCallEvent, ak as ToolCallVeto, al as ToolHooks, am as ToolHooksPlugin, an as ToolResultEvent, ao as ToolWalkResult, ap as ToolboxWalkResult, aq as agent, ar as agentsPlugin, as as buildModelSelection, at as compileAgent, au as compileAgentDefinition, av as compileAgentModule, aw as compileContextWindow, ax as compileProjectContext, ay as compileSkills, az as compileTools, aA as contextualTool, aB as createAgentExecutionContext, aC as createApiErrorHandler, aD as createSdkAgentStream, aE as createThinkTagExtractor, aF as createToolHooksPlugin, aG as delegate, aH as delegateBackground, aI as delegateWithScoring, aJ as extractThinkTagStream, aK as generateAgentManifest, aL as generateAgentRoutes, aM as isAgentContext, aN as isAgentDefinition, aO as isApprovalRequired, aP as isDone, aQ as isError, aR as isPartialToolCall, aS as isTextDelta, aT as isToolCall, aU as isToolResult, aV as ladderReflectionStrategy, aW as loopStrategyConfigSchema, aX as mcpRegistry, aY as mcpToolApprovals, aZ as noopReflectionStrategy, a_ as presentUIMessageStream, a$ as projectContextMetadataOnlyKnobs, b0 as reflectionStrategyConfigSchema, b1 as resolveEnabledSkills, b2 as resolveLoopStrategy, b3 as resolveMcpServers, b4 as runWithApiErrorHandling, b5 as streamAgentResponse, b6 as streamAgentUIMessages, b7 as toAgentFactory, b8 as translateSdkEvent, b9 as validateUniqueRoutes, ba as walkAgentMetadata } from './bridge-entry-BQ6UUSLZ.js';
5
+ import { PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool, InlineSkill } from '@theokit/sdk';
6
6
  import { RetryOptions } from '@theokit/sdk/retry';
7
7
  import { CompressibleMessage } from '@theokit/sdk/compaction';
8
8
  export { CompressibleMessage } from '@theokit/sdk/compaction';
@@ -363,6 +363,110 @@ declare class AgentRunnerBuilder {
363
363
  build(): AgentRunner;
364
364
  }
365
365
 
366
+ /**
367
+ * M52 — the capability layer: object-oriented, composable authoring that produces the EXISTING narrow
368
+ * waist (`CompiledAgentOptions`), which `assembleM8CreateOptions` already turns into `Agent.create`
369
+ * options. No new spec and no new adapter were invented (ADR-1/ADR-2) — a third representation would be
370
+ * the very duplication this initiative removes.
371
+ */
372
+ /** Which capability contributed which fields — makes the wiring inspectable as DATA. */
373
+ interface ProvenanceEntry {
374
+ readonly capability: string;
375
+ readonly contributed: readonly string[];
376
+ }
377
+ /** The mutable draft a capability enriches. `tools`/`agents` are pre-seeded (required in the waist). */
378
+ interface CompiledAgentOptionsDraft extends Partial<Omit<CompiledAgentOptions, 'tools' | 'agents'>> {
379
+ tools: CompiledAgentOptions['tools'];
380
+ agents: CompiledAgentOptions['agents'];
381
+ readonly provenance: ProvenanceEntry[];
382
+ }
383
+ /**
384
+ * **Strategy + value-level Decorator.** N independent ways to enrich an agent (model, tools, skills,
385
+ * MCP, HITL…), added or removed without touching the builder — a central `switch` would violate OCP.
386
+ */
387
+ interface Capability {
388
+ /** Stable identity — used for provenance and conflict messages. */
389
+ readonly name: string;
390
+ apply(draft: CompiledAgentOptionsDraft): void;
391
+ }
392
+ /** Two capabilities set the same scalar field to different values — a composition bug, never last-wins. */
393
+ declare class CapabilityConflictError extends Error {
394
+ readonly name = "CapabilityConflictError";
395
+ constructor(field: string, previous: unknown, next: unknown, capability: string);
396
+ }
397
+ /**
398
+ * A fresh draft. `stream` is deliberately NOT seeded: a pre-seeded value would make
399
+ * `setOnce(draft, 'stream', false, …)` throw a conflict against a default nobody declared, so
400
+ * `stream: false` would be structurally unreachable. The default is applied at finalize instead.
401
+ */
402
+ declare function createDraft(): CompiledAgentOptionsDraft;
403
+ /** A draft that has been finalized — the waist's required `stream` is settled. */
404
+ type FinalizedDraft = CompiledAgentOptionsDraft & {
405
+ stream: boolean;
406
+ };
407
+ /** Apply capabilities in declaration order (deterministic) and return the draft. */
408
+ declare function applyCapabilities(capabilities: readonly Capability[], draft?: CompiledAgentOptionsDraft): FinalizedDraft;
409
+ /** Set a scalar exactly once — fail-fast on a conflicting redeclaration (Rule 8). */
410
+ declare function setOnce<K extends keyof CompiledAgentOptionsDraft>(draft: CompiledAgentOptionsDraft, field: K, value: CompiledAgentOptionsDraft[K], capability: string): void;
411
+
412
+ /**
413
+ * M52 — three real capabilities proving the contract against genuine variation: one that VALIDATES and
414
+ * can conflict (model), one that ACCUMULATES (tools), and one that is pure DATA (skills — a plain
415
+ * factory, because a class with no behavior would be ceremony: KISS).
416
+ */
417
+ /** Typed authoring failure — surfaced at build time, never a silent bad agent. */
418
+ declare class ConfigurationError extends Error {
419
+ readonly name = "ConfigurationError";
420
+ }
421
+ /** Sets the model id (and optional reasoning effort). CLASS: it validates and can conflict. */
422
+ declare class ModelCapability implements Capability {
423
+ private readonly id;
424
+ private readonly reasoningEffort?;
425
+ readonly name = "model";
426
+ constructor(id: string, reasoningEffort?: CompiledAgentOptionsDraft['reasoningEffort']);
427
+ apply(draft: CompiledAgentOptionsDraft): void;
428
+ }
429
+ /** Adds tools. CLASS: it ACCUMULATES (never overwrites), which is behavior worth owning. */
430
+ declare class ToolsCapability implements Capability {
431
+ #private;
432
+ readonly name = "tools";
433
+ constructor(tools: readonly CompiledTool[]);
434
+ apply(draft: CompiledAgentOptionsDraft): void;
435
+ }
436
+ /**
437
+ * Enables skills by name. FUNCTION, not class: it carries no behavior beyond assignment — a class here
438
+ * would be ceremony (the honest counter-example to "everything must be a class").
439
+ */
440
+ declare const skills: (entries: readonly (string | InlineSkill)[]) => Capability;
441
+
442
+ /**
443
+ * M52 — resolution + composition. The registry is what unlocks FILE-BASED authoring (a config lists
444
+ * capability names): resolving name → capability without a switch that grows per feature (OCP).
445
+ */
446
+ /** Fail-fast with the known set — never `undefined` leaking into the pipeline. */
447
+ declare class UnknownCapabilityError extends Error {
448
+ readonly name = "UnknownCapabilityError";
449
+ constructor(requested: string, known: readonly string[]);
450
+ }
451
+ /** **Registry + Factory Method.** */
452
+ declare class CapabilityRegistry {
453
+ #private;
454
+ register(name: string, factory: (arg: unknown) => Capability): this;
455
+ has(name: string): boolean;
456
+ names(): string[];
457
+ resolve(name: string, arg?: unknown): Capability;
458
+ }
459
+ /**
460
+ * **Composite** — a preset behaves like ONE capability, so a caller says `codingAgent()` instead of
461
+ * spreading an array at the call site. Members apply in declaration order (deterministic).
462
+ */
463
+ declare class CapabilityPreset implements Capability {
464
+ #private;
465
+ readonly name: string;
466
+ constructor(name: string, members: readonly Capability[]);
467
+ apply(draft: CompiledAgentOptionsDraft): void;
468
+ }
469
+
366
470
  /**
367
471
  * M15 (theokit-ai-first) — A2A agent card generation (ADR-0040 § D2, home/discovery concern).
368
472
  *
@@ -554,4 +658,4 @@ declare class AcpClient {
554
658
  private handleServerRequest;
555
659
  }
556
660
 
557
- export { type A2AAuth, type A2ACapabilities, type A2ASkill, type A2AToolConfig, AcpClient, AcpMessageDecoder, type AcpTransport, type AgentCard, AgentManifestEntry, AgentRunner, AgentRunnerBuilder, type AgentRunnerRunOptions, type BuildAgentCardOptions, type CompactionCallOptions, type CompactionStrategyConfig, CompiledAgentOptions, CompiledTool, type CostGuardOptions, DEFAULT_KEEP_TOKENS, DelegationResult, Guardrail, LoopStrategy, MCP_PROTOCOL_VERSION, type McpJsonSchema, type McpServerInfo, type McpToolDescriptor, type OutputModerationOptions, type PiiOptions, type PromptInjectionOptions, ReasoningEffort, ReflectionStrategy, RoundStreamFactory, StreamEvent, type Summarize, type TranscriptCompactionStrategy, buildAgentCard, buildMcpToolDescriptors, compactionStrategyConfigSchema, costGuard, createA2ATool, deriveConversationId, encodeAcpMessage, estimateTokens, mcpServerInfo, moderateOutputStream, outputModeration, parseConversationId, piiDetector, promptInjectionDetector, resolveCompactionStrategy, runInputGuards, runOutputGuards, tokenBudgetCompactionStrategy, unicodeNormalizer, wellKnownCardPath };
661
+ export { type A2AAuth, type A2ACapabilities, type A2ASkill, type A2AToolConfig, AcpClient, AcpMessageDecoder, type AcpTransport, type AgentCard, AgentManifestEntry, AgentRunner, AgentRunnerBuilder, type AgentRunnerRunOptions, type BuildAgentCardOptions, type Capability, CapabilityConflictError, CapabilityPreset, CapabilityRegistry, type CompactionCallOptions, type CompactionStrategyConfig, CompiledAgentOptions, type CompiledAgentOptionsDraft, CompiledTool, ConfigurationError, type CostGuardOptions, DEFAULT_KEEP_TOKENS, DelegationResult, type FinalizedDraft, Guardrail, LoopStrategy, MCP_PROTOCOL_VERSION, type McpJsonSchema, type McpServerInfo, type McpToolDescriptor, ModelCapability, type OutputModerationOptions, type PiiOptions, type PromptInjectionOptions, type ProvenanceEntry, ReasoningEffort, ReflectionStrategy, RoundStreamFactory, StreamEvent, type Summarize, ToolsCapability, type TranscriptCompactionStrategy, UnknownCapabilityError, applyCapabilities, buildAgentCard, buildMcpToolDescriptors, compactionStrategyConfigSchema, costGuard, createA2ATool, createDraft, deriveConversationId, encodeAcpMessage, estimateTokens, mcpServerInfo, moderateOutputStream, outputModeration, parseConversationId, piiDetector, promptInjectionDetector, resolveCompactionStrategy, runInputGuards, runOutputGuards, setOnce, skills, tokenBudgetCompactionStrategy, unicodeNormalizer, wellKnownCardPath };
package/dist/index.js CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  compileContextWindow,
21
21
  compileProjectContext,
22
22
  compileSkills,
23
+ compileSkillsSelection,
23
24
  compileTools,
24
25
  contextualTool,
25
26
  costGuard,
@@ -52,6 +53,7 @@ import {
52
53
  noopReflectionStrategy,
53
54
  outputModeration,
54
55
  piiDetector,
56
+ presentUIMessageStream,
55
57
  projectContextMetadataOnlyKnobs,
56
58
  promptInjectionDetector,
57
59
  reflectionStrategyConfigSchema,
@@ -66,16 +68,234 @@ import {
66
68
  toAgentFactory,
67
69
  tokenBudgetCompactionStrategy,
68
70
  translateSdkEvent,
69
- translateToUIMessageStream,
70
71
  unicodeNormalizer,
71
72
  validateUniqueRoutes,
72
73
  walkAgentMetadata
73
- } from "./chunk-XRPFOFYF.js";
74
+ } from "./chunk-FEH7JFH7.js";
74
75
  import "./chunk-NERDIS45.js";
75
76
  import {
76
77
  __name
77
78
  } from "./chunk-7QVYU63E.js";
78
79
 
80
+ // src/capability/capability.ts
81
+ import { isDeepStrictEqual } from "util";
82
+ var CapabilityConflictError = class extends Error {
83
+ static {
84
+ __name(this, "CapabilityConflictError");
85
+ }
86
+ name = "CapabilityConflictError";
87
+ constructor(field, previous, next, capability) {
88
+ super(
89
+ // NUNCA ecoa os valores: um draft montado a partir de arquivo de config pode carregar
90
+ // token de MCP, header de auth, credencial de memória. Reporta a FORMA, como a validação
91
+ // de fronteira das capabilities já faz.
92
+ `capability "${capability}": campo "${field}" j\xE1 declarado (${shapeOf(previous)}) e redeclarado com valor diferente (${shapeOf(next)}) \u2014 declare uma vez s\xF3.`
93
+ );
94
+ }
95
+ };
96
+ function shapeOf(value) {
97
+ if (value === null) return "null";
98
+ if (Array.isArray(value)) return `array(${value.length})`;
99
+ if (typeof value === "object") {
100
+ return `object{${Object.keys(value).sort((a, b) => a.localeCompare(b)).join(",")}}`;
101
+ }
102
+ return typeof value;
103
+ }
104
+ __name(shapeOf, "shapeOf");
105
+ function createDraft() {
106
+ return {
107
+ tools: [],
108
+ agents: {},
109
+ provenance: []
110
+ };
111
+ }
112
+ __name(createDraft, "createDraft");
113
+ function applyCapabilities(capabilities, draft = createDraft()) {
114
+ for (const c of capabilities) c.apply(draft);
115
+ draft.stream ??= true;
116
+ return draft;
117
+ }
118
+ __name(applyCapabilities, "applyCapabilities");
119
+ function setOnce(draft, field, value, capability) {
120
+ if (value === void 0) return;
121
+ const previous = draft[field];
122
+ if (previous !== void 0 && !isDeepStrictEqual(previous, value)) {
123
+ throw new CapabilityConflictError(field, previous, value, capability);
124
+ }
125
+ draft[field] = value;
126
+ draft.provenance.push({
127
+ capability,
128
+ contributed: [
129
+ field
130
+ ]
131
+ });
132
+ }
133
+ __name(setOnce, "setOnce");
134
+
135
+ // src/capability/capabilities.ts
136
+ var ConfigurationError = class extends Error {
137
+ static {
138
+ __name(this, "ConfigurationError");
139
+ }
140
+ name = "ConfigurationError";
141
+ };
142
+ function describe(value) {
143
+ if (value === null) return "null";
144
+ return Array.isArray(value) ? "array" : typeof value;
145
+ }
146
+ __name(describe, "describe");
147
+ var ModelCapability = class {
148
+ static {
149
+ __name(this, "ModelCapability");
150
+ }
151
+ id;
152
+ reasoningEffort;
153
+ name = "model";
154
+ constructor(id, reasoningEffort) {
155
+ this.id = id;
156
+ this.reasoningEffort = reasoningEffort;
157
+ if (typeof id !== "string") {
158
+ throw new ConfigurationError(`model: esperava string, recebi ${describe(id)}`);
159
+ }
160
+ if (id.trim().length === 0) throw new ConfigurationError("model: id n\xE3o pode ser vazio");
161
+ }
162
+ apply(draft) {
163
+ setOnce(draft, "model", this.id, this.name);
164
+ if (this.reasoningEffort !== void 0) {
165
+ setOnce(draft, "reasoningEffort", this.reasoningEffort, this.name);
166
+ }
167
+ }
168
+ };
169
+ var ToolsCapability = class {
170
+ static {
171
+ __name(this, "ToolsCapability");
172
+ }
173
+ name = "tools";
174
+ #tools;
175
+ constructor(tools) {
176
+ this.#tools = tools;
177
+ }
178
+ apply(draft) {
179
+ draft.tools.push(...this.#tools);
180
+ draft.provenance.push({
181
+ capability: this.name,
182
+ contributed: [
183
+ "tools"
184
+ ]
185
+ });
186
+ }
187
+ };
188
+ var skills = /* @__PURE__ */ __name((entries) => {
189
+ if (!Array.isArray(entries)) {
190
+ throw new ConfigurationError(`skills: esperava array de nomes, recebi ${describe(entries)}`);
191
+ }
192
+ for (const e of entries) {
193
+ if (typeof e === "string") {
194
+ if (e.trim().length === 0) {
195
+ throw new ConfigurationError("skills: nome vazio \u2014 use um nome de skill n\xE3o vazio");
196
+ }
197
+ continue;
198
+ }
199
+ if (typeof e !== "object" || e === null || Array.isArray(e)) {
200
+ throw new ConfigurationError(`skills: entrada inv\xE1lida (${describe(e)}) \u2014 use um nome ou um skill inline`);
201
+ }
202
+ for (const field of [
203
+ "name",
204
+ "description",
205
+ "instructions"
206
+ ]) {
207
+ const value = e[field];
208
+ if (typeof value !== "string" || value.trim().length === 0) {
209
+ throw new ConfigurationError(`skills: skill inline sem \`${field}\` v\xE1lido (${describe(value)}) \u2014 name, description e instructions s\xE3o obrigat\xF3rios`);
210
+ }
211
+ }
212
+ }
213
+ return {
214
+ name: "skills",
215
+ apply: /* @__PURE__ */ __name((draft) => {
216
+ const compiled = compileSkillsSelection([
217
+ ...entries
218
+ ]);
219
+ if (compiled.skills === void 0) return;
220
+ const previous = draft.skills;
221
+ draft.skills = previous === void 0 ? compiled.skills : {
222
+ // The spread is exhaustive only because `compileSkillsSelection` emits a FIXED 3-key
223
+ // shape (`enabled`, `autoInject: true`, and `inline` iff non-empty) — `enabled` and
224
+ // `inline` are both re-derived below, and `autoInject` is the same literal on both
225
+ // sides. TRAP for the future: if a capability ever authors `autoInject: false`, this
226
+ // spread would silently normalize it back to `true`. Unreachable today (no capability
227
+ // and no reference array form can express it) — revisit when one can.
228
+ ...previous,
229
+ ...compiled.skills,
230
+ enabled: [
231
+ ...previous.enabled ?? [],
232
+ ...compiled.skills.enabled ?? []
233
+ ],
234
+ ...previous.inline !== void 0 || compiled.skills.inline !== void 0 ? {
235
+ inline: [
236
+ ...previous.inline ?? [],
237
+ ...compiled.skills.inline ?? []
238
+ ]
239
+ } : {}
240
+ };
241
+ draft.provenance.push({
242
+ capability: "skills",
243
+ contributed: [
244
+ "skills"
245
+ ]
246
+ });
247
+ }, "apply")
248
+ };
249
+ }, "skills");
250
+
251
+ // src/capability/registry.ts
252
+ var UnknownCapabilityError = class extends Error {
253
+ static {
254
+ __name(this, "UnknownCapabilityError");
255
+ }
256
+ name = "UnknownCapabilityError";
257
+ constructor(requested, known) {
258
+ super(`capability "${requested}" n\xE3o registrada. Conhecidas: ${known.join(", ") || "(nenhuma)"}.`);
259
+ }
260
+ };
261
+ var CapabilityRegistry = class {
262
+ static {
263
+ __name(this, "CapabilityRegistry");
264
+ }
265
+ #factories = /* @__PURE__ */ new Map();
266
+ register(name, factory) {
267
+ this.#factories.set(name, factory);
268
+ return this;
269
+ }
270
+ has(name) {
271
+ return this.#factories.has(name);
272
+ }
273
+ names() {
274
+ return [
275
+ ...this.#factories.keys()
276
+ ];
277
+ }
278
+ resolve(name, arg) {
279
+ const factory = this.#factories.get(name);
280
+ if (factory === void 0) throw new UnknownCapabilityError(name, this.names());
281
+ return factory(arg);
282
+ }
283
+ };
284
+ var CapabilityPreset = class {
285
+ static {
286
+ __name(this, "CapabilityPreset");
287
+ }
288
+ name;
289
+ #members;
290
+ constructor(name, members) {
291
+ this.name = name;
292
+ this.#members = members;
293
+ }
294
+ apply(draft) {
295
+ for (const member of this.#members) member.apply(draft);
296
+ }
297
+ };
298
+
79
299
  // src/a2a/agent-card.ts
80
300
  function trimTrailingSlash(url) {
81
301
  return url.endsWith("/") ? url.slice(0, -1) : url;
@@ -352,14 +572,22 @@ export {
352
572
  AgentRunnerBuilder,
353
573
  AgentWarningCode,
354
574
  BudgetExceededError,
575
+ CapabilityConflictError,
576
+ CapabilityPreset,
577
+ CapabilityRegistry,
578
+ ConfigurationError,
355
579
  CostBudgetExceededError,
356
580
  DEFAULT_KEEP_TOKENS,
357
581
  DEFAULT_MAX_ITERATIONS,
358
582
  DelegationError,
359
583
  GuardrailViolationError,
360
584
  MCP_PROTOCOL_VERSION,
585
+ ModelCapability,
586
+ ToolsCapability,
587
+ UnknownCapabilityError,
361
588
  agent,
362
589
  agentsPlugin,
590
+ applyCapabilities,
363
591
  buildAgentCard,
364
592
  buildMcpToolDescriptors,
365
593
  buildModelSelection,
@@ -376,6 +604,7 @@ export {
376
604
  createA2ATool,
377
605
  createAgentExecutionContext,
378
606
  createApiErrorHandler,
607
+ createDraft,
379
608
  createSdkAgentStream,
380
609
  createThinkTagExtractor,
381
610
  createToolHooksPlugin,
@@ -407,6 +636,7 @@ export {
407
636
  outputModeration,
408
637
  parseConversationId,
409
638
  piiDetector,
639
+ presentUIMessageStream,
410
640
  projectContextMetadataOnlyKnobs,
411
641
  promptInjectionDetector,
412
642
  reflectionStrategyConfigSchema,
@@ -417,12 +647,13 @@ export {
417
647
  runInputGuards,
418
648
  runOutputGuards,
419
649
  runWithApiErrorHandling,
650
+ setOnce,
651
+ skills,
420
652
  streamAgentResponse,
421
653
  streamAgentUIMessages,
422
654
  toAgentFactory,
423
655
  tokenBudgetCompactionStrategy,
424
656
  translateSdkEvent,
425
- translateToUIMessageStream,
426
657
  unicodeNormalizer,
427
658
  validateUniqueRoutes,
428
659
  walkAgentMetadata,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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"],"sourcesContent":["/**\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 = 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 return [...resolved]\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 : '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,MAAMlB,QAAQiB,MAAMjB,OAAO,CAAA;UAC1Dc,OAAMR,QAAQN,QAAQmB,MAAM;AACjC;IACF;AACA,QAAI/B,gBAAgBY,OAAAA,GAAU;AAC5B,WAAK,KAAKoB,oBAAoBpB,OAAAA;IAChC;EACF;EAEA,MAAcoB,oBAAoBC,KAA0C;AAC1E,UAAMR,UAAU,KAAKnB,SAASqB,IAAIM,IAAIhC,MAAM;AAC5C,QAAI,CAACwB,SAAS;AACZ,WAAKhB,UAAUY,KACbC,iBAAiB;QAAEC,SAAS;QAAOxB,IAAIkC,IAAIlC;QAAI8B,OAAO;UAAEK,MAAM;UAAQtB,SAAS,eAAeqB,IAAIhC,MAAM;QAAG;MAAE,CAAA,CAAA;AAE/G;IACF;AACA,QAAI;AACF,YAAM8B,SAAS,MAAMN,QAAQQ,IAAIjB,MAAM;AACvC,WAAKP,UAAUY,KAAKC,iBAAiB;QAAEC,SAAS;QAAOxB,IAAIkC,IAAIlC;QAAIgC;MAAO,CAAA,CAAA;IAC5E,SAASI,KAAK;AACZ,WAAK1B,UAAUY,KACbC,iBAAiB;QACfC,SAAS;QACTxB,IAAIkC,IAAIlC;QACR8B,OAAO;UAAEK,MAAM;UAAQtB,SAASuB,eAAeL,QAAQK,IAAIvB,UAAU;QAAiB;MACxF,CAAA,CAAA;IAEJ;EACF;AACF;","names":["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","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"]}
1
+ {"version":3,"sources":["../src/capability/capability.ts","../src/capability/capabilities.ts","../src/capability/registry.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"],"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'\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/** Typed authoring failure — surfaced at build time, never a silent bad agent. */\nexport class ConfigurationError extends Error {\n override readonly name = 'ConfigurationError'\n}\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. FUNCTION, not class: it carries no behavior beyond assignment — a class here\n * would be ceremony (the honest counter-example to \"everything must be a class\").\n */\nexport const skills = (entries: readonly (string | InlineSkill)[]): Capability => {\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 return {\n name: 'skills',\n apply: (draft) => {\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([...entries])\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: 'skills', contributed: ['skills'] })\n },\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","/**\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 = 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 return [...resolved]\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"],"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;A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AACvD,QAAIf,WAAWe,OAAAA,GAAU;AACvB,YAAMc,QAAQ,KAAKtB,QAAQuB,IAAIf,QAAQb,EAAE;AACzC,UAAI,CAAC2B,MAAO;AACZ,WAAKtB,QAAQwB,OAAOhB,QAAQb,EAAE;AAC9B,UAAIa,QAAQiB,MAAOH,OAAMP,OAAO,IAAIW,MAAMlB,QAAQiB,MAAMjB,OAAO,CAAA;UAC1Dc,OAAMR,QAAQN,QAAQmB,MAAM;AACjC;IACF;AACA,QAAI/B,gBAAgBY,OAAAA,GAAU;AAC5B,WAAK,KAAKoB,oBAAoBpB,OAAAA;IAChC;EACF;EAEA,MAAcoB,oBAAoBC,KAA0C;AAC1E,UAAMR,UAAU,KAAKnB,SAASqB,IAAIM,IAAIhC,MAAM;AAC5C,QAAI,CAACwB,SAAS;AACZ,WAAKhB,UAAUY,KACbC,iBAAiB;QAAEC,SAAS;QAAOxB,IAAIkC,IAAIlC;QAAI8B,OAAO;UAAEK,MAAM;UAAQtB,SAAS,eAAeqB,IAAIhC,MAAM;QAAG;MAAE,CAAA,CAAA;AAE/G;IACF;AACA,QAAI;AACF,YAAM8B,SAAS,MAAMN,QAAQQ,IAAIjB,MAAM;AACvC,WAAKP,UAAUY,KAAKC,iBAAiB;QAAEC,SAAS;QAAOxB,IAAIkC,IAAIlC;QAAIgC;MAAO,CAAA,CAAA;IAC5E,SAASI,KAAK;AACZ,WAAK1B,UAAUY,KACbC,iBAAiB;QACfC,SAAS;QACTxB,IAAIkC,IAAIlC;QACR8B,OAAO;UAAEK,MAAM;UAAQtB,SAASuB,eAAeL,QAAQK,IAAIvB,UAAU;QAAiB;MACxF,CAAA,CAAA;IAEJ;EACF;AACF;","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","ConfigurationError","Error","name","describe","value","Array","isArray","ModelCapability","id","reasoningEffort","trim","length","apply","draft","setOnce","undefined","ToolsCapability","tools","push","provenance","capability","contributed","skills","entries","e","field","compiled","compileSkillsSelection","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","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","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"]}