@theokit/agents 4.5.0 → 4.7.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/auth.d.ts +1 -1
- package/dist/auth.js +10 -1
- package/dist/auth.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/package.json +10 -10
- package/LICENSE +0 -201
package/dist/auth.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OAuthProviderConfig, CredentialStoreConfig, ResolvedCredential, ensureFreshCredential, OpenAIDeviceConfig, openaiDeviceLogin, OAuthTokens } from '@theokit/sdk/auth';
|
|
2
|
-
export { CredentialStoreConfig, DeviceDeps, OAuthProviderConfig, OAuthTokens, OpenAIDeviceConfig, ResolvedCredential } from '@theokit/sdk/auth';
|
|
2
|
+
export { CredentialError, CredentialStoreConfig, DeviceDeps, OAuthProviderConfig, OAuthTokens, OpenAIDeviceConfig, ResolveCredentialOptions, ResolvedCredential, authFilePath, credentialHome, readAuthFile, readStoredOAuth, writeCredential } from '@theokit/sdk/auth';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* M60 — `AuthProvider`, the OO contract that unifies the SDK's free OAuth-lifecycle functions
|
package/dist/auth.js
CHANGED
|
@@ -42,7 +42,16 @@ var AuthProvider = class {
|
|
|
42
42
|
return persistOAuthTokens(provider, tokens, this.store, env);
|
|
43
43
|
}
|
|
44
44
|
};
|
|
45
|
+
|
|
46
|
+
// src/auth-entry.ts
|
|
47
|
+
import { authFilePath, CredentialError, credentialHome, readAuthFile, readStoredOAuth, writeCredential } from "@theokit/sdk/auth";
|
|
45
48
|
export {
|
|
46
|
-
AuthProvider
|
|
49
|
+
AuthProvider,
|
|
50
|
+
CredentialError,
|
|
51
|
+
authFilePath,
|
|
52
|
+
credentialHome,
|
|
53
|
+
readAuthFile,
|
|
54
|
+
readStoredOAuth,
|
|
55
|
+
writeCredential
|
|
47
56
|
};
|
|
48
57
|
//# sourceMappingURL=auth.js.map
|
package/dist/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/auth-provider.ts"],"sourcesContent":["import { ensureFreshCredential, openaiDeviceLogin, persistOAuthTokens } from '@theokit/sdk/auth'\nimport type {\n CredentialStoreConfig,\n OAuthProviderConfig,\n OAuthTokens,\n OpenAIDeviceConfig,\n ResolvedCredential,\n} from '@theokit/sdk/auth'\n\n/**\n * M60 — `AuthProvider`, the OO contract that unifies the SDK's free OAuth-lifecycle functions\n * (`openaiDeviceLogin` → `persistOAuthTokens` → `ensureFreshCredential`). Those are stateful across a\n * SHARED `config` (`OAuthProviderConfig`) + `store` (`CredentialStoreConfig`); this class holds that\n * state so a consumer authors `new AuthProvider(config, store).persist(...)` / `.ensureFresh(...)`\n * instead of threading `config`/`store` through every call — the `SDK → Theokit → AgentBuilder`\n * boundary applied to the auth domain (ENRICH, per blueprint D2: auth carries orchestration + state).\n *\n * It DELEGATES, never reimplements (parsimony Rung 9): each method forwards verbatim to the SDK\n * function, so login → persist → refresh produces byte-identical state to calling the SDK directly.\n *\n * SECRET-SAFETY (hard rule): this class NEVER logs, stringifies, or otherwise surfaces token material.\n * Methods return exactly what the SDK returns and add no observability — a token is data that flows\n * through, never something this layer emits. The parity/secret tests pin both properties.\n */\n\n/** The HTTP deps of `ensureFreshCredential` (`{ fetch, now }`) — typed off the SDK to avoid drift. */\ntype EnsureFreshHttpDeps = Parameters<typeof ensureFreshCredential>[2]\n/** The device-flow deps + prompt hook of `openaiDeviceLogin` — typed off the SDK. */\ntype DeviceLoginDeps = Parameters<typeof openaiDeviceLogin>[1]\ntype DeviceLoginHooks = Parameters<typeof openaiDeviceLogin>[2]\n\nexport class AuthProvider {\n constructor(\n private readonly config: OAuthProviderConfig,\n private readonly store: CredentialStoreConfig,\n ) {}\n\n /**\n * Refresh a resolved credential if stale. Delegates to `ensureFreshCredential` with the held\n * `config` + `store`; `env` (for reading the store's env overrides) + the `{ fetch, now }` HTTP deps\n * thread through. Returns the fresh `ResolvedCredential` — never logs the rotated token.\n */\n ensureFresh(\n resolved: ResolvedCredential,\n deps: EnsureFreshHttpDeps,\n env?: Record<string, string | undefined>,\n ): Promise<ResolvedCredential> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- `CredentialStoreConfig` (SDK `/auth` subpath) resolves under tsc (root typecheck is clean) but eslint's type-aware project reads `this.store` as error-typed; the assignment is type-safe per tsc.\n return ensureFreshCredential(resolved, { config: this.config, store: this.store, env }, deps)\n }\n\n /**\n * Run the headless OpenAI device-login flow. Delegates to `openaiDeviceLogin` (which JWT-extracts the\n * account id). `deviceConfig` is passed per-call because it is a distinct endpoint set from the\n * refresh `config`. Returns `OAuthTokens` — the caller persists them via {@link AuthProvider.persist}.\n */\n deviceLogin(\n deviceConfig: OpenAIDeviceConfig,\n deps: DeviceLoginDeps,\n hooks: DeviceLoginHooks,\n ): Promise<OAuthTokens> {\n return openaiDeviceLogin(deviceConfig, deps, hooks)\n }\n\n /**\n * Persist freshly-obtained tokens through the held `store`. Delegates to `persistOAuthTokens` and\n * returns the credential-file path (never the token). `env` selects the store's home override.\n */\n persist(provider: string, tokens: OAuthTokens, env?: Record<string, string | undefined>): string {\n return persistOAuthTokens(provider, tokens, this.store, env)\n }\n}\n"],"mappings":";;;;;AAAA,SAASA,uBAAuBC,mBAAmBC,0BAA0B;AA+BtE,IAAMC,eAAN,MAAMA;EA/Bb,OA+BaA;;;;;EACX,YACmBC,QACAC,OACjB;SAFiBD,SAAAA;SACAC,QAAAA;EAChB;;;;;;EAOHC,YACEC,UACAC,MACAC,KAC6B;AAE7B,WAAOC,sBAAsBH,UAAU;MAAEH,QAAQ,KAAKA;MAAQC,OAAO,KAAKA;MAAOI;IAAI,GAAGD,IAAAA;EAC1F;;;;;;EAOAG,YACEC,cACAJ,MACAK,OACsB;AACtB,WAAOC,kBAAkBF,cAAcJ,MAAMK,KAAAA;EAC/C;;;;;EAMAE,QAAQC,UAAkBC,QAAqBR,KAAkD;AAC/F,WAAOS,mBAAmBF,UAAUC,QAAQ,KAAKZ,OAAOI,GAAAA;EAC1D;AACF;","names":["ensureFreshCredential","openaiDeviceLogin","persistOAuthTokens","AuthProvider","config","store","ensureFresh","resolved","deps","env","ensureFreshCredential","deviceLogin","deviceConfig","hooks","openaiDeviceLogin","persist","provider","tokens","persistOAuthTokens"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/auth-provider.ts","../src/auth-entry.ts"],"sourcesContent":["import { ensureFreshCredential, openaiDeviceLogin, persistOAuthTokens } from '@theokit/sdk/auth'\nimport type {\n CredentialStoreConfig,\n OAuthProviderConfig,\n OAuthTokens,\n OpenAIDeviceConfig,\n ResolvedCredential,\n} from '@theokit/sdk/auth'\n\n/**\n * M60 — `AuthProvider`, the OO contract that unifies the SDK's free OAuth-lifecycle functions\n * (`openaiDeviceLogin` → `persistOAuthTokens` → `ensureFreshCredential`). Those are stateful across a\n * SHARED `config` (`OAuthProviderConfig`) + `store` (`CredentialStoreConfig`); this class holds that\n * state so a consumer authors `new AuthProvider(config, store).persist(...)` / `.ensureFresh(...)`\n * instead of threading `config`/`store` through every call — the `SDK → Theokit → AgentBuilder`\n * boundary applied to the auth domain (ENRICH, per blueprint D2: auth carries orchestration + state).\n *\n * It DELEGATES, never reimplements (parsimony Rung 9): each method forwards verbatim to the SDK\n * function, so login → persist → refresh produces byte-identical state to calling the SDK directly.\n *\n * SECRET-SAFETY (hard rule): this class NEVER logs, stringifies, or otherwise surfaces token material.\n * Methods return exactly what the SDK returns and add no observability — a token is data that flows\n * through, never something this layer emits. The parity/secret tests pin both properties.\n */\n\n/** The HTTP deps of `ensureFreshCredential` (`{ fetch, now }`) — typed off the SDK to avoid drift. */\ntype EnsureFreshHttpDeps = Parameters<typeof ensureFreshCredential>[2]\n/** The device-flow deps + prompt hook of `openaiDeviceLogin` — typed off the SDK. */\ntype DeviceLoginDeps = Parameters<typeof openaiDeviceLogin>[1]\ntype DeviceLoginHooks = Parameters<typeof openaiDeviceLogin>[2]\n\nexport class AuthProvider {\n constructor(\n private readonly config: OAuthProviderConfig,\n private readonly store: CredentialStoreConfig,\n ) {}\n\n /**\n * Refresh a resolved credential if stale. Delegates to `ensureFreshCredential` with the held\n * `config` + `store`; `env` (for reading the store's env overrides) + the `{ fetch, now }` HTTP deps\n * thread through. Returns the fresh `ResolvedCredential` — never logs the rotated token.\n */\n ensureFresh(\n resolved: ResolvedCredential,\n deps: EnsureFreshHttpDeps,\n env?: Record<string, string | undefined>,\n ): Promise<ResolvedCredential> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- `CredentialStoreConfig` (SDK `/auth` subpath) resolves under tsc (root typecheck is clean) but eslint's type-aware project reads `this.store` as error-typed; the assignment is type-safe per tsc.\n return ensureFreshCredential(resolved, { config: this.config, store: this.store, env }, deps)\n }\n\n /**\n * Run the headless OpenAI device-login flow. Delegates to `openaiDeviceLogin` (which JWT-extracts the\n * account id). `deviceConfig` is passed per-call because it is a distinct endpoint set from the\n * refresh `config`. Returns `OAuthTokens` — the caller persists them via {@link AuthProvider.persist}.\n */\n deviceLogin(\n deviceConfig: OpenAIDeviceConfig,\n deps: DeviceLoginDeps,\n hooks: DeviceLoginHooks,\n ): Promise<OAuthTokens> {\n return openaiDeviceLogin(deviceConfig, deps, hooks)\n }\n\n /**\n * Persist freshly-obtained tokens through the held `store`. Delegates to `persistOAuthTokens` and\n * returns the credential-file path (never the token). `env` selects the store's home override.\n */\n persist(provider: string, tokens: OAuthTokens, env?: Record<string, string | undefined>): string {\n return persistOAuthTokens(provider, tokens, this.store, env)\n }\n}\n","// M60 — `@theokit/agents/auth`: the OO auth contract. `AuthProvider` (ENRICH — it holds the shared\n// `config`+`store` state and delegates to the SDK's free OAuth-lifecycle functions), plus the auth\n// domain's types re-exported so a consumer types the whole surface from the Theokit layer, never\n// reaching back to `@theokit/sdk/auth`.\nexport { AuthProvider } from './auth/auth-provider.js'\n\n// M73 — \"enriquecer nunca reduz\". A mecânica de store do SDK atravessa como PASS-THROUGH PURO.\n//\n// Antes disto, este subpath exportava 1 valor e 6 tipos enquanto `@theokit/sdk/auth` exportava 19\n// símbolos: nenhuma função atravessava. Como o consumidor tem regra INQUEBRÁVEL de nunca importar\n// `@theokit/sdk*` direto, **reimplementar era a única saída legal** — e o agent-builder reescreveu\n// seis destes nomes, ~120 linhas de mecânica duplicada. A lacuna era daqui, não indisciplina de lá.\n//\n// PURO, e não wrapper (parsimony Rung 9): estas são funções de I/O sem estado a segurar. A camada\n// enriquece onde há orquestração — é o que `AuthProvider` faz com o par `config`+`store`. Envolver\n// isto acrescentaria indireção sem nada dentro, e **quebraria `instanceof`**: o consumidor faz\n// `err instanceof CredentialError`, o que só vale enquanto a classe for a MESMA referência do SDK.\n// `tests/unit/auth-parity.test.ts` trava essa identidade com `toBe`.\n//\n// `resolveCredential` NÃO atravessa, de propósito: o SDK e o agent-builder têm funções DIFERENTES com\n// esse nome (sync vs async, lança vs `undefined`, lê env vs não lê, infere provider vs recusa), e o\n// próprio SDK declara que a precedência de env, a inferência por prefixo e o provider declarado são\n// app policy do consumidor (`internal/auth/credential-store.ts`). Expor os dois no mesmo escopo seria\n// convite a importar o errado, com falha silenciosa.\nexport {\n authFilePath,\n CredentialError,\n credentialHome,\n readAuthFile,\n readStoredOAuth,\n writeCredential,\n} from '@theokit/sdk/auth'\nexport type { ResolveCredentialOptions } from '@theokit/sdk/auth'\nexport type {\n CredentialStoreConfig,\n DeviceDeps,\n OAuthProviderConfig,\n OAuthTokens,\n OpenAIDeviceConfig,\n ResolvedCredential,\n} from '@theokit/sdk/auth'\n"],"mappings":";;;;;AAAA,SAASA,uBAAuBC,mBAAmBC,0BAA0B;AA+BtE,IAAMC,eAAN,MAAMA;EA/Bb,OA+BaA;;;;;EACX,YACmBC,QACAC,OACjB;SAFiBD,SAAAA;SACAC,QAAAA;EAChB;;;;;;EAOHC,YACEC,UACAC,MACAC,KAC6B;AAE7B,WAAOC,sBAAsBH,UAAU;MAAEH,QAAQ,KAAKA;MAAQC,OAAO,KAAKA;MAAOI;IAAI,GAAGD,IAAAA;EAC1F;;;;;;EAOAG,YACEC,cACAJ,MACAK,OACsB;AACtB,WAAOC,kBAAkBF,cAAcJ,MAAMK,KAAAA;EAC/C;;;;;EAMAE,QAAQC,UAAkBC,QAAqBR,KAAkD;AAC/F,WAAOS,mBAAmBF,UAAUC,QAAQ,KAAKZ,OAAOI,GAAAA;EAC1D;AACF;;;AC/CA,SACEU,cACAC,iBACAC,gBACAC,cACAC,iBACAC,uBACK;","names":["ensureFreshCredential","openaiDeviceLogin","persistOAuthTokens","AuthProvider","config","store","ensureFresh","resolved","deps","env","ensureFreshCredential","deviceLogin","deviceConfig","hooks","openaiDeviceLogin","persist","provider","tokens","persistOAuthTokens","authFilePath","CredentialError","credentialHome","readAuthFile","readStoredOAuth","writeCredential"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ import { RetryOptions } from '@theokit/sdk/retry';
|
|
|
7
7
|
import { CompressibleMessage } from '@theokit/sdk/compaction';
|
|
8
8
|
export { CompressibleMessage } from '@theokit/sdk/compaction';
|
|
9
9
|
import { z } from 'zod';
|
|
10
|
+
export { SubAgent } from '@theokit/sdk/a2a';
|
|
11
|
+
export { assertNoSymlinkEscape, isForbiddenPath, safePathJoin } from '@theokit/sdk/path-safety';
|
|
10
12
|
import '@theokit/http';
|
|
11
13
|
import 'ai';
|
|
12
14
|
|
package/dist/index.js
CHANGED
|
@@ -863,6 +863,8 @@ var AcpClient = class {
|
|
|
863
863
|
|
|
864
864
|
// src/index.ts
|
|
865
865
|
import { Agent, Squad, Tool, Provider } from "@theokit/sdk";
|
|
866
|
+
import { SubAgent } from "@theokit/sdk/a2a";
|
|
867
|
+
import { assertNoSymlinkEscape, isForbiddenPath, safePathJoin } from "@theokit/sdk/path-safety";
|
|
866
868
|
export {
|
|
867
869
|
AGENT_BRAND,
|
|
868
870
|
AcpClient,
|
|
@@ -904,6 +906,7 @@ export {
|
|
|
904
906
|
SkillsOptionsCapability,
|
|
905
907
|
SkillsResolverCapability,
|
|
906
908
|
Squad,
|
|
909
|
+
SubAgent,
|
|
907
910
|
SubAgentsCapability,
|
|
908
911
|
Tool,
|
|
909
912
|
ToolboxCapability,
|
|
@@ -911,6 +914,7 @@ export {
|
|
|
911
914
|
UnknownCapabilityError,
|
|
912
915
|
agentsPlugin,
|
|
913
916
|
applyCapabilities,
|
|
917
|
+
assertNoSymlinkEscape,
|
|
914
918
|
buildAgentCard,
|
|
915
919
|
buildMcpToolDescriptors,
|
|
916
920
|
buildModelSelection,
|
|
@@ -943,6 +947,7 @@ export {
|
|
|
943
947
|
isApprovalRequired,
|
|
944
948
|
isDone,
|
|
945
949
|
isError,
|
|
950
|
+
isForbiddenPath,
|
|
946
951
|
isPartialToolCall,
|
|
947
952
|
isTextDelta,
|
|
948
953
|
isToolCall,
|
|
@@ -968,6 +973,7 @@ export {
|
|
|
968
973
|
runInputGuards,
|
|
969
974
|
runOutputGuards,
|
|
970
975
|
runWithApiErrorHandling,
|
|
976
|
+
safePathJoin,
|
|
971
977
|
setOnce,
|
|
972
978
|
streamAgentResponse,
|
|
973
979
|
streamAgentUIMessages,
|
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/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"],"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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,yBAAyB;AAqC3B,IAAMC,0BAAN,cAAsCC,MAAAA;EArC7C,OAqC6CA;;;EACzBC,OAAO;EACzB,YAAYC,OAAeC,UAAmBC,MAAeC,YAAoB;AAC/E;;;;MAIE,eAAeA,UAAAA,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AAAA;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;;;AC7DA,SAASwB,OAAOC,OAAOC,MAAMC,gBAAgB;","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","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"]}
|
|
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/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"],"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 * 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"],"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;IAAG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AK1B,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;;;AC7DA,SAASwB,OAAOC,OAAOC,MAAMC,gBAAgB;AAO7C,SAASC,gBAAgB;AACzB,SAASC,uBAAuBC,iBAAiBC,oBAAoB;","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","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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/agents",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.7.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,
|
|
@@ -49,6 +49,12 @@
|
|
|
49
49
|
"README.md",
|
|
50
50
|
"LICENSE"
|
|
51
51
|
],
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "tsup",
|
|
54
|
+
"test:live": "vitest run --config vitest.live.config.ts",
|
|
55
|
+
"test": "vitest run",
|
|
56
|
+
"test:watch": "vitest"
|
|
57
|
+
},
|
|
52
58
|
"peerDependencies": {
|
|
53
59
|
"@theokit/http": ">=0.1.0-alpha.0",
|
|
54
60
|
"@theokit/sdk": "^4.19.0",
|
|
@@ -69,6 +75,7 @@
|
|
|
69
75
|
}
|
|
70
76
|
},
|
|
71
77
|
"devDependencies": {
|
|
78
|
+
"@theokit/http": "workspace:*",
|
|
72
79
|
"@theokit/sdk": "^4.19.0",
|
|
73
80
|
"@theokit/sdk-pty": "^0.1.0",
|
|
74
81
|
"@theokit/sdk-tools": "^0.20.0",
|
|
@@ -77,16 +84,9 @@
|
|
|
77
84
|
"typescript": "^5.9.3",
|
|
78
85
|
"vitest": "^3.2.6",
|
|
79
86
|
"zod": "^4.4.3",
|
|
80
|
-
"@theokit/
|
|
81
|
-
"@theokit/presenter": "0.3.0"
|
|
87
|
+
"@theokit/presenter": "workspace:*"
|
|
82
88
|
},
|
|
83
89
|
"engines": {
|
|
84
90
|
"node": ">=22.12.0"
|
|
85
|
-
},
|
|
86
|
-
"scripts": {
|
|
87
|
-
"build": "tsup",
|
|
88
|
-
"test:live": "vitest run --config vitest.live.config.ts",
|
|
89
|
-
"test": "vitest run",
|
|
90
|
-
"test:watch": "vitest"
|
|
91
91
|
}
|
|
92
|
-
}
|
|
92
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
Apache License
|
|
2
|
-
Version 2.0, January 2004
|
|
3
|
-
http://www.apache.org/licenses/
|
|
4
|
-
|
|
5
|
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
-
|
|
7
|
-
1. Definitions.
|
|
8
|
-
|
|
9
|
-
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
-
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
-
|
|
12
|
-
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
-
the copyright owner that is granting the License.
|
|
14
|
-
|
|
15
|
-
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
-
other entities that control, are controlled by, or are under common
|
|
17
|
-
control with that entity. For the purposes of this definition,
|
|
18
|
-
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
-
direction or management of such entity, whether by contract or
|
|
20
|
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for describing the origin of the Work and
|
|
141
|
-
reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|
|
177
|
-
|
|
178
|
-
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
-
|
|
180
|
-
To apply the Apache License to your work, attach the following
|
|
181
|
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
-
replaced with your own identifying information. (Don't include
|
|
183
|
-
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
-
comment syntax for the file format. We also recommend that a
|
|
185
|
-
file or class name and description of purpose be included on the
|
|
186
|
-
same "printed page" as the copyright notice for easier
|
|
187
|
-
identification within third-party archives.
|
|
188
|
-
|
|
189
|
-
Copyright 2026 usetheo.dev
|
|
190
|
-
|
|
191
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
-
you may not use this file except in compliance with the License.
|
|
193
|
-
You may obtain a copy of the License at
|
|
194
|
-
|
|
195
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
-
|
|
197
|
-
Unless required by applicable law or agreed to in writing, software
|
|
198
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
-
See the License for the specific language governing permissions and
|
|
201
|
-
limitations under the License.
|