@theokit/sdk 5.0.1 → 5.1.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 +267 -0
- package/dist/a2a/index.cjs +3 -3
- package/dist/a2a/index.js +1 -1
- package/dist/a2a/subagent.d.cts +22 -3
- package/dist/a2a/subagent.d.ts +22 -3
- package/dist/{agent-TKJBWGGQ.cjs → agent-ARLOD4JX.cjs} +9 -9
- package/dist/{agent-TKJBWGGQ.cjs.map → agent-ARLOD4JX.cjs.map} +1 -1
- package/dist/{agent-UGYIYC3R.js → agent-N6WJ54ML.js} +8 -8
- package/dist/{agent-UGYIYC3R.js.map → agent-N6WJ54ML.js.map} +1 -1
- package/dist/{chunk-CC7EYKBJ.cjs → chunk-67SBTGMA.cjs} +4 -4
- package/dist/{chunk-CC7EYKBJ.cjs.map → chunk-67SBTGMA.cjs.map} +1 -1
- package/dist/{chunk-D7WAROJR.js → chunk-AW6F6HZR.js} +3 -3
- package/dist/{chunk-D7WAROJR.js.map → chunk-AW6F6HZR.js.map} +1 -1
- package/dist/{chunk-6WAKKTBO.js → chunk-CFE6QF2Q.js} +19 -3
- package/dist/chunk-CFE6QF2Q.js.map +1 -0
- package/dist/{chunk-CQLVA4CO.cjs → chunk-D3CCY3A2.cjs} +60 -53
- package/dist/chunk-D3CCY3A2.cjs.map +1 -0
- package/dist/{chunk-UFPUHJWS.js → chunk-IUMAQURF.js} +7 -2
- package/dist/chunk-IUMAQURF.js.map +1 -0
- package/dist/{chunk-LTLPBGHC.cjs → chunk-KGANQYP7.cjs} +5 -5
- package/dist/{chunk-LTLPBGHC.cjs.map → chunk-KGANQYP7.cjs.map} +1 -1
- package/dist/{chunk-XDANGA2C.js → chunk-LX7SEXOQ.js} +6 -3
- package/dist/chunk-LX7SEXOQ.js.map +1 -0
- package/dist/{chunk-QME6FDFG.cjs → chunk-NQTD6QOW.cjs} +19 -3
- package/dist/chunk-NQTD6QOW.cjs.map +1 -0
- package/dist/{chunk-DLRP7BI6.cjs → chunk-NYQ3IS7K.cjs} +3 -3
- package/dist/chunk-NYQ3IS7K.cjs.map +1 -0
- package/dist/{chunk-7RHC7HMS.js → chunk-OQRGVTQF.js} +3 -3
- package/dist/{chunk-7RHC7HMS.js.map → chunk-OQRGVTQF.js.map} +1 -1
- package/dist/{chunk-SVWMQCXF.js → chunk-OYD3U3LY.js} +19 -12
- package/dist/chunk-OYD3U3LY.js.map +1 -0
- package/dist/{chunk-UGRS7ZA7.cjs → chunk-QATRS7JD.cjs} +6 -2
- package/dist/chunk-QATRS7JD.cjs.map +1 -0
- package/dist/{chunk-DRL7URI4.cjs → chunk-QDM3OHUT.cjs} +7 -2
- package/dist/chunk-QDM3OHUT.cjs.map +1 -0
- package/dist/{chunk-5AXMNUCY.cjs → chunk-QYLZQ43D.cjs} +5 -5
- package/dist/{chunk-5AXMNUCY.cjs.map → chunk-QYLZQ43D.cjs.map} +1 -1
- package/dist/{chunk-GUKPXDGJ.js → chunk-WMWEI3NS.js} +3 -3
- package/dist/chunk-WMWEI3NS.js.map +1 -0
- package/dist/{chunk-YEL3SP6X.js → chunk-XU6MLSC6.js} +3 -3
- package/dist/{chunk-YEL3SP6X.js.map → chunk-XU6MLSC6.js.map} +1 -1
- package/dist/{context-XQJIGZMR.cjs → context-4QOEWRDF.cjs} +7 -7
- package/dist/{context-XQJIGZMR.cjs.map → context-4QOEWRDF.cjs.map} +1 -1
- package/dist/context-Z3CFTT3H.js +6 -0
- package/dist/{context-FM6UZPTL.js.map → context-Z3CFTT3H.js.map} +1 -1
- package/dist/cron.cjs +8 -8
- package/dist/cron.js +7 -7
- package/dist/eval.cjs +22 -7
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +21 -6
- package/dist/eval.js.map +1 -1
- package/dist/index.cjs +26 -26
- package/dist/index.js +11 -11
- package/dist/internal/concurrency/subagent-credentials.d.ts +45 -0
- package/dist/internal/persistence/index.cjs +4 -4
- package/dist/internal/persistence/index.js +1 -1
- package/dist/internal/runtime/registry/agent-registry-store.d.ts +1 -0
- package/dist/internal/runtime/skills/discover-skills.d.ts +35 -0
- package/dist/judge-call-46M2E5FA.cjs +22 -0
- package/dist/{judge-call-I3P4D5QR.cjs.map → judge-call-46M2E5FA.cjs.map} +1 -1
- package/dist/judge-call-FGUNNWEI.js +5 -0
- package/dist/{judge-call-6MVARKU2.js.map → judge-call-FGUNNWEI.js.map} +1 -1
- package/dist/persistence.cjs +8 -0
- package/dist/persistence.d.cts +1 -1
- package/dist/persistence.d.ts +1 -1
- package/dist/persistence.js +1 -1
- package/dist/skills.cjs +7 -3
- package/dist/skills.d.cts +1 -1
- package/dist/skills.d.ts +1 -1
- package/dist/skills.js +1 -1
- package/dist/subagents-loader-DOBTTICM.js +7 -0
- package/dist/{subagents-loader-7ES7PJNM.js.map → subagents-loader-DOBTTICM.js.map} +1 -1
- package/dist/subagents-loader-GEHYCMEX.cjs +16 -0
- package/dist/{subagents-loader-OMOH6ERO.cjs.map → subagents-loader-GEHYCMEX.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +3 -3
- package/dist/subagents-loader.cjs.map +1 -1
- package/dist/subagents-loader.d.cts +34 -1
- package/dist/subagents-loader.d.ts +34 -1
- package/dist/subagents-loader.js +3 -3
- package/dist/subagents-loader.js.map +1 -1
- package/docs/error-codes.md +2 -2
- package/docs/harness-capability-map.md +5 -1
- package/package.json +1 -1
- package/dist/chunk-6WAKKTBO.js.map +0 -1
- package/dist/chunk-CQLVA4CO.cjs.map +0 -1
- package/dist/chunk-DLRP7BI6.cjs.map +0 -1
- package/dist/chunk-DRL7URI4.cjs.map +0 -1
- package/dist/chunk-GUKPXDGJ.js.map +0 -1
- package/dist/chunk-QME6FDFG.cjs.map +0 -1
- package/dist/chunk-SVWMQCXF.js.map +0 -1
- package/dist/chunk-UFPUHJWS.js.map +0 -1
- package/dist/chunk-UGRS7ZA7.cjs.map +0 -1
- package/dist/chunk-XDANGA2C.js.map +0 -1
- package/dist/context-FM6UZPTL.js +0 -6
- package/dist/judge-call-6MVARKU2.js +0 -5
- package/dist/judge-call-I3P4D5QR.cjs +0 -22
- package/dist/subagents-loader-7ES7PJNM.js +0 -7
- package/dist/subagents-loader-OMOH6ERO.cjs +0 -16
|
@@ -3,6 +3,14 @@ import './sdk-agent-BOiKqOgL.cjs';
|
|
|
3
3
|
import './run-CTAdRU3U.cjs';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* A declared foreign source: a bare kind, or a kind with the surfaces it may be read for.
|
|
8
|
+
*/
|
|
9
|
+
type CompatSourceDeclaration = string | {
|
|
10
|
+
readonly kind: string;
|
|
11
|
+
readonly import?: readonly string[];
|
|
12
|
+
};
|
|
13
|
+
|
|
6
14
|
/**
|
|
7
15
|
* Published as `@theokit/sdk/subagents-loader`.
|
|
8
16
|
*
|
|
@@ -39,6 +47,31 @@ interface DiscoverSubagentsOptions {
|
|
|
39
47
|
* established trust in `cwd` can decline the read rather than filter its result.
|
|
40
48
|
*/
|
|
41
49
|
readonly settingSources?: readonly SubagentSource[];
|
|
50
|
+
/**
|
|
51
|
+
* Foreign configuration dialects to read alongside `.theokit/agents/` (#524). Defaults to none,
|
|
52
|
+
* so this reads `.theokit/` only unless a caller declares otherwise.
|
|
53
|
+
*
|
|
54
|
+
* SEPARATE FROM `settingSources`, and the separation is the contract. That option answers *which
|
|
55
|
+
* sources* — project, and one day user or team. This one answers *which dialects* within them.
|
|
56
|
+
* Folding `"claude-code"` into `SubagentSource` would conflate the two, and the internal loader
|
|
57
|
+
* has kept them apart since #524 precisely because they are orthogonal.
|
|
58
|
+
*
|
|
59
|
+
* ## Why this exists
|
|
60
|
+
*
|
|
61
|
+
* The reader underneath already accepted it; this entry point simply never passed it, so
|
|
62
|
+
* `discoverSubagents` was `.theokit/`-only while the agent's own subagent registry — which goes
|
|
63
|
+
* through `settingSources` + `compatSources` — could see the same files. Measured by the
|
|
64
|
+
* `theocode` session on `5.0.1`, both arms in fresh trusted directories with the same task:
|
|
65
|
+
*
|
|
66
|
+
* roles in .theokit/agents/ delegate_to_team works
|
|
67
|
+
* the SAME files in .claude/agents/ "the `explorer` role is not configured"
|
|
68
|
+
*
|
|
69
|
+
* So a repository adopting the product could delegate TO a `.claude/agents/` subagent by name and
|
|
70
|
+
* could not define its team's roles there — one dialect, two answers, depending on which selector
|
|
71
|
+
* asked. That asymmetry was an omission rather than a decision: the plumbing existed and the
|
|
72
|
+
* public signature did not reach it.
|
|
73
|
+
*/
|
|
74
|
+
readonly compatSources?: readonly CompatSourceDeclaration[];
|
|
42
75
|
}
|
|
43
76
|
/**
|
|
44
77
|
* Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.
|
|
@@ -54,4 +87,4 @@ declare function discoverSubagents(cwd: string, options?: DiscoverSubagentsOptio
|
|
|
54
87
|
*/
|
|
55
88
|
declare function loadSubagentDefinition(name: string, cwd: string, options?: DiscoverSubagentsOptions): Promise<AgentDefinition | undefined>;
|
|
56
89
|
|
|
57
|
-
export { AgentDefinition, type DiscoverSubagentsOptions, type SubagentSource, discoverSubagents, loadSubagentDefinition };
|
|
90
|
+
export { AgentDefinition, type CompatSourceDeclaration, type DiscoverSubagentsOptions, type SubagentSource, discoverSubagents, loadSubagentDefinition };
|
|
@@ -3,6 +3,14 @@ import './sdk-agent-D4a_BR_6.js';
|
|
|
3
3
|
import './run-CTAdRU3U.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* A declared foreign source: a bare kind, or a kind with the surfaces it may be read for.
|
|
8
|
+
*/
|
|
9
|
+
type CompatSourceDeclaration = string | {
|
|
10
|
+
readonly kind: string;
|
|
11
|
+
readonly import?: readonly string[];
|
|
12
|
+
};
|
|
13
|
+
|
|
6
14
|
/**
|
|
7
15
|
* Published as `@theokit/sdk/subagents-loader`.
|
|
8
16
|
*
|
|
@@ -39,6 +47,31 @@ interface DiscoverSubagentsOptions {
|
|
|
39
47
|
* established trust in `cwd` can decline the read rather than filter its result.
|
|
40
48
|
*/
|
|
41
49
|
readonly settingSources?: readonly SubagentSource[];
|
|
50
|
+
/**
|
|
51
|
+
* Foreign configuration dialects to read alongside `.theokit/agents/` (#524). Defaults to none,
|
|
52
|
+
* so this reads `.theokit/` only unless a caller declares otherwise.
|
|
53
|
+
*
|
|
54
|
+
* SEPARATE FROM `settingSources`, and the separation is the contract. That option answers *which
|
|
55
|
+
* sources* — project, and one day user or team. This one answers *which dialects* within them.
|
|
56
|
+
* Folding `"claude-code"` into `SubagentSource` would conflate the two, and the internal loader
|
|
57
|
+
* has kept them apart since #524 precisely because they are orthogonal.
|
|
58
|
+
*
|
|
59
|
+
* ## Why this exists
|
|
60
|
+
*
|
|
61
|
+
* The reader underneath already accepted it; this entry point simply never passed it, so
|
|
62
|
+
* `discoverSubagents` was `.theokit/`-only while the agent's own subagent registry — which goes
|
|
63
|
+
* through `settingSources` + `compatSources` — could see the same files. Measured by the
|
|
64
|
+
* `theocode` session on `5.0.1`, both arms in fresh trusted directories with the same task:
|
|
65
|
+
*
|
|
66
|
+
* roles in .theokit/agents/ delegate_to_team works
|
|
67
|
+
* the SAME files in .claude/agents/ "the `explorer` role is not configured"
|
|
68
|
+
*
|
|
69
|
+
* So a repository adopting the product could delegate TO a `.claude/agents/` subagent by name and
|
|
70
|
+
* could not define its team's roles there — one dialect, two answers, depending on which selector
|
|
71
|
+
* asked. That asymmetry was an omission rather than a decision: the plumbing existed and the
|
|
72
|
+
* public signature did not reach it.
|
|
73
|
+
*/
|
|
74
|
+
readonly compatSources?: readonly CompatSourceDeclaration[];
|
|
42
75
|
}
|
|
43
76
|
/**
|
|
44
77
|
* Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.
|
|
@@ -54,4 +87,4 @@ declare function discoverSubagents(cwd: string, options?: DiscoverSubagentsOptio
|
|
|
54
87
|
*/
|
|
55
88
|
declare function loadSubagentDefinition(name: string, cwd: string, options?: DiscoverSubagentsOptions): Promise<AgentDefinition | undefined>;
|
|
56
89
|
|
|
57
|
-
export { AgentDefinition, type DiscoverSubagentsOptions, type SubagentSource, discoverSubagents, loadSubagentDefinition };
|
|
90
|
+
export { AgentDefinition, type CompatSourceDeclaration, type DiscoverSubagentsOptions, type SubagentSource, discoverSubagents, loadSubagentDefinition };
|
package/dist/subagents-loader.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { loadSubagents } from './chunk-
|
|
2
|
-
import './chunk-
|
|
1
|
+
import { loadSubagents } from './chunk-OQRGVTQF.js';
|
|
2
|
+
import './chunk-WMWEI3NS.js';
|
|
3
3
|
import './chunk-JNAA4G4H.js';
|
|
4
4
|
import { ConfigurationError } from './chunk-ALUN2B4W.js';
|
|
5
5
|
import './chunk-CZJ6Q7CW.js';
|
|
@@ -21,7 +21,7 @@ function resolveSources(options) {
|
|
|
21
21
|
}
|
|
22
22
|
async function discoverSubagents(cwd, options) {
|
|
23
23
|
const sources = resolveSources(options);
|
|
24
|
-
return loadSubagents(cwd, sources.includes("project"), void 0);
|
|
24
|
+
return loadSubagents(cwd, sources.includes("project"), void 0, options?.compatSources ?? []);
|
|
25
25
|
}
|
|
26
26
|
async function loadSubagentDefinition(name, cwd, options) {
|
|
27
27
|
return (await discoverSubagents(cwd, options))[name];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/subagents-loader.ts"],"names":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"sources":["../src/subagents-loader.ts"],"names":[],"mappings":";;;;;;;AAgDA,IAAM,gBAAA,GAA8C,CAAC,SAAS,CAAA;AA0C9D,SAAS,eAAe,OAAA,EAA0E;AAChG,EAAA,MAAM,WAAW,OAAA,EAAS,cAAA;AAC1B,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,gBAAA;AACnC,EAAA,KAAA,MAAW,UAAU,QAAA,EAAU;AAC7B,IAAA,IAAI,CAAC,gBAAA,CAAiB,QAAA,CAAS,MAAM,CAAA,EAAG;AACtC,MAAA,MAAM,IAAI,kBAAA;AAAA,QACR,CAAA,iCAAA,EAAoC,OAAO,MAAM,CAAC,gBAAgB,gBAAA,CAAiB,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AAAA,QAC7F,EAAE,MAAM,iCAAA;AAAkC,OAC5C;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,QAAA;AACT;AAOA,eAAsB,iBAAA,CACpB,KACA,OAAA,EAC0C;AAC1C,EAAA,MAAM,OAAA,GAAU,eAAe,OAAO,CAAA;AACtC,EAAA,OAAO,aAAA,CAAc,GAAA,EAAK,OAAA,CAAQ,QAAA,CAAS,SAAS,GAAG,MAAA,EAAW,OAAA,EAAS,aAAA,IAAiB,EAAE,CAAA;AAChG;AAQA,eAAsB,sBAAA,CACpB,IAAA,EACA,GAAA,EACA,OAAA,EACsC;AACtC,EAAA,OAAA,CAAQ,MAAM,iBAAA,CAAkB,GAAA,EAAK,OAAO,GAAG,IAAI,CAAA;AACrD","file":"subagents-loader.js","sourcesContent":["/**\n * Published as `@theokit/sdk/subagents-loader`.\n *\n * M81 — `.theokit/agents` discovery, exposed so a consumer can read the on-disk subagent\n * definitions with one import instead of hand-rolling a second parser.\n *\n * ## Why this file exists\n *\n * `src/skills.ts` already exposed `discoverSkills` for the sibling domain. Subagents had the same\n * loader — `internal/runtime/skills/subagents-loader.ts` — with no public door. A consumer behind\n * the layer boundary (the agent-builder never imports `@theokit/sdk*` directly) could not reach it,\n * so re-implementing was the only legal option. It re-implemented, and then wrote a test whose only\n * job was to watch the two parsers for drift. That test is the cleanest possible evidence that the\n * duplication should not exist.\n *\n * ## What crosses is the PARSED config\n *\n * The return is `AgentDefinition` — already interpreted — never the `.md` text or the frontmatter\n * shape. Exporting the file format would freeze an internal detail as public API; exporting the\n * parsed value leaves the format free to change.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport type { CompatSourceDeclaration } from \"./internal/runtime/compat/foreign-config-sources.js\";\nimport { loadSubagents } from \"./internal/runtime/skills/subagents-loader.js\";\nimport type { AgentDefinition } from \"./types/agent.js\";\n\n/**\n * Re-exported for the same reason `AgentDefinition` is: a consumer passing `compatSources`\n * must be able to NAME the value without importing from `types/agent`, which no subpath\n * publishes. An option whose type is unreachable is an option only `any` can call.\n */\nexport type { CompatSourceDeclaration } from \"./internal/runtime/compat/foreign-config-sources.js\";\n/**\n * The parsed subagent definition this module hands back.\n *\n * Re-exported here — beside the loader that produces it — so a consumer can NAME the value it\n * receives without reaching into `types/agent`, which no subpath publishes. A layer above may then\n * alias it (`AgentDefinition as SubagentDefinition`) to sidestep a name it has already spent.\n */\nexport type { AgentDefinition } from \"./types/agent.js\";\n\n/**\n * Where subagent definitions may be read from. A closed union rather than a boolean: a third\n * source can join it without breaking the signature, and the call site reads as what it means.\n */\nexport type SubagentSource = \"project\";\n\nconst ACCEPTED_SOURCES: readonly SubagentSource[] = [\"project\"];\n\n/** Options for {@link discoverSubagents} / {@link loadSubagentDefinition}. */\nexport interface DiscoverSubagentsOptions {\n /**\n * Which sources to read. Defaults to `[\"project\"]` — `<cwd>/.theokit/agents/*.md`.\n *\n * An empty list reads NOTHING: the directory is never opened, so a caller that has not yet\n * established trust in `cwd` can decline the read rather than filter its result.\n */\n readonly settingSources?: readonly SubagentSource[];\n\n /**\n * Foreign configuration dialects to read alongside `.theokit/agents/` (#524). Defaults to none,\n * so this reads `.theokit/` only unless a caller declares otherwise.\n *\n * SEPARATE FROM `settingSources`, and the separation is the contract. That option answers *which\n * sources* — project, and one day user or team. This one answers *which dialects* within them.\n * Folding `\"claude-code\"` into `SubagentSource` would conflate the two, and the internal loader\n * has kept them apart since #524 precisely because they are orthogonal.\n *\n * ## Why this exists\n *\n * The reader underneath already accepted it; this entry point simply never passed it, so\n * `discoverSubagents` was `.theokit/`-only while the agent's own subagent registry — which goes\n * through `settingSources` + `compatSources` — could see the same files. Measured by the\n * `theocode` session on `5.0.1`, both arms in fresh trusted directories with the same task:\n *\n * roles in .theokit/agents/ delegate_to_team works\n * the SAME files in .claude/agents/ \"the `explorer` role is not configured\"\n *\n * So a repository adopting the product could delegate TO a `.claude/agents/` subagent by name and\n * could not define its team's roles there — one dialect, two answers, depending on which selector\n * asked. That asymmetry was an omission rather than a decision: the plumbing existed and the\n * public signature did not reach it.\n */\n readonly compatSources?: readonly CompatSourceDeclaration[];\n}\n\n// Validated at the boundary (error-handling.md § 2): the union is erased at runtime, so a JS\n// caller — or a value crossing a serialization hop — can still carry a source nobody honors.\n// Dropping it silently would read as \"no subagents found\", which is the same shape as success.\nfunction resolveSources(options: DiscoverSubagentsOptions | undefined): readonly SubagentSource[] {\n const declared = options?.settingSources;\n if (declared === undefined) return ACCEPTED_SOURCES;\n for (const source of declared) {\n if (!ACCEPTED_SOURCES.includes(source)) {\n throw new ConfigurationError(\n `Unknown subagent setting source \"${String(source)}\" (accepted: ${ACCEPTED_SOURCES.join(\", \")})`,\n { code: \"subagent_unknown_setting_source\" },\n );\n }\n }\n return declared;\n}\n\n/**\n * Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.\n *\n * An absent directory yields `{}` — a project without subagents is the common case, not an error.\n */\nexport async function discoverSubagents(\n cwd: string,\n options?: DiscoverSubagentsOptions,\n): Promise<Record<string, AgentDefinition>> {\n const sources = resolveSources(options);\n return loadSubagents(cwd, sources.includes(\"project\"), undefined, options?.compatSources ?? []);\n}\n\n/**\n * Load ONE subagent definition by name, or `undefined` when it is not defined on disk.\n *\n * A thin selector over {@link discoverSubagents} rather than a second reader: one parser is the\n * whole point of this module.\n */\nexport async function loadSubagentDefinition(\n name: string,\n cwd: string,\n options?: DiscoverSubagentsOptions,\n): Promise<AgentDefinition | undefined> {\n return (await discoverSubagents(cwd, options))[name];\n}\n"]}
|
package/docs/error-codes.md
CHANGED
|
@@ -119,7 +119,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
|
|
|
119
119
|
| `local_provider_http_error` | domain | ConfigurationError | `packages/sdk/src/internal/catalog/local-models.ts:61` |
|
|
120
120
|
| `local_provider_unreachable` | domain | ConfigurationError | `packages/sdk/src/internal/catalog/local-models.ts:46` |
|
|
121
121
|
| `malformed_api_key` | domain | AuthenticationError | `packages/sdk/src/internal/agent/helpers.ts:224` +1 |
|
|
122
|
-
| `max_delegation_depth` | domain | MaxDelegationDepthError | `packages/sdk/src/a2a/subagent.ts:
|
|
122
|
+
| `max_delegation_depth` | domain | MaxDelegationDepthError | `packages/sdk/src/a2a/subagent.ts:239` +1 |
|
|
123
123
|
| `mcp_buffer_overflow` | domain | NetworkError | `packages/sdk/src/internal/mcp/client.ts:332` |
|
|
124
124
|
| `mcp_closed` | domain | NetworkError | `packages/sdk/src/internal/mcp/client.ts:307` |
|
|
125
125
|
| `mcp_crashed` | domain | NetworkError | `packages/sdk/src/internal/mcp/client.ts:222` |
|
|
@@ -202,7 +202,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
|
|
|
202
202
|
| `subagent_reasoning_effort_without_model` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:193` |
|
|
203
203
|
| `subagent_sandbox_not_boolean` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:213` |
|
|
204
204
|
| `subagent_unknown_field` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/subagents-loader.ts:158` |
|
|
205
|
-
| `subagent_unknown_setting_source` | domain | ConfigurationError | `packages/sdk/src/subagents-loader.ts:
|
|
205
|
+
| `subagent_unknown_setting_source` | domain | ConfigurationError | `packages/sdk/src/subagents-loader.ts:96` |
|
|
206
206
|
| `subscribe_baseUrl_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:77` |
|
|
207
207
|
| `subscribe_name_invalid` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:72` |
|
|
208
208
|
| `subscription_descriptor_invalid` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/server-integration.ts:172` |
|
|
@@ -4,7 +4,7 @@ Every public symbol the TheoKit workspace publishes, and the exact specifier to
|
|
|
4
4
|
|
|
5
5
|
A symbol listed under two specifiers is reachable from both, but that does NOT make the two interchangeable: a class emitted separately into a subpath entry is a distinct nominal type from the one in the root bundle, so passing one where the other is expected fails on a private field. When a symbol appears twice, import it and everything it is passed to from the SAME specifier.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
1197 export(s) across 46 entry point(s).
|
|
8
8
|
|
|
9
9
|
## `@theokit/acp`
|
|
10
10
|
|
|
@@ -1198,6 +1198,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
|
|
|
1198
1198
|
| `ForkTranscriptOptions` | interface | Options for {@link forkTranscript } . |
|
|
1199
1199
|
| `isCorruptionError` | function | True when an open error indicates an unreadable / corrupt database file. |
|
|
1200
1200
|
| `JsonlParseError` | class | Raised when a JSONL line is not valid JSON or is not a JSON object. |
|
|
1201
|
+
| `legacyTranscriptPath` | function | The path this session used BEFORE #400 made transcript filenames UUIDs. |
|
|
1201
1202
|
| `LiveSessionError` | class | M81 — the target is a protected session (live pointer / most-recent transcript / active entry). |
|
|
1202
1203
|
| `LiveTranscriptError` | class | M81 — the target is a protected session (live pointer / most-recent transcript / active entry). |
|
|
1203
1204
|
| `loadJsonl` | function | Parse a JSONL file into rows. |
|
|
@@ -1213,6 +1214,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
|
|
|
1213
1214
|
| `SessionArtifact` | type | The kinds of file this SDK leaves in a project's transcript directory. |
|
|
1214
1215
|
| `SessionBusyError` | class | M81 — another process already holds the writer lease for this session. |
|
|
1215
1216
|
| `sessionHasWriter` | function | Does the session have a writer **right now**? |
|
|
1217
|
+
| `sessionUuidFor` | function | The transcript filename for an agent id — always a UUID. |
|
|
1216
1218
|
| `SessionWriterLease` | interface | A held writer lease. |
|
|
1217
1219
|
| `TranscriptBlock` | type | A content block inside {@link TranscriptMessage } . |
|
|
1218
1220
|
| `TranscriptMessage` | interface | The message body of a {@link SessionRecord } . |
|
|
@@ -1334,6 +1336,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
|
|
|
1334
1336
|
| `discoverSkills` | function | Discover `SKILL.md` skills under an arbitrary directory. |
|
|
1335
1337
|
| `DiscoverSkillsOptions` | interface | Options for {@link discoverSkills } . |
|
|
1336
1338
|
| `InvalidSkillInfo` | interface | Information passed to `onInvalidSkill` when a `SKILL.md` is present but its frontmatter is malformed (missing required field or invalid YAML). |
|
|
1339
|
+
| `loadSkillInstructions` | function | Read the BODY of a discovered skill — everything after its frontmatter. |
|
|
1337
1340
|
| `Skill` | interface | A discovered skill's metadata. |
|
|
1338
1341
|
|
|
1339
1342
|
## `@theokit/sdk/subagents`
|
|
@@ -1348,6 +1351,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
|
|
|
1348
1351
|
| Symbol | Kind | Summary |
|
|
1349
1352
|
|---|---|---|
|
|
1350
1353
|
| `AgentDefinition` | interface | Subagent definition. |
|
|
1354
|
+
| `CompatSourceDeclaration` | type | A declared foreign source: a bare kind, or a kind with the surfaces it may be read for. |
|
|
1351
1355
|
| `discoverSubagents` | function | Discover the subagents defined under `<cwd>/.theokit/agents/*.md`. |
|
|
1352
1356
|
| `DiscoverSubagentsOptions` | interface | Options for {@link discoverSubagents } / {@link loadSubagentDefinition } . |
|
|
1353
1357
|
| `loadSubagentDefinition` | function | Load ONE subagent definition by name, or `undefined` when it is not defined on disk. |
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/concurrency/delegation-depth.ts","../src/internal/concurrency/subagent-credentials.ts","../src/a2a/subagent.ts"],"names":["AsyncLocalStorage"],"mappings":";;;;;AA6BA,IAAM,UAAA,GAAa,IAAI,iBAAA,EAA0B;AAWjD,eAAsB,mBAAA,CAAuB,OAAe,EAAA,EAAkC;AAC5F,EAAA,OAAO,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AACjC;AAUO,SAAS,sBAAA,GAAiC;AAC/C,EAAA,OAAO,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esContent":["/**\n * #364 — how deep the current delegation chain already is, delivered through the CALL.\n *\n * ## The bug this replaces\n *\n * `maxDelegationDepth` was checked once, at tool-CONSTRUCTION time, against a `_parentDepth`\n * argument that nothing in the SDK ever incremented. Constructing a tool says nothing about how\n * deep it will later be invoked, so with the documented call — `SubAgent.create(spec)` — the test\n * was `1 > maxDepth`, false for every spec that did not ask for depth 0. A subagent whose tools\n * include another subagent recursed unbounded, which is precisely what the guard exists to stop.\n * The only path that ever tripped it was a caller threading the number by hand.\n *\n * ## Why the async scope closes it\n *\n * Depth is a property of the RUN, not of the object. A child's run loop — and therefore every tool\n * it dispatches — executes inside the async continuation of its parent's handler, so a value\n * published on that context is exactly what a nested dispatch needs to read. This is the same seam\n * `subagent-credentials.ts` uses, and for the same reason: what survives every layer that rebuilds\n * a tool object is the call, never the object.\n *\n * It is kept in its own module rather than folded into the credentials payload because depth is a\n * separate concern with a separate lifetime — the credentials scope is opened once per run by the\n * run loop, while depth is opened per delegation by the dispatching tool.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst depthStore = new AsyncLocalStorage<number>();\n\n/**\n * Run `fn` with `depth` published as the delegation depth of the current chain.\n *\n * Nested scopes shadow the outer one and the outer is restored on return, so two sibling\n * delegations from the same parent each start from the parent's depth rather than from each\n * other's.\n *\n * @internal\n */\nexport async function withDelegationDepth<T>(depth: number, fn: () => Promise<T>): Promise<T> {\n return depthStore.run(depth, fn);\n}\n\n/**\n * The delegation depth of the current chain — `0` outside any delegation.\n *\n * `0` is the honest default rather than a fallback to some previous chain's value: a subagent\n * dispatched with no parent delegation IS at depth zero.\n *\n * @internal\n */\nexport function currentDelegationDepth(): number {\n return depthStore.getStore() ?? 0;\n}\n","/**\n * theokit#148 — the parent's credentials, delivered through the CALL, not through the tool object.\n *\n * ## The class of bug this replaces\n *\n * Credential inheritance used to ride a property installed on the subagent tool object — first a\n * unique `Symbol()`, then `Symbol.for` after #143. Both are the same shape of contract: \"this\n * object will reach the dispatcher with an extra property intact\". Nothing enforces that, and it\n * broke twice for two different reasons:\n *\n * - **Module duplication** (#142/#143): `tsup splitting: false` inlined a separate copy of the\n * module into each public entry, so the two copies disagreed on a unique `Symbol()` key. Fixed at\n * the build level by M78's `splitting: true`, but the fragile contract remained.\n * - **Object normalization** (#148): any layer that rebuilds the tool from its known fields drops\n * the property. `@theokit/agents`' `toCompiledTool` does exactly that, and had to add an explicit\n * `Object.getOwnPropertySymbols` copy loop to compensate — a band-aid the SDK's contract forced\n * onto a consumer. A named field would have been dropped by the same four-field rebuild, which is\n * why \"make it a typed field\" alone does not close this.\n *\n * ## Why the async scope closes it\n *\n * What survives a rebuild is not the object — it is the CALL. A normalizing wrapper builds a new\n * object but still invokes the original handler, inside the parent run's async context. So\n * credentials published on that context reach the handler regardless of what the tool object looks\n * like by then. There is no property left for a layer to drop.\n *\n * It also fixes a defect the per-object slot could not: credentials were stored per tool INSTANCE,\n * so one subagent tool shared by two agents got last-writer-wins. The scope is per run.\n *\n * Nothing is exposed to third-party tool code: the store is module-private, credentials never touch\n * a handler's `ctx`, and `currentInheritedSubAgentCredentials` is `@internal`.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { ModelSelection } from \"../../types/agent-prims.js\";\nimport type { Plugin } from \"../plugins/types.js\";\n\n/**\n * Credentials a parent agent hands down to its subagent tools so the child inherits the parent's\n * auth (and, absent an explicit `spec.model`, its model).\n *\n * Declared here rather than in `a2a/subagent.ts` so the delivery mechanism owns the payload shape\n * and the dependency runs one way (`a2a/subagent` -> this module). `a2a/subagent.ts` briefly\n * re-exported it \"for back-compat\"; knip proved there was no back-compat surface to preserve — the\n * type was never in the public barrel nor the exports map — so the re-export was deleted.\n *\n * Emitted rather than erased: `a2a/subagent.d.ts` imports it by name, and that entry IS published,\n * so erasing this declaration ships a `.d.ts` that does not compile. Not being in the exports map\n * is what keeps it out of the semver contract; erasure is not what does that.\n */\nexport interface InheritedCredentials {\n readonly apiKey?: string;\n readonly model?: ModelSelection;\n /**\n * The parent's shell-sandbox posture (`local.sandboxOptions.enabled`), handed down so a delegated\n * child of a sandboxed parent stays sandboxed unless its role explicitly opts out. Without this a\n * child ran unsandboxed whenever its role omitted `sandbox` — a default-open the sandbox wiring\n * exists to prevent.\n */\n readonly sandbox?: boolean;\n /**\n * #55 — the parent's code-registered plugins (e.g. a `PermissionPlugin`) handed down so the child\n * runs under the SAME policy. Without this, a delegated child's inner tool calls escape the\n * parent's argument-level permission gate. First-party delegation path only — never exposed to\n * third-party tool `ctx`.\n */\n readonly plugins?: readonly Plugin[];\n}\n\nconst credentialsStore = new AsyncLocalStorage<InheritedCredentials>();\n\n/**\n * Run `fn` with `credentials` published as the delegation credentials of the current run.\n *\n * Nested scopes shadow the outer one and the outer is restored on return, so a delegated child that\n * itself delegates hands down ITS credentials, not its parent's.\n *\n * @internal\n */\nexport async function withInheritedSubAgentCredentials<T>(\n credentials: InheritedCredentials,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialsStore.run(credentials, fn);\n}\n\n/**\n * The delegation credentials of the current run, or `undefined` outside a run scope.\n *\n * `undefined` is deliberately NOT a fallback to some previous run's value: a subagent dispatched\n * with no parent context must create its child without an inherited key rather than reuse a\n * credential that belonged to someone else.\n *\n * @internal\n */\nexport function currentInheritedSubAgentCredentials(): InheritedCredentials | undefined {\n return credentialsStore.getStore();\n}\n","/**\n * Subagent delegation — declarative child agent invocable as a tool.\n *\n * Per ADR D2: `defineSubAgent(spec)` returns a `CustomTool` that, when\n * invoked by the LLM, creates a child agent and sends the input as a\n * message. EC-2: delegation depth is tracked across the RUN (#364) — each\n * delegation publishes its depth on the async scope its child executes in, so a\n * subagent that delegates to a subagent is bounded by `maxDelegationDepth`\n * without the caller threading a counter by hand.\n *\n * SE10 — the handler forwards the parent run's `AbortSignal` to the child.\n * SE11 — optional `onDelegationStart` / `onDelegationComplete` lifecycle hooks\n * let the caller reject, rewrite, observe, or annotate a delegation.\n *\n * @public\n */\n\nimport { z } from \"zod\";\nimport { TheokitAgentError } from \"../errors.js\";\nimport {\n currentDelegationDepth,\n withDelegationDepth,\n} from \"../internal/concurrency/delegation-depth.js\";\nimport {\n currentInheritedSubAgentCredentials,\n type InheritedCredentials,\n} from \"../internal/concurrency/subagent-credentials.js\";\nimport { getAgentFacade } from \"../internal/runtime/registry/agent-factory-registry.js\";\nimport type {\n AgentDefinition,\n AgentOptions,\n CustomTool,\n ToolContextMessage,\n} from \"../types/agent.js\";\nimport type { ModelSelection } from \"../types/agent-prims.js\";\nimport type { Run } from \"../types/run.js\";\n\n/** Arguments passed to {@link SubAgentSpec.messageFilter} (SE12). */\nexport interface MessageFilterArgs {\n /** The supervisor transcript (read-only text projection) available to this delegation. */\n messages: readonly ToolContextMessage[];\n /** The prompt about to be delegated (after any `onDelegationStart` rewrite). */\n input: string;\n /** The subagent's name. */\n name: string;\n}\n\n/** Context passed to {@link SubAgentSpec.onDelegationStart} before the child runs. */\nexport interface DelegationStartContext {\n input: string;\n name: string;\n /**\n * SE15 — 1-based count of times THIS subagent tool has been invoked (a\n * per-`defineSubAgent`-instance counter). Incremented before this hook runs;\n * a rejected delegation still counts. Enables reject-after-N patterns.\n */\n iteration: number;\n}\n\n/**\n * Decision returned from {@link SubAgentSpec.onDelegationStart}. Discriminated on\n * `proceed` so a rejection (`proceed: false` + `rejectionReason`) and an approval\n * (`modifiedInput`) cannot be mixed into one nonsensical object.\n */\nexport type DelegationStartDecision =\n | { proceed: false; rejectionReason?: string }\n | {\n proceed?: true;\n modifiedInput?: string;\n /** SE13 — cap the child's iteration count (forwarded as `SendOptions.maxIterations`). */\n modifiedMaxSteps?: number;\n };\n\n/** Context passed to {@link SubAgentSpec.onDelegationComplete} after the child settles. */\nexport interface DelegationCompleteContext {\n input: string;\n name: string;\n /** The child's text result (present on success). */\n result?: string;\n /** The error the child threw (present on failure); the error is still re-thrown. */\n error?: unknown;\n /** SE15 — the same 1-based iteration this delegation's `onDelegationStart` saw. */\n iteration: number;\n}\n\n/**\n * The return of a delegation hook: a decision, a promise of one, or nothing —\n * `void` lets a side-effect-only callback (`(ctx) => { log(ctx) }`) type-check,\n * which is the common case (mirrors a peer framework's `async ctx => { ... }` hooks).\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: `void` is the idiomatic return for an optional-return callback; the rule false-positives on callback return unions.\ntype DelegationHookResult<T> = T | void | Promise<T | void>;\n\n/** Decision returned from {@link SubAgentSpec.onDelegationComplete}. */\nexport interface DelegationCompleteDecision {\n /** Appended to the child's result string. */\n feedback?: string;\n}\n\n/**\n * The declaration of a delegating child agent, handed to `SubAgent.create(spec)`.\n *\n * `name`, `description` and `instructions` are the only required fields: the first\n * two become the tool the supervisor's model sees, the third becomes the child's\n * system prompt. Everything else narrows what the child inherits.\n *\n * const research = SubAgent.create({\n * name: \"research\",\n * description: \"Look a fact up\",\n * instructions: \"You answer with one sentence.\",\n * });\n * const agent = await Agent.create({ tools: [research] });\n *\n * The tool's own input schema is fixed — one required string property, `input`.\n * It is not derived from this spec and cannot be widened here.\n *\n * What the child inherits from the parent AT DISPATCH TIME, not from this object:\n * the API key, the model (unless `model` is set), the parent's plugins, and the\n * parent's sandbox posture (unless `sandbox` is set). An absent `sandbox` inherits;\n * an explicit `sandbox: false` turns confinement OFF for a child of a confined\n * parent, which is not the same thing.\n *\n * How it fails: the child's failure is re-thrown to the supervisor as a tool error\n * — a run ending in `status: \"error\"` becomes\n * `subagent \"<name>\" run failed: <cause>`. `onDelegationStart` and `messageFilter`\n * propagate their own throws; only a throw from `onDelegationComplete` ON THE\n * ERROR PATH is suppressed, so it cannot mask the real cause.\n *\n * Traps:\n * - `model` as a bare string drops reasoning parameters. Pass the\n * {@link ModelSelection} object form when the child needs `params`.\n * - `maxDelegationDepth` (default 3) bounds the delegation CHAIN, counted at\n * dispatch across the run (#364) — the depth is not something you thread. The\n * `parentDepth` argument of `SubAgent.create` still offsets it, for a supervisor\n * that wants a lower ceiling than the chain it sits in.\n * - Context isolation is the DEFAULT. Without `messageFilter` the child sees only\n * the delegated string; without `includeToolResults` the supervisor gets only\n * the child's final text.\n */\nexport interface SubAgentSpec {\n name: string;\n description: string;\n instructions: string;\n /**\n * A bare id string (back-compat) OR a full {@link ModelSelection} carrying\n * `params` (e.g. `[{ id: \"thinking\", value: \"low\" }]` for reasoning effort). The\n * object form is required for per-subagent reasoning effort to survive to the child\n * — the pre-M33 path took only `.id` and dropped params.\n */\n model?: string | ModelSelection;\n tools?: CustomTool[];\n /** Per-subagent shell sandbox toggle (M33). `true` ⇒ child `local.sandboxOptions.enabled`. */\n sandbox?: boolean;\n /**\n * Maximum length of the delegation CHAIN rooted at this tool, counted at dispatch\n * (default 3). Depth 1 is this subagent; a subagent it delegates to is depth 2.\n * Exceeding it throws {@link MaxDelegationDepthError} from the tool handler.\n */\n maxDelegationDepth?: number;\n /**\n * SE11 — called before the supervisor delegates. Return `{ proceed: false }`\n * to reject (the child never runs and `rejectionReason` becomes the tool\n * result), or `{ modifiedInput }` to rewrite the delegated prompt. A throwing\n * hook surfaces (never silently swallowed).\n */\n onDelegationStart?: (\n ctx: DelegationStartContext,\n ) => DelegationHookResult<DelegationStartDecision>;\n /**\n * SE11 — called after the delegation settles. On success `ctx.result` is set\n * and an optional `{ feedback }` is appended to it. On failure `ctx.error` is\n * set and the original error is ALWAYS re-thrown after this hook runs — a throw\n * from this hook on the error path is suppressed so it cannot mask the\n * delegation's real failure (on the success path a throw does propagate).\n */\n onDelegationComplete?: (\n ctx: DelegationCompleteContext,\n ) => DelegationHookResult<DelegationCompleteDecision>;\n /**\n * SE12 — opt-in parent-context forwarding. When set, the supervisor transcript\n * (`ctx.messages`, a read-only text projection) is passed to this filter and the\n * returned subset is forwarded to the child as a role-tagged context preamble\n * prepended to the delegated input. When ABSENT the child runs input-only —\n * memory isolation stays the default. A filter returning `[]` forwards nothing.\n * A throwing filter propagates (fail-fast, never swallowed — same contract as\n * `onDelegationStart`); the delegation surfaces as a tool error.\n */\n messageFilter?: (args: MessageFilterArgs) => readonly ToolContextMessage[];\n /**\n * SE14 — opt-in subagent result-context control. When `true`, the child's\n * completed tool-call results (name + result) are appended to the delegation\n * payload returned to the supervisor, inside a `<subagent-tool-results>` block.\n * When absent/`false` the delegation returns the child's final text only —\n * text-only stays the default (a peer framework's scoped posture). See ADR 0006.\n */\n includeToolResults?: boolean;\n}\n\n/**\n * Raised by `SubAgent.create(spec, parentDepth)` when `parentDepth + 1` exceeds\n * `spec.maxDelegationDepth` (default 3). Carries `currentDepth`, `maxDepth` and a\n * stable `code: \"max_delegation_depth\"`.\n *\n * Thrown from the subagent tool's handler when a delegation would exceed\n * `maxDelegationDepth` (default 3), so it surfaces as the tool call's failure —\n * catching it around the dispatching `agent.send()` works.\n *\n * Also thrown eagerly at TOOL-CONSTRUCTION time when a caller threads its own\n * `parentDepth` that is already past the limit; such a tool could never be\n * dispatched, so refusing to build it fails earlier and clearer.\n *\n * Before #364 the construction-time check was the ONLY one, against a depth\n * nothing in the SDK incremented — so under the documented `SubAgent.create(spec)`\n * call this error could not fire at all and nested delegation was unbounded. The\n * chain length now travels with the run (`internal/runtime/concurrency/delegation-depth.ts`),\n * and a caller-threaded `parentDepth` still adds to it.\n */\nexport class MaxDelegationDepthError extends TheokitAgentError {\n override readonly name = \"MaxDelegationDepthError\";\n override readonly code = \"max_delegation_depth\" as const;\n constructor(\n public readonly currentDepth: number,\n public readonly maxDepth: number,\n ) {\n // Not retryable: the depth is a property of the call graph, and it is the same on a retry.\n super(`Max delegation depth ${maxDepth} exceeded (current: ${currentDepth})`, {\n code: \"max_delegation_depth\",\n isRetryable: false,\n });\n }\n}\n\n/**\n * Run the `onDelegationStart` hook; returns either a rejection or the (possibly\n * rewritten) input plus the optional SE13 `maxSteps` cap.\n */\nasync function applyDelegationStart(\n spec: SubAgentSpec,\n input: string,\n iteration: number,\n): Promise<{ reject: string } | { input: string; maxSteps?: number }> {\n if (spec.onDelegationStart === undefined) return { input };\n const decision = await spec.onDelegationStart({ input, name: spec.name, iteration });\n if (decision === undefined) return { input };\n if (decision.proceed === false)\n return { reject: decision.rejectionReason ?? \"(delegation rejected)\" };\n return {\n input: decision.modifiedInput ?? input,\n ...(decision.modifiedMaxSteps !== undefined ? { maxSteps: decision.modifiedMaxSteps } : {}),\n };\n}\n\n/**\n * SE14 — replay the child run's stream (a safe post-`wait()` idiom — the run buffers\n * events, `stream()` replays them) and collect every completed tool-call result into\n * a delimited block. Returns `\"\"` when the child ran no completed tool calls. See ADR 0006.\n */\nasync function collectChildToolResults(run: Run): Promise<string> {\n const lines: string[] = [];\n for await (const event of run.stream()) {\n if (event.type === \"tool_call\" && event.status === \"completed\") {\n const rendered =\n typeof event.result === \"string\" ? event.result : JSON.stringify(event.result ?? null);\n lines.push(`${event.name}: ${rendered}`);\n }\n }\n if (lines.length === 0) return \"\";\n return `\\n\\n<subagent-tool-results>\\n${lines.join(\"\\n\")}\\n</subagent-tool-results>`;\n}\n\n/**\n * Build the child agent's `Agent.create` options: the child inherits the parent's\n * apiKey (else `Agent.create` throws \"Missing API key\"), its model (unless the spec\n * overrides it), and — #55 — the parent's plugins (permission gate/guards) so the\n * child's inner tool calls run under the same policy.\n */\nexport function buildChildCreateOptions(\n spec: SubAgentSpec,\n inherited: InheritedCredentials | undefined,\n): AgentOptions {\n // M33 — carry the WHOLE model (a bare id becomes `{ id }`; a ModelSelection with\n // `params` keeps its reasoning effort). The pre-M33 path wrapped `spec.model` as\n // `{ id: spec.model }`, which only worked because spec.model was a string and\n // silently dropped reasoning params.\n const model: string | ModelSelection | undefined =\n spec.model !== undefined\n ? typeof spec.model === \"string\"\n ? { id: spec.model }\n : spec.model\n : inherited?.model;\n // M33 — the role's own `sandbox` wins; when it omits the field, inherit the parent's posture. A role's\n // explicit `sandbox: false` therefore confines-OFF a child of a sandboxed parent (distinct from absent).\n const sandbox = spec.sandbox ?? inherited?.sandbox;\n return {\n ...(inherited?.apiKey !== undefined ? { apiKey: inherited.apiKey } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(sandbox !== undefined ? { local: { sandboxOptions: { enabled: sandbox } } } : {}),\n ...(inherited?.plugins !== undefined ? { plugins: inherited.plugins } : {}),\n systemPrompt: spec.instructions,\n tools: spec.tools ?? [],\n };\n}\n\n/**\n * Create the transient child agent and send the input, composing every forwarded\n * `SendOptions` onto ONE `send` call — SE10 `signal` + SE13 `maxIterations`. Absent\n * every option ⇒ the pre-SE10 single-arg `send(input)` shape. SE14 — when\n * `includeToolResults` is set, append the child's completed tool results. Dispose in `finally`.\n */\nasync function runChildAgent(\n spec: SubAgentSpec,\n input: string,\n signal: AbortSignal | undefined,\n maxSteps: number | undefined,\n inherited: InheritedCredentials | undefined,\n depth: number,\n): Promise<string> {\n // #364 — publish THIS delegation's depth for the whole child run. The child's loop, and every\n // tool it dispatches, runs inside this scope, so a nested subagent reads the real chain length\n // instead of the 0 every construction-time check saw.\n return withDelegationDepth(depth, () =>\n runChildAgentInScope(spec, input, signal, maxSteps, inherited),\n );\n}\n\nasync function runChildAgentInScope(\n spec: SubAgentSpec,\n input: string,\n signal: AbortSignal | undefined,\n maxSteps: number | undefined,\n inherited: InheritedCredentials | undefined,\n): Promise<string> {\n // SE45 cycle 3 — use the registered Agent facade via the DIP seam\n // (agent-factory-registry) instead of a dynamic `import(\"../agent.js\")`.\n // This removes the last madge cycle (a2a/subagent -> agent -> ... -> real-local-run-tools\n // -> a2a/subagent): the facade registers itself at module-init via setAgentFacade,\n // so subagent depends only on the registry port, never on the facade module.\n const agent = await getAgentFacade().create(buildChildCreateOptions(spec, inherited));\n try {\n const sendOptions: {\n signal?: AbortSignal;\n maxIterations?: number;\n origin?: import(\"../types/run.js\").MessageOrigin;\n } = {\n ...(signal !== undefined ? { signal } : {}),\n ...(maxSteps !== undefined ? { maxIterations: maxSteps } : {}),\n // SE3 — a delegated child's turn is initiated by the coordinating parent.\n origin: { kind: \"coordinator\" },\n };\n const run = await agent.send(input, sendOptions);\n const result = await run.wait();\n // Fail-fast, don't swallow (Rule 8): a child that ended in error must surface — otherwise a real\n // failure (e.g. `provider_unresolved`) is hidden behind \"(no response)\" and the parent loops on it.\n if (result.status === \"error\") {\n const cause = (result as { error?: { message?: string } }).error;\n throw new Error(\n `subagent \"${spec.name}\" run failed: ${cause?.message ?? \"unknown error\"}`,\n cause !== undefined ? { cause } : undefined,\n );\n }\n const text = result.result ?? \"(no response)\";\n // SE14 — text-only by default; opt-in appends the child's tool results.\n return spec.includeToolResults === true ? text + (await collectChildToolResults(run)) : text;\n } finally {\n agent.dispose();\n }\n}\n\n/**\n * Best-effort error-path notification: run `onDelegationComplete` with the child's\n * error so the caller can observe the failure. The observer's own throw (sync or\n * async) is suppressed here so it cannot mask the delegation's real error, which the\n * handler re-throws next.\n */\nasync function notifyDelegationError(\n spec: SubAgentSpec,\n input: string,\n error: unknown,\n iteration: number,\n): Promise<void> {\n if (spec.onDelegationComplete === undefined) return;\n try {\n await spec.onDelegationComplete({ input, name: spec.name, error, iteration });\n } catch {\n // Subordinate to `error`; the child's real cause wins.\n }\n}\n\n/**\n * SE12 — apply `messageFilter` (if set) and prepend the filtered supervisor\n * transcript to the delegated input as a role-tagged context preamble. Absent\n * filter OR no messages OR an empty filtered subset ⇒ the original input\n * (isolation-by-default preserved).\n */\nfunction applyMessageFilter(\n spec: SubAgentSpec,\n input: string,\n messages: readonly ToolContextMessage[] | undefined,\n): string {\n if (spec.messageFilter === undefined || messages === undefined) return input;\n const filtered = spec.messageFilter({ messages, input, name: spec.name });\n if (filtered.length === 0) return input;\n const preamble = filtered.map((m) => `${m.role}: ${m.content}`).join(\"\\n\");\n return `Prior conversation:\\n${preamble}\\n\\nTask:\\n${input}`;\n}\n\n/** Run the success-path `onDelegationComplete` hook; appends its `feedback` to the result. */\nasync function applyDelegationComplete(\n spec: SubAgentSpec,\n input: string,\n result: string,\n iteration: number,\n): Promise<string> {\n if (spec.onDelegationComplete === undefined) return result;\n const completion = await spec.onDelegationComplete({ input, name: spec.name, result, iteration });\n return completion?.feedback !== undefined ? result + completion.feedback : result;\n}\n\nfunction defineSubAgent(spec: SubAgentSpec, _parentDepth = 0): CustomTool {\n const maxDepth = spec.maxDelegationDepth ?? 3;\n\n // A caller that threads its own depth still gets the eager failure it always got: a spec that is\n // already too deep to ever be dispatchable is worth refusing at construction. What this check\n // CANNOT see is the runtime chain — constructing a tool says nothing about how deep it will later\n // be invoked — which is why the guard that actually bounds recursion lives at dispatch (#364).\n if (_parentDepth + 1 > maxDepth) {\n throw new MaxDelegationDepthError(_parentDepth + 1, maxDepth);\n }\n\n // Zod for RUNTIME validation of the tool_use input …\n const inputZod = z.object({\n input: z.string().describe(\"Task for the subagent\"),\n });\n // … and a real Draft-7 JSON Schema for the LLM. `CustomTool.inputSchema` is sent\n // to the model verbatim; a raw Zod object would serialize to garbage, so the\n // model emits malformed input that fails `inputZod.parse` and the delegation\n // never runs (the previous bug — the schema and the validator are now distinct).\n const inputSchema: Record<string, unknown> = {\n type: \"object\",\n properties: {\n input: { type: \"string\", description: \"Task for the subagent\" },\n },\n required: [\"input\"],\n additionalProperties: false,\n };\n\n // SE15 — per-instance delegation counter, surfaced as `iteration` on the hook\n // contexts. Incremented once per handler invocation before onDelegationStart.\n let iteration = 0;\n\n const tool: CustomTool = {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (\n rawInput: Record<string, unknown>,\n ctx?: {\n signal?: AbortSignal;\n context?: unknown;\n messages?: readonly ToolContextMessage[];\n },\n ): Promise<string> => {\n const { input: parsed } = inputZod.parse(rawInput);\n // theokit#148 — read the parent's credentials from the RUN's async scope, at dispatch time.\n // They used to be stashed on this tool object by the runtime, which meant any layer that\n // rebuilt the object (e.g. `@theokit/agents`' `toCompiledTool`) silently dropped them and the\n // child failed with `provider_unresolved`. The scope travels with the call, so nothing about\n // the object's shape matters — and two concurrent runs sharing one tool each read their own.\n const inherited = currentInheritedSubAgentCredentials();\n // #364 — the real bound. `currentDelegationDepth()` is the length of the chain that led here,\n // published by each ancestor's `runChildAgent`; a caller-threaded `_parentDepth` still adds to\n // it, so the pre-#364 hand-threaded behaviour is unchanged when the ambient depth is 0.\n const currentDepth = _parentDepth + currentDelegationDepth() + 1;\n if (currentDepth > maxDepth) {\n throw new MaxDelegationDepthError(currentDepth, maxDepth);\n }\n iteration += 1; // SE15 — before onDelegationStart; a rejected delegation still counts.\n // Pin THIS invocation's iteration before any await so a concurrent invocation\n // bumping the shared counter cannot change the value onDelegationComplete /\n // notifyDelegationError observe — they see the same iteration onDelegationStart did.\n const capturedIteration = iteration;\n\n const start = await applyDelegationStart(spec, parsed, capturedIteration);\n if (\"reject\" in start) return start.reject;\n // SE12 — opt-in: forward the filtered supervisor transcript as a preamble.\n const input = applyMessageFilter(spec, start.input, ctx?.messages);\n\n let result: string;\n try {\n // SE13 — apply the optional onDelegationStart maxSteps cap on the child send.\n result = await runChildAgent(\n spec,\n input,\n ctx?.signal,\n start.maxSteps,\n inherited,\n currentDepth,\n );\n } catch (error) {\n // SE11 — notify the completion hook of the failure (best-effort observer),\n // then re-throw the ORIGINAL error (Rule 8: never swallow the delegation's\n // own failure).\n await notifyDelegationError(spec, input, error, capturedIteration);\n throw error;\n }\n return applyDelegationComplete(spec, input, result, capturedIteration);\n },\n };\n\n // theokit#148 — nothing is installed on the tool. The credentials arrive through the run's async\n // scope (see `internal/runtime/concurrency/subagent-credentials.ts`), so there is no extra\n // property for a normalizing layer to drop.\n return tool;\n}\n\n/** SE36 — `SubAgent.create` replaces `defineSubAgent` (ADR 0015). @public *\n * `SubAgent.create` returns a **`CustomTool`** — the sub-agent is exposed to the\n * parent as a callable tool, not as a `SubAgent` instance.\n */\nexport class SubAgent {\n private constructor() {}\n static create(spec: SubAgentSpec, parentDepth = 0): CustomTool {\n return defineSubAgent(spec, parentDepth);\n }\n}\n\n/**\n * Convert a parent's declarative `agents` map ({@link AgentDefinition} per key)\n * into delegation tools for the LOCAL runtime — the counterpart of the\n * cloud/fixture subagent wiring. Each child inherits the parent's `apiKey`/model\n * from the CALL, not from the tool object: `inheritSubAgentCredentials` used to\n * attach them to the tool, and any layer that rebuilt that object dropped them —\n * including the SDK's own rebuild (theokit#148). Credentials now ride the\n * dispatch, so a rebuilt tool cannot lose them. `def.model` overrides the model\n * (`\"inherit\"` keeps the parent's), and `def.tools` scopes the child to that\n * subset of the parent's tools (absent → the parent's full toolset, per the\n * `AgentDefinition.tools` contract).\n *\n * M33 — per-subagent `model` (with reasoning `params`) and `sandbox` are now wired\n * into local delegation: each is carried onto the {@link SubAgentSpec} and applied to\n * the child in {@link buildChildCreateOptions}. `\"inherit\"` (or an absent field) keeps\n * the parent's value. Per-subagent `mcp` is rejected at load (see subagents-loader) —\n * resolving server names→config on the local path is a follow-up.\n *\n * @internal\n */\nexport function subAgentToolsFromDefinitions(\n agents: Record<string, AgentDefinition>,\n parentTools: readonly CustomTool[],\n): CustomTool[] {\n return Object.entries(agents).map(([name, def]) => {\n const whitelist =\n Array.isArray(def.tools) && def.tools.length > 0 ? new Set(def.tools) : undefined;\n const childTools = whitelist ? parentTools.filter((t) => whitelist.has(t.name)) : parentTools;\n return defineSubAgent({\n name,\n description: def.description,\n instructions: def.prompt,\n // Carry the FULL ModelSelection (id + reasoning params), not just the id, so\n // per-subagent reasoning effort survives to buildChildCreateOptions.\n ...(def.model !== undefined && def.model !== \"inherit\" ? { model: def.model } : {}),\n ...(def.sandbox !== undefined ? { sandbox: def.sandbox } : {}),\n tools: [...childTools],\n });\n });\n}\n"]}
|