@theokit/sdk 4.2.7 → 4.2.9

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/claude-template/CLAUDE.md +16 -0
  3. package/claude-template/dot-claude/skills/theokit-auth/SKILL.md +102 -0
  4. package/claude-template/dot-claude/skills/theokit-client/SKILL.md +58 -0
  5. package/claude-template/dot-claude/skills/theokit-compaction/SKILL.md +102 -0
  6. package/claude-template/dot-claude/skills/theokit-concurrency/SKILL.md +68 -0
  7. package/claude-template/dot-claude/skills/theokit-filesystem/SKILL.md +74 -0
  8. package/claude-template/dot-claude/skills/theokit-messages/SKILL.md +58 -0
  9. package/claude-template/dot-claude/skills/theokit-models/SKILL.md +79 -0
  10. package/claude-template/dot-claude/skills/theokit-path-safety/SKILL.md +60 -0
  11. package/claude-template/dot-claude/skills/theokit-persistence/SKILL.md +85 -0
  12. package/claude-template/dot-claude/skills/theokit-project/SKILL.md +55 -0
  13. package/claude-template/dot-claude/skills/theokit-retry/SKILL.md +50 -0
  14. package/claude-template/dot-claude/skills/theokit-sandbox/SKILL.md +93 -0
  15. package/claude-template/dot-claude/skills/theokit-sanitize/SKILL.md +66 -0
  16. package/claude-template/dot-claude/skills/theokit-skills/SKILL.md +68 -0
  17. package/claude-template/dot-claude/skills/theokit-subagents/SKILL.md +109 -0
  18. package/claude-template/dot-claude/skills/theokit-task-store/SKILL.md +75 -0
  19. package/dist/a2a/index.cjs +8 -1
  20. package/dist/a2a/index.cjs.map +1 -1
  21. package/dist/a2a/index.js +8 -1
  22. package/dist/a2a/index.js.map +1 -1
  23. package/dist/cron.cjs +20 -16
  24. package/dist/cron.cjs.map +1 -1
  25. package/dist/cron.js +23 -19
  26. package/dist/cron.js.map +1 -1
  27. package/dist/eval.cjs +20 -16
  28. package/dist/eval.cjs.map +1 -1
  29. package/dist/eval.js +23 -19
  30. package/dist/eval.js.map +1 -1
  31. package/dist/index.cjs +20 -16
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +20 -16
  34. package/dist/index.js.map +1 -1
  35. package/package.json +12 -11
@@ -0,0 +1,85 @@
1
+ ---
2
+ user-invocable: false
3
+ paths:
4
+ - "**/*persist*"
5
+ - "**/*Persist*"
6
+ - "**/*.jsonl"
7
+ - "**/*sqlite*"
8
+ description: TheoKit SDK persistence primitives — atomic writes, JSONL persist/resume, resilient SQLite, cross-process locks
9
+ ---
10
+
11
+ # TheoKit Persistence
12
+
13
+ Durable, crash-safe persistence helpers on the STABLE `@theokit/sdk/persistence`
14
+ sub-path. Do NOT import them from `@theokit/sdk/internal/persistence` (semver-exempt).
15
+
16
+ ```ts
17
+ import {
18
+ // atomic writes
19
+ replaceFileAtomic, atomicWriteText, atomicWriteJson,
20
+ // jsonl persist/resume
21
+ appendJsonl, loadJsonl, readJsonlIds, JsonlParseError,
22
+ // resilient sqlite
23
+ openSqliteResilient, applyWalWithFallback, isCorruptionError, sanitizeFts5Query,
24
+ // locks
25
+ withFileLock, withCwdMutex,
26
+ // misc
27
+ PersistenceSchema, transcriptPath, encodeProjectDir,
28
+ } from "@theokit/sdk/persistence";
29
+ ```
30
+
31
+ ## Atomic writes
32
+
33
+ Crash mid-write leaves either the old file intact or the new file complete —
34
+ never a half-written file (temp + fsync + rename). `atomicWriteJson` /
35
+ `atomicWriteText` auto-`mkdir` the parent dir; `replaceFileAtomic` does not.
36
+
37
+ ```ts
38
+ await replaceFileAtomic("/data/config.md", markdown); // (filePath, content)
39
+ await atomicWriteText("/data/notes.txt", text); // + auto-mkdir
40
+ await atomicWriteJson("/data/state.json", { runs: 3 }); // default indent 2, trailing \n
41
+ await atomicWriteJson("/data/state.json", data, { indent: 0, trailingNewline: false });
42
+ ```
43
+
44
+ ## JSONL persist / resume
45
+
46
+ `appendJsonl` writes one `\n`-terminated line per record (synchronous, interleave-safe
47
+ within a process). Resume a crashed batch by reading already-persisted keys.
48
+
49
+ ```ts
50
+ appendJsonl("/data/results.jsonl", { id: "task-1", status: "passed" });
51
+
52
+ // Skip rows already done (partial trailing line tolerated; missing file -> empty set)
53
+ const done = readJsonlIds("/data/results.jsonl", (row) =>
54
+ row.status === "passed" ? String(row.id) : undefined,
55
+ );
56
+
57
+ // loadJsonl throws JsonlParseError (with 1-based .line) on a malformed line
58
+ const rows = loadJsonl<{ id: string }>("/data/results.jsonl");
59
+ ```
60
+
61
+ ## Resilient SQLite
62
+
63
+ `openSqliteResilient` loads the driver, applies WAL (with DELETE fallback), and
64
+ recovers from corruption by renaming the file aside. Apply schema in `onOpen`.
65
+
66
+ ```ts
67
+ const db = await openSqliteResilient({
68
+ filePath: "/data/index.db",
69
+ label: "memory-index",
70
+ onOpen: (db) => db.exec("CREATE TABLE IF NOT EXISTS docs (id TEXT PRIMARY KEY)"),
71
+ });
72
+ applyWalWithFallback(db, "memory-index"); // { mode: "wal"|"delete", fellBack }
73
+ const q = sanitizeFts5Query("error-code"); // "" means caller must short-circuit
74
+ ```
75
+
76
+ ## Locks
77
+
78
+ `withFileLock` takes a cross-process lock (needs the `proper-lockfile` peer dep;
79
+ falls back to in-process `withCwdMutex` with a warning). `withCwdMutex` serializes
80
+ by key within one process.
81
+
82
+ ```ts
83
+ await withFileLock("/data/state.json", async () => { /* exclusive section */ });
84
+ await withCwdMutex("migrate-config", async () => { /* in-process critical section */ });
85
+ ```
@@ -0,0 +1,55 @@
1
+ ---
2
+ user-invocable: false
3
+ paths:
4
+ - "**/*project*"
5
+ - "**/*Project*"
6
+ - "**/THEO.md"
7
+ description: TheoKit SDK project-instruction reader/writer — hierarchical walk-up discovery + atomic write of THEO.md
8
+ ---
9
+
10
+ # TheoKit Project Instructions
11
+
12
+ Hierarchical project-instruction reader/writer on `@theokit/sdk/project`. The
13
+ reader walks up from `cwd` collecting an instruction file (default `THEO.md`) and
14
+ NEVER throws; the writer writes it atomically and FAILS LOUD on error.
15
+
16
+ ```ts
17
+ import {
18
+ readProjectInstructions, writeProjectInstructions,
19
+ } from "@theokit/sdk/project";
20
+ import type {
21
+ ProjectInstructions, ProjectInstructionFile, ProjectInstructionScope,
22
+ ReadProjectInstructionsOptions, WriteProjectInstructionsOptions,
23
+ } from "@theokit/sdk/project";
24
+ ```
25
+
26
+ ## Read (walk-up, never throws)
27
+
28
+ Discovers every `<dir>/<filename>` from `cwd` up to the filesystem root (or
29
+ `stopDir`). Returns `files` nearest-first plus a `content` reduction chosen by
30
+ `scope` (`"nearest"` → innermost file; `"merged"` → all joined root-first).
31
+ No file found → `{ files: [], content: undefined }`.
32
+
33
+ ```ts
34
+ const result: ProjectInstructions = await readProjectInstructions(process.cwd(), {
35
+ filename: "THEO.md", // default "THEO.md"
36
+ scope: "merged", // default "nearest"
37
+ stopDir: "/home/me/repo",
38
+ });
39
+
40
+ if (result.content) applySystemPrompt(result.content);
41
+ for (const f of result.files) console.log(f.path, f.content.length);
42
+ ```
43
+
44
+ ## Write (atomic, fails loud)
45
+
46
+ Writes `<cwd>/<filename>` via temp + fsync + rename. An unsafe `filename`
47
+ (traversal, separators, absolute) is rejected with `ConfigurationError`
48
+ (`code: "unsafe_filename"`); a real write error (e.g. missing parent dir)
49
+ propagates — never silently swallowed.
50
+
51
+ ```ts
52
+ await writeProjectInstructions(process.cwd(), "# Project rules\n…", {
53
+ filename: "THEO.md", // default "THEO.md"
54
+ });
55
+ ```
@@ -0,0 +1,50 @@
1
+ ---
2
+ user-invocable: false
3
+ paths:
4
+ - "**/*retry*"
5
+ - "**/*Retry*"
6
+ description: TheoKit SDK retry primitive — @theokit/sdk/retry (Retry.create executor with exponential backoff + full jitter, RetryOptions)
7
+ ---
8
+
9
+ # TheoKit Retry
10
+
11
+ `@theokit/sdk/retry` exposes one primitive: `Retry`. NOTE — `Retry.create` is an
12
+ EXECUTOR, not a constructor. `Retry.create(fn, opts)` RUNS `fn` with retry/backoff and
13
+ resolves to its result (`Promise<T>`) — it does not return a `Retry` instance.
14
+
15
+ ```typescript
16
+ import { Retry, type RetryOptions } from "@theokit/sdk/retry";
17
+ ```
18
+
19
+ ## Run a fn with retry
20
+
21
+ Exponential backoff with full jitter. The default `isRetryable` predicate is the SDK's
22
+ own `isTransientError`, so retries follow the SDK's error classification (rate-limit /
23
+ network retry; business-rule violations do not).
24
+
25
+ ```typescript
26
+ const data = await Retry.create(() => fetchJson(url));
27
+ // retries transient failures up to 3 times (4 attempts total), then throws the last error
28
+ ```
29
+
30
+ ## Tuning with `RetryOptions`
31
+
32
+ All fields are optional; defaults shown in comments.
33
+
34
+ ```typescript
35
+ const result = await Retry.create(
36
+ () => callFlakyApi(),
37
+ {
38
+ retries: 5, // retries AFTER the first attempt (default 3)
39
+ initialDelayMs: 200, // base backoff for the first retry (default 100)
40
+ maxDelayMs: 10_000, // cap per single sleep (default 30_000)
41
+ backoffMultiplier: 2, // exponential multiplier per retry (default 2)
42
+ isRetryable: (err) => err instanceof NetworkGlitch, // default: isTransientError
43
+ signal: controller.signal, // aborts the backoff loop when triggered
44
+ } satisfies RetryOptions,
45
+ );
46
+ ```
47
+
48
+ `rng` and `sleep` are also injectable — override them for deterministic tests (no real
49
+ timers). When retries are exhausted or the error is not retryable, `Retry.create`
50
+ re-throws the last error.
@@ -0,0 +1,93 @@
1
+ ---
2
+ user-invocable: false
3
+ paths:
4
+ - "**/*sandbox*"
5
+ - "**/*Sandbox*"
6
+ description: TheoKit SDK sandbox reference — SandboxBackend / LocalSandbox execution + provisionRepo
7
+ ---
8
+
9
+ # TheoKit Sandbox
10
+
11
+ ```typescript
12
+ import {
13
+ LocalSandbox,
14
+ provisionRepo,
15
+ SandboxBackend,
16
+ SandboxNotAvailableError,
17
+ SandboxSecurityError,
18
+ RepoProvisionError,
19
+ type ExecuteResult,
20
+ type SandboxConfig,
21
+ type ProvisionRepoOptions,
22
+ } from "@theokit/sdk/sandbox";
23
+ ```
24
+
25
+ ## `LocalSandbox` — subprocess execution
26
+
27
+ `LocalSandbox` runs commands via `/bin/sh -c` in the SAME OS as the host. It is
28
+ **NOT an isolation boundary** — no process, filesystem, or network isolation.
29
+ Its only safety affordances are a wall-clock timeout, an output-size cap, and
30
+ env scrubbing. For real isolation of untrusted code, use a container/VM backend.
31
+
32
+ ```typescript
33
+ const sandbox = new LocalSandbox({
34
+ workDir: "/tmp/work",
35
+ timeoutMs: 5_000,
36
+ maxOutputBytes: 1024,
37
+ // env defaults to "inherit-scrubbed": drops *KEY* / *SECRET* / *TOKEN* /
38
+ // *PASSWORD* / *_AUTH* from the child. Pass "all" or "core" to change.
39
+ });
40
+
41
+ const result: ExecuteResult = await sandbox.execute("echo hi", { timeoutMs: 2_000 });
42
+ console.log(result.stdout, result.exitCode, result.timedOut);
43
+
44
+ // Derived helpers on the base class (no need to reimplement):
45
+ await sandbox.writeFile("a.txt", "content");
46
+ const text = await sandbox.readFile("a.txt");
47
+ const files = await sandbox.glob("**/*.ts");
48
+ const hits = await sandbox.grep("TODO", "src");
49
+ ```
50
+
51
+ ## Custom backend — implement only 2 abstract methods
52
+
53
+ New backends (Docker, Firecracker, E2B) extend `SandboxBackend` and implement
54
+ only `execute` + `uploadFile`; `readFile` / `writeFile` / `glob` / `grep` /
55
+ `listDir` are derived on the base class.
56
+
57
+ ```typescript
58
+ class MyBackend extends SandboxBackend {
59
+ async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {
60
+ // run command remotely; return { stdout, stderr, exitCode, timedOut }
61
+ throw new SandboxNotAvailableError("backend offline");
62
+ }
63
+ async uploadFile(path: string, content: string | Buffer): Promise<void> {
64
+ /* ... */
65
+ }
66
+ }
67
+ ```
68
+
69
+ `SandboxSecurityError` (`code: "sandbox_security"`) and
70
+ `SandboxNotAvailableError` (`code: "sandbox_not_available"`) both extend `Error`.
71
+
72
+ ## `provisionRepo` — clone + checkout into the sandbox
73
+
74
+ Clones `repoUrl` into `<workDir>/<instanceId>` and checks out `ref`, running
75
+ every git command through the sandbox. The `sandbox` argument is optional — when
76
+ omitted a default `LocalSandbox` (process cwd) is used.
77
+
78
+ ```typescript
79
+ const opts: ProvisionRepoOptions = {
80
+ repoUrl: "https://github.com/acme/repo.git",
81
+ ref: "main", // branch, tag, or SHA (rejected if it begins with "-")
82
+ instanceId: "task-001", // validated to [A-Za-z0-9._-] — becomes a dir name
83
+ };
84
+
85
+ const { repoDir } = await provisionRepo(new LocalSandbox({ workDir: "/tmp/work" }), opts);
86
+ // or, with the default LocalSandbox: await provisionRepo(opts);
87
+
88
+ try {
89
+ await provisionRepo({ repoUrl: "bad", ref: "main", instanceId: "x" });
90
+ } catch (err) {
91
+ if (err instanceof RepoProvisionError) console.error(err.instanceId, err.message);
92
+ }
93
+ ```
@@ -0,0 +1,66 @@
1
+ ---
2
+ user-invocable: false
3
+ description: Clean model-emitted tool arguments with sanitizeToolInput from @theokit/sdk/sanitize (total, never throws).
4
+ paths:
5
+ - "**/*sanitize*"
6
+ - "**/*Sanitize*"
7
+ ---
8
+
9
+ # TheoKit SDK -- Sanitize
10
+
11
+ `sanitizeToolInput` cleans the raw arguments a model emitted for a tool call: trim (default on), optionally coerce string values toward their expected type, optionally repair malformed JSON. It is pure, synchronous, and TOTAL -- it NEVER throws (non-object input is returned unchanged) and never changes a value's meaning, only its hygiene/representation.
12
+
13
+ ## Import
14
+
15
+ ```typescript
16
+ import { sanitizeToolInput } from "@theokit/sdk/sanitize";
17
+ import type { SanitizeOptions, SanitizeResult } from "@theokit/sdk/sanitize";
18
+ ```
19
+
20
+ ## Signature
21
+
22
+ ```typescript
23
+ function sanitizeToolInput(
24
+ input: Record<string, unknown>,
25
+ options?: SanitizeOptions,
26
+ ): SanitizeResult;
27
+
28
+ interface SanitizeOptions {
29
+ trim?: boolean; // trim whitespace on string values. Default true
30
+ coerce?: boolean; // "5"->5, "true"->true, "null"->null, JSON. Default false
31
+ repairJson?: boolean; // repair-then-parse malformed JSON strings (jsonrepair). Default false
32
+ schema?: ZodType; // when a z.object(...), coercion is schema-aware per top-level field
33
+ deep?: boolean; // recurse into nested objects/arrays. Default false (shallow)
34
+ maxDepth?: number; // max recursion depth when deep. Default 8
35
+ }
36
+
37
+ interface SanitizeResult<T = Record<string, unknown>> {
38
+ value: T; // the sanitized copy
39
+ changed: boolean; // true when any value was altered
40
+ notes: string[]; // one human-readable line per change (for logging)
41
+ }
42
+ ```
43
+
44
+ ## Trim only (default)
45
+
46
+ ```typescript
47
+ const { value, changed, notes } = sanitizeToolInput({ query: " hello " });
48
+ // value -> { query: "hello" }, changed -> true, notes -> ["query: trimmed whitespace"]
49
+ ```
50
+
51
+ ## Schema-aware coercion inside a tool handler
52
+
53
+ Pass the tool's Zod object schema so a `z.string()` field keeps `"5"` as a string while a `z.number()` field coerces it. Never throws, so it is safe to run before `schema.parse`.
54
+
55
+ ```typescript
56
+ import { z } from "zod";
57
+
58
+ const inputSchema = z.object({ count: z.number(), label: z.string() });
59
+
60
+ const { value } = sanitizeToolInput(
61
+ { count: "5", label: "42" },
62
+ { coerce: true, schema: inputSchema },
63
+ );
64
+ // value -> { count: 5, label: "42" } (label stays a string; count coerced)
65
+ const parsed = inputSchema.parse(value);
66
+ ```
@@ -0,0 +1,68 @@
1
+ ---
2
+ user-invocable: false
3
+ description: Discover SKILL.md packs and render the <skills> block with @theokit/sdk/skills, plus enabling skills on an agent.
4
+ paths:
5
+ - "**/*skill*"
6
+ - "**/*Skill*"
7
+ ---
8
+
9
+ # TheoKit SDK -- Skills
10
+
11
+ `discoverSkills` walks a directory for `<dir>/<name>/SKILL.md` packs, parses strict YAML frontmatter (`name`/`description` required; `category`/`dependencies` optional), skips malformed skills and symlink escapes, and NEVER throws (a missing/unreadable/non-directory path yields `[]`). `buildSkillsBlock` renders the prompt-injection-safe `<skills>` system-prompt block from the discovered list. These are the same primitives the SDK runtime uses internally for `.theokit/skills` discovery.
12
+
13
+ ## Import
14
+
15
+ ```typescript
16
+ import { discoverSkills, buildSkillsBlock } from "@theokit/sdk/skills";
17
+ import type { Skill, DiscoverSkillsOptions, InvalidSkillInfo } from "@theokit/sdk/skills";
18
+ ```
19
+
20
+ ## Signatures
21
+
22
+ ```typescript
23
+ function discoverSkills(dir: string, options?: DiscoverSkillsOptions): Promise<Skill[]>;
24
+ function buildSkillsBlock(
25
+ skills: ReadonlyArray<{ name: string; description: string }>,
26
+ ): string | undefined; // undefined for an empty list
27
+
28
+ interface Skill {
29
+ name: string;
30
+ description: string;
31
+ source: string; // absolute path to the discovered SKILL.md
32
+ category?: string;
33
+ dependencies?: string[];
34
+ }
35
+
36
+ interface DiscoverSkillsOptions {
37
+ onInvalidSkill?: (info: InvalidSkillInfo) => void; // called per malformed SKILL.md
38
+ }
39
+ ```
40
+
41
+ ## Discover and render
42
+
43
+ ```typescript
44
+ const skills = await discoverSkills(".theokit/skills", {
45
+ onInvalidSkill: (info: InvalidSkillInfo) =>
46
+ console.warn(`skipped ${info.name}: ${info.code} — ${info.message}`),
47
+ });
48
+
49
+ // readdir order is OS-dependent; sort for a stable block
50
+ skills.sort((a, b) => a.name.localeCompare(b.name));
51
+
52
+ const block = buildSkillsBlock(skills); // string | undefined
53
+ ```
54
+
55
+ ## Skill packs live at `.theokit/skills/<name>/SKILL.md`
56
+
57
+ Each pack is a directory with a `SKILL.md` whose frontmatter has `name` + `description`. Enable specific packs on an agent by name:
58
+
59
+ ```typescript
60
+ import { Agent } from "@theokit/sdk";
61
+
62
+ const agent = await Agent.create({
63
+ apiKey: process.env.THEOKIT_API_KEY!,
64
+ model: { id: "google/gemini-2.0-flash-001" },
65
+ local: { cwd: process.cwd() },
66
+ skills: { enabled: ["research", "code-review"] },
67
+ });
68
+ ```
@@ -0,0 +1,109 @@
1
+ ---
2
+ user-invocable: false
3
+ paths:
4
+ - "**/*subagent*"
5
+ - "**/*a2a*"
6
+ - "**/*delegat*"
7
+ description: TheoKit SDK subagents — @theokit/sdk/a2a (SubAgent.create, AgentMailbox, MessageBus, delegation hooks) and @theokit/sdk/subagents (subagentToolWhitelist, withSubagentToolScope)
8
+ ---
9
+
10
+ # TheoKit SubAgents
11
+
12
+ Two subpaths cover delegation. `@theokit/sdk/a2a` builds a child agent invocable as
13
+ a tool plus the in-process message bus; `@theokit/sdk/subagents` scopes which tools a
14
+ subagent may call.
15
+
16
+ ```typescript
17
+ import {
18
+ SubAgent,
19
+ AgentMailbox,
20
+ MessageBus,
21
+ MaxDelegationDepthError,
22
+ type SubAgentSpec,
23
+ } from "@theokit/sdk/a2a";
24
+ import { subagentToolWhitelist, withSubagentToolScope } from "@theokit/sdk/subagents";
25
+ ```
26
+
27
+ ## `SubAgent.create` — delegation as a tool
28
+
29
+ `SubAgent.create(spec, parentDepth?)` returns a `CustomTool`. When the LLM invokes it,
30
+ a child agent runs the input as a message. Depth is tracked — exceeding
31
+ `maxDelegationDepth` throws `MaxDelegationDepthError`.
32
+
33
+ ```typescript
34
+ const researcher = SubAgent.create({
35
+ name: "researcher",
36
+ description: "Delegate research questions to a focused child agent",
37
+ instructions: "You research topics and return a concise summary.",
38
+ model: "google/gemini-2.0-flash-001",
39
+ tools: [], // CustomTool[] the child may use
40
+ maxDelegationDepth: 3,
41
+ onDelegationStart: (ctx) => {
42
+ if (ctx.iteration > 5) return { proceed: false, rejectionReason: "too many calls" };
43
+ return { proceed: true };
44
+ },
45
+ onDelegationComplete: (ctx) => {
46
+ if (ctx.result) return { feedback: "(reviewed)" };
47
+ },
48
+ });
49
+
50
+ const agent = await Agent.create({
51
+ apiKey: process.env.THEOKIT_API_KEY!,
52
+ model: { id: "google/gemini-2.0-flash-001" },
53
+ local: { cwd: process.cwd() },
54
+ tools: [researcher],
55
+ });
56
+ ```
57
+
58
+ `SubAgentSpec` also supports `messageFilter` (opt-in parent-context forwarding, off by
59
+ default so memory isolation stays the default) and `includeToolResults` (append the
60
+ child's tool results, otherwise text-only).
61
+
62
+ ## Inline subagents on `Agent.create`
63
+
64
+ Simple cases need no `SubAgent.create` — declare them inline:
65
+
66
+ ```typescript
67
+ const agent = await Agent.create({
68
+ apiKey: process.env.THEOKIT_API_KEY!,
69
+ model: { id: "google/gemini-2.0-flash-001" },
70
+ local: { cwd: process.cwd() },
71
+ agents: {
72
+ reviewer: {
73
+ description: "Reviews code for bugs",
74
+ prompt: "You are a strict code reviewer.",
75
+ model: "google/gemini-2.0-flash-001",
76
+ },
77
+ },
78
+ });
79
+ ```
80
+
81
+ ## Tool scoping — `withSubagentToolScope`
82
+
83
+ `subagentToolWhitelist(definition)` derives the allowed tool-name `Set` (or `undefined`
84
+ when unscoped) from `definition.tools`. `withSubagentToolScope` runs a fn under that
85
+ whitelist so a `tools: ["read_file"]` subagent provably cannot call `write_file`.
86
+
87
+ ```typescript
88
+ const whitelist = subagentToolWhitelist({ tools: ["read_file"] }); // Set(["read_file"])
89
+
90
+ await withSubagentToolScope({ tools: ["read_file"] }, async () => {
91
+ // dispatch veto enforces the whitelist here
92
+ });
93
+ ```
94
+
95
+ ## Agent-to-agent messaging
96
+
97
+ ```typescript
98
+ const bus = new MessageBus();
99
+ const alice = new AgentMailbox("alice", bus);
100
+ const bob = new AgentMailbox("bob", bus);
101
+
102
+ bob.onMessage(async (msg) => ({ type: "ack", payload: { ok: true } }));
103
+
104
+ await alice.send("bob", { type: "greet", payload: { text: "hi" } });
105
+ const reply = await alice.request("bob", { type: "ping", payload: null }, { timeoutMs: 1000 });
106
+
107
+ alice.dispose();
108
+ bob.dispose();
109
+ ```
@@ -0,0 +1,75 @@
1
+ ---
2
+ user-invocable: false
3
+ paths:
4
+ - "**/*task-store*"
5
+ - "**/*taskstore*"
6
+ - "**/*TaskStore*"
7
+ description: TheoKit SDK task persistence — @theokit/sdk/task-store (TaskStore interface, InMemoryTaskStore, JsonFileTaskStore, getTaskStoreFor factory)
8
+ ---
9
+
10
+ # TheoKit Task Store
11
+
12
+ `@theokit/sdk/task-store` is the storage layer behind the task registry. Pick
13
+ `InMemoryTaskStore` (transient, single-process default) or `JsonFileTaskStore` (one JSON
14
+ file per task under a dir; single-process invariant — v0.2 SQLite covers cross-process).
15
+
16
+ ```typescript
17
+ import {
18
+ getTaskStoreFor,
19
+ InMemoryTaskStore,
20
+ JsonFileTaskStore,
21
+ type TaskStore,
22
+ } from "@theokit/sdk/task-store";
23
+ ```
24
+
25
+ ## The `TaskStore` interface
26
+
27
+ All methods are async. `TaskHandle` / `TaskFilter` come from the main `@theokit/sdk`
28
+ barrel.
29
+
30
+ ```typescript
31
+ interface TaskStore {
32
+ insert(handle: TaskHandle): Promise<void>;
33
+ update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;
34
+ get(id: string): Promise<TaskHandle | undefined>;
35
+ list(filter: TaskFilter): Promise<TaskHandle[]>;
36
+ delete(id: string): Promise<boolean>;
37
+ evictTerminalOlderThan(epochMs: number): Promise<number>;
38
+ }
39
+ ```
40
+
41
+ ## Factory — `getTaskStoreFor`
42
+
43
+ Discriminated on `backend`; the `json` backend auto-creates its dir (mkdir recursive).
44
+
45
+ ```typescript
46
+ const memory: TaskStore = getTaskStoreFor({ backend: "memory" });
47
+ const onDisk: TaskStore = getTaskStoreFor({ backend: "json", dir: ".theokit/tasks" });
48
+ ```
49
+
50
+ Or construct directly:
51
+
52
+ ```typescript
53
+ const store = new JsonFileTaskStore(".theokit/tasks"); // constructor(dir: string)
54
+ ```
55
+
56
+ ## Reading tasks
57
+
58
+ `list` returns at most `filter.limit ?? 100` handles; `JsonFileTaskStore` hard-caps
59
+ loaded entries at 256 — page larger timelines via `submittedBefore`.
60
+
61
+ ```typescript
62
+ import type { TaskFilter } from "@theokit/sdk";
63
+
64
+ const filter: TaskFilter = { state: ["running", "queued"], kind: "run", limit: 50 };
65
+ const running = await store.list(filter);
66
+
67
+ for (const h of running) {
68
+ console.log(h.id, h.state, h.submittedAt);
69
+ if (h.cancelRequested) console.log(" (cross-process cancel requested)");
70
+ }
71
+ ```
72
+
73
+ `cancelRequested` is set by the CLI's cross-process best-effort cancel (EC-7); the owning
74
+ process polls it at checkpoints. `evictTerminalOlderThan(epochMs)` removes terminal
75
+ handles older than a cutoff and returns the count removed.
@@ -92,12 +92,19 @@ var MessageBus = class {
92
92
  return [...this._handlers.keys()];
93
93
  }
94
94
  };
95
+
96
+ // src/internal/runtime/registry/agent-factory-registry.ts
97
+ var FACADE_KEY = /* @__PURE__ */ Symbol.for(
98
+ "theokit.internal.runtime.agentFacade"
99
+ );
95
100
  function getAgentFacade() {
96
- {
101
+ const registered = globalThis[FACADE_KEY];
102
+ if (registered === void 0) {
97
103
  throw new Error(
98
104
  "internal: Agent facade not registered. The `agent.ts` module must be loaded before internal subsystems (LocalAgent.runUntil/fork, eval, scorers, cron) invoke it."
99
105
  );
100
106
  }
107
+ return registered;
101
108
  }
102
109
 
103
110
  // src/a2a/subagent.ts