@theokit/sdk 1.6.2 → 1.8.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/CHANGELOG.md +193 -0
- package/bin/init-claude.mjs +34 -0
- package/claude-template/AGENTS.md +139 -0
- package/claude-template/CLAUDE.md +51 -0
- package/claude-template/dot-claude/rules/theokit-conventions.md +33 -0
- package/claude-template/dot-claude/settings.json +16 -0
- package/claude-template/dot-claude/skills/theokit-agent-core/SKILL.md +209 -0
- package/claude-template/dot-claude/skills/theokit-budget/SKILL.md +176 -0
- package/claude-template/dot-claude/skills/theokit-config/SKILL.md +139 -0
- package/claude-template/dot-claude/skills/theokit-cron/SKILL.md +148 -0
- package/claude-template/dot-claude/skills/theokit-di/SKILL.md +233 -0
- package/claude-template/dot-claude/skills/theokit-di-agent/SKILL.md +294 -0
- package/claude-template/dot-claude/skills/theokit-errors/SKILL.md +172 -0
- package/claude-template/dot-claude/skills/theokit-eval/SKILL.md +144 -0
- package/claude-template/dot-claude/skills/theokit-gateways/SKILL.md +209 -0
- package/claude-template/dot-claude/skills/theokit-memory/SKILL.md +176 -0
- package/claude-template/dot-claude/skills/theokit-rag/SKILL.md +226 -0
- package/claude-template/dot-claude/skills/theokit-streaming/SKILL.md +156 -0
- package/claude-template/dot-claude/skills/theokit-subscriptions/SKILL.md +148 -0
- package/claude-template/dot-claude/skills/theokit-tools/SKILL.md +170 -0
- package/claude-template/dot-claude/skills/theokit-workflows/SKILL.md +218 -0
- package/dist/a2a/agent-mailbox.d.cts +27 -0
- package/dist/a2a/agent-mailbox.d.ts +27 -0
- package/dist/a2a/index.cjs +16850 -0
- package/dist/a2a/index.cjs.map +1 -0
- package/dist/a2a/index.d.cts +9 -0
- package/dist/a2a/index.d.ts +9 -0
- package/dist/a2a/index.js +16844 -0
- package/dist/a2a/index.js.map +1 -0
- package/dist/a2a/message-bus.d.cts +27 -0
- package/dist/a2a/message-bus.d.ts +27 -0
- package/dist/a2a/subagent.d.cts +25 -0
- package/dist/a2a/subagent.d.ts +25 -0
- package/dist/a2a/types.d.cts +12 -0
- package/dist/a2a/types.d.ts +12 -0
- package/dist/agent.d.ts +1 -1
- package/dist/client/index.cjs +73 -0
- package/dist/client/index.cjs.map +1 -0
- package/dist/client/index.d.cts +7 -0
- package/dist/client/index.d.ts +7 -0
- package/dist/client/index.js +71 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/theokit-client.d.cts +18 -0
- package/dist/client/theokit-client.d.ts +18 -0
- package/dist/client/types.d.cts +19 -0
- package/dist/client/types.d.ts +19 -0
- package/dist/{run-DkCD5DeO.d.cts → cron-BnywDYLq.d.cts} +496 -910
- package/dist/{run-DkCD5DeO.d.ts → cron-CtZvJD9J.d.ts} +496 -910
- package/dist/cron.cjs +4285 -2893
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.d.cts +2 -3
- package/dist/cron.d.ts +2 -71
- package/dist/cron.js +4289 -2897
- package/dist/cron.js.map +1 -1
- package/dist/{errors-CvAeEWgE.d.ts → errors-ChqOmFH1.d.cts} +52 -6
- package/dist/{errors-CK8brCJ1.d.cts → errors-DV9e0rcp.d.ts} +52 -6
- package/dist/errors.cjs +218 -3
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -3
- package/dist/errors.d.ts +50 -4
- package/dist/errors.js +217 -4
- package/dist/errors.js.map +1 -1
- package/dist/eval.cjs +4285 -2893
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.d.cts +35 -0
- package/dist/eval.js +4289 -2897
- package/dist/eval.js.map +1 -1
- package/dist/event-bus.d.ts +23 -0
- package/dist/index.cjs +5132 -4200
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +298 -278
- package/dist/index.d.ts +1898 -24
- package/dist/index.js +6441 -5509
- package/dist/index.js.map +1 -1
- package/dist/internal/agent-loop/loop-context-init.d.ts +2 -0
- package/dist/internal/agent-loop/tool-dispatch.d.ts +22 -1
- package/dist/internal/auth/api-key-validator.d.ts +46 -0
- package/dist/internal/llm/anthropic-shared.d.ts +8 -1
- package/dist/internal/llm/retry.d.ts +22 -0
- package/dist/internal/llm/types.d.ts +47 -1
- package/dist/internal/memory/active-memory-cache.d.ts +3 -3
- package/dist/internal/memory/active-memory-types.d.ts +8 -0
- package/dist/internal/memory/active-memory.d.ts +24 -20
- package/dist/internal/memory/adapters/azure-openai-embedding.d.ts +2 -0
- package/dist/internal/memory/adapters/cohere-embedding.d.ts +2 -0
- package/dist/internal/memory/adapters/gemini-embedding.d.ts +2 -0
- package/dist/internal/memory/adapters/jina-embedding.d.ts +2 -0
- package/dist/internal/memory/index-manager-contract.d.ts +26 -0
- package/dist/internal/memory/index-manager-dispatch.d.ts +1 -1
- package/dist/internal/memory/index-manager.d.ts +8 -26
- package/dist/internal/memory/{chunk-markdown.d.ts → storage/chunk-markdown.d.ts} +1 -1
- package/dist/internal/memory/{markdown-store.d.ts → storage/markdown-store.d.ts} +1 -1
- package/dist/internal/memory/{reader.d.ts → storage/reader.d.ts} +1 -1
- package/dist/internal/observability/context.d.cts +23 -0
- package/dist/internal/observability/context.d.ts +23 -0
- package/dist/internal/observability/index.cjs +38 -0
- package/dist/internal/observability/index.cjs.map +1 -0
- package/dist/internal/observability/index.d.cts +8 -0
- package/dist/internal/observability/index.d.ts +8 -0
- package/dist/internal/observability/index.js +33 -0
- package/dist/internal/observability/index.js.map +1 -0
- package/dist/internal/observability/tracer-loader.d.cts +20 -0
- package/dist/internal/persistence/conversation-storage-fs.d.cts +37 -0
- package/dist/internal/persistence/conversation-storage-memory.d.cts +24 -0
- package/dist/internal/persistence/credential-pool-store.d.cts +32 -0
- package/dist/internal/persistence/credential-pool-store.d.ts +32 -0
- package/dist/internal/persistence/cwd-mutex.d.cts +1 -0
- package/dist/internal/persistence/exclusive-create.d.cts +22 -0
- package/dist/internal/persistence/exclusive-create.d.ts +22 -0
- package/dist/internal/persistence/file-lock.d.cts +14 -0
- package/dist/internal/persistence/fts5-sanitize.d.cts +16 -0
- package/dist/internal/persistence/index.cjs +359 -0
- package/dist/internal/persistence/index.cjs.map +1 -0
- package/dist/internal/persistence/index.d.cts +20 -0
- package/dist/internal/persistence/index.d.ts +20 -0
- package/dist/internal/persistence/index.js +341 -0
- package/dist/internal/persistence/index.js.map +1 -0
- package/dist/internal/persistence/markdown-config-loader.d.cts +35 -0
- package/dist/internal/persistence/paths.d.cts +19 -0
- package/dist/internal/persistence/persistence-schema.d.cts +21 -0
- package/dist/internal/persistence/persistence-schema.d.ts +4 -0
- package/dist/internal/persistence/schema-version.d.cts +13 -0
- package/dist/internal/persistence/sqlite-cas.d.cts +25 -0
- package/dist/internal/persistence/sqlite-cas.d.ts +25 -0
- package/dist/internal/persistence/sqlite-wal.d.cts +10 -0
- package/dist/internal/plugins/context.d.cts +31 -0
- package/dist/internal/plugins/index.cjs +228 -0
- package/dist/internal/plugins/index.cjs.map +1 -0
- package/dist/internal/plugins/index.d.cts +8 -0
- package/dist/internal/plugins/index.d.ts +8 -0
- package/dist/internal/plugins/index.js +222 -0
- package/dist/internal/plugins/index.js.map +1 -0
- package/dist/internal/plugins/lifecycle.d.cts +14 -0
- package/dist/internal/plugins/lifecycle.d.ts +14 -0
- package/dist/internal/plugins/manager.d.cts +37 -0
- package/dist/internal/plugins/types.d.cts +102 -0
- package/dist/internal/providers/catalog-loader.d.ts +39 -0
- package/dist/internal/runtime/agent-session-store.d.ts +1 -1
- package/dist/internal/runtime/agent-session.d.ts +1 -0
- package/dist/internal/runtime/budget-tracker.d.ts +73 -0
- package/dist/internal/runtime/{context-manager.d.ts → context/context-manager.d.ts} +1 -1
- package/dist/internal/runtime/{fixture-events.d.ts → fixtures/fixture-events.d.ts} +1 -1
- package/dist/internal/runtime/{fixture-run-base.d.ts → fixtures/fixture-run-base.d.ts} +4 -4
- package/dist/internal/runtime/{fixture-scripts.d.ts → fixtures/fixture-scripts.d.ts} +1 -1
- package/dist/internal/runtime/local-agent-bootstrap.d.ts +2 -2
- package/dist/internal/runtime/local-agent-memory-provider.d.ts +57 -0
- package/dist/internal/runtime/memory-path-selector.d.ts +73 -0
- package/dist/internal/runtime/memory-provider.d.ts +165 -0
- package/dist/internal/runtime/{agent-registry.d.ts → registry/agent-registry-contract.d.ts} +15 -9
- package/dist/internal/runtime/registry/agent-registry.d.ts +7 -0
- package/dist/internal/runtime/{live-agent-registry.d.ts → registry/live-agent-registry.d.ts} +1 -1
- package/dist/internal/runtime/{run-registry.d.ts → registry/run-registry.d.ts} +1 -1
- package/dist/internal/runtime/session-types.d.ts +35 -0
- package/dist/internal/runtime/system-prompt/sources/skills-provider.d.ts +1 -0
- package/dist/internal/runtime/validate-response.d.ts +18 -0
- package/dist/internal/security/index.cjs +361 -0
- package/dist/internal/security/index.cjs.map +1 -0
- package/dist/internal/security/index.d.cts +11 -0
- package/dist/internal/security/index.js +350 -0
- package/dist/internal/security/index.js.map +1 -0
- package/dist/internal/security/path-guard.d.cts +59 -0
- package/dist/internal/security/path-guard.d.ts +3 -0
- package/dist/internal/security/redact.d.cts +21 -0
- package/dist/internal/security/secret-redactor.d.cts +1 -0
- package/dist/internal/security/secret-redactor.d.ts +1 -0
- package/dist/internal/security/test-reset.d.cts +10 -0
- package/dist/internal/security/test-reset.d.ts +10 -0
- package/dist/internal/telemetry/adapters/arize.d.ts +2 -0
- package/dist/internal/telemetry/adapters/braintrust.d.ts +2 -0
- package/dist/internal/telemetry/adapters/datadog.d.ts +2 -0
- package/dist/internal/telemetry/adapters/langsmith.d.ts +2 -0
- package/dist/internal/telemetry/span-names.d.ts +6 -0
- package/dist/internal/telemetry/tracer.d.ts +1 -0
- package/dist/internal/workflow/evented-executor.d.ts +42 -0
- package/dist/internal/workflow/scheduler.d.ts +23 -0
- package/dist/internal/zod/to-json-schema.d.ts +5 -15
- package/dist/job-queue.d.ts +28 -0
- package/dist/path-safety.cjs +67 -6
- package/dist/path-safety.cjs.map +1 -1
- package/dist/path-safety.d.cts +15 -0
- package/dist/path-safety.d.ts +1 -1
- package/dist/path-safety.js +67 -7
- package/dist/path-safety.js.map +1 -1
- package/dist/permission-engine.d.ts +21 -0
- package/dist/provider-catalog.json +702 -0
- package/dist/rag/index.cjs +136 -0
- package/dist/rag/index.cjs.map +1 -0
- package/dist/rag/index.d.cts +11 -0
- package/dist/rag/index.d.ts +11 -0
- package/dist/rag/index.js +129 -0
- package/dist/rag/index.js.map +1 -0
- package/dist/rag/reranker.d.cts +26 -0
- package/dist/rag/reranker.d.ts +26 -0
- package/dist/rag/retriever.d.cts +25 -0
- package/dist/rag/retriever.d.ts +25 -0
- package/dist/rag/text-splitter.d.cts +12 -0
- package/dist/rag/text-splitter.d.ts +12 -0
- package/dist/rag/types.d.cts +37 -0
- package/dist/rag/types.d.ts +37 -0
- package/dist/run-DrwUpFxZ.d.cts +823 -0
- package/dist/run-DrwUpFxZ.d.ts +823 -0
- package/dist/sandbox/index.cjs +133 -0
- package/dist/sandbox/index.cjs.map +1 -0
- package/dist/sandbox/index.d.cts +2 -0
- package/dist/sandbox/index.d.ts +2 -0
- package/dist/sandbox/index.js +128 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/local-sandbox.d.cts +17 -0
- package/dist/sandbox/local-sandbox.d.ts +17 -0
- package/dist/sandbox/types.d.cts +44 -0
- package/dist/sandbox/types.d.ts +44 -0
- package/dist/server/adapter/express.d.cts +9 -0
- package/dist/server/adapter/express.d.ts +9 -0
- package/dist/server/adapter/fastify.d.cts +9 -0
- package/dist/server/adapter/fastify.d.ts +9 -0
- package/dist/server/adapter/hono.d.cts +9 -0
- package/dist/server/adapter/hono.d.ts +9 -0
- package/dist/server/adapter/index.d.cts +8 -0
- package/dist/server/adapter/index.d.ts +8 -0
- package/dist/server/adapter/shared-handler.d.cts +9 -0
- package/dist/server/adapter/shared-handler.d.ts +9 -0
- package/dist/server/adapter/types.d.cts +33 -0
- package/dist/server/adapter/types.d.ts +33 -0
- package/dist/server/auth/errors.d.cts +53 -0
- package/dist/server/auth/errors.d.ts +53 -0
- package/dist/server/auth/index.cjs +38 -41
- package/dist/server/auth/index.cjs.map +1 -1
- package/dist/server/auth/index.d.cts +11 -172
- package/dist/server/auth/index.d.ts +11 -172
- package/dist/server/auth/index.js +39 -42
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/auth/oauth-transaction-store.d.cts +39 -0
- package/dist/server/auth/oauth-transaction-store.d.ts +39 -0
- package/dist/server/auth/orchestrator.d.cts +8 -0
- package/dist/server/auth/orchestrator.d.ts +8 -0
- package/dist/server/auth/types.d.cts +91 -0
- package/dist/server/auth/types.d.ts +91 -0
- package/dist/server/auth/validate-return-to.d.cts +17 -0
- package/dist/server/auth/validate-return-to.d.ts +17 -0
- package/dist/server/errors-envelope.cjs +409 -0
- package/dist/server/errors-envelope.cjs.map +1 -0
- package/dist/server/errors-envelope.d.cts +61 -0
- package/dist/server/errors-envelope.d.ts +61 -0
- package/dist/server/errors-envelope.js +405 -0
- package/dist/server/errors-envelope.js.map +1 -0
- package/dist/subscription/define-subscription.d.cts +63 -0
- package/dist/subscription/define-subscription.d.ts +63 -0
- package/dist/subscription/index.cjs +402 -0
- package/dist/subscription/index.cjs.map +1 -0
- package/dist/subscription/index.d.cts +18 -0
- package/dist/subscription/index.d.ts +18 -0
- package/dist/subscription/index.js +394 -0
- package/dist/subscription/index.js.map +1 -0
- package/dist/subscription/internal/adapter-types.d.cts +11 -0
- package/dist/subscription/internal/adapter-types.d.ts +11 -0
- package/dist/subscription/internal/backpressure.d.cts +24 -0
- package/dist/subscription/internal/backpressure.d.ts +24 -0
- package/dist/subscription/internal/server-integration.d.cts +17 -0
- package/dist/subscription/internal/server-integration.d.ts +17 -0
- package/dist/subscription/internal/sse-encoder.d.cts +13 -0
- package/dist/subscription/internal/sse-encoder.d.ts +13 -0
- package/dist/subscription/internal/sse-parser.d.cts +15 -0
- package/dist/subscription/internal/sse-parser.d.ts +15 -0
- package/dist/subscription/internal/subscription-runtime.d.cts +9 -0
- package/dist/subscription/internal/subscription-runtime.d.ts +9 -0
- package/dist/subscription/internal/ws-adapter-node.d.cts +10 -0
- package/dist/subscription/internal/ws-adapter-node.d.ts +10 -0
- package/dist/subscription/theokit-subscribe.d.cts +41 -0
- package/dist/subscription/theokit-subscribe.d.ts +41 -0
- package/dist/subscription/types.d.cts +140 -0
- package/dist/subscription/types.d.ts +140 -0
- package/dist/task-store.cjs +30 -2
- package/dist/task-store.cjs.map +1 -1
- package/dist/task-store.d.cts +8 -0
- package/dist/task-store.js +31 -3
- package/dist/task-store.js.map +1 -1
- package/dist/types/agent-prims.d.ts +61 -0
- package/dist/types/agent.d.ts +48 -53
- package/dist/types/conversation.d.ts +20 -8
- package/dist/types/index.d.ts +0 -2
- package/dist/types/messages-base.d.ts +20 -0
- package/dist/types/messages.d.ts +1 -1
- package/dist/types/run.d.ts +1 -1
- package/dist/types/updates.d.ts +1 -1
- package/dist/voice/index.d.ts +7 -0
- package/dist/voice/openai-realtime.d.ts +21 -0
- package/dist/voice/types.d.ts +35 -0
- package/dist/workflow.cjs +179 -88
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +97 -0
- package/dist/workflow.js +180 -89
- package/dist/workflow.js.map +1 -1
- package/package.json +128 -25
- package/dist/budget.d.ts +0 -48
- package/dist/cache.d.ts +0 -74
- package/dist/cron-1yxL3K2S.d.cts +0 -221
- package/dist/cron-BYVdYzob.d.ts +0 -221
- package/dist/handoff.d.ts +0 -55
- package/dist/internal/budget/calendar-window.d.ts +0 -19
- package/dist/internal/budget/enforcement.d.ts +0 -32
- package/dist/internal/budget/ledger.d.ts +0 -25
- package/dist/internal/budget/normalize-usage.d.ts +0 -27
- package/dist/internal/budget/registry.d.ts +0 -16
- package/dist/internal/cache/cosine.d.ts +0 -14
- package/dist/internal/cache/embed-helper.d.ts +0 -15
- package/dist/internal/cache/key.d.ts +0 -15
- package/dist/internal/cache/lookup.d.ts +0 -28
- package/dist/internal/cache/store-handler.d.ts +0 -24
- package/dist/internal/cache/store-json.d.ts +0 -48
- package/dist/internal/cache/store.d.ts +0 -54
- package/dist/internal/cache/telemetry.d.ts +0 -20
- package/dist/internal/cache/ttl.d.ts +0 -11
- package/dist/internal/catalog/fixtures.d.ts +0 -16
- package/dist/internal/catalog/local-models.d.ts +0 -24
- package/dist/internal/handoff/dispatcher.d.ts +0 -29
- package/dist/internal/handoff/registry.d.ts +0 -23
- package/dist/internal/handoff/telemetry.d.ts +0 -18
- package/dist/internal/handoff/tool-injector.d.ts +0 -34
- package/dist/internal/memory/atomic-write.d.ts +0 -7
- package/dist/internal/memory/dreaming/diary.d.ts +0 -4
- package/dist/internal/memory/dreaming/phases.d.ts +0 -15
- package/dist/internal/memory/dreaming/run.d.ts +0 -10
- package/dist/internal/memory/migrate-sqlite-to-lance.d.ts +0 -15
- package/dist/memory-adapter-helpers.d.ts +0 -28
- package/dist/memory.d.ts +0 -123
- package/dist/migrate.d.ts +0 -33
- package/dist/security.d.ts +0 -67
- package/dist/task.d.ts +0 -87
- package/dist/theokit.d.ts +0 -84
- package/dist/tools/_path-scope.d.ts +0 -8
- package/dist/tools/_subprocess.d.ts +0 -28
- package/dist/tools/git-diff.d.ts +0 -22
- package/dist/tools/index.d.ts +0 -29
- package/dist/tools/list-dir.d.ts +0 -26
- package/dist/tools/read-file.d.ts +0 -31
- package/dist/tools/run-vitest.d.ts +0 -46
- package/dist/tools/search-text.d.ts +0 -32
- package/dist/tools.cjs +0 -690
- package/dist/tools.cjs.map +0 -1
- package/dist/tools.js +0 -683
- package/dist/tools.js.map +0 -1
- package/dist/trajectory-helpers.d.ts +0 -31
- package/dist/types/cache.d.ts +0 -76
- package/dist/types/handoff.d.ts +0 -135
- /package/dist/{internal/cron/run-job.d.ts → agent-helpers.d.ts} +0 -0
- /package/dist/internal/{cron/scheduler.d.ts → agent-loop/loop-llm-stream.d.ts} +0 -0
- /package/dist/internal/{cron/store.d.ts → agent-loop/tool-executors.d.ts} +0 -0
- /package/dist/internal/{cron/validate.d.ts → memory/index-manager-helpers.d.ts} +0 -0
- /package/dist/internal/memory/{session-loader.d.ts → storage/session-loader.d.ts} +0 -0
- /package/dist/internal/memory/{session-summary-writer.d.ts → storage/session-summary-writer.d.ts} +0 -0
- /package/dist/internal/memory/{transcript-store.d.ts → storage/transcript-store.d.ts} +0 -0
- /package/dist/internal/memory/{wiki-loader.d.ts → storage/wiki-loader.d.ts} +0 -0
- /package/dist/internal/{memory/cwd-mutex.d.ts → persistence/atomic-write.d.cts} +0 -0
- /package/dist/internal/runtime/{context-aggregator.d.ts → context/context-aggregator.d.ts} +0 -0
- /package/dist/internal/runtime/{context-discovery-runner.d.ts → context/context-discovery-runner.d.ts} +0 -0
- /package/dist/internal/runtime/{context-discovery.d.ts → context/context-discovery.d.ts} +0 -0
- /package/dist/internal/runtime/{context-frontmatter.d.ts → context/context-frontmatter.d.ts} +0 -0
- /package/dist/internal/runtime/{context-import-resolver.d.ts → context/context-import-resolver.d.ts} +0 -0
- /package/dist/internal/runtime/{context-loaders.d.ts → context/context-loaders.d.ts} +0 -0
- /package/dist/internal/runtime/{context-mdc-parser.d.ts → context/context-mdc-parser.d.ts} +0 -0
- /package/dist/internal/runtime/{fixture-responder.d.ts → fixtures/fixture-responder.d.ts} +0 -0
- /package/dist/internal/runtime/{fixture-types.d.ts → fixtures/fixture-types.d.ts} +0 -0
- /package/dist/internal/runtime/{plugins-manager.d.ts → local-agent-send.d.ts} +0 -0
- /package/dist/internal/runtime/{plugin-frontmatter.d.ts → plugins/plugin-frontmatter.d.ts} +0 -0
- /package/dist/internal/runtime/{system-prompt/providers/active-memory-provider.d.ts → plugins/plugins-manager.d.ts} +0 -0
- /package/dist/internal/runtime/{agent-factory-registry.d.ts → registry/agent-factory-registry.d.ts} +0 -0
- /package/dist/internal/runtime/{agent-registry-store.d.ts → registry/agent-registry-store.d.ts} +0 -0
- /package/dist/internal/runtime/system-prompt/{providers/base-provider.d.ts → sources/active-memory-provider.d.ts} +0 -0
- /package/dist/internal/runtime/system-prompt/{providers/context-provider.d.ts → sources/base-provider.d.ts} +0 -0
- /package/dist/internal/runtime/system-prompt/{providers/memory-provider.d.ts → sources/context-provider.d.ts} +0 -0
- /package/dist/internal/runtime/system-prompt/{providers/skills-provider.d.ts → sources/memory-provider.d.ts} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,198 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
## [1.8.0] - 2026-06-12
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `.claude/` consumer template with 15 domain-specific passive skills, convention rules, AGENTS.md (cross-agent), and CLAUDE.md for AI coding tool integration. Scaffold via `npx theokit-init-claude`. Skills auto-inject TheoKit API knowledge when editing files matching each domain (Agent Core, Tools, Memory, DI, DI-Agent, Gateways, RAG, Workflows, Eval, Cron, Subscriptions, Errors, Config, Streaming, Budget). 33 tests.
|
|
10
|
+
|
|
11
|
+
## [1.7.0] - 2026-06-11
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- Resolve 12 jscpd code duplication clones: extract shared server adapter handler, consolidate evented-executor step logic, share NOOP_SPAN/collapseSystemText/sleepWithAbort, deduplicate memory peer routing helpers. 0 clones remaining.
|
|
16
|
+
- Extract helper modules from 5 god-files for SRP compliance: `agent.ts` → `agent-helpers.ts`, `loop.ts` → `loop-context-init.ts` + `loop-llm-stream.ts`, `tool-dispatch.ts` → `tool-executors.ts`, `index-manager.ts` → `index-manager-helpers.ts`, `local-agent.ts` → `local-agent-send.ts`. Total ~1300 lines redistributed; zero behavior change, all 2591 tests GREEN.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- **Compression config resolution module (T2.2 step 2/N of plan `sdk-superiority-2026-06-07`, ADR D440)**: `resolveCompressionConfig(agentModel, config): ResolvedCompressionConfig` bridges the compression-model-registry (step 1) with the `Agent.create({compression})` override surface. Resolves: (a) compression model — registry default OR explicit `config.model` override; (b) API key — first-match chain: explicit `config.apiKey` → `THEOKIT_COMPRESSION_API_KEY` env var → undefined (signals aux-LLM client to use agent's main CredentialPool); (c) maxAttempts (default 3) + grace (default 1). Pure config resolution — no I/O. 11 new tests at `tests/internal/runtime/compression-config.test.ts`. Foundation for step 3 (aux-llm-client with OTel span) and step 4 (agent-loop wire).
|
|
21
|
+
|
|
22
|
+
- **Model capabilities introspection registry (T3.10c step 1 of plan `sdk-superiority-2026-06-07`, DR3 #17)**: pre-T3.10c the SDK had no way to query a model's capability flags before sending a request — consumers who sent vision content to a text-only model or structured-output requests to a model without json_schema support got an opaque 400 from the provider. T3.10c step 1 adds the foundation pure-function registry `resolveModelCapabilities(modelId): ModelCapabilities` with typed per-model flags: `supportsVision`, `supportsStructuredOutput`, `supportsToolUse`, `supportsCacheControl`, `maxContextTokens`, `maxOutputTokens`. Resolution algorithm: strip routing prefixes (openrouter/, vertex/, bedrock/), exact-match against the vendor-model registry, then infer vendor from model name (claude-* → anthropic/, gpt-* → openai/, gemini-* → google/) for routing-prefixed lookups. Unknown models return conservative defaults (all false, 4096/4096 token counts) — never optimistic assumptions. Initial registry covers OpenAI (gpt-4o/4o-mini/4-turbo/o1/o3) and Anthropic (claude-opus-4/sonnet-4/3-5-sonnet/3-haiku/3-opus) families. 9 new tests at `tests/internal/llm/model-capabilities.test.ts`. Foundation for step 2 (public `Theokit.models.capabilities()` API) and step 3 (Agent.create boundary gate + `CapabilityNotSupportedError`).
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- Fix `EventedWorkflowExecutor` referencing `handler` instead of `fn` from `FnStep` interface; provide full `StepContext` (runId + log + suspend)
|
|
27
|
+
- Fix missing `await` in `TheoKitContainer.run()` causing `.send()` to be called on a Promise
|
|
28
|
+
- Fix `CohereReranker` null guard for out-of-bounds `chunks[r.index]` array access
|
|
29
|
+
- Fix `Theokit.models.capabilities()` null guard on `split("/")[0]` return value
|
|
30
|
+
- Fix dynamic catalog overwriting first-party builtin providers (ollama/lmstudio/llamacpp) — builtins now take priority
|
|
31
|
+
|
|
32
|
+
### Security
|
|
33
|
+
|
|
34
|
+
- **Move-corrupt-aside + 1MB cap on markdown config files (T5.10 of plan `sdk-superiority-2026-06-07`, DR6 finding #10)**: pre-T5.10 `readVersionedJson` left corrupt JSON files in place after logging a warning — on next run the same warning fired again (no healing). T5.10 renames the corrupt file to `<path>.corrupt.<epoch>` so the user can investigate later while the original path is freed for a fresh default. Additionally, `loadMarkdownEntities` now rejects individual config files > 1MB before reading them into memory (pre-T5.10 no size cap existed — "`.theokit/` is trusted source" comment at line 63). A crafted multi-MB config file was a local DoS vector on resource-constrained environments (edge, CI workers). 4 new tests at `tests/internal/persistence/corrupt-aside-and-size-cap.test.ts`. 142/142 persistence tests GREEN across 17 files. Closes DR6 finding #10.
|
|
35
|
+
|
|
36
|
+
- **proper-lockfile supply-chain hardening (T5.9 of plan `sdk-superiority-2026-06-07`, DR6 finding #9)**: pre-T5.9 `getProperLockfile()` did a bare `import("proper-lockfile")` with a catch-all that swallowed every error — including import of a tampered or incompatible version. If an attacker replaced the module on disk (npm supply-chain attack), or if a transitive dep pulled a breaking major, the SDK would silently use whatever it got. T5.9 adds structural validation after the dynamic import succeeds: `typeof lib.lock === "function" && typeof lib.unlock === "function"`. If the imported module doesn't expose the API surface we depend on, it's treated as "not installed" (fallback to in-process `withCwdMutex`) + a one-shot supply-chain advisory warning is emitted via stderr pointing to `pnpm add proper-lockfile@^11`. Never throws — supply-chain validation is advisory + graceful fallback, not blocking. New `__TESTING__validateLockModule` + `__TESTING__resetFileLockCache` test seams exposed for unit tests; NOT in the public barrel. 7 new tests at `tests/internal/persistence/file-lock-supply-chain.test.ts`. 138/138 persistence tests GREEN across 16 files (no regressions). Closes DR6 finding #9.
|
|
37
|
+
|
|
38
|
+
### Added (SDK 2.0 — Stage 4 optional-peer routing — iter 76-80, 2026-06-09)
|
|
39
|
+
|
|
40
|
+
- **Optional-peer routing through `@theokit/sdk-memory`** (ADR 0002): the public `Memory` class (`Memory.openIndex`, `Memory.runDreamingSweep`) and the `migrateSqliteToLance` wrapper now delegate to the `@theokit/sdk-memory` package when installed. When sdk-memory is absent, methods fall back to sdk-core's legacy `internal/memory/*` implementations — v1.x behavior preserved. No source-level API change for consumers; the routing is opaque. Foundation files: `src/internal/memory/sdk-memory-peer-loader.ts` (canonical loader with `SdkMemoryModule` structural mirror + memoized dynamic import + test escape hatches `resetSdkMemoryPeerCacheForTests` / `forceSdkMemoryPeerAbsentForTests`). Test coverage: 24 tests across 5 files in `tests/` — loader contract pin, Memory class routing for both methods, migrate wrapper routing, behavior parity gate (sdk-core ↔ sdk-memory produce byte-equivalent results for shape + error messages), legacy fallback branch coverage via force-absent flag. See `docs/adr/0002-sdk-memory-optional-peer-routing.md` for full architectural rationale + sunset condition.
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **Provider-agnostic compression-model registry (T2.2 step 1/N of plan `sdk-superiority-2026-06-07`, ADR D440)**: pre-T2.2 the `D91/D92 compression` path (`compression-helpers.ts`) was dead code — no auxiliary-LLM contract was specified. T2.2 step 1 ships the foundation: a pure-function registry that resolves the agent's main model to a cheaper-tier summarization model in the SAME vendor family. Algorithm: (a) exact match (e.g., `openai/gpt-4o` → `openai/gpt-4o-mini`; `anthropic/claude-sonnet-4` → `anthropic/claude-3-5-haiku-latest`); (b) wildcard match for region-prefixed Bedrock variants (`bedrock/anthropic.claude-sonnet*` → `bedrock/anthropic.claude-3-haiku*`); (c) `authType: "none"` providers (Ollama / LM Studio / llama.cpp) return SAME model id (local — cost N/A); (d) no match throws the new typed `CompressionModelUnresolvedError` at `Agent.create` TIME (not runtime) with the actionable message naming the model and pointing to the override surface + registry-PR remediation. Crucial design: zero cross-provider calls — a consumer running Anthropic-only never gets a silent OpenAI fallback for compression. Initial registry covers OpenAI family (gpt-4o / gpt-4-turbo / o1 / o3), Anthropic family (claude-opus-4 / sonnet-4 / 3-5-sonnet / 3-opus / 3-sonnet), Vertex (Gemini + Anthropic-on-Vertex), OpenRouter (OpenAI + Anthropic), and Bedrock Anthropic (wildcard). 18 new tests at `tests/internal/runtime/compression-model-registry.test.ts`. Foundation for steps 2-4 (compression-config integration, OTel-instrumented aux-llm-client, agent-loop wire on `ContextWindowExceededError`).
|
|
45
|
+
|
|
46
|
+
### Security
|
|
47
|
+
|
|
48
|
+
- **NFS / SMB / CIFS / FUSE detection + warn-once on atomic write (T5.8 of plan `sdk-superiority-2026-06-07`, DR6 finding #8)**: pre-T5.8 `replaceFileAtomic` happily called `rename(tmp, filePath)` on any filesystem. POSIX `rename` is atomic on local filesystems (ext4 / btrfs / APFS / NTFS), but on network filesystems (NFS / SMB / CIFS) and many FUSE implementations atomicity is best-effort: NFS clients can return stale cached reads for seconds after a successful server-side rename; SMB / CIFS cross-directory rename is non-atomic on some Samba configurations; FUSE behavior is entirely implementation-dependent (sshfs / s3fs / rclone-mount have known non-atomic rename). T5.8 does NOT change the write path — `replaceFileAtomic` remains a best-effort atomic write — but adds a warn-once-per-(directory, label) telemetry surface so operators see `[theokit-sdk] atomic-write: detected network fs (nfs) at /mnt/share — rename() atomicity guarantees may be weaker than expected` once and know to plan accordingly. Pattern mirrors `sqlite-wal.ts:54-61`'s warn-once-per-label (D63). Detection: Linux `statfs().type` magic numbers (NFS 0x6969, SMB 0x517B, CIFS 0xFF534D42, FUSE 0x65735546); silent fallback on Windows / Node < 18.15 / statfs EACCES. New `detectNetworkFsName(typeMagic): string | null` pure function (test seam `__TESTING__detectNetworkFsName`) + `warnOnNetworkFsOnce(dirPath, label)` wired into `replaceFileAtomic`. 9 new tests at `tests/internal/persistence/atomic-write-nfs-detection.test.ts` covering all 4 network FS magic numbers + 3 local-FS negatives + reset helper idempotence. 29/29 atomic-write + credential-pool persistence tests GREEN. Closes DR6 finding #8.
|
|
49
|
+
|
|
50
|
+
- **Crypto-random tmp file names + mode 0o600 + dir 0o700 (T5.7 of plan `sdk-superiority-2026-06-07`, DR6 finding #7)**: pre-T5.7 `replaceFileAtomic` had two attacks open. (a) **Predictable tmp path**: the suffix used `Math.random().toString(36).slice(2, 10)` — Math.random is NOT a CSPRNG, an attacker observing the process could predict the next tmp path and pre-stage a hostile file there to be renamed into place. (b) **World-readable tmp file**: `open(tmp, "w")` fell back to the process umask — typically 0o644 on POSIX (world-readable). The tmp file holds the FULL in-flight content (credential pool snapshot, OAuth tokens, etc.) before the rename — any process could read it during the ms-window between open and rename (TOCTOU disclosure). T5.7 fixes both: (a) suffix now uses `randomBytes(8).toString("hex")` from `node:crypto` — 16 hex chars / 64 bits of CSPRNG entropy; (b) `open(tmp, "w", 0o600)` passes the secure mode argument so both the tmp file AND (via rename inheritance on modern Linux) the final target are owner-only. Also tightens `saveCredentialPoolStore` parent directory creation from default umask (0o755 = world-listable) to `mode: 0o700` so an attacker enumerating the parent cannot even see the pool exists. 3 new tests at `tests/internal/persistence/atomic-write-tmp-secure.test.ts` (mode 0o600 verified via stat, content roundtrip, concurrent-write no collision). 46/47 persistence tests GREEN — the 1 pre-existing failure (`integration-stack.test.ts:75`) is unrelated NODE_MODULE_VERSION mismatch on `better-sqlite3` native binding from the preflight workaround documented in `CLAUDE.md`. Closes DR6 finding #7.
|
|
51
|
+
|
|
52
|
+
- **`__Host-` cookie prefix + deterministic clear (T5.3 of plan `sdk-superiority-2026-06-07`, DR6 finding #3, BREAKING)**: pre-T5.3 the OAuth tx-cookie was named `theo_oauth_tx` — browsers accepted it without enforcing any cookie-prefix contract, leaving the subdomain-fixation vector open (a malicious page on `evil.example.com` could plant a same-name cookie that the parent app at `example.com` would happily decrypt). T5.3 renames the cookie to `__Host-theo_oauth_tx` per RFC 6265bis — browsers now enforce the contract that the cookie MUST be set with `Secure`, MUST NOT carry a `Domain` attribute, and MUST have `Path=/`. Pre-T5.3 `clearCookie` also did a buggy double-write: first an empty-value `setCookie` (which still carried `Max-Age=600` from the live cookie) AND THEN a separate explicit `Max-Age=0` header — creating a duplicate Set-Cookie response some legacy clients did not handle deterministically. T5.3 collapses this to a single clean clear with both `Max-Age=0` (modern browsers) AND `Expires=Thu, 01 Jan 1970 00:00:00 GMT` (legacy fallback), while preserving all `__Host-` prefix attributes (HttpOnly + Secure + SameSite=Lax + Path=/). **Breaking only at the wire — no public API change**: consumers calling `defineAuth().startSignIn()` / `finishSignIn()` see no source-level change because the cookie name is internal; only the HTTP wire format moves from `theo_oauth_tx=...` to `__Host-theo_oauth_tx=...`. In-flight cookies from pre-T5.3 sessions will fail decryption on the next callback and the flow restarts cleanly. 6 new tests at `tests/server-auth-host-cookie-prefix.test.ts` + 1 fixture update at `tests/server-auth.test.ts` (cookie header line widened to the prefixed name). 29/29 server-auth tests GREEN.
|
|
53
|
+
|
|
54
|
+
- **Forbidden-path blocklist expansion + case-insensitive matching (T5.6 of plan `sdk-superiority-2026-06-07`, DR6 finding #6)**: pre-T5.6 `isForbiddenPath` blocked only `.env*`, `.git/`, `node_modules/`, `.theo/`, and 4 lockfile basenames — and it compared case-sensitively. A coding agent recursing through a developer laptop could happily read `.ssh/id_rsa`, `.aws/credentials`, `.docker/config.json`, `.kube/config`, `.npmrc`, `.netrc`, `.pgpass`, `authorized_keys`, `known_hosts`, OR any `*.pem` / `*.key` file. On macOS/Windows case-insensitive filesystems, `.ENV` and `.SSH/` slipped through entirely because the path string was compared verbatim against lowercase constants. T5.6 (a) lowercases the normalized path BEFORE matching, defeating case-only bypass; (b) adds 3 new pattern sets: `SENSITIVE_FIRST_SEGMENTS` (.ssh / .aws / .docker / .kube / .npmrc / .netrc / .pgpass at top level), `SENSITIVE_BASENAMES` (id_rsa / id_ed25519 / id_ecdsa / id_dsa / authorized_keys / known_hosts / .npmrc / .netrc / .pgpass at any depth), and `SENSITIVE_SUFFIXES` (.pem / .key / .p12 / .pfx at any depth). Implementation matches the `.env.example` allowlist contract — `isForbiddenPath` returns false for safe templates. 28 new tests at `tests/internal/security/path-guard-forbidden-expansion.test.ts`; 102/102 path-guard sink tests GREEN across 6 files. Closes DR6 finding #6.
|
|
55
|
+
|
|
56
|
+
- **NUL byte + C0/DEL control-char rejection across path-guard primitives (T5.5 of plan `sdk-superiority-2026-06-07`, DR6 finding #5)**: pre-T5.5 `safePathJoin`, `assertNoSymlinkEscape`, and `sanitizeIdentifier` did NOT explicitly reject NUL (`\x00`) or C0/DEL control characters (`\x01-\x1F`, `\x7F`) in path-shaped or identifier-shaped inputs. NUL bytes in path strings have a long history of security bugs: legacy N-API callers historically truncated paths silently at the NUL boundary, letting `foo.txt\x00.env` be opened as `foo.txt` while the upstream caller saw the full string and approved it. C0 control chars are universally invalid in POSIX paths and identifiers. `validateArtifactPath` (T1.4 — line 269) already rejected NUL, so T5.5 propagates the same defense to the sibling primitives so a caller can never bypass NUL/control checks by choosing a different entrypoint. New internal helper `rejectNulAndControlChars(input, role)` centralizes the check; wired into `safePathJoin` (for `base` + each `part`), `assertNoSymlinkEscape` (for `path` + `base`), and `sanitizeIdentifier`. The latter previously threw a generic "invalid characters" message via the alphanumeric-only `IDENTIFIER_PATTERN`; T5.5 routes NUL through the same helper so operators see a precise `<nul-byte>` / `<control-char-0x..>` diagnostic instead — making prompt-injection traces legible per Inquebrável Rule 3. 11 new tests at `tests/internal/security/path-guard-nul-rejection.test.ts` + 1 pre-existing assertion at `tests/internal/security/path-guard.test.ts:249` updated to match the new specific NUL message. 68/68 path-guard sink tests GREEN across 4 files (path-guard unit / property / public-api / agent-session-store).
|
|
57
|
+
|
|
58
|
+
- **HKDF-SHA256 key derivation for OAuth tx-cookie AES-256-GCM key (T5.1 of plan `sdk-superiority-2026-06-07`, CRITICAL — DR6 finding #1)**: pre-T5.1 `server/auth/oauth-transaction-store.ts:deriveKey` zero-padded secret bytes to 32 if shorter and truncated if longer. This is NOT a key derivation function. Two near-identical secrets (e.g., `"a".repeat(31)` vs `"b".repeat(31)`) produced AES keys differing in only one byte across 32 — an attacker who recovered one cookie could brute-force adjacent deployments cheaply. T5.1 replaces the zero-padding with HKDF-SHA256 (RFC 5869) using `info="theokit:oauth-tx-v1"` and a salt sourced from `THEOKIT_OAUTH_TX_SALT` env var (defaults to RFC 5869 zero-string; operators MUST set per-app salt in production to eliminate cross-deployment collision risk). Distinct secrets now produce avalanche-distinct keys (Hamming distance > 160 bits empirically). **Breaking validation**: `encodeTransaction` (and via the SDK's `defineAuth` chain, any `startSignIn`/`finishSignIn` flow) now throws the new typed `AuthSecretTooShortError` when the configured secret has fewer than 32 bytes of UTF-8 encoded entropy. Pre-T5.1 secrets shorter than 32 bytes were silently zero-padded and produced insecure keys; rejecting them surfaces the misconfiguration honestly per Inquebrável Rule 3. Generate a fresh value with `openssl rand -base64 33`. New test seam `__TESTING__deriveKey` exposed for unit-test avalanche assertions; NOT in the public barrel. 7 new tests at `tests/server-auth-hkdf-derive-key.test.ts` + 1 fixture update at `tests/server-auth.test.ts` (`secret` widened 31 → 32 bytes). 23/23 server-auth tests GREEN.
|
|
59
|
+
|
|
60
|
+
### Added
|
|
61
|
+
|
|
62
|
+
- **Redactor pattern expansion (12 → 30 builtin patterns) (T5.4 of plan `sdk-superiority-2026-06-07`)**: pre-T5.4 the canonical redactor at `internal/security/redact.ts:48-63` shipped only 12 vendor-specific builtin regex patterns (Anthropic / OpenAI / OpenAI-project / GitHub PAT classic+fine-grained / GitLab / AWS / Google API / Slack / Sentry / Stripe live+restricted). DR6 finding #4 + #24 surfaced major credential classes leaking through unmasked: JWT (3-segment base64url), GCP service-account PEM private_key block, Azure Storage SAS signature, HuggingFace tokens, Anthropic admin keys, plus a long tail of vendor-specific prefixes (Perplexity / Groq / Replicate / Voyage / xAI / Fireworks / Pinecone / npm / SendGrid / Twilio / Mailgun / Discord / LaunchDarkly). T5.4 grows BUILTIN_PATTERNS to 30 with PEM block first (so the multi-line span runs before any per-line patterns can fire), JWT second, Azure SAS third (lookbehind on `?sig=`/`&sig=`), and the rest alphabetized by prefix for maintainability. PARAM_PATTERN keyword set expanded from 6 → 16 (added `client_secret`, `credential`, `credentials`, `id_token`, `jwt`, `private_key`, `refresh_token`, `service_account`, `session_token`, `token`); `auth` and `bearer` deliberately excluded — they would re-catch the post-BUILTIN-masked form (D71 prefix-preservation `sk-ant...xxxx`) and double-mask to `***`. The `redactSecrets` callback gains a guard that skips PARAM masking when the value contains the D71 `...` separator, preserving prefix-mask debuggability when BUILTIN already fired. New test seam `__TESTING__BUILTIN_PATTERN_COUNT()` exposed via `test-reset.ts` for the floor assertion. 23 new tests at `tests/internal/security/redact-pattern-expansion.test.ts`; 158/158 redaction-sink tests GREEN across 13 files (security/lint/telemetry/migration/agent-session). Closes DR6 finding #4 (pattern coverage) + #24 (PARAM keyword vocabulary).
|
|
63
|
+
|
|
64
|
+
### Refactored
|
|
65
|
+
|
|
66
|
+
- **Cycle #4 closed via `types/handoff-descriptor.ts` leaf with TAgent generic (iter-20)**: `HandoffDescriptor` + `HandoffOptions` + `HandoffContext` + `HandoffHistory` + `HandoffResult` moved to a new leaf file. The leaf has `HandoffDescriptor<TInput, TAgent>` parameterized over the target agent shape — no dependency on `SDKAgent` or any other agent.ts type. `types/handoff.ts` re-exports the leaf types with `TAgent = SDKAgent` pinned for back-compat callers. `types/agent.ts` now imports `HandoffDescriptor` from the leaf, breaking the bidirectional `types/agent.ts ↔ types/handoff.ts` edge. madge final state: **2 cycles** (only D428-acknowledged rollup-dts subscribe-at-sub-path remain). Cycle gate threshold tightened ≤ 2.
|
|
67
|
+
- **`internal/runtime/plugins/` sub-folder promotion + T5.1 complete (4 of 4, FO#1)**: 2 plugin-* files moved from `internal/runtime/` to `internal/runtime/plugins/` via `git mv`. Direct file count: 50 → 48. **T5.1 complete across 4 iterations (15-18)**: cumulative 21 files moved across fixtures/ (5) + context/ (8) + registry/ (6) + plugins/ (2). `internal/runtime/` direct file count dropped 69 → 48. Audit ideal heuristic is 25; remaining 23-file gap is documented as out-of-scope (no further cohesive 5+ file cluster remains). 254/254 runtime + architecture tests GREEN.
|
|
68
|
+
- **`internal/runtime/registry/` sub-folder promotion (T5.1 partial 3 of 4, FO#1)**: 6 *-registry* files moved from `internal/runtime/` to `internal/runtime/registry/` via `git mv`. Direct file count: 56 → 50. T5.1 status PARTIAL — 3 of 4 clusters done (fixtures + context + registry). Remaining: plugins/. Cross-package caller surgery covered: `src/agent.ts`, `src/index.ts`, 5 runtime siblings, 4 test files, 1 dynamic `import("./agent-factory-registry.js")` in `local-agent-runtime-extensions.ts`. 253/253 runtime + architecture tests GREEN; madge unchanged.
|
|
69
|
+
- **`internal/runtime/context/` sub-folder promotion (T5.1 partial 2 of 4, FO#1)**: 8 context-* files moved from `internal/runtime/` to `internal/runtime/context/` via `git mv`. Direct file count: 64 → 56. T5.1 status PARTIAL — 2 of 4 clusters done (fixtures + context). Remaining: registry/, plugins/. Sibling callers (`local-agent`, `local-agent-bootstrap`, `system-prompt/local-assembly`) had their imports rewritten to `./context/context-X.js` (or `../context/context-X.js` from system-prompt/). 8 test files updated. 252/252 runtime + architecture tests GREEN.
|
|
70
|
+
- **`internal/runtime/fixtures/` sub-folder promotion (T5.1 partial, FO#1)**: 5 fixture-* files moved from `internal/runtime/` to `internal/runtime/fixtures/` via `git mv`. Direct file count: 69 → 64. T5.1 status PARTIAL — fixtures is 1 of 4 clusters (context/registry/plugins remain for follow-up iterations). Internal-only refactor; sibling callers (`cloud-run`, `local-run`, `real-local-run`, `real-cloud-run`) had their imports rewritten to `./fixtures/fixture-X.js`. 251/251 runtime + architecture tests GREEN; madge cycle count unchanged.
|
|
71
|
+
- **`internal/memory/storage/` sub-folder promotion (T10.1, FO#3)**: 7 storage-primitive files moved from `internal/memory/` to `internal/memory/storage/` via `git mv` — `markdown-store.ts`, `transcript-store.ts`, `session-loader.ts`, `session-summary-writer.ts`, `reader.ts`, `wiki-loader.ts`, `chunk-markdown.ts`. Direct file count in `internal/memory/`: 28 → 22 (under the 25-file god-folder heuristic). Internal-only refactor; zero public API surface change. All sibling imports, runtime/* callers, and test paths updated in the same slice. Architecture guard `tests/architecture/memory-folder-budget.test.ts` (NEW) asserts the budget. 140/140 architecture + memory tests GREEN; madge cycle count unchanged.
|
|
72
|
+
- **`dispatchSingleCall` orchestrator split (T10.4, PV#2)**: the 158 LOC body in `internal/agent-loop/tool-dispatch.ts` was decomposed into 7 named single-concern helpers (`applyRepairAndExtractCall`, `vetoFromForkWhitelist`, `startToolCallSpan`, `vetoFromPluginPreHook`, `vetoFromFileHookPreDecision`, `runToolWithLifecycle`, `finalizeSpanAndPostHook`). The orchestrator now reads as a ~28 LOC sequence; the previous complexity-suppression `biome-ignore` directive is removed. Zero public-API surface change; 51/51 regression tests (tool-dispatch + hooks + golden custom-tools) continue to pass.
|
|
73
|
+
|
|
74
|
+
### Fixed
|
|
75
|
+
|
|
76
|
+
- **5 LOW type-only cycles closed via 3 leaf extractions + self-ref drop (T4.1, ADR D438)**:
|
|
77
|
+
- `types/agent-prims.ts` (NEW leaf) holds `ModelParameterValue`, `ModelSelection`, `CustomTool`; `types/run.ts` + `types/messages.ts` now import these from the leaf (no longer from `types/agent.ts`). Re-exported via `types/agent.ts` barrel — `import type { ModelSelection, CustomTool } from "@theokit/sdk"` keeps working.
|
|
78
|
+
- `types/messages-base.ts` (NEW leaf) holds `UserMessage`; `types/updates.ts` imports from the leaf. Re-exported via `types/conversation.ts`.
|
|
79
|
+
- `internal/memory/active-memory-types.ts` (NEW leaf) holds `ActiveMemoryQueryMode`, `ActiveMemoryStatus`, `ActiveMemoryResult`; `active-memory-cache.ts` imports from leaf. Re-exported via `active-memory.ts`.
|
|
80
|
+
- Self-cycle on `types/agent.ts` (audit #3) closed by replacing the inline `import("./agent.js").SDKAgent` in `AgentOptions.handoffs?` with a direct forward-reference to the locally-defined `SDKAgent` interface.
|
|
81
|
+
- madge cycle count: **8 → 3** in one slice. Closed: cycles #3/#5/#6/#7/#10. Remaining: #1+#2 D428-acknowledged (rollup-dts subscribe-at-sub-path); #4 documented as deviation requiring HIGH-impact SDKAgent-interface extraction (out of T4.1 scope).
|
|
82
|
+
- Zero public type surface change. Public-type-surface smoke test in `tests/architecture/type-cycles-closed.test.ts` verifies barrels still resolve.
|
|
83
|
+
- **Architecture-test integrity fix (T4.1 follow-up)**: `tests/architecture/cycle-{8,9,11-12-13}-closed.test.ts` were passing **vacuously** because `repoRoot = resolve(__dirname, "../../../../..")` (5 ups) landed in the meta-repo `theokit-tools` which has no pnpm workspace — `pnpm exec madge` errored out and the cycle-line filter returned `[]`. Corrected to 4 ups (theokit-sdk workspace root). The underlying cycle closures from T1.1/T2.1/T3.1 are real (12/12 architecture tests now PASS against actual `madge --circular` output post-fix); the prior test integrity bug is surfaced honestly here per Inquebrável Rule 3 rather than buried.
|
|
84
|
+
- **CRITICAL runtime↔persistence cycle #9 closed**: extracted `internal/runtime/session-types.ts` (leaf types file ~15 LOC) holding `SessionMessage`. `agent-session-store.ts` now imports the type from this leaf; `agent-session.ts` re-exports it for back-compat with downstream importers. Closes the audit's only CRITICAL cycle (Phase 5 cartographer cycle #9 — `agent-session.ts → conversation-storage-fs.ts → agent-session-store.ts → agent-session.ts`, runtime↔persistence layer-crossing). madge cycle count: 9 → 8. Architecture test asserts via spawnSync. **Plan-vs-reality deviation:** ADR D432 prescribed a full port-and-adapter refactor; empirical inspection found the back-edge was a single types-only import, so type-leaf extraction is the smallest break that actually closes the cycle. Documented in `session-types.ts` JSDoc.
|
|
85
|
+
- **Memory cluster cycles #11 + #12 + #13 closed**: extracted `internal/memory/index-manager-contract.ts` (leaf types file holding `MemorySearchHit`, `IndexStatus`, `SearchOptions`, `MemoryBackend`, `OpenIndexOptions`). All 4 cluster members (`index-manager.ts`, `index-manager-dispatch.ts`, `lance-memory-adapter.ts`, `memory-index.ts`) now import these types from the contract; only the orchestrator imports runtime functions from dispatch (one direction). Single ~70 LOC extraction closes 3 HIGH cycles in one move (T2.1 of plan `arch-review-fixes-2026-06-06`, ADR D433). madge cycle count: 12 → 9. Back-compat re-export preserved on `index-manager.ts`. No public API touched.
|
|
86
|
+
- **Runtime cycle #8 closed**: extracted `internal/runtime/agent-registry-contract.ts` (leaf types file, ~60 LOC) holding `AgentRuntime` + `RegisteredAgent`. Both `agent-registry.ts` and `agent-registry-store.ts` now import these types from the contract; the previous runtime↔store 2-node cycle is closed (T3.1 of plan `arch-review-fixes-2026-06-06`, ADR D431). Back-compat re-export preserved on `agent-registry.ts` for existing downstream importers — no public API change. madge cycle count: 13 → 12 (HIGH cycle #8 resolved; remaining 12 covered by T1.1/T2.1/T4.1).
|
|
87
|
+
|
|
88
|
+
### Changed
|
|
89
|
+
|
|
90
|
+
- **BREAKING (shape only): `AgentRunError.providerError` getter now returns a redacted string (T1.5 of plan `sdk-superiority-2026-06-07`)**: pre-T1.5 the getter returned the raw `metadata.raw` object reference, which could carry `sk-...` tokens, Bearer JWTs, or other secret-shaped substrings straight into logs / Sentry / Langfuse. T1.5 wraps the value in `redactSecrets()` at the getter boundary and stringifies non-string payloads. Object identity is intentionally NOT preserved — secrets are stripped at the boundary. New `AgentRunError.toJSON()` OMITS `metadata.raw` from JSON output by default; operators opt in via `THEOKIT_DEBUG_RAW_ERRORS=1` to surface the (still-redacted) raw payload for diagnostics. All other fields (name/message/code/provider/requestId/conversationId/metadata.provider/metadata.endpoint/metadata.code/...) remain accessible. 5 new tests at `tests/security/error-redact.test.ts`; 2 pre-existing tests updated to reflect the new contract.
|
|
91
|
+
|
|
92
|
+
### Added
|
|
93
|
+
|
|
94
|
+
- **Reconnect storm prevention via `CredentialPool.waitForAvailable` (T3.9 of plan `sdk-superiority-2026-06-07`)**: pre-T3.9 the pool exposed only the instantaneous `hasAvailable()` probe (`internal/llm/credential-pool.ts:107-109`); concurrent callers that observed `select() === null` threw `CredentialPoolExhaustedError` immediately. Outer-layer retries then re-hit the pool the moment the first cooldown expired — every waiter woke at the same instant and hammered the upstream provider, defeating the cooldown's protective intent. T3.9 adds two new internal helpers on `CredentialPool`: `earliestResetAt()` (smallest `lastErrorResetAt` across exhausted entries) and `waitForAvailable(signal, { maxWaitMs, sleeper? })`. The wait loop uses full-jitter exponential backoff (AWS Brooker 2015 — same pattern shipped in T3.4's `computeBackoffMs`): each iteration sleeps a random fraction of the window to the earliest cooldown reset, so concurrent waiters stagger their re-probe instead of synchronizing. The `sleeper` parameter is a dependency-injection seam so tests stay deterministic without `vi.useFakeTimers()` — that timer mismatch was the blocker that deferred T3.4's wiring; T3.9 sidesteps it entirely. `PoolAwareLlmClient.stream()` now calls `pool.waitForAvailable` when `select()` returns null and the new `waitForAvailableMs` constructor option (default `30_000`) is non-zero; passing `0` opts out for legacy callers and for the two existing `pool-aware-client.test.ts` tests that assert the throw-fast contract. 5 new tests at `tests/internal/llm/credential-pool-wait-for-available.test.ts`; 110/110 llm tests GREEN. Closes DR3 finding #9 (reconnect storm under multi-tenant pool exhaustion).
|
|
95
|
+
|
|
96
|
+
- **Anthropic native cache-token surfacing on `LlmFinish` (T3.8 of plan `sdk-superiority-2026-06-07`)**: pre-T3.8 the Anthropic accumulator at `internal/llm/anthropic.ts:167-170` read only `input_tokens` and `output_tokens` from `message_delta.usage` — silently dropped `cache_creation_input_tokens` and `cache_read_input_tokens` even though Anthropic emits them when the `cache_control: {type:"ephemeral"}` annotation (shipped in T3.5) is present on system blocks. As a result the budget accumulator's 5-bucket telemetry stayed at zero and cost calculations couldn't apply the 1.25x cache_write / 0.1x cache_read discounts. T3.8 widens the `AnthropicMessageDelta` type, threads both counters through `handleMessageDelta` (treating 0 as "no cache activity" to mirror the usage-accumulator filter), and emits them on `LlmFinish`. New `__testing__AnthropicAccumulator` seam exposes the class directly so unit tests drive the message_delta path without spinning the SSE parser. 4 new tests at `tests/internal/llm/anthropic-cache-tokens.test.ts`; 105/105 llm tests GREEN. Closes the algorithm half of DR3 finding #8 (telemetry observability); real-LLM proof (live Anthropic round-trip with a ≥ 1024-token cacheable prefix returning `cache_read_input_tokens > 0` on the second send) lands in T6.1.
|
|
97
|
+
- **`ErrorCode.quota_exceeded` + provider-mapping completeness (T3.7 of plan `sdk-superiority-2026-06-07`)**: `ErrorCode` union widened with `quota_exceeded` (was missing per the TODO comment in `internal/errors/mappers/openai-compatible.ts:110`). `mapOpenAICompatibleError` now returns the canonical bucket for HTTP 402, OpenRouter "Insufficient credits", and body codes `insufficient_quota` / `quota_exceeded` — previously folded into `invalid_request`. Anthropic 529 (overloaded) and Vertex 401/403 are pinned by new contract tests (already correctly mapped to `server_error` and `auth_failed` respectively). 5 new tests at `tests/internal/errors/mappers/t3-7-quota-completeness.test.ts`; 2 pre-existing tests updated to assert the new T3.7 contract. 53/53 mapper tests GREEN. Closes DR3 finding #7 (MEDIUM — error-mapping completeness).
|
|
98
|
+
- **OpenAI structured outputs `response_format: json_schema` emission (T3.6 of plan `sdk-superiority-2026-06-07`)**: new `LlmResponseFormat` discriminated union at `internal/llm/types.ts` covers both `{type:"json_schema", jsonSchema:{name, schema, strict?}}` (canonical, defaults `strict: true`) and `{type:"json_object"}` (legacy JSON-mode hint). New `LlmRequest.responseFormat?: LlmResponseFormat`. `internal/llm/openai.ts:buildOpenAIBody` routes via new `encodeOpenAIResponseFormat` helper to emit OpenAI's wire shape verbatim. Same patch closes a latent T3.5 bug: `buildOpenAIBody` was naively pushing `request.system` (now `string | LlmSystemBlock[]`) into OpenAI's `content` field — would break for the array form. New `openAISystemText` helper collapses to a joined string the same way `ollamaSystemText` does. Real-LLM proof (Agent.generateObject prefers native path against `gpt-4o-2024-08-06+`) deferred to T6.1 with the live API. 4 new tests at `tests/internal/llm/openai-structured-outputs.test.ts`; 101/101 llm tests GREEN. Closes DR3 finding #6 (HIGH — native structured outputs unreachable).
|
|
99
|
+
- **Anthropic prompt-cache emit + `LlmRequest.system` widening (T3.5 of plan `sdk-superiority-2026-06-07`)**: new `LlmSystemBlock` type at `internal/llm/types.ts` with `text: string` + `cacheable?: boolean`. `LlmRequest.system` widened from `string` to `string | LlmSystemBlock[]` (back-compat preserved — pre-T3.5 string callers unchanged). `internal/llm/anthropic-shared.ts:buildAnthropicCommonBody` now translates the array form into Anthropic's content-block wire shape `{type:"text", text, cache_control?: {type:"ephemeral"}}` so consumers can opt into Anthropic prompt caching (1-3x cache_read billing discount on subsequent same-content turns). Empty array short-circuits to `undefined` (omitted system). `ollama-native.ts:buildOllamaChatBody` collapses the array form into a joined string for providers that don't support per-block caching. Real-LLM proof (cache_read_input_tokens > 0 on second send) lands in T3.8 + T6.1 with a ≥ 1024-token static prefix. 5 new tests at `tests/internal/llm/anthropic-prompt-cache.test.ts`; 97/97 llm tests GREEN.
|
|
100
|
+
- **Exponential backoff + full jitter helper (T3.4 of plan `sdk-superiority-2026-06-07`, partial)**: new `internal/llm/retry.ts` exposes `computeBackoffMs({attempt, baseMs?, capMs?, retryAfterMs?, rng?})` (AWS Brooker 2015 full-jitter pattern with provider Retry-After hint precedence + cap clamp) and `sleepWithAbort(ms, signal)` (resolves early on abort). Closes the algorithm half of DR3 finding #4 (pre-T3.4 the pool retried 429 immediately with no wait, burning every credential in <1ms under coordinated load). 10 new tests cover Retry-After in/out of range, exponential ceiling doubling, jitter spread (50-sample distinctness), cap enforcement, and abort-aware sleep. **Wiring into `pool-aware-client.ts` deferred to follow-up**: existing pool-aware-client tests use `vi.useFakeTimers()` which would stall on the new `setTimeout`-based sleeps; integration requires either test refactor to advance timers OR a sleeper-injection seam (out of iter scope). Helper module shipped + tested standalone.
|
|
101
|
+
|
|
102
|
+
### Fixed
|
|
103
|
+
|
|
104
|
+
- **SSE / NDJSON body stream cancels on EVERY exit path (T3.3 of plan `sdk-superiority-2026-06-07`, CRITICAL)**: extends T3.2's abort-only cancel to also cover consumer break (early `[DONE]` exit, satisfied stop condition) and consumer throw (JSON.parse failure, downstream `yield event` rejection). Pre-T3.3 the cancel-on-abort flag-tracking only fired when `signal.aborted === true`; if the OpenAI / Anthropic consumer broke out on `[DONE]` without aborting, the body stayed open and the TCP socket leaked. T3.3 collapses the conditional to unconditional `reader.cancel()` inside both `parseSseStream` and `parseNdjsonStream` finally blocks. WHATWG spec guarantees `cancel()` on a finished stream is a no-op, so always-cancel is safe. Helper renamed `cancelOnAbort → cancelReaderQuietly`. 2 new tests at `tests/internal/llm/sse-break-cancels-body.test.ts` (break + throw paths both observe `ReadableStream.cancel`). Zero regression across 82 llm tests. Closes DR3 finding #2 (T3.2+T3.3 together — required for T6.2 1000-conn load test).
|
|
105
|
+
- **SSE / NDJSON abort now cancels the body stream (T3.2 of plan `sdk-superiority-2026-06-07`, CRITICAL)**: pre-T3.2 `internal/llm/sse.ts:30-37` and `internal/llm/ollama-native.ts:243` only released the reader lock when `AbortSignal` fired — the underlying ReadableStream kept draining and the upstream HTTP connection's TCP socket stayed in CLOSE_WAIT. Over 100s of concurrent SSE clients (T6.2 load test) this leaked sockets to exhaustion. T3.2 mirrors a `aborted` flag and calls `reader.cancel()` in the `finally` block when the signal aborted, so cancellation propagates to the body stream. Best-effort catch around `cancel()` per ADR D34 safe-exporter contract (cancel-time errors never propagate to caller). 2 new tests at `tests/internal/llm/sse-abort-cancels-body.test.ts` (aborted signal triggers `ReadableStream.cancel`; normal close does NOT). Zero regression across 80 existing llm tests. Closes DR3 finding #2.
|
|
106
|
+
- **SSE parser HTML Living Standard § 9.2.6 compliance (T3.1 of plan `sdk-superiority-2026-06-07`, CRITICAL)**: `internal/llm/sse.ts:73` previously called `.trim()` on every `data:` / `event:` value, which (a) stripped ALL leading whitespace instead of exactly one space, and (b) destroyed legitimate trailing whitespace in payloads. Per HTML LS § 9.2.6 step 5 of "Process the field", only a single leading U+0020 SPACE should be removed. T3.1 replaces `.trim()` with a `stripOneLeadingSpace` helper. The bug was the root cause of intermittent stream truncation observed in DR3 review finding #1 — payloads with intentional padding (chunked JSON, message-id headers ending in a space) lost characters. 6 new tests at `tests/internal/llm/sse-spec-compliance.test.ts` cover both `data:` and `event:` fields, multi-line payloads, and chunk-boundary preservation. Zero regression across 78 existing llm tests.
|
|
107
|
+
|
|
108
|
+
### Added
|
|
109
|
+
|
|
110
|
+
- **`validateResponse` D93 bailout wiring (T2.1 of plan `sdk-superiority-2026-06-07`)**: previously `internal/runtime/validate-response.ts` was an orphan export with ZERO production callers (DR2 finding #1). The bailout-detector exists for the weak-model failure mode where Gemini Flash / Mistral 7B sometimes return `{ stopReason: "end_turn", text: "", toolCalls: [] }` and the run silently "finishes" with no visible answer. T2.1 wires `validateResponse` in `continueOrTerminate` and adds `LoopContext.nudgeAttempts` capped at 2: empty/whitespace-only bailout shapes inject a "Please continue or provide a final answer" user message and re-run the LLM turn. If the model still bails after 2 nudges, the loop finishes (gives up — break out of infinite spin). 4 new tests at `tests/internal/agent-loop/validate-response-nudge.test.ts` (LLM stub returns empty then real; whitespace-only triggers same path; nudgeAttempts cap; non-empty does NOT over-fire). Zero regression across 20 existing agent-loop + validate-response tests.
|
|
111
|
+
- **`downloadArtifact` path-traversal hardening (T1.4 of plan `sdk-superiority-2026-06-07`)**: previous inline check only rejected `..` substring + leading `/`. New centralized `validateArtifactPath` in `internal/security/path-guard.ts` rejects 7 vectors at the boundary: classic `..` parent-directory traversal, backslash escapes (`..\\windows`), URL-encoded `%2e%2e` (with double-decode to defeat `%252e%252e`), NUL byte injection (`\x00`), Windows drive letter prefix (`C:`, `D:\\`), home-tilde expansion (`~/`, `~root/`), and absolute paths (`/etc/passwd`). `cloud-agent.ts:downloadArtifact` delegates to the validator and preserves the typed `ConfigurationError({code:"artifact_path_traversal"})` contract. 7 new tests at `tests/security/artifact-path-traversal.test.ts`. Closes DR1 finding #2 (CRITICAL path traversal).
|
|
112
|
+
- **API key boundary validation (T1.3 of plan `sdk-superiority-2026-06-07`)**: new `internal/auth/api-key-validator.ts` exposes `validateApiKeyShape(key, opts?)` with a two-tier check — Tier 1 always rejects empty / whitespace-only / sub-4-char shapes; Tier 2 (strict, default-on) adds 16-char minimum + provider-prefix sanity (`sk-` for openai, `sk-ant-` for anthropic, `sk-or-` for openrouter) + embedded-whitespace rejection. Strict tier is bypassed when `shouldUseRealLocalRuntime(key)` is true (the env-credential path doesn't use the apiKey for the provider fetch). `Agent.create` wires the validator into both `createLocalAgent` and `createCloudAgent`. Failures throw `AuthenticationError({code:"malformed_api_key", message})`. 14 new tests at `tests/security/api-key-validation.test.ts` + zero regressions across 209 telemetry/errors/golden tests.
|
|
113
|
+
- **`RegisteredAgent` contract snapshot test (T1.2 of plan `sdk-superiority-2026-06-07`)**: new `tests/contract/registered-agent.test.ts` pins the public shape of `RegisteredAgent` + `AgentRuntime` + `RegisteredAgent.status` closed union. Tsc enforces the snapshot; any field drop / rename / type change surfaces at typecheck. Note: the leaf-extraction part of T1.2 (`agent-registry-contract.ts`) was already shipped under the prior plan `arch-review-fixes-2026-06-06` T3.1 / ADR D431. Madge cycle count unchanged (2 baseline).
|
|
114
|
+
|
|
115
|
+
### Changed
|
|
116
|
+
|
|
117
|
+
- **BREAKING (type-level only): `AgentRunErrorCode` is now closed (T1.1 of plan `sdk-superiority-2026-06-07`)**: the previous `(string & {})` escape hatch is removed. New canonical type `KnownAgentRunErrorCode` exposes the closed literal union; `AgentRunErrorCode` remains as a back-compat re-export alias (no source change required for code that uses the alias). Boundary helper `coerceToKnownAgentRunErrorCode(raw)` collapses unknown strings to `"unknown"` at the call boundary; `Agent.prompt` adopted it for `RunErrorDetail.code` translation. Migration codemod ships at `packages/sdk/scripts/migrations/error-code-string-2-known.mjs` (regex-based dry-run by default; pass `--write` to apply). Closes DR1 finding #1 (CRITICAL).
|
|
118
|
+
|
|
119
|
+
### Added
|
|
120
|
+
|
|
121
|
+
- **Load + chaos suite scaffold (T0.3 of plan `sdk-superiority-2026-06-07`)**: 6 new test files at `tests/load/{1000-concurrent-sse,leaky-generators,slow-consumer-backpressure}.test.ts` and `tests/chaos/{kill-mid-stream,partition-fs,oom-recovery}.test.ts`. Three harness modules ship alongside: `tests/load/_harness/sse-driver.ts` (in-process SSE driver — NOT autocannon — per SEPA brief § E; tracks p50/p95/p99 latencies + SSE event count via `\n\n` terminators per HTML LS § 9.2.6), `tests/load/_harness/socket-monitor.ts` (Linux-only `ss -tnp` probe with no-op fallback for Mac/Win; CI asserts `closeWaitCount ≤ threshold`), `tests/chaos/_harness/process-control.ts` (child-process spawn + SIGKILL injection per ADR D37 methodology). Today's scaffold uses 100 concurrent SSE (override via `T0_3_CONCURRENCY=1000`); T6.2 ratchets to the full 1000-conn p95 < 200ms perf gate, T6.3 wires the kill-mid-stream chaos against the SDK's real streaming surface, T6.4 wires partition-fs against persistence paths, T6.5 wires OOM against the memory subsystem.
|
|
122
|
+
- **Real-LLM CI matrix scaffold (T0.2 of plan `sdk-superiority-2026-06-07`)**: 15 env-gated integration test files at `tests/integration/real-llm/{openai,anthropic,openrouter}-{tools,vision,stream,cache,structured}.test.ts`. Each file uses `describe.skipIf(...)` so the suite is silent when the relevant API key is absent. `tests/integration/real-llm/_helpers/real-llm-env.ts` centralizes the provider-key resolver with OpenRouter fallback for non-native scenarios (Anthropic cache stays native-only per SEPA initial brief § C). With keys set the matrix validates the happy path for tool use, streaming, vision content parts, prompt caching, and structured outputs across the 3 routes — expanded depth (cache_read_input_tokens > 0 assertion, parallel tool dispatch, error-retry) lands in T3.5 / T3.8 / T6.1. Default model `openai/gpt-4o-mini` per cost budget. Today: 15/15 files skip cleanly.
|
|
123
|
+
- **OTel hot-path wiring foundation (T0.1 of plan `sdk-superiority-2026-06-07`)**: emit canonical spans `agent.create`, `agent.send` (parent), and `memory.recall` when `telemetry.enabled: true`. New closed-enum `internal/telemetry/span-names.ts` (14 names + `SpanName` literal type) anticipates the no-`(string & {})` discipline of T1.1. `TelemetryHandle` interface extended with `recordHistogram(name, valueMs, attrs)` and the OTel `metrics` namespace is lazy-loaded the same way `trace` is (graceful no-op when missing). First histogram name registered: `theokit_memory_recall_duration_ms` (recorded with `userId/namespace/scope/status` dimensions). Integration tests use a real `@opentelemetry/sdk-trace-base` `InMemorySpanExporter` (NOT module mocks) — added as devDep alongside `@opentelemetry/api` and `@opentelemetry/sdk-metrics`. Wiring triad: pillar (a) callers are `Agent.create` (production), `LocalAgent.send` (production), `runActiveMemory` (production); pillar (b) covered by `tests/telemetry/*.test.ts` (8 tests). Remaining acceptance items — `agent.send.<step>` 8 child spans, `tool.call`, `llm.call` spans — deferred to T1.7 / T2.4 / T3.* per SEPA brief (zero plan-deviation).
|
|
124
|
+
- **`SecretRedactor` interface** at `internal/security/secret-redactor.ts` (T9.1 of plan `arch-review-fixes-2026-06-06`, ADR D437). Types-only — no runtime exports; canonical `redactSecrets` from `redact.ts` satisfies the interface structurally. Closes AF#16 (Martin Zone of Pain D=0.923) from the 2026-06-06 architecture audit through documentation + minimal abstraction without violating D68/D69/D70/D71/D73 (security primitives stay concrete + stable). Rationale + coupling metrics at `internal/security/README.md`.
|
|
125
|
+
|
|
126
|
+
### Changed
|
|
127
|
+
|
|
128
|
+
- **Renamed `internal/runtime/system-prompt/providers/` → `internal/runtime/system-prompt/sources/`** (FO#6, plan `arch-review-fixes-2026-06-06` T10.3). The directory previously shared its basename with `internal/providers/` (LLM provider profiles per ADR D105-D107) — auditor flagged the duplicate folder name as a findability hazard. `sources/` better describes the semantic: these 5 modules are system-prompt *sources* (ActiveMemoryPromptProvider, BasePromptProvider, ContextPromptProvider, MemoryPromptProvider, SkillsPromptProvider), not LLM provider profiles. Internal-only rename; no public API touched. Git-rename detection preserved (5/5 files moved with `git mv`); import paths in `pipeline.ts` + 5 golden tests updated atomically.
|
|
129
|
+
|
|
130
|
+
### Fixed
|
|
131
|
+
|
|
132
|
+
- **`safeListTools` no longer silently swallows MCP failures** (PV#6, plan `arch-review-fixes-2026-06-06` T8.1). When `client.listTools()` throws (MCP server unreachable, auth refused, etc.), the agent loop now emits a structured `[theokit-sdk] mcp listTools failed (server=<name>): <error>` line to stderr **while preserving the empty-list fallback** that consumers depend on for graceful degradation. The previous behaviour violated Inquebrável Rule 8 (`FALHE alto, FALHE cedo, FALHE claro`). `safeListTools` is now `export`ed from `internal/agent-loop/loop.ts` to enable unit-test access to the catch path — NOT promoted to the public `@theokit/sdk` API surface.
|
|
133
|
+
|
|
134
|
+
### Notes
|
|
135
|
+
|
|
136
|
+
- **Cycles #1, #2 (type-only, ADR D428 acknowledged):** the 2026-06-06 architecture audit (`/loop-architecture-review`) found 2 type-only dependency cycles in `packages/sdk/src/types/agent.ts ↔ internal/runtime/fork-agent.ts` that manifest in the rollup-dts bundle. Per ADR D428 (subscribe-at-sub-path) these are intentional: keeping `subscribe` at the `@theokit/sdk/subscription` sub-path avoids promoting types through the cycle. They are NOT runtime cycles (JS-erased at build time) and are not breakable without regressing D428. Plan `arch-review-fixes-2026-06-06` T11.1 documents this rationale.
|
|
137
|
+
- **PV#8 — ISP / SDKAgent bundles local + cloud methods (ADR D122 acknowledged):** the 2026-06-06 architecture audit flagged the `SDKAgent` public interface as bundling local-only and cloud-only methods (ISP marginal). Per ADR D122 (`run-until-cloud-unsupported`), `CloudAgent` throws `UnsupportedRunOperationError` for runtime ops it cannot service while sharing the same TypeScript surface — the bundled shape is intentional cross-runtime API parity, not a design defect. Splitting `SDKAgent` into local/cloud interfaces would force consumers to branch on runtime at call sites, contradicting D122's "single typed surface" decision. Plan `arch-review-fixes-2026-06-06` T11.1 documents this rationale.
|
|
138
|
+
|
|
139
|
+
### Fixed
|
|
140
|
+
|
|
141
|
+
- Restored green `pnpm validate` after G8 subscription landing (`9fda7d7`). Biome 2.4 gate: 24 lint findings in `subscription/` prod + tests resolved with `biome-ignore` annotations (9× `useYield` intentional empty/throw test handlers; 13× `noExcessiveCognitiveComplexity` refactor-candidate; 1× `noConfusingVoidType` idiomatic callback shape; 1× `noAssignInExpressions` idiomatic line-parser). Stale `// eslint-disable-next-line require-yield` comments replaced — Biome does not honor ESLint pragmas. Lint-gate T1.5.2 `no-unredacted-sink` whitelisted `subscription/internal/server-integration.ts` (writes declarative `SubscriptionManifest`, no PII). Build/publint: `scripts/mirror-dts-to-cts.mjs` targets extended to cover `subscription/` so `dist/subscription/index.d.cts` is emitted (fixes `pkg.exports["./subscription"].require.types` missing). Dead-code/knip: ignore glob extended from `src/internal/**` to `src/**/internal/**` for per-feature internal namespaces. Architecture/depcruise `no-orphans`: `pathNot` extended with `(^|/)packages/sdk/src/[^/]+/internal/` (same exemption rationale as `src/internal/` — type-only exports erased at runtime).
|
|
142
|
+
|
|
143
|
+
## 1.7.0 - 2026-06-04
|
|
144
|
+
|
|
145
|
+
### Added
|
|
146
|
+
|
|
147
|
+
- **`@theokit/sdk/subscription` sub-path** (per blueprint G8 SHIPPABLE 98.3) — typed subscription primitive with WS + W3C SSE transports + opaque resume tokens (`lastEventId`). Form 4 Hybrid (D423): low-level adapters (`createNodeWsAdapter`, `encodeSseChunk`, `parseSseW3C`) + high-level DSL (`defineSubscription`, `subscribe`, `tracked`).
|
|
148
|
+
- **8 exports** at `@theokit/sdk/subscription`:
|
|
149
|
+
- `defineSubscription<TInput, TOutput>({input, output, handler})` — server-side typed RPC factory (D427)
|
|
150
|
+
- `subscribe<TInput, TOutput>(name, input, opts)` — client-side AsyncGenerator with transparent reconnect + lastEventId propagation (D428)
|
|
151
|
+
- `tracked(id, payload)` + `isTrackedEnvelope(value)` — resume token envelope helpers
|
|
152
|
+
- `SubscriptionTransport = 'ws' | 'sse' | 'auto'` (D425)
|
|
153
|
+
- `SubscriptionCtx`, `SubscriptionDescriptor<TInput, TOutput>`, `TrackedEnvelope<T>` (types)
|
|
154
|
+
- **3 typed error classes:** `SubscriptionError`, `SubscriptionInputError` (carries Zod `issues`), `SubscriptionDisconnectError` (carries `closeCode`/`closeReason`). All extend `TheokitAgentError`.
|
|
155
|
+
- **`ws@>=8.0.0` + `@types/ws@>=8.0.0` optional peer deps** — Node WS adapter loads `ws` via dynamic `import()` with actionable error when missing (D426). SSE-only consumers pay zero cost.
|
|
156
|
+
- **W3C-spec SSE encoder + parser** — independent of D38 Vercel AI Data Stream v1 wire format (which stays locked for `streamAssistant` LLM streaming). Both coexist (D429).
|
|
157
|
+
- **Server integration primitives** — `scanSubscriptions({appDir, outFile})` emits `.theo/subscriptions.json` mirroring G6 routes scanner; `mountSubscriptions({manifest, appDir})` returns `{handleSseRequest, handleWsUpgrade}` ready to wire into `http.Server`. theokit-side Vite plugin + dev-server wiring is a cross-repo follow-up (D430).
|
|
158
|
+
|
|
159
|
+
### ADRs absorbed
|
|
160
|
+
|
|
161
|
+
- **D423** — Form 4 Hybrid (low-level primitives + high-level DSL)
|
|
162
|
+
- **D424** — `lastEventId` opaque, server-defined replay semantics
|
|
163
|
+
- **D425** — Transport selection `'ws' | 'sse' | 'auto'` (default `'auto'` = WS-preferred)
|
|
164
|
+
- **D426** — `ws` Node canonical (optional peer); CF Workers / Bun / Deno deferred to v1.8.x as separate packages
|
|
165
|
+
- **D427** — `defineSubscription` AsyncGenerator + Zod input/output
|
|
166
|
+
- **D428** — `subscribe` lives at `@theokit/sdk/subscription` sub-path only (NOT promoted to `Theokit.subscribe` due to pre-existing `agent.ts ↔ fork-agent.ts` rollup-dts cycle; same isolation pattern as `path-safety`)
|
|
167
|
+
- **D429** — W3C SSE wire format (independent of D38 Vercel AI Data Stream)
|
|
168
|
+
- **D430** — Server auto-route via `theokit.subscriptions` scanner (cross-repo follow-up for theokit-side wiring)
|
|
169
|
+
|
|
170
|
+
### Security threats addressed
|
|
171
|
+
|
|
172
|
+
| Threat | Mitigation |
|
|
173
|
+
|---|---|
|
|
174
|
+
| Resume token replay | Consumer SHOULD bind token to session + rotate per reconnect; SDK ships TTL knob via custom `tracked()` envelope semantics |
|
|
175
|
+
| WS connection hijacking | Auth at HTTP upgrade — `WsAdapter.upgrade(ctx, raw)` exposes the `request` so consumer middleware (G11 `defineAuth`) runs BEFORE upgrade. Rejected upgrade returns null → caller responds 401 |
|
|
176
|
+
| Subscription input tampering | Zod schema validation BEFORE handler invocation; throws `SubscriptionInputError` carrying issues |
|
|
177
|
+
| Resource exhaustion | Per-subscription `AbortSignal`; `SubscriptionRuntime.getActiveConnectionCount()` for ops visibility; consumer wires rate-limit middleware (P#10) at upgrade boundary |
|
|
178
|
+
| Sensitive data in logs | Telemetry seam (D34) captures metadata only (`subscriptionName`, `lastEventId`, `connectionId`); never payloads (per D73 redact at output boundaries) |
|
|
179
|
+
| Long-lived WS survives token expiry | `ctx.disconnect(code, reason)` lets consumer's auth middleware force-close when session revoked |
|
|
180
|
+
|
|
181
|
+
### Multi-runtime compatibility matrix
|
|
182
|
+
|
|
183
|
+
| Runtime | v1.7.0 | v1.8.x (planned) |
|
|
184
|
+
|---|---|---|
|
|
185
|
+
| Node 22+ | yes (canonical `ws` peer) | yes |
|
|
186
|
+
| Cloudflare Workers | consumer adapter only | yes (`@theokit/sdk-ws-cloudflare`) |
|
|
187
|
+
| Bun | consumer adapter only | yes (`@theokit/sdk-ws-bun`) |
|
|
188
|
+
| Deno | consumer adapter only | yes (`@theokit/sdk-ws-deno`) |
|
|
189
|
+
|
|
190
|
+
### Notes
|
|
191
|
+
|
|
192
|
+
- v1.7.0 is **additive** — no breaking changes. Existing `streamAssistant` (Vercel AI Data Stream, D38) untouched.
|
|
193
|
+
- Tests: **45 GREEN + 1 honest-SKIP** under `tests/subscription/` + `tests/integration/subscription-resume.test.ts` (real `ws.WebSocketServer` + `http.Server` real SSE roundtrip + lastEventId resume) + `tests/integration/subscription-real-llm.test.ts` (env-gated `OPENROUTER_API_KEY` — verified GREEN against real OpenRouter `openai/gpt-4o-mini` per `real-llm-validation.md`).
|
|
194
|
+
- Build: `dist/subscription/index.{js,cjs,d.ts,d.cts}` emitted; JS+CJS via tsup, DTS via tsc + `tsconfig.tools-dts.json` (mirrors `tools/` + `path-safety` pattern to avoid pre-existing `types/agent.ts ↔ fork-agent.ts` rollup-dts cycle).
|
|
195
|
+
|
|
3
196
|
## 1.6.0 - 2026-06-03
|
|
4
197
|
|
|
5
198
|
### Added
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { cpSync, existsSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
// EC-1: Node version guard (matches SDK engines.node)
|
|
6
|
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
|
7
|
+
if (major < 22 || (major === 22 && minor < 12)) {
|
|
8
|
+
console.error(`@theokit/sdk requires Node >= 22.12.0. Current: ${process.version}`);
|
|
9
|
+
process.exit(1);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const templateDir = join(import.meta.dirname, "../claude-template");
|
|
13
|
+
const cwd = process.cwd();
|
|
14
|
+
const targetDir = join(cwd, ".claude");
|
|
15
|
+
const force = process.argv.includes("--force");
|
|
16
|
+
|
|
17
|
+
// EC-4: Check .claude/, AGENTS.md, CLAUDE.md independently
|
|
18
|
+
const conflicts = [];
|
|
19
|
+
if (existsSync(targetDir)) conflicts.push(".claude/");
|
|
20
|
+
if (existsSync(join(cwd, "AGENTS.md"))) conflicts.push("AGENTS.md");
|
|
21
|
+
if (existsSync(join(cwd, "CLAUDE.md"))) conflicts.push("CLAUDE.md");
|
|
22
|
+
|
|
23
|
+
if (conflicts.length > 0 && !force) {
|
|
24
|
+
console.error(`Already exists: ${conflicts.join(", ")}. Use --force to overwrite.`);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
cpSync(join(templateDir, "dot-claude"), targetDir, { recursive: true });
|
|
29
|
+
cpSync(join(templateDir, "AGENTS.md"), join(cwd, "AGENTS.md"));
|
|
30
|
+
cpSync(join(templateDir, "CLAUDE.md"), join(cwd, "CLAUDE.md"));
|
|
31
|
+
|
|
32
|
+
console.log("Created .claude/ with TheoKit SDK configuration (15 domain skills).");
|
|
33
|
+
console.log("Created AGENTS.md (cross-agent) and CLAUDE.md (Claude Code).");
|
|
34
|
+
console.log("\nNext: open Claude Code and start building with TheoKit.");
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# @theokit/sdk — TypeScript SDK for AI Agents
|
|
2
|
+
|
|
3
|
+
Build AI agents that run locally or in the cloud. Same code, same API, pick your runtime.
|
|
4
|
+
|
|
5
|
+
## Setup
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @theokit/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Set your API key:
|
|
12
|
+
```bash
|
|
13
|
+
export THEOKIT_API_KEY="your-key"
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Import Map
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
import { Agent } from "@theokit/sdk"; // Core: Agent, Run, SDKMessage
|
|
20
|
+
import { defineTool } from "@theokit/sdk"; // Tool definitions
|
|
21
|
+
import { TheokitAgentError } from "@theokit/sdk/errors"; // Error hierarchy
|
|
22
|
+
import { Cron } from "@theokit/sdk/cron"; // Scheduled jobs
|
|
23
|
+
import { Eval } from "@theokit/sdk/eval"; // Evaluation suite
|
|
24
|
+
import { Workflow } from "@theokit/sdk/workflow"; // Multi-step workflows
|
|
25
|
+
import { defineSubscription } from "@theokit/sdk/subscription"; // SSE/WebSocket subscriptions
|
|
26
|
+
import { VectorRetriever } from "@theokit/sdk/rag"; // RAG: retrievers, rerankers, splitters
|
|
27
|
+
import { defineSubAgent } from "@theokit/sdk/a2a"; // Agent-to-agent delegation
|
|
28
|
+
import { SandboxBackend } from "@theokit/sdk/sandbox"; // Sandbox backends
|
|
29
|
+
import { defineAuth } from "@theokit/sdk/server/auth"; // Authentication
|
|
30
|
+
import { TaskStore } from "@theokit/sdk/task-store"; // Task persistence
|
|
31
|
+
import { createClient } from "@theokit/sdk/client"; // HTTP client
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
const agent = await Agent.create({
|
|
38
|
+
apiKey: process.env.THEOKIT_API_KEY!,
|
|
39
|
+
model: { id: "google/gemini-2.0-flash-001" },
|
|
40
|
+
local: { cwd: process.cwd() },
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const run = await agent.send("Summarize this repository");
|
|
44
|
+
for await (const event of run.stream()) {
|
|
45
|
+
if (event.type === "assistant") console.log(event.content);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
agent.dispose(); // Always clean up
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Core Patterns
|
|
52
|
+
|
|
53
|
+
### Agent lifecycle
|
|
54
|
+
- `Agent.create(options)` — create an agent (local or cloud)
|
|
55
|
+
- `agent.send(prompt)` — send a message, get a Run
|
|
56
|
+
- `run.stream()` — AsyncGenerator of SDKMessage events
|
|
57
|
+
- `agent.dispose()` — clean up resources (or use `await using`)
|
|
58
|
+
- `Agent.prompt(options, prompt)` — one-shot: create, send, dispose
|
|
59
|
+
|
|
60
|
+
### Tool definition
|
|
61
|
+
```typescript
|
|
62
|
+
const searchTool = defineTool({
|
|
63
|
+
name: "search",
|
|
64
|
+
description: "Search the web",
|
|
65
|
+
inputSchema: z.object({ query: z.string() }),
|
|
66
|
+
execute: async ({ query }) => ({ results: await search(query) }),
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Streaming events (SDKMessage)
|
|
71
|
+
- `{ type: "assistant", content }` — text from the model
|
|
72
|
+
- `{ type: "tool_use", name, input }` — tool call
|
|
73
|
+
- `{ type: "tool_result", name, output }` — tool response
|
|
74
|
+
- `{ type: "status", status }` — run status change
|
|
75
|
+
- `{ type: "error", error }` — error event
|
|
76
|
+
- `{ type: "usage", tokens }` — token usage update
|
|
77
|
+
|
|
78
|
+
### Error handling
|
|
79
|
+
```typescript
|
|
80
|
+
try {
|
|
81
|
+
await agent.send("...");
|
|
82
|
+
} catch (e) {
|
|
83
|
+
if (e instanceof TheokitAgentError) {
|
|
84
|
+
console.error(e.code, e.message); // typed error with code
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### DI decorators (`@theokit/di` + `@theokit/di-agent`)
|
|
90
|
+
```typescript
|
|
91
|
+
import { Injectable, Container } from "@theokit/di";
|
|
92
|
+
import { Tool, Workflow, Cron, InjectAgent } from "@theokit/di-agent";
|
|
93
|
+
|
|
94
|
+
@Injectable()
|
|
95
|
+
class MyService {
|
|
96
|
+
@Tool({ name: "search", description: "Search" })
|
|
97
|
+
searchTool!: ToolOptions;
|
|
98
|
+
|
|
99
|
+
@Cron({ schedule: "*/5 * * * *" })
|
|
100
|
+
cleanup() { /* runs every 5 min */ }
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Gateways
|
|
105
|
+
```typescript
|
|
106
|
+
import { defineGateway } from "@theokit/gateway-telegram"; // or -slack, -discord, etc.
|
|
107
|
+
const gateway = defineGateway({ token: process.env.BOT_TOKEN });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Available: telegram, slack, discord, whatsapp, teams, email, sms, mattermost, line, matrix.
|
|
111
|
+
|
|
112
|
+
## Anti-patterns
|
|
113
|
+
|
|
114
|
+
- NEVER import from `@theokit/sdk/internal/...` — internal paths are not public API
|
|
115
|
+
- NEVER import from `@theokit/sdk/dist/...` — use the exports map above
|
|
116
|
+
- NEVER forget `agent.dispose()` — causes resource leaks
|
|
117
|
+
- NEVER use `new Agent()` — always use `Agent.create()`
|
|
118
|
+
- NEVER use `any` for tool input schemas — use Zod schemas
|
|
119
|
+
|
|
120
|
+
## Packages
|
|
121
|
+
|
|
122
|
+
| Package | Purpose |
|
|
123
|
+
|---------|---------|
|
|
124
|
+
| `@theokit/sdk` | Core SDK (Agent, Run, Tools, Memory, Streaming) |
|
|
125
|
+
| `@theokit/di` | Dependency injection container |
|
|
126
|
+
| `@theokit/di-agent` | 15 agentic decorators for DI |
|
|
127
|
+
| `@theokit/gateway-*` | Platform gateways (Telegram, Slack, etc.) |
|
|
128
|
+
| `@theokit/react` | React hooks for agent UIs |
|
|
129
|
+
|
|
130
|
+
## Configuration
|
|
131
|
+
|
|
132
|
+
Project config lives in `.theokit/`:
|
|
133
|
+
- `.theokit/mcp.json` — MCP server configuration
|
|
134
|
+
- `.theokit/hooks.json` — lifecycle hooks
|
|
135
|
+
- `.theokit/agents/*.md` — agent instruction files
|
|
136
|
+
|
|
137
|
+
Environment variables:
|
|
138
|
+
- `THEOKIT_API_KEY` — API key (required)
|
|
139
|
+
- `THEOKIT_MODEL_ID` — default model override
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
@AGENTS.md
|
|
2
|
+
|
|
3
|
+
## Claude Code — TheoKit SDK Extensions
|
|
4
|
+
|
|
5
|
+
This project uses `@theokit/sdk`. The AGENTS.md above contains the full API reference. Below are Claude Code-specific extensions.
|
|
6
|
+
|
|
7
|
+
### Available Skills (auto-loaded by domain)
|
|
8
|
+
|
|
9
|
+
These skills inject TheoKit knowledge automatically when you edit files matching their domain:
|
|
10
|
+
|
|
11
|
+
| Skill | Triggers on files matching |
|
|
12
|
+
|-------|---------------------------|
|
|
13
|
+
| `theokit-agent-core` | `*agent*`, `*Agent*`, `sdk.*` |
|
|
14
|
+
| `theokit-tools` | `*tool*`, `*Tool*` |
|
|
15
|
+
| `theokit-memory` | `*memory*`, `*Memory*`, `*embed*` |
|
|
16
|
+
| `theokit-di` | `*container*`, `*inject*`, `*provider*`, `*module*` |
|
|
17
|
+
| `theokit-di-agent` | `*decorator*`, `*Decorator*`, `di-agent*` |
|
|
18
|
+
| `theokit-gateways` | `*gateway*`, `*telegram*`, `*slack*`, `*discord*` |
|
|
19
|
+
| `theokit-rag` | `*retriev*`, `*rerank*`, `*splitter*`, `*rag*` |
|
|
20
|
+
| `theokit-workflows` | `*workflow*`, `*Workflow*`, `*step*` |
|
|
21
|
+
| `theokit-eval` | `*eval*`, `*Eval*`, `*scorer*` |
|
|
22
|
+
| `theokit-cron` | `*cron*`, `*Cron*`, `*job*`, `*schedule*` |
|
|
23
|
+
| `theokit-subscriptions` | `*subscri*`, `*sse*`, `*websocket*`, `*ws.*` |
|
|
24
|
+
| `theokit-errors` | `*error*`, `*Error*`, `*exception*` |
|
|
25
|
+
| `theokit-config` | `.theokit/**`, `config.*`, `theo.config.*` |
|
|
26
|
+
| `theokit-streaming` | `*stream*`, `*Stream*`, `*SDKMessage*` |
|
|
27
|
+
| `theokit-budget` | `*budget*`, `*Budget*`, `*cost*`, `*token*` |
|
|
28
|
+
|
|
29
|
+
### Settings
|
|
30
|
+
|
|
31
|
+
`.claude/settings.json` is pre-configured with safe defaults:
|
|
32
|
+
- Allows: `npm run *`, `pnpm *`, `git status`, `git diff`, reading `src/` and `docs/`
|
|
33
|
+
- Denies: `.env*` file reads, `sudo`, `rm -rf`
|
|
34
|
+
- Override locally: create `.claude/settings.local.json` (add to `.gitignore`)
|
|
35
|
+
|
|
36
|
+
### Customization
|
|
37
|
+
|
|
38
|
+
Add your project-specific instructions below this line. The SDK knowledge above stays current with your installed `@theokit/sdk` version.
|
|
39
|
+
|
|
40
|
+
```markdown
|
|
41
|
+
## My Project
|
|
42
|
+
|
|
43
|
+
Build: `npm run build`
|
|
44
|
+
Test: `npm test`
|
|
45
|
+
Lint: `npm run lint`
|
|
46
|
+
|
|
47
|
+
## Architecture
|
|
48
|
+
- `src/agents/` — agent definitions
|
|
49
|
+
- `src/tools/` — tool implementations
|
|
50
|
+
- `src/services/` — business logic
|
|
51
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# TheoKit SDK Conventions
|
|
2
|
+
|
|
3
|
+
## Agent lifecycle
|
|
4
|
+
- Always use `Agent.create()` to create agents — NEVER `new Agent()`
|
|
5
|
+
- Always call `agent.dispose()` or use `await using` when done
|
|
6
|
+
- Use `Agent.prompt()` for one-shot operations (auto-disposes)
|
|
7
|
+
|
|
8
|
+
## Imports
|
|
9
|
+
- Use `@theokit/sdk` for core (Agent, defineTool, Memory)
|
|
10
|
+
- Use `@theokit/sdk/errors` for error types
|
|
11
|
+
- Use `@theokit/sdk/subscription` for SSE/WebSocket
|
|
12
|
+
- Use `@theokit/sdk/rag` for retrievers, rerankers, splitters
|
|
13
|
+
- Use `@theokit/sdk/cron` for scheduled jobs
|
|
14
|
+
- Use `@theokit/sdk/eval` for evaluation
|
|
15
|
+
- Use `@theokit/sdk/workflow` for workflows
|
|
16
|
+
- NEVER import from `@theokit/sdk/internal/...`
|
|
17
|
+
- NEVER import from `@theokit/sdk/dist/...`
|
|
18
|
+
|
|
19
|
+
## Tools
|
|
20
|
+
- Tool `inputSchema` MUST use Zod schemas — NEVER `any` or untyped objects
|
|
21
|
+
- Tool `execute` MUST return a serializable value
|
|
22
|
+
|
|
23
|
+
## DI
|
|
24
|
+
- Use `@Injectable()` + `@Inject()` from `@theokit/di`
|
|
25
|
+
- NEVER manually `new` a service — let the container resolve it
|
|
26
|
+
|
|
27
|
+
## Error handling
|
|
28
|
+
- Catch `TheokitAgentError` (base class) and check `error.code`
|
|
29
|
+
- NEVER silently swallow errors — log with context or rethrow
|
|
30
|
+
|
|
31
|
+
## Gateways
|
|
32
|
+
- One gateway per agent instance
|
|
33
|
+
- Configure via `defineGateway()` from the specific gateway package
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"permissions": {
|
|
3
|
+
"allow": [
|
|
4
|
+
"Bash(npm run *)",
|
|
5
|
+
"Bash(pnpm *)",
|
|
6
|
+
"Bash(npx *)",
|
|
7
|
+
"Read(./src/**)",
|
|
8
|
+
"Read(./docs/**)",
|
|
9
|
+
"Read(./tests/**)",
|
|
10
|
+
"Bash(git status)",
|
|
11
|
+
"Bash(git diff)",
|
|
12
|
+
"Bash(git log *)"
|
|
13
|
+
],
|
|
14
|
+
"deny": ["Read(.env*)", "Read(**/.env*)", "Bash(sudo *)", "Bash(rm -rf *)"]
|
|
15
|
+
}
|
|
16
|
+
}
|