@theokit/agents 0.3.0 → 0.5.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/decorators/main-loop.ts","../src/decorators/tool.ts","../src/decorators/hook.ts","../src/decorators/conversation.ts","../src/decorators/human-in-the-loop.ts","../src/decorators/model.ts","../src/decorators/artifact.ts","../src/decorators/checkpoint.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 * @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\nexport function HumanInTheLoop(options: HumanInTheLoopOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(HITL_CONFIG, actualTarget, {\n timeout: 300_000,\n onTimeout: 'abort',\n showInput: true,\n ...options,\n }, propertyKey)\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 * @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 * @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: 'drizzle',\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 from checkpoint:\n * // POST /agents/research/chat { resumeToken: 'chk_abc123' }\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 * @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,CAAC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AAI,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","HITL_CONFIG","Symbol","for","HumanInTheLoop","options","target","propertyKey","actualTarget","setMeta","timeout","onTimeout","showInput","getHumanInTheLoopConfig","getMeta","createDecorator","Model","ARTIFACT_CONFIG","Symbol","for","Artifact","options","target","propertyKey","actualTarget","setMeta","streamable","maxSize","getArtifactConfig","getMeta","CHECKPOINT_CONFIG","Symbol","for","Checkpoint","options","target","setMeta","storage","strategy","maxCheckpoints","ttl","getCheckpointConfig","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,8 +1,8 @@
1
- import { A as AgentOptions, d as MainLoopOptions, c as MainLoopMeta, T as ToolOptions, n as ToolboxOptions, B as BudgetOptions, k as PolicyHandler, a as ApprovalOptions } from './mcp-DmtwLSF-.js';
2
- export { G as Gateway, b as GatewayOptions, M as MCP, e as McpServerConfig, f as McpServersMap, g as Memory, h as MemoryOptions, i as MemoryProvider, j as MemoryScope, P as PlatformName, S as SessionStrategy, l as Skills, m as SkillsOptions, o as getGatewayConfig, p as getMcpConfig, q as getMemoryConfig, r as getSkillsConfig, s as resolveSessionId } from './mcp-DmtwLSF-.js';
1
+ import { A as AgentOptions, f as MainLoopOptions, e as MainLoopMeta, T as ToolOptions, r as ToolboxOptions, B as BudgetOptions, m as PolicyHandler, a as ApprovalOptions } from './skills-DnfvEUSg.js';
2
+ export { C as ContextCompactionStrategy, b as ContextWindow, c as ContextWindowOptions, G as Gateway, d as GatewayOptions, I as IndexStrategy, M as MCP, g as McpServerConfig, h as McpServersMap, i as Memory, j as MemoryOptions, k as MemoryProvider, l as MemoryScope, P as PlatformName, n as ProjectContext, o as ProjectContextOptions, R as RelevanceStrategy, S as SessionStrategy, p as Skills, q as SkillsOptions, s as getContextWindowConfig, t as getGatewayConfig, u as getMcpConfig, v as getMemoryConfig, w as getProjectContextConfig, x as getSkillsConfig, y as resolveSessionId } from './skills-DnfvEUSg.js';
3
3
  import 'zod';
4
4
 
5
- declare function Agent(options: AgentOptions): ClassDecorator;
5
+ declare function Agent(options?: Partial<AgentOptions>): ClassDecorator;
6
6
  declare function getAgentConfig(target: Function): AgentOptions | undefined;
7
7
 
8
8
  declare function MainLoop(options?: MainLoopOptions): MethodDecorator;
@@ -71,22 +71,6 @@ interface HumanInTheLoopOptions {
71
71
  declare function HumanInTheLoop(options: HumanInTheLoopOptions): MethodDecorator;
72
72
  declare function getHumanInTheLoopConfig(target: Function, propertyKey: string | symbol): HumanInTheLoopOptions | undefined;
73
73
 
74
- type ContextCompactionStrategy = 'truncate-oldest' | 'summarize-oldest' | 'sliding-window' | 'priority-based';
75
- interface ContextWindowOptions {
76
- /** Maximum tokens before compaction triggers. */
77
- maxTokens?: number;
78
- /** How to compact when maxTokens is exceeded. */
79
- compactionStrategy?: ContextCompactionStrategy;
80
- /** Always preserve the system prompt during compaction (default: true). */
81
- preserveSystemPrompt?: boolean;
82
- /** Number of recent messages to always keep intact (default: 10). */
83
- preserveLastN?: number;
84
- /** Keep all tool results even during compaction (default: true). */
85
- preserveToolResults?: boolean;
86
- }
87
- declare function ContextWindow(options?: ContextWindowOptions): ClassDecorator;
88
- declare function getContextWindowConfig(target: Function): ContextWindowOptions | undefined;
89
-
90
74
  /** Override the LLM model for an agent class or a specific tool method. */
91
75
  declare const Model: (value: string) => MethodDecorator & ClassDecorator;
92
76
 
@@ -191,25 +175,6 @@ type EditFormatType = 'search-replace' | 'unified-diff' | 'full-file' | 'line-ra
191
175
  /** Declare the edit format a tool produces. */
192
176
  declare const EditFormat: (value: EditFormatType) => MethodDecorator & ClassDecorator;
193
177
 
194
- type IndexStrategy = 'tree-sitter' | 'regex' | 'none';
195
- type RelevanceStrategy = 'git-history' | 'import-graph' | 'semantic' | 'manual';
196
- interface ProjectContextOptions {
197
- /** Files that mark the project root (searched upward from cwd). */
198
- rootMarkers?: string[];
199
- /** How to index the codebase for structural understanding. */
200
- indexStrategy?: IndexStrategy;
201
- /** Maximum files to include in context per request. */
202
- maxFilesInContext?: number;
203
- /** How to rank file relevance when selecting context. */
204
- relevanceStrategy?: RelevanceStrategy;
205
- /** Glob patterns to exclude from indexing and context. */
206
- ignorePatterns?: string[];
207
- /** File extensions to include in indexing (default: all text files). */
208
- includeExtensions?: string[];
209
- }
210
- declare function ProjectContext(options?: ProjectContextOptions): ClassDecorator;
211
- declare function getProjectContextConfig(target: Function): ProjectContextOptions | undefined;
212
-
213
178
  /**
214
179
  * applyDecorators() — compose multiple decorators into a single reusable decorator.
215
180
  *
@@ -245,4 +210,4 @@ declare function applyDecorators(...decorators: AnyDecorator[]): ClassDecorator
245
210
  declare function Mixin(...mixinClasses: Function[]): ClassDecorator;
246
211
  declare function getMixins(target: Function): Function[];
247
212
 
248
- export { Agent, AgentOptions, ApprovalOptions, Artifact, type ArtifactOptions, type ArtifactResult, Audit, Budget, BudgetOptions, Checkpoint, type CheckpointOptions, type CheckpointState, type CheckpointStorage, type CheckpointStrategy, type CommandPermissions, type CompactionStrategy, type ContextCompactionStrategy, ContextWindow, type ContextWindowOptions, Conversation, type ConversationOptions, type ConversationStorage, EditFormat, type EditFormatType, type FilesystemPermissions, Hook, type HookEntry, type HookPoint, HumanInTheLoop, type HumanInTheLoopOptions, type IndexStrategy, MainLoop, MainLoopMeta, MainLoopOptions, Mixin, Model, Observable, type ObservableEntry, Policy, PolicyHandler, ProjectContext, type ProjectContextOptions, type RelevanceStrategy, RequiresApproval, RequiresCapability, Sandbox, type SandboxOptions, SubAgents, type TimeoutAction, Tool, ToolOptions, Toolbox, ToolboxOptions, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getContextWindowConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getProjectContextConfig, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed };
213
+ export { Agent, AgentOptions, ApprovalOptions, Artifact, type ArtifactOptions, type ArtifactResult, Audit, Budget, BudgetOptions, Checkpoint, type CheckpointOptions, type CheckpointState, type CheckpointStorage, type CheckpointStrategy, type CommandPermissions, type CompactionStrategy, Conversation, type ConversationOptions, type ConversationStorage, EditFormat, type EditFormatType, type FilesystemPermissions, Hook, type HookEntry, type HookPoint, HumanInTheLoop, type HumanInTheLoopOptions, MainLoop, MainLoopMeta, MainLoopOptions, Mixin, Model, Observable, type ObservableEntry, Policy, PolicyHandler, RequiresApproval, RequiresCapability, Sandbox, type SandboxOptions, SubAgents, type TimeoutAction, Tool, ToolOptions, Toolbox, ToolboxOptions, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed };
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  Artifact,
3
3
  Checkpoint,
4
- ContextWindow,
5
4
  Conversation,
6
5
  EditFormat,
7
6
  Hook,
@@ -9,14 +8,12 @@ import {
9
8
  MainLoop,
10
9
  Model,
11
10
  Observable,
12
- ProjectContext,
13
11
  Sandbox,
14
12
  Tool,
15
13
  Toolbox,
16
14
  applyDecorators,
17
15
  getArtifactConfig,
18
16
  getCheckpointConfig,
19
- getContextWindowConfig,
20
17
  getConversationConfig,
21
18
  getHooks,
22
19
  getHooksByPoint,
@@ -24,37 +21,41 @@ import {
24
21
  getMainLoop,
25
22
  getObservableByChannel,
26
23
  getObservables,
27
- getProjectContextConfig,
28
24
  getSandboxConfig,
29
25
  getToolConfig,
30
26
  getToolMethods,
31
27
  getToolboxConfig,
32
28
  isCommandAllowed,
33
29
  isPathAllowed
34
- } from "./chunk-QNPXMBSH.js";
30
+ } from "./chunk-XWVZS2PQ.js";
35
31
  import {
36
32
  Agent,
37
33
  Audit,
38
34
  Budget,
35
+ ContextWindow,
39
36
  Gateway,
40
37
  MCP,
41
38
  Memory,
42
39
  Mixin,
43
40
  Policy,
41
+ ProjectContext,
44
42
  RequiresApproval,
45
43
  RequiresCapability,
46
44
  Skills,
47
45
  SubAgents,
48
46
  Trace,
49
47
  getAgentConfig,
48
+ getContextWindowConfig,
50
49
  getGatewayConfig,
51
50
  getMcpConfig,
52
51
  getMemoryConfig,
53
52
  getMixins,
53
+ getProjectContextConfig,
54
54
  getSkillsConfig,
55
55
  getSubAgents,
56
56
  resolveSessionId
57
- } from "./chunk-3LCIXX3T.js";
57
+ } from "./chunk-MVEY7HEY.js";
58
+ import "./chunk-7QVYU63E.js";
58
59
  export {
59
60
  Agent,
60
61
  Artifact,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- export { Agent, Artifact, ArtifactOptions, ArtifactResult, Audit, Budget, Checkpoint, CheckpointOptions, CheckpointState, CheckpointStorage, CheckpointStrategy, CommandPermissions, CompactionStrategy, ContextCompactionStrategy, ContextWindow, ContextWindowOptions, Conversation, ConversationOptions, ConversationStorage, EditFormat, EditFormatType, FilesystemPermissions, Hook, HookEntry, HookPoint, HumanInTheLoop, HumanInTheLoopOptions, IndexStrategy, MainLoop, Mixin, Model, Observable, ObservableEntry, Policy, ProjectContext, ProjectContextOptions, RelevanceStrategy, RequiresApproval, RequiresCapability, Sandbox, SandboxOptions, SubAgents, TimeoutAction, Tool, Toolbox, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getContextWindowConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getProjectContextConfig, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed } from './decorators.js';
2
- export { A as AgentOptions, a as ApprovalOptions, B as BudgetOptions, G as Gateway, b as GatewayOptions, M as MCP, c as MainLoopMeta, d as MainLoopOptions, e as McpServerConfig, f as McpServersMap, g as Memory, h as MemoryOptions, i as MemoryProvider, j as MemoryScope, P as PlatformName, k as PolicyHandler, S as SessionStrategy, l as Skills, m as SkillsOptions, T as ToolOptions, n as ToolboxOptions, o as getGatewayConfig, p as getMcpConfig, q as getMemoryConfig, r as getSkillsConfig, s as resolveSessionId } from './mcp-DmtwLSF-.js';
3
- export { AgentExecutionContext, AgentManifest, AgentManifestEntry, AgentManifestTool, AgentRoute, AgentRouteContext, AgentRunInfo, AgentStreamEvent, AgentWalkResult, AgentsPluginOptions, ApprovalRequiredEvent, ArtifactChunkEvent, ArtifactStartEvent, BudgetExceededError, CheckpointSavedEvent, CompiledAgentOptions, CompiledTool, DelegateOptions, DelegationError, DelegationResult, DoneEvent, ErrorEvent, FileEditEvent, IterationEvent, RunStartedEvent, StateUpdateEvent, StreamEvent, TextDeltaEvent, ThinkingEvent, ToolCallEvent, ToolResultEvent, ToolWalkResult, ToolboxWalkResult, agentsPlugin, compileAgent, compileTools, createAgentExecutionContext, createRealAgentStream, delegate, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, streamAgentResponse, validateUniqueRoutes, walkAgentMetadata } from './bridge.js';
1
+ export { Agent, Artifact, ArtifactOptions, ArtifactResult, Audit, Budget, Checkpoint, CheckpointOptions, CheckpointState, CheckpointStorage, CheckpointStrategy, CommandPermissions, CompactionStrategy, Conversation, ConversationOptions, ConversationStorage, EditFormat, EditFormatType, FilesystemPermissions, Hook, HookEntry, HookPoint, HumanInTheLoop, HumanInTheLoopOptions, MainLoop, Mixin, Model, Observable, ObservableEntry, Policy, RequiresApproval, RequiresCapability, Sandbox, SandboxOptions, SubAgents, TimeoutAction, Tool, Toolbox, Trace, applyDecorators, getAgentConfig, getArtifactConfig, getCheckpointConfig, getConversationConfig, getHooks, getHooksByPoint, getHumanInTheLoopConfig, getMainLoop, getMixins, getObservableByChannel, getObservables, getSandboxConfig, getSubAgents, getToolConfig, getToolMethods, getToolboxConfig, isCommandAllowed, isPathAllowed } from './decorators.js';
2
+ export { A as AgentOptions, a as ApprovalOptions, B as BudgetOptions, C as ContextCompactionStrategy, b as ContextWindow, c as ContextWindowOptions, G as Gateway, d as GatewayOptions, I as IndexStrategy, M as MCP, e as MainLoopMeta, f as MainLoopOptions, g as McpServerConfig, h as McpServersMap, i as Memory, j as MemoryOptions, k as MemoryProvider, l as MemoryScope, P as PlatformName, m as PolicyHandler, n as ProjectContext, o as ProjectContextOptions, R as RelevanceStrategy, S as SessionStrategy, p as Skills, q as SkillsOptions, T as ToolOptions, r as ToolboxOptions, s as getContextWindowConfig, t as getGatewayConfig, u as getMcpConfig, v as getMemoryConfig, w as getProjectContextConfig, x as getSkillsConfig, y as resolveSessionId } from './skills-DnfvEUSg.js';
3
+ export { AgentExecutionContext, AgentManifest, AgentManifestEntry, AgentManifestTool, AgentRoute, AgentRouteContext, AgentRunInfo, AgentStreamEvent, AgentWalkResult, AgentWarningCode, AgentsPluginOptions, ApprovalRequiredEvent, ArtifactChunkEvent, ArtifactStartEvent, BudgetExceededError, CheckpointSavedEvent, CompiledAgentOptions, CompiledContextWindow, CompiledTool, DelegateOptions, DelegationError, DelegationResult, DoneEvent, ErrorEvent, FileEditEvent, IterationEvent, RunStartedEvent, SdkMessage, StateUpdateEvent, StreamEvent, TextDeltaEvent, ThinkingEvent, ToolCallEvent, ToolResultEvent, ToolWalkResult, ToolboxWalkResult, agentsPlugin, compileAgent, compileContextWindow, compileProjectContext, compileSkills, compileTools, createAgentExecutionContext, createSdkAgentStream, delegate, generateAgentManifest, generateAgentRoutes, isAgentContext, isApprovalRequired, isDone, isError, isTextDelta, isToolCall, isToolResult, projectContextMetadataOnlyKnobs, streamAgentResponse, translateSdkEvent, validateUniqueRoutes, walkAgentMetadata } from './bridge.js';
4
4
  import 'zod';
5
- import '@theokit/http-decorators';
5
+ import '@theokit/http';
6
+ import '@theokit/sdk';
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  Artifact,
3
3
  Checkpoint,
4
- ContextWindow,
5
4
  Conversation,
6
5
  EditFormat,
7
6
  Hook,
@@ -9,14 +8,12 @@ import {
9
8
  MainLoop,
10
9
  Model,
11
10
  Observable,
12
- ProjectContext,
13
11
  Sandbox,
14
12
  Tool,
15
13
  Toolbox,
16
14
  applyDecorators,
17
15
  getArtifactConfig,
18
16
  getCheckpointConfig,
19
- getContextWindowConfig,
20
17
  getConversationConfig,
21
18
  getHooks,
22
19
  getHooksByPoint,
@@ -24,22 +21,25 @@ import {
24
21
  getMainLoop,
25
22
  getObservableByChannel,
26
23
  getObservables,
27
- getProjectContextConfig,
28
24
  getSandboxConfig,
29
25
  getToolConfig,
30
26
  getToolMethods,
31
27
  getToolboxConfig,
32
28
  isCommandAllowed,
33
29
  isPathAllowed
34
- } from "./chunk-QNPXMBSH.js";
30
+ } from "./chunk-XWVZS2PQ.js";
35
31
  import {
32
+ AgentWarningCode,
36
33
  BudgetExceededError,
37
34
  DelegationError,
38
35
  agentsPlugin,
39
36
  compileAgent,
37
+ compileContextWindow,
38
+ compileProjectContext,
39
+ compileSkills,
40
40
  compileTools,
41
41
  createAgentExecutionContext,
42
- createRealAgentStream,
42
+ createSdkAgentStream,
43
43
  delegate,
44
44
  generateAgentManifest,
45
45
  generateAgentRoutes,
@@ -50,35 +50,43 @@ import {
50
50
  isTextDelta,
51
51
  isToolCall,
52
52
  isToolResult,
53
+ projectContextMetadataOnlyKnobs,
53
54
  streamAgentResponse,
55
+ translateSdkEvent,
54
56
  validateUniqueRoutes,
55
57
  walkAgentMetadata
56
- } from "./chunk-SWPOX3LR.js";
58
+ } from "./chunk-2MI27XCA.js";
57
59
  import {
58
60
  Agent,
59
61
  Audit,
60
62
  Budget,
63
+ ContextWindow,
61
64
  Gateway,
62
65
  MCP,
63
66
  Memory,
64
67
  Mixin,
65
68
  Policy,
69
+ ProjectContext,
66
70
  RequiresApproval,
67
71
  RequiresCapability,
68
72
  Skills,
69
73
  SubAgents,
70
74
  Trace,
71
75
  getAgentConfig,
76
+ getContextWindowConfig,
72
77
  getGatewayConfig,
73
78
  getMcpConfig,
74
79
  getMemoryConfig,
75
80
  getMixins,
81
+ getProjectContextConfig,
76
82
  getSkillsConfig,
77
83
  getSubAgents,
78
84
  resolveSessionId
79
- } from "./chunk-3LCIXX3T.js";
85
+ } from "./chunk-MVEY7HEY.js";
86
+ import "./chunk-7QVYU63E.js";
80
87
  export {
81
88
  Agent,
89
+ AgentWarningCode,
82
90
  Artifact,
83
91
  Audit,
84
92
  Budget,
@@ -110,9 +118,12 @@ export {
110
118
  agentsPlugin,
111
119
  applyDecorators,
112
120
  compileAgent,
121
+ compileContextWindow,
122
+ compileProjectContext,
123
+ compileSkills,
113
124
  compileTools,
114
125
  createAgentExecutionContext,
115
- createRealAgentStream,
126
+ createSdkAgentStream,
116
127
  delegate,
117
128
  generateAgentManifest,
118
129
  generateAgentRoutes,
@@ -147,8 +158,10 @@ export {
147
158
  isTextDelta,
148
159
  isToolCall,
149
160
  isToolResult,
161
+ projectContextMetadataOnlyKnobs,
150
162
  resolveSessionId,
151
163
  streamAgentResponse,
164
+ translateSdkEvent,
152
165
  validateUniqueRoutes,
153
166
  walkAgentMetadata
154
167
  };
@@ -1,4 +1,4 @@
1
- import { ZodTypeAny } from 'zod';
1
+ import { z } from 'zod';
2
2
 
3
3
  /** Configuration stored by @Agent() decorator. */
4
4
  interface AgentOptions {
@@ -45,7 +45,7 @@ interface ToolOptions {
45
45
  /** LLM-facing description. */
46
46
  description: string;
47
47
  /** Zod input schema — compiled to JSON Schema via defineTool(). */
48
- input: ZodTypeAny;
48
+ input: z.ZodType;
49
49
  /** Risk level (informational — feeds manifest + UI). */
50
50
  risk?: 'low' | 'medium' | 'high';
51
51
  }
@@ -66,6 +66,22 @@ type PolicyHandler = (user: {
66
66
  roles: string[];
67
67
  }) => boolean;
68
68
 
69
+ type ContextCompactionStrategy = 'truncate-oldest' | 'summarize-oldest' | 'sliding-window' | 'priority-based';
70
+ interface ContextWindowOptions {
71
+ /** Maximum tokens before compaction triggers. */
72
+ maxTokens?: number;
73
+ /** How to compact when maxTokens is exceeded. */
74
+ compactionStrategy?: ContextCompactionStrategy;
75
+ /** Always preserve the system prompt during compaction (default: true). */
76
+ preserveSystemPrompt?: boolean;
77
+ /** Number of recent messages to always keep intact (default: 10). */
78
+ preserveLastN?: number;
79
+ /** Keep all tool results even during compaction (default: true). */
80
+ preserveToolResults?: boolean;
81
+ }
82
+ declare function ContextWindow(options?: ContextWindowOptions): ClassDecorator;
83
+ declare function getContextWindowConfig(target: Function): ContextWindowOptions | undefined;
84
+
69
85
  type PlatformName = 'telegram' | 'discord' | 'slack' | 'whatsapp' | 'teams' | 'email' | 'sms' | 'mattermost' | 'line' | 'matrix';
70
86
  type SessionStrategy = 'per-user' | 'per-channel' | 'per-thread';
71
87
  interface GatewayOptions {
@@ -92,6 +108,20 @@ declare function resolveSessionId(strategy: SessionStrategy, platform: string, s
92
108
  topicId?: string;
93
109
  }): string;
94
110
 
111
+ interface McpServerConfig {
112
+ /** Command to start the MCP server. */
113
+ command: string;
114
+ /** Arguments passed to the command. */
115
+ args?: string[];
116
+ /** Environment variables for the server process. */
117
+ env?: Record<string, string>;
118
+ /** Working directory for the server process. */
119
+ cwd?: string;
120
+ }
121
+ type McpServersMap = Record<string, McpServerConfig>;
122
+ declare function MCP(servers: McpServersMap): ClassDecorator;
123
+ declare function getMcpConfig(target: Function): McpServersMap | undefined;
124
+
95
125
  type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0';
96
126
  type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global';
97
127
  interface MemoryOptions {
@@ -109,6 +139,25 @@ interface MemoryOptions {
109
139
  declare function Memory(options?: MemoryOptions): ClassDecorator;
110
140
  declare function getMemoryConfig(target: Function): MemoryOptions | undefined;
111
141
 
142
+ type IndexStrategy = 'tree-sitter' | 'regex' | 'none';
143
+ type RelevanceStrategy = 'git-history' | 'import-graph' | 'semantic' | 'manual';
144
+ interface ProjectContextOptions {
145
+ /** Files that mark the project root (searched upward from cwd). */
146
+ rootMarkers?: string[];
147
+ /** How to index the codebase for structural understanding. */
148
+ indexStrategy?: IndexStrategy;
149
+ /** Maximum files to include in context per request. */
150
+ maxFilesInContext?: number;
151
+ /** How to rank file relevance when selecting context. */
152
+ relevanceStrategy?: RelevanceStrategy;
153
+ /** Glob patterns to exclude from indexing and context. */
154
+ ignorePatterns?: string[];
155
+ /** File extensions to include in indexing (default: all text files). */
156
+ includeExtensions?: string[];
157
+ }
158
+ declare function ProjectContext(options?: ProjectContextOptions): ClassDecorator;
159
+ declare function getProjectContextConfig(target: Function): ProjectContextOptions | undefined;
160
+
112
161
  interface SkillsOptions {
113
162
  /** Skill names to include (resolved from .theokit/skills/<name>/SKILL.md). */
114
163
  include: string[];
@@ -118,18 +167,4 @@ interface SkillsOptions {
118
167
  declare function Skills(namesOrOptions: string[] | SkillsOptions): ClassDecorator;
119
168
  declare function getSkillsConfig(target: Function): SkillsOptions | undefined;
120
169
 
121
- interface McpServerConfig {
122
- /** Command to start the MCP server. */
123
- command: string;
124
- /** Arguments passed to the command. */
125
- args?: string[];
126
- /** Environment variables for the server process. */
127
- env?: Record<string, string>;
128
- /** Working directory for the server process. */
129
- cwd?: string;
130
- }
131
- type McpServersMap = Record<string, McpServerConfig>;
132
- declare function MCP(servers: McpServersMap): ClassDecorator;
133
- declare function getMcpConfig(target: Function): McpServersMap | undefined;
134
-
135
- export { type AgentOptions as A, type BudgetOptions as B, Gateway as G, MCP as M, type PlatformName as P, type SessionStrategy as S, type ToolOptions as T, type ApprovalOptions as a, type GatewayOptions as b, type MainLoopMeta as c, type MainLoopOptions as d, type McpServerConfig as e, type McpServersMap as f, Memory as g, type MemoryOptions as h, type MemoryProvider as i, type MemoryScope as j, type PolicyHandler as k, Skills as l, type SkillsOptions as m, type ToolboxOptions as n, getGatewayConfig as o, getMcpConfig as p, getMemoryConfig as q, getSkillsConfig as r, resolveSessionId as s };
170
+ export { type AgentOptions as A, type BudgetOptions as B, type ContextCompactionStrategy as C, Gateway as G, type IndexStrategy as I, MCP as M, type PlatformName as P, type RelevanceStrategy as R, type SessionStrategy as S, type ToolOptions as T, type ApprovalOptions as a, ContextWindow as b, type ContextWindowOptions as c, type GatewayOptions as d, type MainLoopMeta as e, type MainLoopOptions as f, type McpServerConfig as g, type McpServersMap as h, Memory as i, type MemoryOptions as j, type MemoryProvider as k, type MemoryScope as l, type PolicyHandler as m, ProjectContext as n, type ProjectContextOptions as o, Skills as p, type SkillsOptions as q, type ToolboxOptions as r, getContextWindowConfig as s, getGatewayConfig as t, getMcpConfig as u, getMemoryConfig as v, getProjectContextConfig as w, getSkillsConfig as x, resolveSessionId as y };
@@ -0,0 +1,47 @@
1
+ /**
2
+ * createMockAgentStream — test agents without an LLM API key.
3
+ *
4
+ * Returns an AsyncIterable that yields typed SSE events in sequence,
5
+ * simulating an agent conversation. Use in vitest/jest to test agent
6
+ * wiring, tool call handling, and UI rendering without real LLM costs.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { createMockAgentStream } from '@theokit/agents/testing'
11
+ *
12
+ * const stream = createMockAgentStream({
13
+ * responses: [
14
+ * { type: 'text', content: 'Here are your tasks:' },
15
+ * { type: 'tool_call', name: 'tasks.list', input: {}, output: '[{"id":1}]' },
16
+ * { type: 'text', content: 'You have 1 task.' },
17
+ * ],
18
+ * })
19
+ *
20
+ * const events = []
21
+ * for await (const event of stream('hello', 'session-1')) {
22
+ * events.push(event)
23
+ * }
24
+ * // events: [run_started, text_delta, tool_call, tool_result, text_delta, done]
25
+ * ```
26
+ */
27
+ interface MockResponse {
28
+ type: 'text' | 'tool_call' | 'error';
29
+ content?: string;
30
+ name?: string;
31
+ input?: unknown;
32
+ output?: string;
33
+ message?: string;
34
+ }
35
+ interface MockAgentStreamOptions {
36
+ agentName?: string;
37
+ responses: MockResponse[];
38
+ /** Simulated cost in USD (default: 0). */
39
+ cost?: number;
40
+ }
41
+ interface MockStreamEvent {
42
+ type: string;
43
+ [key: string]: unknown;
44
+ }
45
+ declare function createMockAgentStream(opts: MockAgentStreamOptions): (_message: string, _sessionId: string) => AsyncIterable<MockStreamEvent>;
46
+
47
+ export { type MockAgentStreamOptions, type MockResponse, type MockStreamEvent, createMockAgentStream };
@@ -0,0 +1,73 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/testing/mock-stream.ts
6
+ function createMockAgentStream(opts) {
7
+ return (_message, _sessionId) => ({
8
+ async *[Symbol.asyncIterator]() {
9
+ await Promise.resolve();
10
+ const runId = `mock-${Date.now()}`;
11
+ yield {
12
+ type: "run_started",
13
+ runId,
14
+ agentName: opts.agentName ?? "mock-agent",
15
+ model: "mock"
16
+ };
17
+ let totalTokens = 0;
18
+ for (const r of opts.responses) {
19
+ if (r.type === "text" && r.content) {
20
+ const words = r.content.split(" ");
21
+ for (const word of words) {
22
+ yield {
23
+ type: "text_delta",
24
+ content: word + " "
25
+ };
26
+ totalTokens += 2;
27
+ }
28
+ } else if (r.type === "tool_call") {
29
+ const callId = `tc-${Date.now()}-${crypto.randomUUID().slice(0, 4)}`;
30
+ yield {
31
+ type: "tool_call",
32
+ callId,
33
+ toolName: r.name ?? "unknown",
34
+ input: r.input ?? {}
35
+ };
36
+ yield {
37
+ type: "tool_result",
38
+ callId,
39
+ toolName: r.name ?? "unknown",
40
+ output: r.output ?? "",
41
+ durationMs: 0,
42
+ isError: false
43
+ };
44
+ totalTokens += 10;
45
+ } else if (r.type === "error") {
46
+ yield {
47
+ type: "error",
48
+ code: "MOCK_ERROR",
49
+ message: r.message ?? "Mock error",
50
+ retryable: false
51
+ };
52
+ return;
53
+ }
54
+ }
55
+ yield {
56
+ type: "done",
57
+ result: opts.responses.filter((r) => r.type === "text").map((r) => r.content).join(" "),
58
+ usage: {
59
+ inputTokens: totalTokens,
60
+ outputTokens: totalTokens,
61
+ totalTokens: totalTokens * 2
62
+ },
63
+ durationMs: 0,
64
+ cost: opts.cost ?? 0
65
+ };
66
+ }
67
+ });
68
+ }
69
+ __name(createMockAgentStream, "createMockAgentStream");
70
+ export {
71
+ createMockAgentStream
72
+ };
73
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing/mock-stream.ts"],"sourcesContent":["/**\n * createMockAgentStream — test agents without an LLM API key.\n *\n * Returns an AsyncIterable that yields typed SSE events in sequence,\n * simulating an agent conversation. Use in vitest/jest to test agent\n * wiring, tool call handling, and UI rendering without real LLM costs.\n *\n * @example\n * ```ts\n * import { createMockAgentStream } from '@theokit/agents/testing'\n *\n * const stream = createMockAgentStream({\n * responses: [\n * { type: 'text', content: 'Here are your tasks:' },\n * { type: 'tool_call', name: 'tasks.list', input: {}, output: '[{\"id\":1}]' },\n * { type: 'text', content: 'You have 1 task.' },\n * ],\n * })\n *\n * const events = []\n * for await (const event of stream('hello', 'session-1')) {\n * events.push(event)\n * }\n * // events: [run_started, text_delta, tool_call, tool_result, text_delta, done]\n * ```\n */\n\nexport interface MockResponse {\n type: 'text' | 'tool_call' | 'error'\n content?: string\n name?: string\n input?: unknown\n output?: string\n message?: string\n}\n\nexport interface MockAgentStreamOptions {\n agentName?: string\n responses: MockResponse[]\n /** Simulated cost in USD (default: 0). */\n cost?: number\n}\n\nexport interface MockStreamEvent {\n type: string\n [key: string]: unknown\n}\n\nexport function createMockAgentStream(opts: MockAgentStreamOptions) {\n return (_message: string, _sessionId: string): AsyncIterable<MockStreamEvent> => ({\n async *[Symbol.asyncIterator]() {\n await Promise.resolve() // yield to event loop for async contract\n const runId = `mock-${Date.now()}`\n yield { type: 'run_started', runId, agentName: opts.agentName ?? 'mock-agent', model: 'mock' }\n\n let totalTokens = 0\n for (const r of opts.responses) {\n if (r.type === 'text' && r.content) {\n const words = r.content.split(' ')\n for (const word of words) {\n yield { type: 'text_delta', content: word + ' ' }\n totalTokens += 2\n }\n } else if (r.type === 'tool_call') {\n const callId = `tc-${Date.now()}-${crypto.randomUUID().slice(0, 4)}`\n yield { type: 'tool_call', callId, toolName: r.name ?? 'unknown', input: r.input ?? {} }\n yield {\n type: 'tool_result',\n callId,\n toolName: r.name ?? 'unknown',\n output: r.output ?? '',\n durationMs: 0,\n isError: false,\n }\n totalTokens += 10\n } else if (r.type === 'error') {\n yield {\n type: 'error',\n code: 'MOCK_ERROR',\n message: r.message ?? 'Mock error',\n retryable: false,\n }\n return\n }\n }\n\n yield {\n type: 'done',\n result: opts.responses\n .filter((r) => r.type === 'text')\n .map((r) => r.content)\n .join(' '),\n usage: {\n inputTokens: totalTokens,\n outputTokens: totalTokens,\n totalTokens: totalTokens * 2,\n },\n durationMs: 0,\n cost: opts.cost ?? 0,\n }\n },\n })\n}\n"],"mappings":";;;;;AAgDO,SAASA,sBAAsBC,MAA4B;AAChE,SAAO,CAACC,UAAkBC,gBAAwD;IAChF,QAAQC,OAAOC,aAAa,IAAC;AAC3B,YAAMC,QAAQC,QAAO;AACrB,YAAMC,QAAQ,QAAQC,KAAKC,IAAG,CAAA;AAC9B,YAAM;QAAEC,MAAM;QAAeH;QAAOI,WAAWX,KAAKW,aAAa;QAAcC,OAAO;MAAO;AAE7F,UAAIC,cAAc;AAClB,iBAAWC,KAAKd,KAAKe,WAAW;AAC9B,YAAID,EAAEJ,SAAS,UAAUI,EAAEE,SAAS;AAClC,gBAAMC,QAAQH,EAAEE,QAAQE,MAAM,GAAA;AAC9B,qBAAWC,QAAQF,OAAO;AACxB,kBAAM;cAAEP,MAAM;cAAcM,SAASG,OAAO;YAAI;AAChDN,2BAAe;UACjB;QACF,WAAWC,EAAEJ,SAAS,aAAa;AACjC,gBAAMU,SAAS,MAAMZ,KAAKC,IAAG,CAAA,IAAMY,OAAOC,WAAU,EAAGC,MAAM,GAAG,CAAA,CAAA;AAChE,gBAAM;YAAEb,MAAM;YAAaU;YAAQI,UAAUV,EAAEW,QAAQ;YAAWC,OAAOZ,EAAEY,SAAS,CAAC;UAAE;AACvF,gBAAM;YACJhB,MAAM;YACNU;YACAI,UAAUV,EAAEW,QAAQ;YACpBE,QAAQb,EAAEa,UAAU;YACpBC,YAAY;YACZC,SAAS;UACX;AACAhB,yBAAe;QACjB,WAAWC,EAAEJ,SAAS,SAAS;AAC7B,gBAAM;YACJA,MAAM;YACNoB,MAAM;YACNC,SAASjB,EAAEiB,WAAW;YACtBC,WAAW;UACb;AACA;QACF;MACF;AAEA,YAAM;QACJtB,MAAM;QACNuB,QAAQjC,KAAKe,UACVmB,OAAO,CAACpB,MAAMA,EAAEJ,SAAS,MAAA,EACzByB,IAAI,CAACrB,MAAMA,EAAEE,OAAO,EACpBoB,KAAK,GAAA;QACRC,OAAO;UACLC,aAAazB;UACb0B,cAAc1B;UACdA,aAAaA,cAAc;QAC7B;QACAe,YAAY;QACZY,MAAMxC,KAAKwC,QAAQ;MACrB;IACF;EACF;AACF;AAtDgBzC;","names":["createMockAgentStream","opts","_message","_sessionId","Symbol","asyncIterator","Promise","resolve","runId","Date","now","type","agentName","model","totalTokens","r","responses","content","words","split","word","callId","crypto","randomUUID","slice","toolName","name","input","output","durationMs","isError","code","message","retryable","result","filter","map","join","usage","inputTokens","outputTokens","cost"]}