@theokit/agents 0.33.0 → 0.34.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/LICENSE +201 -0
- package/dist/{bridge-entry-BydskfrI.d.ts → bridge-entry-DG3jbXjs.d.ts} +13 -8
- package/dist/bridge.d.ts +2 -2
- package/dist/bridge.js +2 -4
- package/dist/{chunk-MD35WBR4.js → chunk-B24BAVE6.js} +164 -164
- package/dist/chunk-B24BAVE6.js.map +1 -0
- package/dist/{chunk-TXEY3IUO.js → chunk-IAE4FWBV.js} +28 -3
- package/dist/chunk-IAE4FWBV.js.map +1 -0
- package/dist/decorators.d.ts +2 -2
- package/dist/decorators.js +237 -29
- package/dist/decorators.js.map +1 -1
- package/dist/index.d.ts +4 -5
- package/dist/index.js +2 -121
- package/dist/index.js.map +1 -1
- package/dist/{types-S7k_lt1_.d.ts → types-DVA4LQsA.d.ts} +1 -1
- package/package.json +10 -14
- package/dist/chunk-GEV2EQW2.js +0 -265
- package/dist/chunk-GEV2EQW2.js.map +0 -1
- package/dist/chunk-MD35WBR4.js.map +0 -1
- package/dist/chunk-TXEY3IUO.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/a2a/agent-card.ts","../src/a2a/mcp-server-manifest.ts","../src/a2a/a2a-client.ts","../src/conversation-scope.ts","../src/skills-resolver.ts","../src/acp/protocol.ts","../src/acp/client.ts"],"sourcesContent":["/**\n * M15 (theokit-ai-first) — A2A agent card generation (ADR-0040 § D2, home/discovery concern).\n *\n * Produces an [A2A](https://github.com/google/A2A)-spec Agent Card from the framework's\n * `AgentManifestEntry`, so other systems can discover a TheoKit agent's capabilities over HTTP at\n * `/.well-known/<name>/agent-card.json`. Pure data transform — no LLM, no runtime (G2).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** A single capability exposed by an A2A agent (maps from a TheoKit tool). */\nexport interface A2ASkill {\n id: string\n name: string\n description: string\n}\n\n/** A2A agent-card capabilities block. */\nexport interface A2ACapabilities {\n streaming: boolean\n pushNotifications: boolean\n stateTransitionHistory: boolean\n}\n\n/** An A2A-spec Agent Card (the subset TheoKit advertises). */\nexport interface AgentCard {\n name: string\n description: string\n url: string\n version: string\n capabilities: A2ACapabilities\n defaultInputModes: string[]\n defaultOutputModes: string[]\n skills: A2ASkill[]\n}\n\nexport interface BuildAgentCardOptions {\n /** Absolute base URL of the deployment (e.g. `https://app.example.com`). A trailing slash is trimmed. */\n baseUrl: string\n /** Human description of the agent. Defaults to a generated sentence when omitted (spec requires non-empty). */\n description?: string\n}\n\n/** Strip a single trailing slash so `${baseUrl}${route}` never doubles the separator. */\nfunction trimTrailingSlash(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url\n}\n\n/** Build an A2A agent card from a manifest entry. */\nexport function buildAgentCard(entry: AgentManifestEntry, options: BuildAgentCardOptions): AgentCard {\n const base = trimTrailingSlash(options.baseUrl)\n return {\n name: entry.name,\n description: options.description ?? `TheoKit agent \"${entry.name}\".`,\n url: `${base}${entry.route}`,\n version: '1.0',\n capabilities: {\n streaming: entry.stream,\n pushNotifications: false,\n stateTransitionHistory: false,\n },\n defaultInputModes: ['text'],\n defaultOutputModes: ['text'],\n skills: entry.tools.map((t) => ({ id: t.name, name: t.name, description: t.description })),\n }\n}\n\n/** The A2A discovery path for an agent: `/.well-known/<name>/agent-card.json`. */\nexport function wellKnownCardPath(agentName: string): string {\n return `/.well-known/${agentName}/agent-card.json`\n}\n","/**\n * M16 (theokit-ai-first) — MCP server manifest generation (ADR-0040 § D2, home concern).\n *\n * Exposes a TheoKit agent's tools to external MCP clients as `tools/list` descriptors, so the app\n * can advertise its agents over its OWN HTTP routes. Pure data transform — no LLM, no runtime, and\n * NO stdio transport (that stays SDK-side per sdk-runtime.md). Serving these over `GET /mcp` and the\n * JSON-RPC envelope are follow-ups (mount path).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** The MCP protocol revision these descriptors target. */\nexport const MCP_PROTOCOL_VERSION = '2024-11-05'\n\n/** A JSON-schema object (the shape MCP expects for a tool's `inputSchema`). */\nexport interface McpJsonSchema {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n}\n\n/** An MCP `tools/list` tool descriptor. */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: McpJsonSchema\n}\n\n/** MCP `initialize` server info. */\nexport interface McpServerInfo {\n name: string\n version: string\n protocolVersion: string\n}\n\n/**\n * Map an agent's tools to MCP tool descriptors. The manifest tool carries name + description; the\n * per-tool JSON schema is not retained in the manifest, so a permissive empty-object schema is\n * emitted (MCP clients accept it and pass through arbitrary args). Wiring the real per-tool schema\n * is a follow-up once the manifest carries it.\n */\nexport function buildMcpToolDescriptors(entry: AgentManifestEntry): McpToolDescriptor[] {\n return entry.tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: { type: 'object', properties: {} },\n }))\n}\n\n/** Build the MCP `initialize` server-info block for an agent. */\nexport function mcpServerInfo(entry: AgentManifestEntry): McpServerInfo {\n return { name: entry.name, version: '1.0', protocolVersion: MCP_PROTOCOL_VERSION }\n}\n","/**\n * M15 (theokit-ai-first) — A2A client: call a remote A2A agent as a tool (ADR-0040 § D2).\n *\n * `createA2ATool` returns a `CustomTool` whose handler POSTs the input message to a remote agent's\n * HTTP endpoint and returns its text response — cross-network delegation. Uses `fetch` (Web\n * Standards, G8). The target is a remote AGENT endpoint, not an LLM provider, so the G2 grep guard\n * (`openrouter.ai|api.openai.com|api.anthropic.com`) is unaffected. `fetchImpl` is injectable for tests.\n */\nimport type { CustomTool } from '@theokit/sdk'\n\n/** How to authenticate to the remote agent. */\nexport interface A2AAuth {\n /** Bearer token → `Authorization: Bearer <token>`. */\n bearer?: string\n /** API-key header pair → `<name>: <value>` (e.g. `x-api-key`). */\n apiKey?: { header: string; value: string }\n}\n\nexport interface A2AToolConfig {\n /** Remote agent endpoint URL (POST target). */\n url: string\n /** Tool name the model calls. */\n name: string\n /** Tool description surfaced to the model. */\n description: string\n /** Static headers merged into every request. */\n headers?: Record<string, string>\n /** Auth applied to every request. */\n auth?: A2AAuth\n /** Injected fetch (defaults to the global). Narrowed to the call shape this client uses. */\n fetchImpl?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/** Build the request headers from static headers + auth. */\nfunction buildHeaders(config: A2AToolConfig): Record<string, string> {\n const headers: Record<string, string> = { 'content-type': 'application/json', ...config.headers }\n if (config.auth?.bearer) headers.authorization = `Bearer ${config.auth.bearer}`\n if (config.auth?.apiKey) headers[config.auth.apiKey.header] = config.auth.apiKey.value\n return headers\n}\n\n/**\n * Create a tool that delegates to a remote A2A agent. The remote is expected to answer a\n * `{ message }` POST with a JSON body carrying a `response` (or `text`) string.\n */\nexport function createA2ATool(config: A2AToolConfig): CustomTool {\n const doFetch = config.fetchImpl ?? fetch\n return {\n name: config.name,\n description: config.description,\n inputSchema: {\n type: 'object',\n properties: { message: { type: 'string', description: 'The message to send to the remote agent.' } },\n required: ['message'],\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n // The input schema requires `message: string`; narrow defensively (never base-to-string).\n const message = typeof input.message === 'string' ? input.message : ''\n const res = await doFetch(config.url, {\n method: 'POST',\n headers: buildHeaders(config),\n body: JSON.stringify({ message }),\n })\n if (!res.ok) {\n throw new Error(`A2A call to \"${config.name}\" failed: ${res.status} ${res.statusText}`)\n }\n const data = (await res.json()) as { response?: string; text?: string }\n return data.response ?? data.text ?? ''\n },\n }\n}\n","/**\n * M11 (theokit-ai-first) — {resource, thread} conversation scoping (ADR-0040 § D2, home concern).\n *\n * Maps a request's (resource, thread) pair to a deterministic, collision-safe conversation id so\n * multi-tenant apps isolate history without hand-building `user-${id}-thread-${id}` strings. This\n * is the app's request→conversation mapping — NOT the SDK's storage engine (which the derived id is\n * simply handed to). Background compression of long histories stays SDK-side.\n *\n * Encoding: each component is `encodeURIComponent`-escaped and joined with `/`. Since\n * `encodeURIComponent` escapes a raw `/` to `%2F`, the separator is unambiguous — `('a/b','c')` and\n * `('a','b/c')` derive DIFFERENT ids (collision-safe). Reversible via {@link parseConversationId}.\n */\n\nconst SEPARATOR = '/'\n\n/** Derive a deterministic conversation id from a (resource, thread) pair. Fails fast on empty input. */\nexport function deriveConversationId(resource: string, thread: string): string {\n if (!resource) throw new Error('[@theokit/agents] deriveConversationId: resource must be non-empty')\n if (!thread) throw new Error('[@theokit/agents] deriveConversationId: thread must be non-empty')\n return `${encodeURIComponent(resource)}${SEPARATOR}${encodeURIComponent(thread)}`\n}\n\n/**\n * Reverse a derived conversation id back to its (resource, thread). Returns `null` for a value that\n * is not a derived scope id (no separator, or an empty component) — callers treat that as \"opaque id,\n * not scoped\".\n */\nexport function parseConversationId(id: string): { resource: string; thread: string } | null {\n const idx = id.indexOf(SEPARATOR)\n if (idx <= 0 || idx >= id.length - 1) return null\n const resource = decodeURIComponent(id.slice(0, idx))\n const thread = decodeURIComponent(id.slice(idx + 1))\n if (!resource || !thread) return null\n return { resource, thread }\n}\n","/**\n * M13 (theokit-ai-first) — per-request skills resolution (ADR-0040 § D2, home/boundary concern).\n *\n * The static `skills.enabled` filter already works (`compile-skills` maps `include` → the SDK's\n * `enabled`). This adds a PER-REQUEST resolver so multi-tenant apps expose different skill sets to\n * different users. A selection is either a static list or a function of the request context (the M7\n * run-context). Discovery + injection stay in the SDK; this only CHOOSES the enabled set per call.\n */\n\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 enabled skill set is chosen:\n * - `string[]` — a static list (same shape `skills.enabled` accepts today).\n * - a function — resolved per request from the {@link SkillsRequestContext} (sync or async).\n */\nexport type SkillsSelection =\n | readonly string[]\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.\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') return [...selection]\n const resolved = await selection(ctx)\n if (!Array.isArray(resolved)) {\n throw new Error('[@theokit/agents] skills resolver must return an array of skill names')\n }\n return [...resolved]\n}\n","/**\n * M17 (theokit-ai-first) — ACP (Agent Client Protocol) stdio framing.\n *\n * ACP talks to a coding agent (Claude Code, Amp, Codex) over stdio as newline-delimited JSON. This\n * is the transport-agnostic CORE: encode a message to a line, and decode a byte/char stream that may\n * split a message across chunks. Pure — no subprocess, no Node API. The subprocess spawn lives in the\n * adapter layer (G8) / SDK; `createACPTool` (wrapping this codec + an injected transport) is a\n * follow-up once the adapter ships.\n */\n\n/** Serialize a message to a single newline-terminated JSON line. */\nexport function encodeAcpMessage(message: unknown): string {\n return `${JSON.stringify(message)}\\n`\n}\n\n/**\n * Incremental decoder for newline-delimited JSON. Feed it chunks with {@link push}; it buffers a\n * partial trailing line across calls and returns every WHOLE message parsed so far. Blank lines are\n * skipped. A completed non-JSON line fails fast with a typed error (error-handling.md) — a corrupt\n * frame must never be silently dropped.\n */\nexport class AcpMessageDecoder {\n private buffer = ''\n\n /** Feed a chunk; returns the messages completed by this chunk (possibly empty). */\n push(chunk: string): unknown[] {\n this.buffer += chunk\n const messages: unknown[] = []\n let newlineIndex = this.buffer.indexOf('\\n')\n while (newlineIndex !== -1) {\n const line = this.buffer.slice(0, newlineIndex).trim()\n this.buffer = this.buffer.slice(newlineIndex + 1)\n if (line.length > 0) {\n try {\n messages.push(JSON.parse(line))\n } catch (cause) {\n throw new Error(`[@theokit/agents] ACP decode failed on line: ${line}`, { cause })\n }\n }\n newlineIndex = this.buffer.indexOf('\\n')\n }\n return messages\n }\n}\n","/**\n * M17 (theokit-ai-first) — ACP client: JSON-RPC over the stdio framing.\n *\n * Drives a coding agent (Claude Code, Amp, Codex) over an INJECTED {@link AcpTransport}. The\n * subprocess spawn is a Node API and lives in the adapter layer (G8); this client is transport-\n * agnostic and testable. It correlates responses to requests by `id`, and dispatches server→client\n * requests (e.g. `session/request_permission`) to a registered handler, replying with its decision.\n */\nimport { AcpMessageDecoder, encodeAcpMessage } from './protocol.js'\n\n/** The stdio channel to the coding-agent subprocess (abstracted for testability + G8). */\nexport interface AcpTransport {\n /** Write one already-encoded (newline-terminated) line to the agent's stdin. */\n send(line: string): void\n /** Subscribe to raw lines/chunks from the agent's stdout. */\n subscribe(onData: (chunk: string) => void): void\n}\n\ninterface JsonRpcResponse {\n id: number\n result?: unknown\n error?: { code: number; message: string }\n}\ninterface JsonRpcServerRequest {\n id: number\n method: string\n params?: unknown\n}\n\ninterface Pending {\n resolve: (value: unknown) => void\n reject: (err: Error) => void\n}\n/** Return a value or a Promise — `unknown` already includes `Promise<unknown>`; `await` handles both. */\ntype ServerRequestHandler = (params: unknown) => unknown\n\nfunction isResponse(m: Record<string, unknown>): m is JsonRpcResponse & Record<string, unknown> {\n return typeof m.id === 'number' && (('result' in m) || ('error' in m)) && !('method' in m)\n}\nfunction isServerRequest(m: Record<string, unknown>): m is JsonRpcServerRequest & Record<string, unknown> {\n return typeof m.method === 'string' && typeof m.id === 'number'\n}\n\nexport class AcpClient {\n private nextId = 1\n private readonly pending = new Map<number, Pending>()\n private readonly handlers = new Map<string, ServerRequestHandler>()\n private readonly decoder = new AcpMessageDecoder()\n\n constructor(private readonly transport: AcpTransport) {\n transport.subscribe((chunk) => {\n for (const message of this.decoder.push(chunk)) {\n this.dispatch(message as Record<string, unknown>)\n }\n })\n }\n\n /** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n request(method: string, params: unknown): Promise<unknown> {\n const id = this.nextId++\n return new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { resolve, reject })\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id, method, params }))\n })\n }\n\n /** Register a handler for a server→client request method (e.g. `session/request_permission`). */\n onRequest(method: string, handler: ServerRequestHandler): void {\n this.handlers.set(method, handler)\n }\n\n private dispatch(message: Record<string, unknown>): void {\n if (isResponse(message)) {\n const entry = this.pending.get(message.id)\n if (!entry) return\n this.pending.delete(message.id)\n if (message.error) entry.reject(new Error(message.error.message))\n else entry.resolve(message.result)\n return\n }\n if (isServerRequest(message)) {\n void this.handleServerRequest(message)\n }\n }\n\n private async handleServerRequest(req: JsonRpcServerRequest): Promise<void> {\n const handler = this.handlers.get(req.method)\n if (!handler) {\n this.transport.send(\n encodeAcpMessage({ jsonrpc: '2.0', id: req.id, error: { code: -32601, message: `No handler: ${req.method}` } }),\n )\n return\n }\n try {\n const result = await handler(req.params)\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id: req.id, result }))\n } catch (err) {\n this.transport.send(\n encodeAcpMessage({\n jsonrpc: '2.0',\n id: req.id,\n error: { code: -32603, message: err instanceof Error ? err.message : 'handler failed' },\n }),\n )\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAASA,kBAAkBC,KAAW;AACpC,SAAOA,IAAIC,SAAS,GAAA,IAAOD,IAAIE,MAAM,GAAG,EAAC,IAAKF;AAChD;AAFSD;AAKF,SAASI,eAAeC,OAA2BC,SAA8B;AACtF,QAAMC,OAAOP,kBAAkBM,QAAQE,OAAO;AAC9C,SAAO;IACLC,MAAMJ,MAAMI;IACZC,aAAaJ,QAAQI,eAAe,kBAAkBL,MAAMI,IAAI;IAChER,KAAK,GAAGM,IAAAA,GAAOF,MAAMM,KAAK;IAC1BC,SAAS;IACTC,cAAc;MACZC,WAAWT,MAAMU;MACjBC,mBAAmB;MACnBC,wBAAwB;IAC1B;IACAC,mBAAmB;MAAC;;IACpBC,oBAAoB;MAAC;;IACrBC,QAAQf,MAAMgB,MAAMC,IAA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ACbC,iBAAiB;QACfC,SAAS;QACTxB,IAAIkC,IAAIlC;QACR8B,OAAO;UAAEK,MAAM;UAAQtB,SAASuB,eAAeL,QAAQK,IAAIvB,UAAU;QAAiB;MACxF,CAAA,CAAA;IAEJ;EACF;AACF;","names":["trimTrailingSlash","url","endsWith","slice","buildAgentCard","entry","options","base","baseUrl","name","description","route","version","capabilities","streaming","stream","pushNotifications","stateTransitionHistory","defaultInputModes","defaultOutputModes","skills","tools","map","t","id","wellKnownCardPath","agentName","MCP_PROTOCOL_VERSION","buildMcpToolDescriptors","entry","tools","map","t","name","description","inputSchema","type","properties","mcpServerInfo","version","protocolVersion","buildHeaders","config","headers","auth","bearer","authorization","apiKey","header","value","createA2ATool","doFetch","fetchImpl","fetch","name","description","inputSchema","type","properties","message","required","handler","input","res","url","method","body","JSON","stringify","ok","Error","status","statusText","data","json","response","text","SEPARATOR","deriveConversationId","resource","thread","Error","encodeURIComponent","parseConversationId","id","idx","indexOf","length","decodeURIComponent","slice","resolveEnabledSkills","selection","ctx","undefined","resolved","Array","isArray","Error","encodeAcpMessage","message","JSON","stringify","AcpMessageDecoder","buffer","push","chunk","messages","newlineIndex","indexOf","line","slice","trim","length","parse","cause","Error","isResponse","m","id","isServerRequest","method","AcpClient","nextId","pending","Map","handlers","decoder","AcpMessageDecoder","transport","subscribe","chunk","message","push","dispatch","request","params","Promise","resolve","reject","set","send","encodeAcpMessage","jsonrpc","onRequest","handler","entry","get","delete","error","Error","result","handleServerRequest","req","code","err"]}
|
|
1
|
+
{"version":3,"sources":["../src/a2a/agent-card.ts","../src/a2a/mcp-server-manifest.ts","../src/a2a/a2a-client.ts","../src/conversation-scope.ts","../src/skills-resolver.ts","../src/acp/protocol.ts","../src/acp/client.ts"],"sourcesContent":["/**\n * M15 (theokit-ai-first) — A2A agent card generation (ADR-0040 § D2, home/discovery concern).\n *\n * Produces an [A2A](https://github.com/google/A2A)-spec Agent Card from the framework's\n * `AgentManifestEntry`, so other systems can discover a TheoKit agent's capabilities over HTTP at\n * `/.well-known/<name>/agent-card.json`. Pure data transform — no LLM, no runtime (G2).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** A single capability exposed by an A2A agent (maps from a TheoKit tool). */\nexport interface A2ASkill {\n id: string\n name: string\n description: string\n}\n\n/** A2A agent-card capabilities block. */\nexport interface A2ACapabilities {\n streaming: boolean\n pushNotifications: boolean\n stateTransitionHistory: boolean\n}\n\n/** An A2A-spec Agent Card (the subset TheoKit advertises). */\nexport interface AgentCard {\n name: string\n description: string\n url: string\n version: string\n capabilities: A2ACapabilities\n defaultInputModes: string[]\n defaultOutputModes: string[]\n skills: A2ASkill[]\n}\n\nexport interface BuildAgentCardOptions {\n /** Absolute base URL of the deployment (e.g. `https://app.example.com`). A trailing slash is trimmed. */\n baseUrl: string\n /** Human description of the agent. Defaults to a generated sentence when omitted (spec requires non-empty). */\n description?: string\n}\n\n/** Strip a single trailing slash so `${baseUrl}${route}` never doubles the separator. */\nfunction trimTrailingSlash(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url\n}\n\n/** Build an A2A agent card from a manifest entry. */\nexport function buildAgentCard(entry: AgentManifestEntry, options: BuildAgentCardOptions): AgentCard {\n const base = trimTrailingSlash(options.baseUrl)\n return {\n name: entry.name,\n description: options.description ?? `TheoKit agent \"${entry.name}\".`,\n url: `${base}${entry.route}`,\n version: '1.0',\n capabilities: {\n streaming: entry.stream,\n pushNotifications: false,\n stateTransitionHistory: false,\n },\n defaultInputModes: ['text'],\n defaultOutputModes: ['text'],\n skills: entry.tools.map((t) => ({ id: t.name, name: t.name, description: t.description })),\n }\n}\n\n/** The A2A discovery path for an agent: `/.well-known/<name>/agent-card.json`. */\nexport function wellKnownCardPath(agentName: string): string {\n return `/.well-known/${agentName}/agent-card.json`\n}\n","/**\n * M16 (theokit-ai-first) — MCP server manifest generation (ADR-0040 § D2, home concern).\n *\n * Exposes a TheoKit agent's tools to external MCP clients as `tools/list` descriptors, so the app\n * can advertise its agents over its OWN HTTP routes. Pure data transform — no LLM, no runtime, and\n * NO stdio transport (that stays SDK-side per sdk-runtime.md). Serving these over `GET /mcp` and the\n * JSON-RPC envelope are follow-ups (mount path).\n */\nimport type { AgentManifestEntry } from '../manifest/agent-manifest.js'\n\n/** The MCP protocol revision these descriptors target. */\nexport const MCP_PROTOCOL_VERSION = '2024-11-05'\n\n/** A JSON-schema object (the shape MCP expects for a tool's `inputSchema`). */\nexport interface McpJsonSchema {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n}\n\n/** An MCP `tools/list` tool descriptor. */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: McpJsonSchema\n}\n\n/** MCP `initialize` server info. */\nexport interface McpServerInfo {\n name: string\n version: string\n protocolVersion: string\n}\n\n/**\n * Map an agent's tools to MCP tool descriptors. The manifest tool carries name + description; the\n * per-tool JSON schema is not retained in the manifest, so a permissive empty-object schema is\n * emitted (MCP clients accept it and pass through arbitrary args). Wiring the real per-tool schema\n * is a follow-up once the manifest carries it.\n */\nexport function buildMcpToolDescriptors(entry: AgentManifestEntry): McpToolDescriptor[] {\n return entry.tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: { type: 'object', properties: {} },\n }))\n}\n\n/** Build the MCP `initialize` server-info block for an agent. */\nexport function mcpServerInfo(entry: AgentManifestEntry): McpServerInfo {\n return { name: entry.name, version: '1.0', protocolVersion: MCP_PROTOCOL_VERSION }\n}\n","/**\n * M15 (theokit-ai-first) — A2A client: call a remote A2A agent as a tool (ADR-0040 § D2).\n *\n * `createA2ATool` returns a `CustomTool` whose handler POSTs the input message to a remote agent's\n * HTTP endpoint and returns its text response — cross-network delegation. Uses `fetch` (Web\n * Standards, G8). The target is a remote AGENT endpoint, not an LLM provider, so the G2 grep guard\n * (`openrouter.ai|api.openai.com|api.anthropic.com`) is unaffected. `fetchImpl` is injectable for tests.\n */\nimport type { CustomTool } from '@theokit/sdk'\n\n/** How to authenticate to the remote agent. */\nexport interface A2AAuth {\n /** Bearer token → `Authorization: Bearer <token>`. */\n bearer?: string\n /** API-key header pair → `<name>: <value>` (e.g. `x-api-key`). */\n apiKey?: { header: string; value: string }\n}\n\nexport interface A2AToolConfig {\n /** Remote agent endpoint URL (POST target). */\n url: string\n /** Tool name the model calls. */\n name: string\n /** Tool description surfaced to the model. */\n description: string\n /** Static headers merged into every request. */\n headers?: Record<string, string>\n /** Auth applied to every request. */\n auth?: A2AAuth\n /** Injected fetch (defaults to the global). Narrowed to the call shape this client uses. */\n fetchImpl?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/** Build the request headers from static headers + auth. */\nfunction buildHeaders(config: A2AToolConfig): Record<string, string> {\n const headers: Record<string, string> = { 'content-type': 'application/json', ...config.headers }\n if (config.auth?.bearer) headers.authorization = `Bearer ${config.auth.bearer}`\n if (config.auth?.apiKey) headers[config.auth.apiKey.header] = config.auth.apiKey.value\n return headers\n}\n\n/**\n * Create a tool that delegates to a remote A2A agent. The remote is expected to answer a\n * `{ message }` POST with a JSON body carrying a `response` (or `text`) string.\n */\nexport function createA2ATool(config: A2AToolConfig): CustomTool {\n const doFetch = config.fetchImpl ?? fetch\n return {\n name: config.name,\n description: config.description,\n inputSchema: {\n type: 'object',\n properties: { message: { type: 'string', description: 'The message to send to the remote agent.' } },\n required: ['message'],\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n // The input schema requires `message: string`; narrow defensively (never base-to-string).\n const message = typeof input.message === 'string' ? input.message : ''\n const res = await doFetch(config.url, {\n method: 'POST',\n headers: buildHeaders(config),\n body: JSON.stringify({ message }),\n })\n if (!res.ok) {\n throw new Error(`A2A call to \"${config.name}\" failed: ${res.status} ${res.statusText}`)\n }\n const data = (await res.json()) as { response?: string; text?: string }\n return data.response ?? data.text ?? ''\n },\n }\n}\n","/**\n * M11 (theokit-ai-first) — {resource, thread} conversation scoping (ADR-0040 § D2, home concern).\n *\n * Maps a request's (resource, thread) pair to a deterministic, collision-safe conversation id so\n * multi-tenant apps isolate history without hand-building `user-${id}-thread-${id}` strings. This\n * is the app's request→conversation mapping — NOT the SDK's storage engine (which the derived id is\n * simply handed to). Background compression of long histories stays SDK-side.\n *\n * Encoding: each component is `encodeURIComponent`-escaped and joined with `/`. Since\n * `encodeURIComponent` escapes a raw `/` to `%2F`, the separator is unambiguous — `('a/b','c')` and\n * `('a','b/c')` derive DIFFERENT ids (collision-safe). Reversible via {@link parseConversationId}.\n */\n\nconst SEPARATOR = '/'\n\n/** Derive a deterministic conversation id from a (resource, thread) pair. Fails fast on empty input. */\nexport function deriveConversationId(resource: string, thread: string): string {\n if (!resource) throw new Error('[@theokit/agents] deriveConversationId: resource must be non-empty')\n if (!thread) throw new Error('[@theokit/agents] deriveConversationId: thread must be non-empty')\n return `${encodeURIComponent(resource)}${SEPARATOR}${encodeURIComponent(thread)}`\n}\n\n/**\n * Reverse a derived conversation id back to its (resource, thread). Returns `null` for a value that\n * is not a derived scope id (no separator, or an empty component) — callers treat that as \"opaque id,\n * not scoped\".\n */\nexport function parseConversationId(id: string): { resource: string; thread: string } | null {\n const idx = id.indexOf(SEPARATOR)\n if (idx <= 0 || idx >= id.length - 1) return null\n const resource = decodeURIComponent(id.slice(0, idx))\n const thread = decodeURIComponent(id.slice(idx + 1))\n if (!resource || !thread) return null\n return { resource, thread }\n}\n","/**\n * M13 (theokit-ai-first) — per-request skills resolution (ADR-0040 § D2, home/boundary concern).\n *\n * The static `skills.enabled` filter already works (`compile-skills` maps `include` → the SDK's\n * `enabled`). This adds a PER-REQUEST resolver so multi-tenant apps expose different skill sets to\n * different users. A selection is either a static list or a function of the request context (the M7\n * run-context). Discovery + injection stay in the SDK; this only CHOOSES the enabled set per call.\n */\n\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 enabled skill set is chosen:\n * - `string[]` — a static list (same shape `skills.enabled` accepts today).\n * - a function — resolved per request from the {@link SkillsRequestContext} (sync or async).\n */\nexport type SkillsSelection =\n | readonly string[]\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.\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') return [...selection]\n const resolved = await selection(ctx)\n if (!Array.isArray(resolved)) {\n throw new Error('[@theokit/agents] skills resolver must return an array of skill names')\n }\n return [...resolved]\n}\n","/**\n * M17 (theokit-ai-first) — ACP (Agent Client Protocol) stdio framing.\n *\n * ACP talks to a coding agent (Claude Code, Amp, Codex) over stdio as newline-delimited JSON. This\n * is the transport-agnostic CORE: encode a message to a line, and decode a byte/char stream that may\n * split a message across chunks. Pure — no subprocess, no Node API. The subprocess spawn lives in the\n * adapter layer (G8) / SDK; `createACPTool` (wrapping this codec + an injected transport) is a\n * follow-up once the adapter ships.\n */\n\n/** Serialize a message to a single newline-terminated JSON line. */\nexport function encodeAcpMessage(message: unknown): string {\n return `${JSON.stringify(message)}\\n`\n}\n\n/**\n * Incremental decoder for newline-delimited JSON. Feed it chunks with {@link push}; it buffers a\n * partial trailing line across calls and returns every WHOLE message parsed so far. Blank lines are\n * skipped. A completed non-JSON line fails fast with a typed error (error-handling.md) — a corrupt\n * frame must never be silently dropped.\n */\nexport class AcpMessageDecoder {\n private buffer = ''\n\n /** Feed a chunk; returns the messages completed by this chunk (possibly empty). */\n push(chunk: string): unknown[] {\n this.buffer += chunk\n const messages: unknown[] = []\n let newlineIndex = this.buffer.indexOf('\\n')\n while (newlineIndex !== -1) {\n const line = this.buffer.slice(0, newlineIndex).trim()\n this.buffer = this.buffer.slice(newlineIndex + 1)\n if (line.length > 0) {\n try {\n messages.push(JSON.parse(line))\n } catch (cause) {\n throw new Error(`[@theokit/agents] ACP decode failed on line: ${line}`, { cause })\n }\n }\n newlineIndex = this.buffer.indexOf('\\n')\n }\n return messages\n }\n}\n","/**\n * M17 (theokit-ai-first) — ACP client: JSON-RPC over the stdio framing.\n *\n * Drives a coding agent (Claude Code, Amp, Codex) over an INJECTED {@link AcpTransport}. The\n * subprocess spawn is a Node API and lives in the adapter layer (G8); this client is transport-\n * agnostic and testable. It correlates responses to requests by `id`, and dispatches server→client\n * requests (e.g. `session/request_permission`) to a registered handler, replying with its decision.\n */\nimport { AcpMessageDecoder, encodeAcpMessage } from './protocol.js'\n\n/** The stdio channel to the coding-agent subprocess (abstracted for testability + G8). */\nexport interface AcpTransport {\n /** Write one already-encoded (newline-terminated) line to the agent's stdin. */\n send(line: string): void\n /** Subscribe to raw lines/chunks from the agent's stdout. */\n subscribe(onData: (chunk: string) => void): void\n}\n\ninterface JsonRpcResponse {\n id: number\n result?: unknown\n error?: { code: number; message: string }\n}\ninterface JsonRpcServerRequest {\n id: number\n method: string\n params?: unknown\n}\n\ninterface Pending {\n resolve: (value: unknown) => void\n reject: (err: Error) => void\n}\n/** Return a value or a Promise — `unknown` already includes `Promise<unknown>`; `await` handles both. */\ntype ServerRequestHandler = (params: unknown) => unknown\n\nfunction isResponse(m: Record<string, unknown>): m is JsonRpcResponse & Record<string, unknown> {\n return typeof m.id === 'number' && (('result' in m) || ('error' in m)) && !('method' in m)\n}\nfunction isServerRequest(m: Record<string, unknown>): m is JsonRpcServerRequest & Record<string, unknown> {\n return typeof m.method === 'string' && typeof m.id === 'number'\n}\n\nexport class AcpClient {\n private nextId = 1\n private readonly pending = new Map<number, Pending>()\n private readonly handlers = new Map<string, ServerRequestHandler>()\n private readonly decoder = new AcpMessageDecoder()\n\n constructor(private readonly transport: AcpTransport) {\n transport.subscribe((chunk) => {\n for (const message of this.decoder.push(chunk)) {\n this.dispatch(message as Record<string, unknown>)\n }\n })\n }\n\n /** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n request(method: string, params: unknown): Promise<unknown> {\n const id = this.nextId++\n return new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { resolve, reject })\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id, method, params }))\n })\n }\n\n /** Register a handler for a server→client request method (e.g. `session/request_permission`). */\n onRequest(method: string, handler: ServerRequestHandler): void {\n this.handlers.set(method, handler)\n }\n\n private dispatch(message: Record<string, unknown>): void {\n if (isResponse(message)) {\n const entry = this.pending.get(message.id)\n if (!entry) return\n this.pending.delete(message.id)\n if (message.error) entry.reject(new Error(message.error.message))\n else entry.resolve(message.result)\n return\n }\n if (isServerRequest(message)) {\n void this.handleServerRequest(message)\n }\n }\n\n private async handleServerRequest(req: JsonRpcServerRequest): Promise<void> {\n const handler = this.handlers.get(req.method)\n if (!handler) {\n this.transport.send(\n encodeAcpMessage({ jsonrpc: '2.0', id: req.id, error: { code: -32601, message: `No handler: ${req.method}` } }),\n )\n return\n }\n try {\n const result = await handler(req.params)\n this.transport.send(encodeAcpMessage({ jsonrpc: '2.0', id: req.id, result }))\n } catch (err) {\n this.transport.send(\n encodeAcpMessage({\n jsonrpc: '2.0',\n id: req.id,\n error: { code: -32603, message: err instanceof Error ? err.message : 'handler failed' },\n }),\n )\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAASA,kBAAkBC,KAAW;AACpC,SAAOA,IAAIC,SAAS,GAAA,IAAOD,IAAIE,MAAM,GAAG,EAAC,IAAKF;AAChD;AAFSD;AAKF,SAASI,eAAeC,OAA2BC,SAA8B;AACtF,QAAMC,OAAOP,kBAAkBM,QAAQE,OAAO;AAC9C,SAAO;IACLC,MAAMJ,MAAMI;IACZC,aAAaJ,QAAQI,eAAe,kBAAkBL,MAAMI,IAAI;IAChER,KAAK,GAAGM,IAAAA,GAAOF,MAAMM,KAAK;IAC1BC,SAAS;IACTC,cAAc;MACZC,WAAWT,MAAMU;MACjBC,mBAAmB;MACnBC,wBAA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xB,IAAIkC,IAAIlC;QAAIgC;MAAO,CAAA,CAAA;IAC5E,SAASI,KAAK;AACZ,WAAK1B,UAAUY,KACbC,iBAAiB;QACfC,SAAS;QACTxB,IAAIkC,IAAIlC;QACR8B,OAAO;UAAEK,MAAM;UAAQtB,SAASuB,eAAeL,QAAQK,IAAIvB,UAAU;QAAiB;MACxF,CAAA,CAAA;IAEJ;EACF;AACF;","names":["trimTrailingSlash","url","endsWith","slice","buildAgentCard","entry","options","base","baseUrl","name","description","route","version","capabilities","streaming","stream","pushNotifications","stateTransitionHistory","defaultInputModes","defaultOutputModes","skills","tools","map","t","id","wellKnownCardPath","agentName","MCP_PROTOCOL_VERSION","buildMcpToolDescriptors","entry","tools","map","t","name","description","inputSchema","type","properties","mcpServerInfo","version","protocolVersion","buildHeaders","config","headers","auth","bearer","authorization","apiKey","header","value","createA2ATool","doFetch","fetchImpl","fetch","name","description","inputSchema","type","properties","message","required","handler","input","res","url","method","body","JSON","stringify","ok","Error","status","statusText","data","json","response","text","SEPARATOR","deriveConversationId","resource","thread","Error","encodeURIComponent","parseConversationId","id","idx","indexOf","length","decodeURIComponent","slice","resolveEnabledSkills","selection","ctx","undefined","resolved","Array","isArray","Error","encodeAcpMessage","message","JSON","stringify","AcpMessageDecoder","buffer","push","chunk","messages","newlineIndex","indexOf","line","slice","trim","length","parse","cause","Error","isResponse","m","id","isServerRequest","method","AcpClient","nextId","pending","Map","handlers","decoder","AcpMessageDecoder","transport","subscribe","chunk","message","push","dispatch","request","params","Promise","resolve","reject","set","send","encodeAcpMessage","jsonrpc","onRequest","handler","entry","get","delete","error","Error","result","handleServerRequest","req","code","err"]}
|
|
@@ -310,4 +310,4 @@ declare class CostBudgetExceededError extends Error {
|
|
|
310
310
|
constructor(usedTokens: number, maxTokens: number);
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
-
export { getSkillsConfig as $, type AgentOptions as A, type BudgetOptions as B,
|
|
313
|
+
export { getSkillsConfig as $, type AgentOptions as A, type BudgetOptions as B, CostBudgetExceededError as C, type MemoryProvider as D, type MemoryScope as E, type PlatformName as F, type Guardrail as G, type HumanInTheLoopOptions as H, type IndexStrategy as I, ProjectContext as J, type ProjectContextOptions as K, type RelevanceStrategy as L, type MainLoopMeta as M, Skills as N, type SkillsOptions as O, type PolicyHandler as P, getCheckpointConfig as Q, type ReasoningEffort as R, type SessionStrategy as S, type TimeoutAction as T, getCompactionConfig as U, getContextWindowConfig as V, getGatewayConfig as W, getHumanInTheLoopConfig as X, getMcpConfig as Y, getMemoryConfig as Z, getProjectContextConfig as _, type ApprovalOptions as a, resolveSessionId as a0, type GuardrailAction as b, type GuardrailPhase as c, type GuardrailResult as d, GuardrailViolationError as e, type MainLoopOptions as f, type ToolOptions as g, type ToolboxOptions as h, Checkpoint as i, type CheckpointOptions as j, type CheckpointState as k, type CheckpointStorage as l, type CheckpointStrategy as m, Compaction as n, type CompactionDecoratorConfig as o, type ContextCompactionStrategy as p, ContextWindow as q, type ContextWindowOptions as r, Gateway as s, type GatewayOptions as t, HumanInTheLoop as u, MCP as v, type McpServerConfig as w, type McpServersMap as x, Memory as y, type MemoryOptions as z };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/agents",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.34.0",
|
|
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,
|
|
7
7
|
"main": "./dist/index.js",
|
|
@@ -11,10 +11,6 @@
|
|
|
11
11
|
"import": "./dist/index.js",
|
|
12
12
|
"types": "./dist/index.d.ts"
|
|
13
13
|
},
|
|
14
|
-
"./decorators": {
|
|
15
|
-
"import": "./dist/decorators.js",
|
|
16
|
-
"types": "./dist/decorators.d.ts"
|
|
17
|
-
},
|
|
18
14
|
"./bridge": {
|
|
19
15
|
"import": "./dist/bridge.js",
|
|
20
16
|
"types": "./dist/bridge.d.ts"
|
|
@@ -29,11 +25,6 @@
|
|
|
29
25
|
"README.md",
|
|
30
26
|
"LICENSE"
|
|
31
27
|
],
|
|
32
|
-
"scripts": {
|
|
33
|
-
"build": "tsup",
|
|
34
|
-
"test": "vitest run",
|
|
35
|
-
"test:watch": "vitest"
|
|
36
|
-
},
|
|
37
28
|
"peerDependencies": {
|
|
38
29
|
"@theokit/http": ">=0.1.0-alpha.0",
|
|
39
30
|
"@theokit/sdk": ">=2.20.0",
|
|
@@ -51,7 +42,6 @@
|
|
|
51
42
|
}
|
|
52
43
|
},
|
|
53
44
|
"devDependencies": {
|
|
54
|
-
"@theokit/http": "workspace:*",
|
|
55
45
|
"@theokit/sdk": "^2.20.0",
|
|
56
46
|
"@theokit/sdk-tools": "^0.2.0",
|
|
57
47
|
"ai": "^7.0.14",
|
|
@@ -59,9 +49,15 @@
|
|
|
59
49
|
"tsup": "^8.5.1",
|
|
60
50
|
"typescript": "^5.9.3",
|
|
61
51
|
"vitest": "^3.2.6",
|
|
62
|
-
"zod": "^4.4.3"
|
|
52
|
+
"zod": "^4.4.3",
|
|
53
|
+
"@theokit/http": "0.5.4"
|
|
63
54
|
},
|
|
64
55
|
"engines": {
|
|
65
56
|
"node": ">=22.12.0"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsup",
|
|
60
|
+
"test": "vitest run",
|
|
61
|
+
"test:watch": "vitest"
|
|
66
62
|
}
|
|
67
|
-
}
|
|
63
|
+
}
|
package/dist/chunk-GEV2EQW2.js
DELETED
|
@@ -1,265 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AGENT_MAIN_LOOP,
|
|
3
|
-
TOOLBOX_CONFIG,
|
|
4
|
-
TOOL_CONFIG,
|
|
5
|
-
TOOL_METHODS,
|
|
6
|
-
getMeta,
|
|
7
|
-
setMeta
|
|
8
|
-
} from "./chunk-MD35WBR4.js";
|
|
9
|
-
import {
|
|
10
|
-
__name
|
|
11
|
-
} from "./chunk-7QVYU63E.js";
|
|
12
|
-
|
|
13
|
-
// src/decorators/main-loop.ts
|
|
14
|
-
function MainLoop(options = {}) {
|
|
15
|
-
return (target, propertyKey) => {
|
|
16
|
-
const actualTarget = target.constructor;
|
|
17
|
-
const existing = getMeta(AGENT_MAIN_LOOP, actualTarget);
|
|
18
|
-
if (existing) {
|
|
19
|
-
console.warn(`[@theokit/agents] ${actualTarget.name}: @MainLoop() already declared on '${String(existing.propertyKey)}'. Overwriting with '${String(propertyKey)}'.`);
|
|
20
|
-
}
|
|
21
|
-
const meta = {
|
|
22
|
-
propertyKey,
|
|
23
|
-
strategy: options.strategy ?? "simple-chat",
|
|
24
|
-
maxIterations: options.maxIterations,
|
|
25
|
-
timeoutMs: options.timeoutMs
|
|
26
|
-
};
|
|
27
|
-
setMeta(AGENT_MAIN_LOOP, actualTarget, meta);
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
__name(MainLoop, "MainLoop");
|
|
31
|
-
function getMainLoop(target) {
|
|
32
|
-
return getMeta(AGENT_MAIN_LOOP, target);
|
|
33
|
-
}
|
|
34
|
-
__name(getMainLoop, "getMainLoop");
|
|
35
|
-
|
|
36
|
-
// src/decorators/tool.ts
|
|
37
|
-
function inferNamespace(className) {
|
|
38
|
-
const stripped = className.replace(/Tools$/, "");
|
|
39
|
-
return stripped.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").toLowerCase();
|
|
40
|
-
}
|
|
41
|
-
__name(inferNamespace, "inferNamespace");
|
|
42
|
-
function Toolbox(options = {}) {
|
|
43
|
-
return (target) => {
|
|
44
|
-
const ns = options.namespace ?? inferNamespace(target.name);
|
|
45
|
-
setMeta(TOOLBOX_CONFIG, target, {
|
|
46
|
-
...options,
|
|
47
|
-
namespace: ns
|
|
48
|
-
});
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
__name(Toolbox, "Toolbox");
|
|
52
|
-
function Tool(options) {
|
|
53
|
-
return (target, propertyKey) => {
|
|
54
|
-
const actualTarget = target.constructor;
|
|
55
|
-
setMeta(TOOL_CONFIG, actualTarget, options, propertyKey);
|
|
56
|
-
const existing = getMeta(TOOL_METHODS, actualTarget) ?? [];
|
|
57
|
-
setMeta(TOOL_METHODS, actualTarget, [
|
|
58
|
-
...existing,
|
|
59
|
-
propertyKey
|
|
60
|
-
]);
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
__name(Tool, "Tool");
|
|
64
|
-
function getToolboxConfig(target) {
|
|
65
|
-
return getMeta(TOOLBOX_CONFIG, target);
|
|
66
|
-
}
|
|
67
|
-
__name(getToolboxConfig, "getToolboxConfig");
|
|
68
|
-
function getToolMethods(target) {
|
|
69
|
-
return getMeta(TOOL_METHODS, target) ?? [];
|
|
70
|
-
}
|
|
71
|
-
__name(getToolMethods, "getToolMethods");
|
|
72
|
-
function getToolConfig(target, propertyKey) {
|
|
73
|
-
return getMeta(TOOL_CONFIG, target, propertyKey);
|
|
74
|
-
}
|
|
75
|
-
__name(getToolConfig, "getToolConfig");
|
|
76
|
-
|
|
77
|
-
// src/decorators/hook.ts
|
|
78
|
-
var HOOKS_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:hooks");
|
|
79
|
-
function Hook(point) {
|
|
80
|
-
return (target, propertyKey) => {
|
|
81
|
-
const actualTarget = target.constructor;
|
|
82
|
-
const existing = getMeta(HOOKS_CONFIG, actualTarget) ?? [];
|
|
83
|
-
setMeta(HOOKS_CONFIG, actualTarget, [
|
|
84
|
-
...existing,
|
|
85
|
-
{
|
|
86
|
-
point,
|
|
87
|
-
propertyKey
|
|
88
|
-
}
|
|
89
|
-
]);
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
__name(Hook, "Hook");
|
|
93
|
-
function getHooks(target) {
|
|
94
|
-
return getMeta(HOOKS_CONFIG, target) ?? [];
|
|
95
|
-
}
|
|
96
|
-
__name(getHooks, "getHooks");
|
|
97
|
-
function getHooksByPoint(target, point) {
|
|
98
|
-
return getHooks(target).filter((h) => h.point === point);
|
|
99
|
-
}
|
|
100
|
-
__name(getHooksByPoint, "getHooksByPoint");
|
|
101
|
-
|
|
102
|
-
// src/decorators/conversation.ts
|
|
103
|
-
var CONVERSATION_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:conversation");
|
|
104
|
-
function Conversation(options = {}) {
|
|
105
|
-
return (target) => {
|
|
106
|
-
setMeta(CONVERSATION_CONFIG, target, {
|
|
107
|
-
storage: "memory",
|
|
108
|
-
maxHistory: 0,
|
|
109
|
-
compaction: "truncate",
|
|
110
|
-
ttl: 0,
|
|
111
|
-
preserveLastN: 5,
|
|
112
|
-
...options
|
|
113
|
-
});
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
__name(Conversation, "Conversation");
|
|
117
|
-
function getConversationConfig(target) {
|
|
118
|
-
return getMeta(CONVERSATION_CONFIG, target);
|
|
119
|
-
}
|
|
120
|
-
__name(getConversationConfig, "getConversationConfig");
|
|
121
|
-
|
|
122
|
-
// src/decorators/model.ts
|
|
123
|
-
import { createDecorator } from "@theokit/http";
|
|
124
|
-
var Model = createDecorator();
|
|
125
|
-
|
|
126
|
-
// src/decorators/artifact.ts
|
|
127
|
-
var ARTIFACT_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:artifact");
|
|
128
|
-
function Artifact(options) {
|
|
129
|
-
return (target, propertyKey) => {
|
|
130
|
-
const actualTarget = target.constructor;
|
|
131
|
-
setMeta(ARTIFACT_CONFIG, actualTarget, {
|
|
132
|
-
streamable: true,
|
|
133
|
-
maxSize: 0,
|
|
134
|
-
...options
|
|
135
|
-
}, propertyKey);
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
__name(Artifact, "Artifact");
|
|
139
|
-
function getArtifactConfig(target, propertyKey) {
|
|
140
|
-
return getMeta(ARTIFACT_CONFIG, target, propertyKey);
|
|
141
|
-
}
|
|
142
|
-
__name(getArtifactConfig, "getArtifactConfig");
|
|
143
|
-
|
|
144
|
-
// src/decorators/observable.ts
|
|
145
|
-
var OBSERVABLE_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:observable");
|
|
146
|
-
function Observable(channel) {
|
|
147
|
-
return (target, propertyKey) => {
|
|
148
|
-
const actualTarget = target.constructor;
|
|
149
|
-
const existing = getMeta(OBSERVABLE_CONFIG, actualTarget) ?? [];
|
|
150
|
-
setMeta(OBSERVABLE_CONFIG, actualTarget, [
|
|
151
|
-
...existing,
|
|
152
|
-
{
|
|
153
|
-
channel,
|
|
154
|
-
propertyKey
|
|
155
|
-
}
|
|
156
|
-
]);
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
__name(Observable, "Observable");
|
|
160
|
-
function getObservables(target) {
|
|
161
|
-
return getMeta(OBSERVABLE_CONFIG, target) ?? [];
|
|
162
|
-
}
|
|
163
|
-
__name(getObservables, "getObservables");
|
|
164
|
-
function getObservableByChannel(target, channel) {
|
|
165
|
-
return getObservables(target).find((o) => o.channel === channel);
|
|
166
|
-
}
|
|
167
|
-
__name(getObservableByChannel, "getObservableByChannel");
|
|
168
|
-
|
|
169
|
-
// src/decorators/sandbox.ts
|
|
170
|
-
import { resolve } from "path";
|
|
171
|
-
var SANDBOX_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:sandbox");
|
|
172
|
-
function Sandbox(options) {
|
|
173
|
-
return (target) => {
|
|
174
|
-
setMeta(SANDBOX_CONFIG, target, {
|
|
175
|
-
network: true,
|
|
176
|
-
commandTimeout: 12e4,
|
|
177
|
-
...options
|
|
178
|
-
});
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
__name(Sandbox, "Sandbox");
|
|
182
|
-
function getSandboxConfig(target) {
|
|
183
|
-
return getMeta(SANDBOX_CONFIG, target);
|
|
184
|
-
}
|
|
185
|
-
__name(getSandboxConfig, "getSandboxConfig");
|
|
186
|
-
function isPathAllowed(sandbox, filePath, operation) {
|
|
187
|
-
if (filePath.includes("\0")) return false;
|
|
188
|
-
const normalized = resolve("/", filePath).slice(1);
|
|
189
|
-
const fs = sandbox.filesystem;
|
|
190
|
-
if (!fs) return true;
|
|
191
|
-
if (fs.deny?.some((pattern) => matchGlob(pattern, normalized))) return false;
|
|
192
|
-
const allowList = operation === "read" ? fs.read : fs.write;
|
|
193
|
-
if (!allowList) return true;
|
|
194
|
-
return allowList.some((pattern) => matchGlob(pattern, normalized));
|
|
195
|
-
}
|
|
196
|
-
__name(isPathAllowed, "isPathAllowed");
|
|
197
|
-
var SHELL_METACHARS = /[;|&$`(){}<>\n\r]/;
|
|
198
|
-
function isCommandAllowed(sandbox, command) {
|
|
199
|
-
const cmds = sandbox.commands;
|
|
200
|
-
if (!cmds) return true;
|
|
201
|
-
if (SHELL_METACHARS.test(command)) return false;
|
|
202
|
-
const binary = command.split(/\s+/)[0];
|
|
203
|
-
if (cmds.deny?.some((d) => binary === d || command.startsWith(d + " ") || command === d)) return false;
|
|
204
|
-
if (!cmds.allow) return true;
|
|
205
|
-
return cmds.allow.some((a) => binary === a || command.startsWith(a + " ") || command === a);
|
|
206
|
-
}
|
|
207
|
-
__name(isCommandAllowed, "isCommandAllowed");
|
|
208
|
-
function matchGlob(pattern, filePath) {
|
|
209
|
-
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0GLOBSTAR\0").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\0GLOBSTAR\0/g, ".*");
|
|
210
|
-
const regex = buildGlobRegex(escaped);
|
|
211
|
-
return regex.test(filePath);
|
|
212
|
-
}
|
|
213
|
-
__name(matchGlob, "matchGlob");
|
|
214
|
-
function buildGlobRegex(escapedPattern) {
|
|
215
|
-
return RegExp(`^${escapedPattern}$`);
|
|
216
|
-
}
|
|
217
|
-
__name(buildGlobRegex, "buildGlobRegex");
|
|
218
|
-
|
|
219
|
-
// src/decorators/edit-format.ts
|
|
220
|
-
import { createDecorator as createDecorator2 } from "@theokit/http";
|
|
221
|
-
var EditFormat = createDecorator2();
|
|
222
|
-
|
|
223
|
-
// src/decorators/apply-decorators.ts
|
|
224
|
-
function applyDecorators(...decorators) {
|
|
225
|
-
return (target, propertyKey, descriptor) => {
|
|
226
|
-
for (const decorator of decorators) {
|
|
227
|
-
if (propertyKey !== void 0 && descriptor !== void 0) {
|
|
228
|
-
;
|
|
229
|
-
decorator(target, propertyKey, descriptor);
|
|
230
|
-
} else {
|
|
231
|
-
;
|
|
232
|
-
decorator(target);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
__name(applyDecorators, "applyDecorators");
|
|
238
|
-
|
|
239
|
-
export {
|
|
240
|
-
MainLoop,
|
|
241
|
-
getMainLoop,
|
|
242
|
-
Toolbox,
|
|
243
|
-
Tool,
|
|
244
|
-
getToolboxConfig,
|
|
245
|
-
getToolMethods,
|
|
246
|
-
getToolConfig,
|
|
247
|
-
Hook,
|
|
248
|
-
getHooks,
|
|
249
|
-
getHooksByPoint,
|
|
250
|
-
Conversation,
|
|
251
|
-
getConversationConfig,
|
|
252
|
-
Model,
|
|
253
|
-
Artifact,
|
|
254
|
-
getArtifactConfig,
|
|
255
|
-
Observable,
|
|
256
|
-
getObservables,
|
|
257
|
-
getObservableByChannel,
|
|
258
|
-
Sandbox,
|
|
259
|
-
getSandboxConfig,
|
|
260
|
-
isPathAllowed,
|
|
261
|
-
isCommandAllowed,
|
|
262
|
-
EditFormat,
|
|
263
|
-
applyDecorators
|
|
264
|
-
};
|
|
265
|
-
//# sourceMappingURL=chunk-GEV2EQW2.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/decorators/main-loop.ts","../src/decorators/tool.ts","../src/decorators/hook.ts","../src/decorators/conversation.ts","../src/decorators/model.ts","../src/decorators/artifact.ts","../src/decorators/observable.ts","../src/decorators/sandbox.ts","../src/decorators/edit-format.ts","../src/decorators/apply-decorators.ts"],"sourcesContent":["/**\n * @MainLoop() — marks the execution entry point of an agent.\n *\n * Only one @MainLoop per agent class. Second application overwrites (last-wins, with warning).\n */\nimport { setMeta, getMeta, AGENT_MAIN_LOOP } from '../metadata/index.js'\nimport type { MainLoopOptions, MainLoopMeta } from '../types.js'\n\nexport function MainLoop(options: MainLoopOptions = {}): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, actualTarget)\n if (existing) {\n console.warn(\n `[@theokit/agents] ${actualTarget.name}: @MainLoop() already declared on '${String(existing.propertyKey)}'. Overwriting with '${String(propertyKey)}'.`,\n )\n }\n const meta: MainLoopMeta = {\n propertyKey,\n strategy: options.strategy ?? 'simple-chat',\n maxIterations: options.maxIterations,\n timeoutMs: options.timeoutMs,\n }\n setMeta(AGENT_MAIN_LOOP, actualTarget, meta)\n }\n}\n\nexport function getMainLoop(target: Function): MainLoopMeta | undefined {\n return getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, target)\n}\n","/**\n * @Toolbox() + @Tool() — group and define agent tools.\n *\n * @Toolbox({ namespace }) is a class decorator that groups related tools.\n * @Tool({ name, description, input, risk }) is a method decorator compiled to defineTool().\n *\n * @UseGuards on @Toolbox applies to ALL tools (per ADR D7).\n */\nimport { setMeta, getMeta, TOOLBOX_CONFIG, TOOL_CONFIG, TOOL_METHODS } from '../metadata/index.js'\nimport type { ToolboxOptions, ToolOptions } from '../types.js'\n\n/**\n * Convention: TaskTools → namespace: 'tasks', ProjectTools → namespace: 'projects'\n * Strips \"Tools\" suffix, converts to kebab-case.\n */\nfunction inferNamespace(className: string): string {\n const stripped = className.replace(/Tools$/, '')\n return stripped\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase()\n}\n\nexport function Toolbox(options: ToolboxOptions = {}): ClassDecorator {\n return (target: Function) => {\n const ns = options.namespace ?? inferNamespace(target.name)\n setMeta(TOOLBOX_CONFIG, target, { ...options, namespace: ns })\n }\n}\n\nexport function Tool(options: ToolOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(TOOL_CONFIG, actualTarget, options, propertyKey)\n // Accumulate tool methods list\n const existing = getMeta<(string | symbol)[]>(TOOL_METHODS, actualTarget) ?? []\n setMeta(TOOL_METHODS, actualTarget, [...existing, propertyKey])\n }\n}\n\nexport function getToolboxConfig(target: Function): ToolboxOptions | undefined {\n return getMeta<ToolboxOptions>(TOOLBOX_CONFIG, target)\n}\n\nexport function getToolMethods(target: Function): (string | symbol)[] {\n return getMeta<(string | symbol)[]>(TOOL_METHODS, target) ?? []\n}\n\nexport function getToolConfig(\n target: Function,\n propertyKey: string | symbol,\n): ToolOptions | undefined {\n return getMeta<ToolOptions>(TOOL_CONFIG, target, propertyKey)\n}\n","/**\n * @Hook() — lifecycle hooks WITHIN the agent loop.\n *\n * Unlike HTTP interceptors (which wrap the entire handler), hooks fire at\n * specific points during the agent's reasoning → tool → response cycle.\n *\n * Hook points:\n * - 'before:llm-call' — before each LLM API call\n * - 'after:llm-call' — after each LLM response\n * - 'before:tool-call' — before each tool execution\n * - 'after:tool-call' — after each tool result\n * - 'on:iteration' — at each loop iteration\n * - 'on:complete' — when the agent produces a final answer\n * - 'on:error' — when the agent encounters an error\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n *\n * @Hook('before:llm-call')\n * async injectContext(ctx: HookContext) {\n * ctx.appendSystemPrompt(`Time: ${new Date().toISOString()}`)\n * }\n *\n * @Hook('after:tool-call')\n * async trackCost(ctx: HookContext) {\n * await billing.track(ctx.toolCall!.name, ctx.toolCall!.durationMs)\n * }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst HOOKS_CONFIG = Symbol.for('theokit:agents:hooks')\n\nexport type HookPoint =\n | 'before:llm-call'\n | 'after:llm-call'\n | 'before:tool-call'\n | 'after:tool-call'\n | 'on:iteration'\n | 'on:complete'\n | 'on:error'\n\nexport interface HookEntry {\n point: HookPoint\n propertyKey: string | symbol\n}\n\nexport function Hook(point: HookPoint): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<HookEntry[]>(HOOKS_CONFIG, actualTarget) ?? []\n setMeta(HOOKS_CONFIG, actualTarget, [...existing, { point, propertyKey }])\n }\n}\n\nexport function getHooks(target: Function): HookEntry[] {\n return getMeta<HookEntry[]>(HOOKS_CONFIG, target) ?? []\n}\n\nexport function getHooksByPoint(target: Function, point: HookPoint): HookEntry[] {\n return getHooks(target).filter((h) => h.point === point)\n}\n","/**\n * @Conversation() — declares conversation persistence strategy for an agent.\n *\n * Controls how the agent remembers message history across sessions.\n * Compiles to SDK's ConversationStorageAdapter configuration.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * @Conversation({\n * storage: 'drizzle',\n * maxHistory: 100,\n * compaction: 'summarize',\n * ttl: 24 * 60 * 60 * 1000,\n * })\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CONVERSATION_CONFIG = Symbol.for('theokit:agents:conversation')\n\nexport type ConversationStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis'\nexport type CompactionStrategy = 'truncate' | 'summarize' | 'sliding-window'\n\nexport interface ConversationOptions {\n /** Storage backend for conversation history. */\n storage?: ConversationStorage\n /** Maximum messages before compaction triggers (0 = no limit). */\n maxHistory?: number\n /** How to compact when maxHistory is exceeded. */\n compaction?: CompactionStrategy\n /** Time-to-live in milliseconds before conversation expires (0 = never). */\n ttl?: number\n /** Number of recent messages to always preserve during compaction. */\n preserveLastN?: number\n}\n\nexport function Conversation(options: ConversationOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CONVERSATION_CONFIG, target, {\n storage: 'memory',\n maxHistory: 0,\n compaction: 'truncate',\n ttl: 0,\n preserveLastN: 5,\n ...options,\n })\n }\n}\n\nexport function getConversationConfig(target: Function): ConversationOptions | undefined {\n return getMeta<ConversationOptions>(CONVERSATION_CONFIG, target)\n}\n","/**\n * @Model() — override the LLM model at agent or tool level.\n *\n * Hierarchical resolution via Reflector.getAllAndOverride:\n * tool @Model > agent @Model > @Agent({ model }) > config default\n *\n * This is a MODEL selector, not a PROVIDER selector. Provider routing\n * (which API key, which endpoint, fallback chains) lives in theo.config.ts\n * as runtime configuration — not in decorators.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * @Model('claude-sonnet-4-5-20250929') // default for all tools\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n * }\n *\n * @Toolbox({ namespace: 'code' })\n * class CodeTools {\n * @Tool({ name: 'generate', description: 'Generate code', input: z.object({...}) })\n * @Model('claude-opus-4-6') // this tool needs the most capable model\n * async generate() { ... }\n *\n * @Tool({ name: 'lint', description: 'Lint code', input: z.object({...}) })\n * // no @Model — inherits from agent level\n * async lint() { ... }\n * }\n * ```\n */\nimport { createDecorator } from '@theokit/http'\n\n/** Override the LLM model for an agent class or a specific tool method. */\nexport const Model = createDecorator<string>()\n","/**\n * @Artifact() — marks a tool as producing structured output artifacts.\n *\n * Artifacts are SEPARATE from text responses. When a tool produces an artifact\n * (code file, document, diagram, JSON data), the SSE stream emits artifact_start\n * + artifact_chunk events alongside text_delta events.\n *\n * Inspired by assistant-ui's A2AArtifact pattern where artifacts have their own\n * lifecycle (start → chunks → complete) independent of message content.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'code' })\n * class CodeTools {\n * @Tool({ name: 'generate', description: 'Generate code', input: z.object({...}) })\n * @Artifact({ mimeType: 'text/typescript', streamable: true })\n * async generate(input: { spec: string }): Promise<ArtifactResult> {\n * return {\n * content: generatedCode,\n * filename: 'component.tsx',\n * metadata: { language: 'typescript', loc: 42 },\n * }\n * }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst ARTIFACT_CONFIG = Symbol.for('theokit:agents:artifact')\n\nexport interface ArtifactOptions {\n /** MIME type of the artifact output. */\n mimeType: string\n /** Whether the artifact can be streamed in chunks (default: true). */\n streamable?: boolean\n /** Maximum size in bytes (0 = no limit). */\n maxSize?: number\n}\n\n/** Return type for tools decorated with @Artifact. */\nexport interface ArtifactResult {\n /** The artifact content (string for text, Buffer for binary). */\n content: string\n /** Optional filename hint for the client. */\n filename?: string\n /** Optional metadata attached to the artifact. */\n metadata?: Record<string, unknown>\n}\n\nexport function Artifact(options: ArtifactOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(ARTIFACT_CONFIG, actualTarget, { streamable: true, maxSize: 0, ...options }, propertyKey)\n }\n}\n\nexport function getArtifactConfig(\n target: Function,\n propertyKey: string | symbol,\n): ArtifactOptions | undefined {\n return getMeta<ArtifactOptions>(ARTIFACT_CONFIG, target, propertyKey)\n}\n","/**\n * @Observable() — exposes agent internal state as a real-time stream.\n *\n * Clients subscribe to named observables to monitor agent execution in real-time:\n * token usage, cost, iteration progress, pending approvals, retrieved facts.\n *\n * Inspired by Liveblocks' Presence pattern and tRPC subscriptions. The agent\n * pushes state updates via SSE alongside response events — clients are never\n * \"blind\" during long-running agent operations.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * class ResearchAgent {\n * @MainLoop()\n * async run() {}\n *\n * @Observable('metrics')\n * getMetrics(ctx: AgentContext): AgentMetrics {\n * return {\n * tokensUsed: ctx.tokenCount,\n * costUsd: ctx.costUsd,\n * iteration: ctx.iteration,\n * pendingApprovals: ctx.pendingApprovals.length,\n * }\n * }\n * }\n *\n * // SSE emits: { type: 'state_update', channel: 'metrics', data: {...} }\n * // Client: eventSource.addEventListener('state_update', handler)\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst OBSERVABLE_CONFIG = Symbol.for('theokit:agents:observable')\n\nexport interface ObservableEntry {\n channel: string\n propertyKey: string | symbol\n}\n\nexport function Observable(channel: string): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<ObservableEntry[]>(OBSERVABLE_CONFIG, actualTarget) ?? []\n setMeta(OBSERVABLE_CONFIG, actualTarget, [...existing, { channel, propertyKey }])\n }\n}\n\nexport function getObservables(target: Function): ObservableEntry[] {\n return getMeta<ObservableEntry[]>(OBSERVABLE_CONFIG, target) ?? []\n}\n\nexport function getObservableByChannel(target: Function, channel: string): ObservableEntry | undefined {\n return getObservables(target).find((o) => o.channel === channel)\n}\n","/**\n * @Sandbox() — declares file/command permission scope for code assistant agents.\n *\n * Controls what the agent can read, write, and execute. The runtime enforces\n * these permissions BEFORE tool execution — a tool that tries to write to a\n * denied path gets a typed error, not a crash.\n *\n * Inspired by Claude Code's permission system (allow/deny per tool + path).\n *\n * @example\n * ```ts\n * @Agent({ name: 'coder', route: '/agents/coder' })\n * @Sandbox({\n * filesystem: {\n * read: ['src/**', 'tests/**', 'package.json'],\n * write: ['src/**', 'tests/**'],\n * deny: ['node_modules/**', '.env', '*.key'],\n * },\n * commands: {\n * allow: ['npm test', 'tsc --noEmit', 'git diff'],\n * deny: ['rm -rf', 'git push --force', 'npm publish'],\n * },\n * network: false,\n * })\n * class CoderAgent { ... }\n * ```\n */\nimport { resolve } from 'node:path'\n\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst SANDBOX_CONFIG = Symbol.for('theokit:agents:sandbox')\n\nexport interface FilesystemPermissions {\n /** Glob patterns for allowed read paths. */\n read?: string[]\n /** Glob patterns for allowed write paths. */\n write?: string[]\n /** Glob patterns for DENIED paths (overrides read/write). */\n deny?: string[]\n}\n\nexport interface CommandPermissions {\n /** Command prefixes allowed to execute. */\n allow?: string[]\n /** Command prefixes denied (overrides allow). */\n deny?: string[]\n}\n\nexport interface SandboxOptions {\n /** Filesystem read/write permissions. */\n filesystem?: FilesystemPermissions\n /** Shell command execution permissions. */\n commands?: CommandPermissions\n /** Allow outbound network from tools (default: true). */\n network?: boolean\n /** Maximum execution time per command in ms (default: 120_000). */\n commandTimeout?: number\n /** Working directory root (default: process.cwd()). */\n cwd?: string\n}\n\nexport function Sandbox(options: SandboxOptions): ClassDecorator {\n return (target: Function) => {\n setMeta(SANDBOX_CONFIG, target, {\n network: true,\n commandTimeout: 120_000,\n ...options,\n })\n }\n}\n\nexport function getSandboxConfig(target: Function): SandboxOptions | undefined {\n return getMeta<SandboxOptions>(SANDBOX_CONFIG, target)\n}\n\n/**\n * Check if a file path is allowed for the given operation.\n * Deny patterns always win over allow patterns.\n *\n * Security: normalizes paths to prevent traversal (../) and rejects null bytes.\n */\nexport function isPathAllowed(\n sandbox: SandboxOptions,\n filePath: string,\n operation: 'read' | 'write',\n): boolean {\n // EC-2: null byte injection — reject before any processing\n if (filePath.includes('\\x00')) return false\n\n // Path traversal fix: normalize to remove ../ sequences\n const normalized = resolve('/', filePath).slice(1)\n\n const fs = sandbox.filesystem\n if (!fs) return true // no filesystem restrictions\n\n // Deny always wins\n if (fs.deny?.some((pattern) => matchGlob(pattern, normalized))) return false\n\n const allowList = operation === 'read' ? fs.read : fs.write\n if (!allowList) return true // no explicit allow = allow all (minus deny)\n\n return allowList.some((pattern) => matchGlob(pattern, normalized))\n}\n\n/**\n * Shell metacharacters that indicate injection attempts.\n * EC-1: includes redirect operators (>, <) and newlines (\\n, \\r).\n */\nconst SHELL_METACHARS = /[;|&$`(){}<>\\n\\r]/\n\n/**\n * Check if a command is allowed to execute.\n * Deny patterns always win. Rejects shell metacharacters.\n *\n * Security: tokenizes command to match binary name, not arbitrary prefix.\n */\nexport function isCommandAllowed(sandbox: SandboxOptions, command: string): boolean {\n const cmds = sandbox.commands\n if (!cmds) return true\n\n // Reject any command with shell metacharacters (injection prevention)\n if (SHELL_METACHARS.test(command)) return false\n\n // Extract binary name (first whitespace-delimited token)\n const binary = command.split(/\\s+/)[0]\n\n // Deny always wins — check both exact binary match and full command prefix\n if (cmds.deny?.some((d) => binary === d || command.startsWith(d + ' ') || command === d))\n return false\n\n if (!cmds.allow) return true\n\n // Allow: match exact binary or full command prefix\n return cmds.allow.some((a) => binary === a || command.startsWith(a + ' ') || command === a)\n}\n\n/**\n * Glob matcher — converts glob pattern to regex at call time.\n * Uses a pre-built RegExp from a sanitized pattern string.\n * Supports *, **, and ? glob characters.\n */\nfunction matchGlob(pattern: string, filePath: string): boolean {\n // Escape all regex specials except glob chars (* and ?)\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '\\0GLOBSTAR\\0')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\?/g, '[^/]')\n .replace(/\\0GLOBSTAR\\0/g, '.*')\n // Pre-compile regex outside of hot path (pattern is controlled by developer, not user input)\n const regex = buildGlobRegex(escaped)\n return regex.test(filePath)\n}\n\n/** Build a regex from a pre-escaped glob pattern string. */\nfunction buildGlobRegex(escapedPattern: string): RegExp {\n return RegExp(`^${escapedPattern}$`)\n}\n","/**\n * @EditFormat() — declares how a tool outputs file edits.\n *\n * Code assistants show DIFFS, not entire files. This decorator tells the\n * runtime which format the tool produces so the SSE stream emits the\n * correct `file_edit` event type.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'editor' })\n * class EditorTools {\n * @Tool({ name: 'edit', description: 'Edit file', input: editSchema })\n * @EditFormat('search-replace')\n * async edit(input: { file: string; search: string; replace: string }) {\n * return { file: input.file, search: input.search, replace: input.replace }\n * }\n *\n * @Tool({ name: 'write', description: 'Write file', input: writeSchema })\n * @EditFormat('full-file')\n * async write(input: { file: string; content: string }) {\n * return { file: input.file, content: input.content }\n * }\n * }\n * ```\n */\nimport { createDecorator } from '@theokit/http'\n\nexport type EditFormatType =\n | 'search-replace' // { file, search, replace } — Claude Code Edit pattern\n | 'unified-diff' // Standard unified diff format\n | 'full-file' // Complete file content (Write pattern)\n | 'line-range' // { file, startLine, endLine, content }\n\n/** Declare the edit format a tool produces. */\nexport const EditFormat = createDecorator<EditFormatType>()\n","/**\n * applyDecorators() — compose multiple decorators into a single reusable decorator.\n *\n * NestJS-compatible utility. Enables creating \"preset\" decorators that bundle\n * common configurations (auth + throttle + trace + memory + ...) into one decorator.\n *\n * @example\n * ```ts\n * // Create a reusable preset\n * const ProductionAgent = (name: string, route: string) => applyDecorators(\n * Agent({ name, route, model: 'claude-sonnet-4-5-20250929' }),\n * UseGuards(AuthGuard, TenantGuard),\n * Throttle({ limit: 30, ttl: 60_000 }),\n * Budget({ maxCostUsd: 5.00 }),\n * Trace(true),\n * )\n *\n * // Apply preset to any agent\n * @ProductionAgent('support', '/api/agents/support')\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n * }\n * ```\n */\n\ntype AnyDecorator = ClassDecorator | MethodDecorator | PropertyDecorator\n\n/**\n * Compose multiple decorators into a single decorator.\n * Works for both class-level and method-level decorators.\n */\nexport function applyDecorators(\n ...decorators: AnyDecorator[]\n): ClassDecorator & MethodDecorator {\n return (\n target: object | Function,\n propertyKey?: string | symbol,\n descriptor?: PropertyDescriptor,\n ) => {\n for (const decorator of decorators) {\n if (propertyKey !== undefined && descriptor !== undefined) {\n // Method-level\n ;(decorator as MethodDecorator)(target, propertyKey, descriptor)\n } else {\n // Class-level\n ;(decorator as ClassDecorator)(target as Function)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAQO,SAASA,SAASC,UAA2B,CAAC,GAAC;AACpD,SAAO,CAACC,QAAgBC,gBAAAA;AACtB,UAAMC,eAAeF,OAAO;AAC5B,UAAMG,WAAWC,QAAsBC,iBAAiBH,YAAAA;AACxD,QAAIC,UAAU;AACZG,cAAQC,KACN,qBAAqBL,aAAaM,IAAI,sCAAsCC,OAAON,SAASF,WAAW,CAAA,wBAAyBQ,OAAOR,WAAAA,CAAAA,IAAgB;IAE3J;AACA,UAAMS,OAAqB;MACzBT;MACAU,UAAUZ,QAAQY,YAAY;MAC9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nB,QAAQoB;AACrB,MAAI,CAACD,KAAM,QAAO;AAGlB,MAAIH,gBAAgBK,KAAKH,OAAAA,EAAU,QAAO;AAG1C,QAAMI,SAASJ,QAAQK,MAAM,KAAA,EAAO,CAAA;AAGpC,MAAIJ,KAAKV,MAAMC,KAAK,CAACc,MAAMF,WAAWE,KAAKN,QAAQO,WAAWD,IAAI,GAAA,KAAQN,YAAYM,CAAAA,EACpF,QAAO;AAET,MAAI,CAACL,KAAKO,MAAO,QAAO;AAGxB,SAAOP,KAAKO,MAAMhB,KAAK,CAACiB,MAAML,WAAWK,KAAKT,QAAQO,WAAWE,IAAI,GAAA,KAAQT,YAAYS,CAAAA;AAC3F;AAlBgBV;AAyBhB,SAASL,UAAUD,SAAiBV,UAAgB;AAElD,QAAM2B,UAAUjB,QACbkB,QAAQ,qBAAqB,MAAA,EAC7BA,QAAQ,SAAS,cAAA,EACjBA,QAAQ,OAAO,OAAA,EACfA,QAAQ,OAAO,MAAA,EACfA,QAAQ,iBAAiB,IAAA;AAE5B,QAAMC,QAAQC,eAAeH,OAAAA;AAC7B,SAAOE,MAAMT,KAAKpB,QAAAA;AACpB;AAXSW;AAcT,SAASmB,eAAeC,gBAAsB;AAC5C,SAAOC,OAAO,IAAID,cAAAA,GAAiB;AACrC;AAFSD;;;ACnIT,SAASG,mBAAAA,wBAAuB;AASzB,IAAMC,aAAaD,iBAAAA;;;ACFnB,SAASE,mBACXC,YAA0B;AAE7B,SAAO,CACLC,QACAC,aACAC,eAAAA;AAEA,eAAWC,aAAaJ,YAAY;AAClC,UAAIE,gBAAgBG,UAAaF,eAAeE,QAAW;;AAEvDD,kBAA8BH,QAAQC,aAAaC,UAAAA;MACvD,OAAO;;AAEHC,kBAA6BH,MAAAA;MACjC;IACF;EACF;AACF;AAlBgBF;","names":["MainLoop","options","target","propertyKey","actualTarget","existing","getMeta","AGENT_MAIN_LOOP","console","warn","name","String","meta","strategy","maxIterations","timeoutMs","setMeta","getMainLoop","inferNamespace","className","stripped","replace","toLowerCase","Toolbox","options","target","ns","namespace","name","setMeta","TOOLBOX_CONFIG","Tool","propertyKey","actualTarget","TOOL_CONFIG","existing","getMeta","TOOL_METHODS","getToolboxConfig","getToolMethods","getToolConfig","HOOKS_CONFIG","Symbol","for","Hook","point","target","propertyKey","actualTarget","existing","getMeta","setMeta","getHooks","getHooksByPoint","filter","h","CONVERSATION_CONFIG","Symbol","for","Conversation","options","target","setMeta","storage","maxHistory","compaction","ttl","preserveLastN","getConversationConfig","getMeta","createDecorator","Model","ARTIFACT_CONFIG","Symbol","for","Artifact","options","target","propertyKey","actualTarget","setMeta","streamable","maxSize","getArtifactConfig","getMeta","OBSERVABLE_CONFIG","Symbol","for","Observable","channel","target","propertyKey","actualTarget","existing","getMeta","setMeta","getObservables","getObservableByChannel","find","o","resolve","SANDBOX_CONFIG","Symbol","for","Sandbox","options","target","setMeta","network","commandTimeout","getSandboxConfig","getMeta","isPathAllowed","sandbox","filePath","operation","includes","normalized","resolve","slice","fs","filesystem","deny","some","pattern","matchGlob","allowList","read","write","SHELL_METACHARS","isCommandAllowed","command","cmds","commands","test","binary","split","d","startsWith","allow","a","escaped","replace","regex","buildGlobRegex","escapedPattern","RegExp","createDecorator","EditFormat","applyDecorators","decorators","target","propertyKey","descriptor","decorator","undefined"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/metadata/index.ts","../src/metadata/keys.ts","../src/decorators/agent.ts","../src/decorators/policies.ts","../src/decorators/observability.ts","../src/decorators/gateway.ts","../src/decorators/sub-agents.ts","../src/decorators/memory.ts","../src/decorators/skills.ts","../src/decorators/guardrails.ts","../src/decorators/mcp.ts","../src/decorators/human-in-the-loop.ts","../src/decorators/context-window.ts","../src/decorators/compaction.ts","../src/decorators/checkpoint.ts","../src/decorators/project-context.ts","../src/decorators/mixin.ts"],"sourcesContent":["// Re-export setMeta/getMeta from http-decorators (DRY — single metadata engine)\n// Relative path for workspace-local usage; vitest resolves via alias\nexport { setMeta, getMeta } from '@theokit/http'\n\nexport * from './keys.js'\n","/** Symbol.for metadata keys for agent decorators — cross-module safe with SWC loader. */\n\nexport const AGENT_CONFIG = Symbol.for('theokit:agents:config')\nexport const AGENT_MAIN_LOOP = Symbol.for('theokit:agents:main-loop')\nexport const TOOLBOX_CONFIG = Symbol.for('theokit:agents:toolbox')\nexport const TOOL_CONFIG = Symbol.for('theokit:agents:tool')\nexport const TOOL_METHODS = Symbol.for('theokit:agents:tool-methods')\n","/**\n * @Agent() — marks a class as an AI agent controller.\n *\n * Convention over configuration:\n * @Agent() → name + route inferred from class name\n * @Agent({ model: '...' }) → name + route inferred, model explicit\n * @Agent({ name, route, model }) → fully explicit\n *\n * @example\n * ```ts\n * // Convention: SupportAgent → name: 'support', route: '/api/agents/support'\n * @Agent()\n * class SupportAgent { ... }\n *\n * // Partial: infer name + route, set model\n * @Agent({ model: 'claude-sonnet-4-5-20250929' })\n * class SupportAgent { ... }\n *\n * // Explicit: full control\n * @Agent({ name: 'support-agent', route: '/api/agents/support', model: '...' })\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta, AGENT_CONFIG } from '../metadata/index.js'\nimport type { AgentOptions } from '../types.js'\n\n/**\n * Infer agent name and route from class name (Rails-style convention).\n *\n * SupportAgent → name: 'support', route: '/api/agents/support'\n * ResearchAgent → name: 'research', route: '/api/agents/research'\n * CodeReviewAgent → name: 'code-review', route: '/api/agents/code-review'\n */\nfunction inferAgentMeta(className: string): { name: string; route: string } {\n const stripped = className.replace(/Agent$/, '')\n const kebab = stripped\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase()\n return { name: kebab, route: `/api/agents/${kebab}` }\n}\n\nexport function Agent(options?: Partial<AgentOptions>): ClassDecorator {\n return (target: Function) => {\n const inferred = inferAgentMeta(target.name)\n setMeta(AGENT_CONFIG, target, {\n stream: true,\n name: inferred.name,\n route: inferred.route,\n ...options, // explicit values override inferred\n })\n }\n}\n\nexport function getAgentConfig(target: Function): AgentOptions | undefined {\n return getMeta<AgentOptions>(AGENT_CONFIG, target)\n}\n","/**\n * Agent-native policy decorators — built on http-decorators' createDecorator<T>().\n *\n * These decorators work with Reflector.getAllAndOverride() for hierarchical\n * resolution: tool → toolbox → agent (method-level overrides class-level).\n */\nimport { createDecorator } from '@theokit/http'\n\nimport type { ApprovalOptions, BudgetOptions, PolicyHandler } from '../types.js'\n\n/** Mark a tool as requiring human approval before execution. */\nexport const RequiresApproval = createDecorator<ApprovalOptions>()\n\n/** Require specific capabilities (permissions) to execute a tool. */\nexport const RequiresCapability = createDecorator<string[]>()\n\n/** Set a cost budget for an agent or tool scope. */\nexport const Budget = createDecorator<BudgetOptions>()\n\n/** Attach policy handler functions (CASL-style authorization). */\nexport const Policy = createDecorator<PolicyHandler[]>()\n","/**\n * Observability decorators for agent tracing and auditing.\n */\nimport { createDecorator } from '@theokit/http'\n\n/** Enable distributed tracing for a tool/toolbox/agent. */\nexport const Trace = createDecorator<boolean>()\n\n/** Enable audit logging for a tool/toolbox/agent. */\nexport const Audit = createDecorator<boolean>()\n","/**\n * @Gateway() — declares which platform adapters an agent supports.\n *\n * Stores gateway configuration metadata on the agent class.\n * The GatewayRunner reads this to auto-wire adapters without manual plumbing.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Gateway({\n * platforms: ['telegram', 'discord', 'slack'],\n * sessionStrategy: 'per-user',\n * })\n * @UseGuards(AuthGuard)\n * class SupportAgent {\n * @MainLoop()\n * async run(ctx: AgentContext) { ... }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst GATEWAY_CONFIG = Symbol.for('theokit:agents:gateway')\n\nexport type PlatformName =\n | 'telegram'\n | 'discord'\n | 'slack'\n | 'whatsapp'\n | 'teams'\n | 'email'\n | 'sms'\n | 'mattermost'\n | 'line'\n | 'matrix'\n\nexport type SessionStrategy =\n | 'per-user' // telegram-dm-{userId}\n | 'per-channel' // telegram-grp-{channelId}\n | 'per-thread' // telegram-tpc-{channelId}-{topicId}\n\nexport interface GatewayOptions {\n /** Platform adapters this agent supports. */\n platforms: PlatformName[]\n /** How to resolve agentId from inbound events (default: 'per-user'). */\n sessionStrategy?: SessionStrategy\n /** Auto-start typing indicator while agent processes (default: true). */\n typing?: boolean\n}\n\nexport function Gateway(options: GatewayOptions): ClassDecorator {\n return (target: Function) => {\n setMeta(GATEWAY_CONFIG, target, { typing: true, sessionStrategy: 'per-user', ...options })\n }\n}\n\nexport function getGatewayConfig(target: Function): GatewayOptions | undefined {\n return getMeta<GatewayOptions>(GATEWAY_CONFIG, target)\n}\n\n/**\n * Resolve a stable agentId from a platform event based on the session strategy.\n *\n * Mirrors @theokit/gateway SessionRouter.defaultStrategy() but is configurable\n * via the @Gateway decorator.\n */\nexport function resolveSessionId(\n strategy: SessionStrategy,\n platform: string,\n sender: { id: string },\n channel: { id: string; type: 'dm' | 'group' | 'thread'; topicId?: string },\n): string {\n switch (strategy) {\n case 'per-user':\n return `${platform}-dm-${sender.id}`\n case 'per-channel':\n return `${platform}-grp-${channel.id}`\n case 'per-thread':\n return `${platform}-tpc-${channel.id}-${channel.topicId ?? 'main'}`\n }\n}\n","/**\n * @SubAgents() — declares child agents that a parent agent can handoff to.\n *\n * Compiles to the SDK's `AgentOptions.agents` map. The parent agent\n * can delegate work to sub-agents via the built-in Agent tool.\n *\n * @example\n * ```ts\n * @Agent({ name: 'orchestrator', route: '/api/agents/orchestrator' })\n * @SubAgents([ResearchAgent, CoderAgent, ReviewerAgent])\n * class OrchestratorAgent {\n * @MainLoop({ strategy: 'plan-act-reflect' })\n * async run(ctx: AgentContext) { ... }\n * }\n * ```\n *\n * Each referenced class MUST be decorated with @Agent().\n * The compiler reads their metadata to build the SDK agents map.\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nimport { getAgentConfig } from './agent.js'\n\nconst SUB_AGENTS = Symbol.for('theokit:agents:sub-agents')\n\nexport function SubAgents(agentClasses: Function[]): ClassDecorator {\n return (target: Function) => {\n // Validate at decoration time: all classes must have @Agent\n for (const cls of agentClasses) {\n const config = getAgentConfig(cls)\n if (!config) {\n throw new Error(\n `[@theokit/agents] @SubAgents on ${target.name}: class ${cls.name} is missing @Agent() decorator.`,\n )\n }\n }\n setMeta(SUB_AGENTS, target, agentClasses)\n }\n}\n\nexport function getSubAgents(target: Function): Function[] {\n return getMeta<Function[]>(SUB_AGENTS, target) ?? []\n}\n","/**\n * @Memory() — declares persistent memory configuration for an agent.\n *\n * Compiles to SDK's MemorySettings in Agent.create({ memory }).\n * Memory is per-agent, scoped by session strategy.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Memory({ provider: 'built-in', embeddings: true, fts: true, scope: 'per-user' })\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst MEMORY_CONFIG = Symbol.for('theokit:agents:memory')\n\nexport type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0'\nexport type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global'\n\nexport interface MemoryOptions {\n /** Memory provider backend. */\n provider?: MemoryProvider\n /** Enable semantic search via embeddings. */\n embeddings?: boolean\n /** Enable full-text search (FTS5). */\n fts?: boolean\n /** Memory isolation scope (default: 'per-user'). */\n scope?: MemoryScope\n /** Maximum facts to retain per scope (0 = unlimited). */\n maxFacts?: number\n}\n\nexport function Memory(options: MemoryOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(MEMORY_CONFIG, target, {\n provider: 'built-in',\n embeddings: false,\n fts: false,\n scope: 'per-user',\n ...options,\n })\n }\n}\n\nexport function getMemoryConfig(target: Function): MemoryOptions | undefined {\n return getMeta<MemoryOptions>(MEMORY_CONFIG, target)\n}\n","/**\n * @Skills() — declares markdown skill files injected into the agent's system prompt.\n *\n * Compiles to SDK's SkillsSettings in Agent.create({ skills }).\n * Skills are .theokit/skills/<name>/SKILL.md files discovered at agent creation.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Skills(['customer-service', 'refund-policy', 'escalation-protocol'])\n * class SupportAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst SKILLS_CONFIG = Symbol.for('theokit:agents:skills')\n\nexport interface SkillsOptions {\n /** Skill names to include (resolved from .theokit/skills/<name>/SKILL.md). */\n include: string[]\n /** Auto-discover all skills in .theokit/skills/ (default: false). */\n autoDiscover?: boolean\n}\n\nexport function Skills(namesOrOptions: string[] | SkillsOptions): ClassDecorator {\n return (target: Function) => {\n const options: SkillsOptions = Array.isArray(namesOrOptions)\n ? { include: namesOrOptions, autoDiscover: false }\n : namesOrOptions\n setMeta(SKILLS_CONFIG, target, options)\n }\n}\n\nexport function getSkillsConfig(target: Function): SkillsOptions | undefined {\n return getMeta<SkillsOptions>(SKILLS_CONFIG, target)\n}\n","/**\n * `@Guardrails([...])` — M9 class-decorator surface for input/output guardrails.\n *\n * The functional `defineAgent({ guardrails: [...] })` path already applies guards at the framework\n * boundary (ADR-0040 § D2). This decorator gives the `@Agent` class path the SAME capability: the\n * declared guards compile into `compiled.guardrails` (via `walkAgentMetadata`), so `AgentRunner`\n * applies them identically. Metadata-only (like `@MCP`/`@Skills`) — it describes, the runner runs.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/api/agents/support' })\n * @Guardrails([promptInjectionDetector(), piiDetector({ redact: true })])\n * class SupportAgent {}\n * ```\n */\nimport type { Guardrail } from '../guardrails/index.js'\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst GUARDRAILS_CONFIG = Symbol.for('theokit:agents:guardrails')\n\nexport function Guardrails(guardrails: readonly Guardrail[]): ClassDecorator {\n return (target: Function) => {\n setMeta(GUARDRAILS_CONFIG, target, guardrails)\n }\n}\n\nexport function getGuardrailsConfig(target: Function): readonly Guardrail[] | undefined {\n return getMeta<readonly Guardrail[]>(GUARDRAILS_CONFIG, target)\n}\n","/**\n * @MCP() — declares Model Context Protocol servers available to an agent.\n *\n * Compiles to SDK's mcpServers in Agent.create({ mcpServers }).\n * Each key is a server name; the value is the server configuration.\n *\n * @example\n * ```ts\n * @Agent({ name: 'dev', route: '/api/agents/dev' })\n * @MCP({\n * github: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] },\n * filesystem: { command: 'npx', args: ['-y', '@mcp/server-filesystem', '/workspace'] },\n * })\n * class DevAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst MCP_CONFIG = Symbol.for('theokit:agents:mcp')\n\nexport interface McpServerConfig {\n /** Command to start the MCP server. */\n command: string\n /** Arguments passed to the command. */\n args?: string[]\n /** Environment variables for the server process. */\n env?: Record<string, string>\n /** Working directory for the server process. */\n cwd?: string\n}\n\nexport type McpServersMap = Record<string, McpServerConfig>\n\nexport function MCP(servers: McpServersMap): ClassDecorator {\n return (target: Function) => {\n setMeta(MCP_CONFIG, target, servers)\n }\n}\n\nexport function getMcpConfig(target: Function): McpServersMap | undefined {\n return getMeta<McpServersMap>(MCP_CONFIG, target)\n}\n","/**\n * @HumanInTheLoop() — pause agent execution to request human approval.\n *\n * When applied to a @Tool method, the agent pauses before executing the tool\n * and emits an 'approval_required' SSE event. The client must POST to the\n * callback URL to approve or deny. If denied or timed out, the tool is skipped.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'ops' })\n * class OpsTools {\n * @Tool({ name: 'deploy', description: 'Deploy to prod', input: z.object({...}) })\n * @HumanInTheLoop({\n * question: 'Confirm deployment to production?',\n * timeout: 300_000,\n * onTimeout: 'abort',\n * })\n * async deploy(input: {...}) { ... }\n * }\n * ```\n *\n * SSE event emitted:\n * ```json\n * { \"type\": \"approval_required\", \"toolName\": \"ops.deploy\", \"question\": \"...\", \"callbackUrl\": \"/agents/x/approve/call-123\" }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst HITL_CONFIG = Symbol.for('theokit:agents:human-in-the-loop')\n\nexport type TimeoutAction = 'abort' | 'proceed' | 'retry'\n\nexport interface HumanInTheLoopOptions {\n /** Question shown to the human approver. */\n question: string\n /** Timeout in milliseconds before onTimeout fires (default: 300_000 = 5 min). */\n timeout?: number\n /** Action when timeout expires (default: 'abort'). */\n onTimeout?: TimeoutAction\n /** Show the tool input to the approver (default: true). */\n showInput?: boolean\n /**\n * M20 — an optional JSON-schema descriptor of the custom payload the approver may attach (edited\n * args, a review note). Carried into the `approval_required` event + `GET /approvals` so the UI\n * knows what to collect. A plain JSON object, not a live Zod schema (keeps the wire serializable).\n */\n payloadSchema?: Record<string, unknown>\n}\n\nexport function HumanInTheLoop(options: HumanInTheLoopOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(\n HITL_CONFIG,\n actualTarget,\n {\n timeout: 300_000,\n onTimeout: 'abort',\n showInput: true,\n ...options,\n },\n propertyKey,\n )\n }\n}\n\nexport function getHumanInTheLoopConfig(\n target: Function,\n propertyKey: string | symbol,\n): HumanInTheLoopOptions | undefined {\n return getMeta<HumanInTheLoopOptions>(HITL_CONFIG, target, propertyKey)\n}\n","/**\n * @ContextWindow() — declares context window management strategy.\n *\n * Controls how the agent handles context when conversation history grows\n * beyond the LLM's context window. Mirrors Claude Code's PreCompact behavior.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * @ContextWindow({\n * maxTokens: 100_000,\n * compactionStrategy: 'summarize-oldest',\n * preserveSystemPrompt: true,\n * preserveLastN: 10,\n * })\n * class ResearchAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CONTEXT_WINDOW_CONFIG = Symbol.for('theokit:agents:context-window')\n\nexport type ContextCompactionStrategy =\n | 'truncate-oldest' // Drop oldest messages beyond limit\n | 'summarize-oldest' // LLM-summarize oldest messages into a single message\n | 'sliding-window' // Keep last N messages only\n | 'priority-based' // Keep tool results + recent; summarize reasoning\n\nexport interface ContextWindowOptions {\n /** Maximum tokens before compaction triggers. */\n maxTokens?: number\n /** How to compact when maxTokens is exceeded. */\n compactionStrategy?: ContextCompactionStrategy\n /** Always preserve the system prompt during compaction (default: true). */\n preserveSystemPrompt?: boolean\n /** Number of recent messages to always keep intact (default: 10). */\n preserveLastN?: number\n /** Keep all tool results even during compaction (default: true). */\n preserveToolResults?: boolean\n}\n\nexport function ContextWindow(options: ContextWindowOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CONTEXT_WINDOW_CONFIG, target, {\n maxTokens: 100_000,\n compactionStrategy: 'summarize-oldest',\n preserveSystemPrompt: true,\n preserveLastN: 10,\n preserveToolResults: true,\n ...options,\n })\n }\n}\n\nexport function getContextWindowConfig(target: Function): ContextWindowOptions | undefined {\n return getMeta<ContextWindowOptions>(CONTEXT_WINDOW_CONFIG, target)\n}\n","/**\n * `@Compaction(name, opts)` — declares the agent's transcript-compaction strategy\n * (V4-F). Metadata-only: it records the choice; `AgentRunner.build()` resolves it\n * to a concrete {@link TranscriptCompactionStrategy} via `resolveCompactionStrategy`\n * (EC-5 — an invalid name/budget fails fast at build, not at decoration).\n *\n * Mirrors the `@ContextWindow` metadata pattern (`setMeta`/`getMeta` + a unique\n * Symbol). NOT auto-applied by the loop (ADR D1) — the resolved strategy is exposed\n * as `runner.compaction` for the app to call.\n *\n * @example\n * ```ts\n * @Agent({ model })\n * @Compaction('token-budget', { keepTokens: 8000 })\n * class CodeAgent {}\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst COMPACTION_CONFIG = Symbol.for('theokit:agents:compaction')\n\n/** Stored `@Compaction` declaration (resolved + validated at `AgentRunner.build()`). */\nexport interface CompactionDecoratorConfig {\n /** Strategy name (e.g. `'token-budget'`). Validated at resolve time. */\n name: string\n /** Token budget for `'token-budget'`. Required at resolve time (EC-2). */\n keepTokens?: number\n}\n\nexport function Compaction(name: string, options: { keepTokens?: number } = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(COMPACTION_CONFIG, target, { name, keepTokens: options.keepTokens })\n }\n}\n\nexport function getCompactionConfig(target: Function): CompactionDecoratorConfig | undefined {\n return getMeta<CompactionDecoratorConfig>(COMPACTION_CONFIG, target)\n}\n","/**\n * @Checkpoint() — enables resumable agent execution from the last successful step.\n *\n * Long-running agents (research, code review, multi-step workflows) can fail\n * partway through. Without checkpointing, users restart from step 1 — wasting\n * tokens, time, and cost.\n *\n * Inspired by tRPC's tracked() + lastEventId pattern and Dapr's actor state\n * checkpointing. The agent persists a recovery point after each successful\n * tool call or iteration, and can resume from that point on retry.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * @Checkpoint({\n * storage: 'filesystem', // only 'filesystem' resumes across requests in the M2 harness (M4)\n * strategy: 'after-tool-call',\n * maxCheckpoints: 20,\n * ttl: 3_600_000, // 1h\n * })\n * class ResearchAgent {\n * @MainLoop({ strategy: 'plan-act-reflect', maxIterations: 15 })\n * async run() {}\n * }\n *\n * // Resume: a follow-up POST /api/agents/research with the SAME sessionId replays the persisted\n * // history. NOTE (M4): only `storage: 'filesystem'` resumes across requests today — `memory`\n * // (the default below) is per-run; `drizzle`/`redis` are not shipped by the SDK. A non-filesystem\n * // @Checkpoint emits a THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY warning (honest enforcement).\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst CHECKPOINT_CONFIG = Symbol.for('theokit:agents:checkpoint')\n\nexport type CheckpointStrategy =\n | 'after-tool-call' // checkpoint after every successful tool execution\n | 'after-iteration' // checkpoint after every loop iteration\n | 'manual' // only checkpoint when explicitly called via ctx.checkpoint()\n\nexport type CheckpointStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis'\n\nexport interface CheckpointOptions {\n /** Where to persist checkpoints. */\n storage?: CheckpointStorage\n /** When to auto-checkpoint (default: 'after-tool-call'). */\n strategy?: CheckpointStrategy\n /** Maximum checkpoints to retain per run (rolling window). */\n maxCheckpoints?: number\n /** Time-to-live in ms before checkpoints expire (default: 3_600_000 = 1h). */\n ttl?: number\n}\n\n/** Serializable checkpoint state. */\nexport interface CheckpointState {\n id: string\n runId: string\n agentName: string\n step: number\n messages: unknown[]\n toolResults: unknown[]\n createdAt: number\n resumeToken: string\n}\n\nexport function Checkpoint(options: CheckpointOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(CHECKPOINT_CONFIG, target, {\n storage: 'memory',\n strategy: 'after-tool-call',\n maxCheckpoints: 10,\n ttl: 3_600_000,\n ...options,\n })\n }\n}\n\nexport function getCheckpointConfig(target: Function): CheckpointOptions | undefined {\n return getMeta<CheckpointOptions>(CHECKPOINT_CONFIG, target)\n}\n","/**\n * @ProjectContext() — declares how the agent understands the codebase.\n *\n * A code assistant needs to know: what's the project root, which files\n * are relevant, how to parse code structure, what to ignore. This\n * metadata feeds the context window management and file discovery.\n *\n * @example\n * ```ts\n * @Agent({ name: 'coder', route: '/agents/coder' })\n * @ProjectContext({\n * rootMarkers: ['package.json', 'tsconfig.json'],\n * indexStrategy: 'tree-sitter',\n * maxFilesInContext: 20,\n * relevanceStrategy: 'git-history',\n * ignorePatterns: ['node_modules', 'dist', '.git'],\n * })\n * class CoderAgent { ... }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst PROJECT_CONTEXT_CONFIG = Symbol.for('theokit:agents:project-context')\n\nexport type IndexStrategy =\n | 'tree-sitter' // Parse AST for structural understanding\n | 'regex' // Simple regex-based symbol extraction\n | 'none' // No indexing — rely on grep/glob only\n\nexport type RelevanceStrategy =\n | 'git-history' // Prioritize recently-edited files\n | 'import-graph' // Follow import chains from entry points\n | 'semantic' // Embedding-based similarity search\n | 'manual' // Only files explicitly provided\n\nexport interface ProjectContextOptions {\n /** Files that mark the project root (searched upward from cwd). */\n rootMarkers?: string[]\n /** How to index the codebase for structural understanding. */\n indexStrategy?: IndexStrategy\n /** Maximum files to include in context per request. */\n maxFilesInContext?: number\n /** How to rank file relevance when selecting context. */\n relevanceStrategy?: RelevanceStrategy\n /** Glob patterns to exclude from indexing and context. */\n ignorePatterns?: string[]\n /** File extensions to include in indexing (default: all text files). */\n includeExtensions?: string[]\n}\n\nexport function ProjectContext(options: ProjectContextOptions = {}): ClassDecorator {\n return (target: Function) => {\n setMeta(PROJECT_CONTEXT_CONFIG, target, {\n rootMarkers: ['package.json', 'tsconfig.json', 'go.mod', 'Cargo.toml', 'pyproject.toml'],\n indexStrategy: 'regex',\n maxFilesInContext: 20,\n relevanceStrategy: 'git-history',\n ignorePatterns: ['node_modules', 'dist', 'build', '.git', 'coverage', '__pycache__'],\n ...options,\n })\n }\n}\n\nexport function getProjectContextConfig(target: Function): ProjectContextOptions | undefined {\n return getMeta<ProjectContextOptions>(PROJECT_CONTEXT_CONFIG, target)\n}\n","/**\n * @Mixin() — compose reusable capability classes into an agent.\n *\n * Mixins are classes with @Tool methods that can be shared across agents.\n * @Mixin copies tool metadata from mixin classes to the decorated agent,\n * making those tools available without inheritance.\n *\n * @example\n * ```ts\n * // Define reusable capabilities\n * class WithSearchCapability {\n * @Tool({ name: 'web_search', description: 'Search', input: z.object({...}) })\n * async webSearch(input) { ... }\n * }\n *\n * class WithFileSystem {\n * @Tool({ name: 'read_file', description: 'Read', input: z.object({...}) })\n * async readFile(input) { ... }\n * }\n *\n * // Compose into agent\n * @Agent({ name: 'research', route: '/research' })\n * @Mixin(WithSearchCapability, WithFileSystem)\n * class ResearchAgent {\n * @MainLoop()\n * async run() {}\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst MIXIN_CLASSES = Symbol.for('theokit:agents:mixins')\n\nexport function Mixin(...mixinClasses: Function[]): ClassDecorator {\n return (target: Function) => {\n const existing = getMeta<Function[]>(MIXIN_CLASSES, target) ?? []\n setMeta(MIXIN_CLASSES, target, [...existing, ...mixinClasses])\n }\n}\n\nexport function getMixins(target: Function): Function[] {\n return getMeta<Function[]>(MIXIN_CLASSES, target) ?? []\n}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;AAE1B,SAASC,SAASC,cAAwB;AAC/C,SAAO,CAACC,WAAAA;AACN,UAAMC,WAAWC,QAAoBP,eAAeK,MAAAA,KAAW,CAAA;AAC/DG,YAAQR,eAAeK,QAAQ;SAAIC;SAAaF;KAAa;EAC/D;AACF;AALgBD;AAOT,SAASM,UAAUJ,QAAgB;AACxC,SAAOE,QAAoBP,eAAeK,MAAAA,KAAW,CAAA;AACvD;AAFgBI;","names":["setMeta","getMeta","AGENT_CONFIG","Symbol","for","AGENT_MAIN_LOOP","TOOLBOX_CONFIG","TOOL_CONFIG","TOOL_METHODS","inferAgentMeta","className","stripped","replace","kebab","toLowerCase","name","route","Agent","options","target","inferred","setMeta","AGENT_CONFIG","stream","getAgentConfig","getMeta","createDecorator","RequiresApproval","RequiresCapability","Budget","Policy","createDecorator","Trace","Audit","GATEWAY_CONFIG","Symbol","for","Gateway","options","target","setMeta","typing","sessionStrategy","getGatewayConfig","getMeta","resolveSessionId","strategy","platform","sender","channel","id","topicId","SUB_AGENTS","Symbol","for","SubAgents","agentClasses","target","cls","config","getAgentConfig","Error","name","setMeta","getSubAgents","getMeta","MEMORY_CONFIG","Symbol","for","Memory","options","target","setMeta","provider","embeddings","fts","scope","getMemoryConfig","getMeta","SKILLS_CONFIG","Symbol","for","Skills","namesOrOptions","target","options","Array","isArray","include","autoDiscover","setMeta","getSkillsConfig","getMeta","GUARDRAILS_CONFIG","Symbol","for","Guardrails","guardrails","target","setMeta","getGuardrailsConfig","getMeta","MCP_CONFIG","Symbol","for","MCP","servers","target","setMeta","getMcpConfig","getMeta","HITL_CONFIG","Symbol","for","HumanInTheLoop","options","target","propertyKey","actualTarget","setMeta","timeout","onTimeout","showInput","getHumanInTheLoopConfig","getMeta","CONTEXT_WINDOW_CONFIG","Symbol","for","ContextWindow","options","target","setMeta","maxTokens","compactionStrategy","preserveSystemPrompt","preserveLastN","preserveToolResults","getContextWindowConfig","getMeta","COMPACTION_CONFIG","Symbol","for","Compaction","name","options","target","setMeta","keepTokens","getCompactionConfig","getMeta","CHECKPOINT_CONFIG","Symbol","for","Checkpoint","options","target","setMeta","storage","strategy","maxCheckpoints","ttl","getCheckpointConfig","getMeta","PROJECT_CONTEXT_CONFIG","Symbol","for","ProjectContext","options","target","setMeta","rootMarkers","indexStrategy","maxFilesInContext","relevanceStrategy","ignorePatterns","getProjectContextConfig","getMeta","MIXIN_CLASSES","Symbol","for","Mixin","mixinClasses","target","existing","getMeta","setMeta","getMixins"]}
|