@theokit/agents 0.47.0 → 1.0.1
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/dist/{bridge-entry-BQ6UUSLZ.d.ts → bridge-entry-F9kHGaIn.d.ts} +378 -106
- package/dist/bridge.d.ts +1 -2
- package/dist/bridge.js +3 -12
- package/dist/{chunk-FEH7JFH7.js → chunk-PTHRG25K.js} +143 -359
- package/dist/chunk-PTHRG25K.js.map +1 -0
- package/dist/index.d.ts +173 -15
- package/dist/index.js +233 -15
- package/dist/index.js.map +1 -1
- package/package.json +2 -4
- package/dist/chunk-FEH7JFH7.js.map +0 -1
- package/dist/chunk-NERDIS45.js +0 -329
- package/dist/chunk-NERDIS45.js.map +0 -1
- package/dist/decorators.d.ts +0 -176
- package/dist/decorators.js +0 -308
- package/dist/decorators.js.map +0 -1
- package/dist/types-DVA4LQsA.d.ts +0 -313
package/dist/decorators.js
DELETED
|
@@ -1,308 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AGENT_MAIN_LOOP,
|
|
3
|
-
Agent,
|
|
4
|
-
Audit,
|
|
5
|
-
Budget,
|
|
6
|
-
Checkpoint,
|
|
7
|
-
Compaction,
|
|
8
|
-
ContextWindow,
|
|
9
|
-
Gateway,
|
|
10
|
-
Guardrails,
|
|
11
|
-
HumanInTheLoop,
|
|
12
|
-
MCP,
|
|
13
|
-
Memory,
|
|
14
|
-
Mixin,
|
|
15
|
-
Policy,
|
|
16
|
-
ProjectContext,
|
|
17
|
-
RequiresApproval,
|
|
18
|
-
RequiresCapability,
|
|
19
|
-
Skills,
|
|
20
|
-
SubAgents,
|
|
21
|
-
TOOLBOX_CONFIG,
|
|
22
|
-
TOOL_CONFIG,
|
|
23
|
-
TOOL_METHODS,
|
|
24
|
-
Trace,
|
|
25
|
-
getAgentConfig,
|
|
26
|
-
getCheckpointConfig,
|
|
27
|
-
getCompactionConfig,
|
|
28
|
-
getContextWindowConfig,
|
|
29
|
-
getGatewayConfig,
|
|
30
|
-
getGuardrailsConfig,
|
|
31
|
-
getHumanInTheLoopConfig,
|
|
32
|
-
getMcpConfig,
|
|
33
|
-
getMemoryConfig,
|
|
34
|
-
getMeta,
|
|
35
|
-
getMixins,
|
|
36
|
-
getProjectContextConfig,
|
|
37
|
-
getSkillsConfig,
|
|
38
|
-
getSubAgents,
|
|
39
|
-
resolveSessionId,
|
|
40
|
-
setMeta
|
|
41
|
-
} from "./chunk-NERDIS45.js";
|
|
42
|
-
import {
|
|
43
|
-
__name
|
|
44
|
-
} from "./chunk-7QVYU63E.js";
|
|
45
|
-
|
|
46
|
-
// src/decorators/main-loop.ts
|
|
47
|
-
function MainLoop(options = {}) {
|
|
48
|
-
return (target, propertyKey) => {
|
|
49
|
-
const actualTarget = target.constructor;
|
|
50
|
-
const existing = getMeta(AGENT_MAIN_LOOP, actualTarget);
|
|
51
|
-
if (existing) {
|
|
52
|
-
console.warn(`[@theokit/agents] ${actualTarget.name}: @MainLoop() already declared on '${String(existing.propertyKey)}'. Overwriting with '${String(propertyKey)}'.`);
|
|
53
|
-
}
|
|
54
|
-
const meta = {
|
|
55
|
-
propertyKey,
|
|
56
|
-
strategy: options.strategy ?? "simple-chat",
|
|
57
|
-
maxIterations: options.maxIterations,
|
|
58
|
-
timeoutMs: options.timeoutMs
|
|
59
|
-
};
|
|
60
|
-
setMeta(AGENT_MAIN_LOOP, actualTarget, meta);
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
__name(MainLoop, "MainLoop");
|
|
64
|
-
function getMainLoop(target) {
|
|
65
|
-
return getMeta(AGENT_MAIN_LOOP, target);
|
|
66
|
-
}
|
|
67
|
-
__name(getMainLoop, "getMainLoop");
|
|
68
|
-
|
|
69
|
-
// src/decorators/tool.ts
|
|
70
|
-
function inferNamespace(className) {
|
|
71
|
-
const stripped = className.replace(/Tools$/, "");
|
|
72
|
-
return stripped.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").toLowerCase();
|
|
73
|
-
}
|
|
74
|
-
__name(inferNamespace, "inferNamespace");
|
|
75
|
-
function Toolbox(options = {}) {
|
|
76
|
-
return (target) => {
|
|
77
|
-
const ns = options.namespace ?? inferNamespace(target.name);
|
|
78
|
-
setMeta(TOOLBOX_CONFIG, target, {
|
|
79
|
-
...options,
|
|
80
|
-
namespace: ns
|
|
81
|
-
});
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
__name(Toolbox, "Toolbox");
|
|
85
|
-
function Tool(options) {
|
|
86
|
-
return (target, propertyKey) => {
|
|
87
|
-
const actualTarget = target.constructor;
|
|
88
|
-
setMeta(TOOL_CONFIG, actualTarget, options, propertyKey);
|
|
89
|
-
const existing = getMeta(TOOL_METHODS, actualTarget) ?? [];
|
|
90
|
-
setMeta(TOOL_METHODS, actualTarget, [
|
|
91
|
-
...existing,
|
|
92
|
-
propertyKey
|
|
93
|
-
]);
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
__name(Tool, "Tool");
|
|
97
|
-
function getToolboxConfig(target) {
|
|
98
|
-
return getMeta(TOOLBOX_CONFIG, target);
|
|
99
|
-
}
|
|
100
|
-
__name(getToolboxConfig, "getToolboxConfig");
|
|
101
|
-
function getToolMethods(target) {
|
|
102
|
-
return getMeta(TOOL_METHODS, target) ?? [];
|
|
103
|
-
}
|
|
104
|
-
__name(getToolMethods, "getToolMethods");
|
|
105
|
-
function getToolConfig(target, propertyKey) {
|
|
106
|
-
return getMeta(TOOL_CONFIG, target, propertyKey);
|
|
107
|
-
}
|
|
108
|
-
__name(getToolConfig, "getToolConfig");
|
|
109
|
-
|
|
110
|
-
// src/decorators/hook.ts
|
|
111
|
-
var HOOKS_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:hooks");
|
|
112
|
-
function Hook(point) {
|
|
113
|
-
return (target, propertyKey) => {
|
|
114
|
-
const actualTarget = target.constructor;
|
|
115
|
-
const existing = getMeta(HOOKS_CONFIG, actualTarget) ?? [];
|
|
116
|
-
setMeta(HOOKS_CONFIG, actualTarget, [
|
|
117
|
-
...existing,
|
|
118
|
-
{
|
|
119
|
-
point,
|
|
120
|
-
propertyKey
|
|
121
|
-
}
|
|
122
|
-
]);
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
__name(Hook, "Hook");
|
|
126
|
-
function getHooks(target) {
|
|
127
|
-
return getMeta(HOOKS_CONFIG, target) ?? [];
|
|
128
|
-
}
|
|
129
|
-
__name(getHooks, "getHooks");
|
|
130
|
-
function getHooksByPoint(target, point) {
|
|
131
|
-
return getHooks(target).filter((h) => h.point === point);
|
|
132
|
-
}
|
|
133
|
-
__name(getHooksByPoint, "getHooksByPoint");
|
|
134
|
-
|
|
135
|
-
// src/decorators/model.ts
|
|
136
|
-
import { createDecorator } from "@theokit/http";
|
|
137
|
-
var Model = createDecorator();
|
|
138
|
-
|
|
139
|
-
// src/decorators/artifact.ts
|
|
140
|
-
var ARTIFACT_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:artifact");
|
|
141
|
-
function Artifact(options) {
|
|
142
|
-
return (target, propertyKey) => {
|
|
143
|
-
const actualTarget = target.constructor;
|
|
144
|
-
setMeta(ARTIFACT_CONFIG, actualTarget, {
|
|
145
|
-
streamable: true,
|
|
146
|
-
maxSize: 0,
|
|
147
|
-
...options
|
|
148
|
-
}, propertyKey);
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
__name(Artifact, "Artifact");
|
|
152
|
-
function getArtifactConfig(target, propertyKey) {
|
|
153
|
-
return getMeta(ARTIFACT_CONFIG, target, propertyKey);
|
|
154
|
-
}
|
|
155
|
-
__name(getArtifactConfig, "getArtifactConfig");
|
|
156
|
-
|
|
157
|
-
// src/decorators/observable.ts
|
|
158
|
-
var OBSERVABLE_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:observable");
|
|
159
|
-
function Observable(channel) {
|
|
160
|
-
return (target, propertyKey) => {
|
|
161
|
-
const actualTarget = target.constructor;
|
|
162
|
-
const existing = getMeta(OBSERVABLE_CONFIG, actualTarget) ?? [];
|
|
163
|
-
setMeta(OBSERVABLE_CONFIG, actualTarget, [
|
|
164
|
-
...existing,
|
|
165
|
-
{
|
|
166
|
-
channel,
|
|
167
|
-
propertyKey
|
|
168
|
-
}
|
|
169
|
-
]);
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
__name(Observable, "Observable");
|
|
173
|
-
function getObservables(target) {
|
|
174
|
-
return getMeta(OBSERVABLE_CONFIG, target) ?? [];
|
|
175
|
-
}
|
|
176
|
-
__name(getObservables, "getObservables");
|
|
177
|
-
function getObservableByChannel(target, channel) {
|
|
178
|
-
return getObservables(target).find((o) => o.channel === channel);
|
|
179
|
-
}
|
|
180
|
-
__name(getObservableByChannel, "getObservableByChannel");
|
|
181
|
-
|
|
182
|
-
// src/decorators/sandbox.ts
|
|
183
|
-
import { resolve } from "path";
|
|
184
|
-
var SANDBOX_CONFIG = /* @__PURE__ */ Symbol.for("theokit:agents:sandbox");
|
|
185
|
-
function Sandbox(options) {
|
|
186
|
-
return (target) => {
|
|
187
|
-
setMeta(SANDBOX_CONFIG, target, {
|
|
188
|
-
network: true,
|
|
189
|
-
commandTimeout: 12e4,
|
|
190
|
-
...options
|
|
191
|
-
});
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
__name(Sandbox, "Sandbox");
|
|
195
|
-
function getSandboxConfig(target) {
|
|
196
|
-
return getMeta(SANDBOX_CONFIG, target);
|
|
197
|
-
}
|
|
198
|
-
__name(getSandboxConfig, "getSandboxConfig");
|
|
199
|
-
function isPathAllowed(sandbox, filePath, operation) {
|
|
200
|
-
if (filePath.includes("\0")) return false;
|
|
201
|
-
const normalized = resolve("/", filePath).slice(1);
|
|
202
|
-
const fs = sandbox.filesystem;
|
|
203
|
-
if (!fs) return true;
|
|
204
|
-
if (fs.deny?.some((pattern) => matchGlob(pattern, normalized))) return false;
|
|
205
|
-
const allowList = operation === "read" ? fs.read : fs.write;
|
|
206
|
-
if (!allowList) return true;
|
|
207
|
-
return allowList.some((pattern) => matchGlob(pattern, normalized));
|
|
208
|
-
}
|
|
209
|
-
__name(isPathAllowed, "isPathAllowed");
|
|
210
|
-
var SHELL_METACHARS = /[;|&$`(){}<>\n\r]/;
|
|
211
|
-
function isCommandAllowed(sandbox, command) {
|
|
212
|
-
const cmds = sandbox.commands;
|
|
213
|
-
if (!cmds) return true;
|
|
214
|
-
if (SHELL_METACHARS.test(command)) return false;
|
|
215
|
-
const binary = command.split(/\s+/)[0];
|
|
216
|
-
if (cmds.deny?.some((d) => binary === d || command.startsWith(d + " ") || command === d)) return false;
|
|
217
|
-
if (!cmds.allow) return true;
|
|
218
|
-
return cmds.allow.some((a) => binary === a || command.startsWith(a + " ") || command === a);
|
|
219
|
-
}
|
|
220
|
-
__name(isCommandAllowed, "isCommandAllowed");
|
|
221
|
-
function matchGlob(pattern, filePath) {
|
|
222
|
-
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0GLOBSTAR\0").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\0GLOBSTAR\0/g, ".*");
|
|
223
|
-
const regex = buildGlobRegex(escaped);
|
|
224
|
-
return regex.test(filePath);
|
|
225
|
-
}
|
|
226
|
-
__name(matchGlob, "matchGlob");
|
|
227
|
-
function buildGlobRegex(escapedPattern) {
|
|
228
|
-
return RegExp(`^${escapedPattern}$`);
|
|
229
|
-
}
|
|
230
|
-
__name(buildGlobRegex, "buildGlobRegex");
|
|
231
|
-
|
|
232
|
-
// src/decorators/edit-format.ts
|
|
233
|
-
import { createDecorator as createDecorator2 } from "@theokit/http";
|
|
234
|
-
var EditFormat = createDecorator2();
|
|
235
|
-
|
|
236
|
-
// src/decorators/apply-decorators.ts
|
|
237
|
-
function applyDecorators(...decorators) {
|
|
238
|
-
return (target, propertyKey, descriptor) => {
|
|
239
|
-
for (const decorator of decorators) {
|
|
240
|
-
if (propertyKey !== void 0 && descriptor !== void 0) {
|
|
241
|
-
;
|
|
242
|
-
decorator(target, propertyKey, descriptor);
|
|
243
|
-
} else {
|
|
244
|
-
;
|
|
245
|
-
decorator(target);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
__name(applyDecorators, "applyDecorators");
|
|
251
|
-
export {
|
|
252
|
-
Agent,
|
|
253
|
-
Artifact,
|
|
254
|
-
Audit,
|
|
255
|
-
Budget,
|
|
256
|
-
Checkpoint,
|
|
257
|
-
Compaction,
|
|
258
|
-
ContextWindow,
|
|
259
|
-
EditFormat,
|
|
260
|
-
Gateway,
|
|
261
|
-
Guardrails,
|
|
262
|
-
Hook,
|
|
263
|
-
HumanInTheLoop,
|
|
264
|
-
MCP,
|
|
265
|
-
MainLoop,
|
|
266
|
-
Memory,
|
|
267
|
-
Mixin,
|
|
268
|
-
Model,
|
|
269
|
-
Observable,
|
|
270
|
-
Policy,
|
|
271
|
-
ProjectContext,
|
|
272
|
-
RequiresApproval,
|
|
273
|
-
RequiresCapability,
|
|
274
|
-
Sandbox,
|
|
275
|
-
Skills,
|
|
276
|
-
SubAgents,
|
|
277
|
-
Tool,
|
|
278
|
-
Toolbox,
|
|
279
|
-
Trace,
|
|
280
|
-
applyDecorators,
|
|
281
|
-
getAgentConfig,
|
|
282
|
-
getArtifactConfig,
|
|
283
|
-
getCheckpointConfig,
|
|
284
|
-
getCompactionConfig,
|
|
285
|
-
getContextWindowConfig,
|
|
286
|
-
getGatewayConfig,
|
|
287
|
-
getGuardrailsConfig,
|
|
288
|
-
getHooks,
|
|
289
|
-
getHooksByPoint,
|
|
290
|
-
getHumanInTheLoopConfig,
|
|
291
|
-
getMainLoop,
|
|
292
|
-
getMcpConfig,
|
|
293
|
-
getMemoryConfig,
|
|
294
|
-
getMixins,
|
|
295
|
-
getObservableByChannel,
|
|
296
|
-
getObservables,
|
|
297
|
-
getProjectContextConfig,
|
|
298
|
-
getSandboxConfig,
|
|
299
|
-
getSkillsConfig,
|
|
300
|
-
getSubAgents,
|
|
301
|
-
getToolConfig,
|
|
302
|
-
getToolMethods,
|
|
303
|
-
getToolboxConfig,
|
|
304
|
-
isCommandAllowed,
|
|
305
|
-
isPathAllowed,
|
|
306
|
-
resolveSessionId
|
|
307
|
-
};
|
|
308
|
-
//# sourceMappingURL=decorators.js.map
|
package/dist/decorators.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/decorators/main-loop.ts","../src/decorators/tool.ts","../src/decorators/hook.ts","../src/decorators/model.ts","../src/decorators/artifact.ts","../src/decorators/observable.ts","../src/decorators/sandbox.ts","../src/decorators/edit-format.ts","../src/decorators/apply-decorators.ts"],"sourcesContent":["/**\n * @MainLoop() — marks the execution entry point of an agent.\n *\n * Only one @MainLoop per agent class. Second application overwrites (last-wins, with warning).\n */\nimport { setMeta, getMeta, AGENT_MAIN_LOOP } from '../metadata/index.js'\nimport type { MainLoopOptions, MainLoopMeta } from '../types.js'\n\nexport function MainLoop(options: MainLoopOptions = {}): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, actualTarget)\n if (existing) {\n console.warn(\n `[@theokit/agents] ${actualTarget.name}: @MainLoop() already declared on '${String(existing.propertyKey)}'. Overwriting with '${String(propertyKey)}'.`,\n )\n }\n const meta: MainLoopMeta = {\n propertyKey,\n strategy: options.strategy ?? 'simple-chat',\n maxIterations: options.maxIterations,\n timeoutMs: options.timeoutMs,\n }\n setMeta(AGENT_MAIN_LOOP, actualTarget, meta)\n }\n}\n\nexport function getMainLoop(target: Function): MainLoopMeta | undefined {\n return getMeta<MainLoopMeta>(AGENT_MAIN_LOOP, target)\n}\n","/**\n * @Toolbox() + @Tool() — group and define agent tools.\n *\n * @Toolbox({ namespace }) is a class decorator that groups related tools.\n * @Tool({ name, description, input, risk }) is a method decorator compiled to defineTool().\n *\n * @UseGuards on @Toolbox applies to ALL tools (per ADR D7).\n */\nimport { setMeta, getMeta, TOOLBOX_CONFIG, TOOL_CONFIG, TOOL_METHODS } from '../metadata/index.js'\nimport type { ToolboxOptions, ToolOptions } from '../types.js'\n\n/**\n * Convention: TaskTools → namespace: 'tasks', ProjectTools → namespace: 'projects'\n * Strips \"Tools\" suffix, converts to kebab-case.\n */\nfunction inferNamespace(className: string): string {\n const stripped = className.replace(/Tools$/, '')\n return stripped\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase()\n}\n\nexport function Toolbox(options: ToolboxOptions = {}): ClassDecorator {\n return (target: Function) => {\n const ns = options.namespace ?? inferNamespace(target.name)\n setMeta(TOOLBOX_CONFIG, target, { ...options, namespace: ns })\n }\n}\n\nexport function Tool(options: ToolOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(TOOL_CONFIG, actualTarget, options, propertyKey)\n // Accumulate tool methods list\n const existing = getMeta<(string | symbol)[]>(TOOL_METHODS, actualTarget) ?? []\n setMeta(TOOL_METHODS, actualTarget, [...existing, propertyKey])\n }\n}\n\nexport function getToolboxConfig(target: Function): ToolboxOptions | undefined {\n return getMeta<ToolboxOptions>(TOOLBOX_CONFIG, target)\n}\n\nexport function getToolMethods(target: Function): (string | symbol)[] {\n return getMeta<(string | symbol)[]>(TOOL_METHODS, target) ?? []\n}\n\nexport function getToolConfig(\n target: Function,\n propertyKey: string | symbol,\n): ToolOptions | undefined {\n return getMeta<ToolOptions>(TOOL_CONFIG, target, propertyKey)\n}\n","/**\n * @Hook() — lifecycle hooks WITHIN the agent loop.\n *\n * Unlike HTTP interceptors (which wrap the entire handler), hooks fire at\n * specific points during the agent's reasoning → tool → response cycle.\n *\n * Hook points:\n * - 'before:llm-call' — before each LLM API call\n * - 'after:llm-call' — after each LLM response\n * - 'before:tool-call' — before each tool execution\n * - 'after:tool-call' — after each tool result\n * - 'on:iteration' — at each loop iteration\n * - 'on:complete' — when the agent produces a final answer\n * - 'on:error' — when the agent encounters an error\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n *\n * @Hook('before:llm-call')\n * async injectContext(ctx: HookContext) {\n * ctx.appendSystemPrompt(`Time: ${new Date().toISOString()}`)\n * }\n *\n * @Hook('after:tool-call')\n * async trackCost(ctx: HookContext) {\n * await billing.track(ctx.toolCall!.name, ctx.toolCall!.durationMs)\n * }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst HOOKS_CONFIG = Symbol.for('theokit:agents:hooks')\n\nexport type HookPoint =\n | 'before:llm-call'\n | 'after:llm-call'\n | 'before:tool-call'\n | 'after:tool-call'\n | 'on:iteration'\n | 'on:complete'\n | 'on:error'\n\nexport interface HookEntry {\n point: HookPoint\n propertyKey: string | symbol\n}\n\nexport function Hook(point: HookPoint): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<HookEntry[]>(HOOKS_CONFIG, actualTarget) ?? []\n setMeta(HOOKS_CONFIG, actualTarget, [...existing, { point, propertyKey }])\n }\n}\n\nexport function getHooks(target: Function): HookEntry[] {\n return getMeta<HookEntry[]>(HOOKS_CONFIG, target) ?? []\n}\n\nexport function getHooksByPoint(target: Function, point: HookPoint): HookEntry[] {\n return getHooks(target).filter((h) => h.point === point)\n}\n","/**\n * @Model() — override the LLM model at agent or tool level.\n *\n * Hierarchical resolution via Reflector.getAllAndOverride:\n * tool @Model > agent @Model > @Agent({ model }) > config default\n *\n * This is a MODEL selector, not a PROVIDER selector. Provider routing\n * (which API key, which endpoint, fallback chains) lives in theo.config.ts\n * as runtime configuration — not in decorators.\n *\n * @example\n * ```ts\n * @Agent({ name: 'support', route: '/support' })\n * @Model('claude-sonnet-4-5-20250929') // default for all tools\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n * }\n *\n * @Toolbox({ namespace: 'code' })\n * class CodeTools {\n * @Tool({ name: 'generate', description: 'Generate code', input: z.object({...}) })\n * @Model('claude-opus-4-6') // this tool needs the most capable model\n * async generate() { ... }\n *\n * @Tool({ name: 'lint', description: 'Lint code', input: z.object({...}) })\n * // no @Model — inherits from agent level\n * async lint() { ... }\n * }\n * ```\n */\nimport { createDecorator } from '@theokit/http'\n\n/** Override the LLM model for an agent class or a specific tool method. */\nexport const Model = createDecorator<string>()\n","/**\n * @Artifact() — marks a tool as producing structured output artifacts.\n *\n * Artifacts are SEPARATE from text responses. When a tool produces an artifact\n * (code file, document, diagram, JSON data), the SSE stream emits artifact_start\n * + artifact_chunk events alongside text_delta events.\n *\n * Inspired by assistant-ui's A2AArtifact pattern where artifacts have their own\n * lifecycle (start → chunks → complete) independent of message content.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'code' })\n * class CodeTools {\n * @Tool({ name: 'generate', description: 'Generate code', input: z.object({...}) })\n * @Artifact({ mimeType: 'text/typescript', streamable: true })\n * async generate(input: { spec: string }): Promise<ArtifactResult> {\n * return {\n * content: generatedCode,\n * filename: 'component.tsx',\n * metadata: { language: 'typescript', loc: 42 },\n * }\n * }\n * }\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst ARTIFACT_CONFIG = Symbol.for('theokit:agents:artifact')\n\nexport interface ArtifactOptions {\n /** MIME type of the artifact output. */\n mimeType: string\n /** Whether the artifact can be streamed in chunks (default: true). */\n streamable?: boolean\n /** Maximum size in bytes (0 = no limit). */\n maxSize?: number\n}\n\n/** Return type for tools decorated with @Artifact. */\nexport interface ArtifactResult {\n /** The artifact content (string for text, Buffer for binary). */\n content: string\n /** Optional filename hint for the client. */\n filename?: string\n /** Optional metadata attached to the artifact. */\n metadata?: Record<string, unknown>\n}\n\nexport function Artifact(options: ArtifactOptions): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n setMeta(ARTIFACT_CONFIG, actualTarget, { streamable: true, maxSize: 0, ...options }, propertyKey)\n }\n}\n\nexport function getArtifactConfig(\n target: Function,\n propertyKey: string | symbol,\n): ArtifactOptions | undefined {\n return getMeta<ArtifactOptions>(ARTIFACT_CONFIG, target, propertyKey)\n}\n","/**\n * @Observable() — exposes agent internal state as a real-time stream.\n *\n * Clients subscribe to named observables to monitor agent execution in real-time:\n * token usage, cost, iteration progress, pending approvals, retrieved facts.\n *\n * Inspired by Liveblocks' Presence pattern and tRPC subscriptions. The agent\n * pushes state updates via SSE alongside response events — clients are never\n * \"blind\" during long-running agent operations.\n *\n * @example\n * ```ts\n * @Agent({ name: 'research', route: '/research' })\n * class ResearchAgent {\n * @MainLoop()\n * async run() {}\n *\n * @Observable('metrics')\n * getMetrics(ctx: AgentContext): AgentMetrics {\n * return {\n * tokensUsed: ctx.tokenCount,\n * costUsd: ctx.costUsd,\n * iteration: ctx.iteration,\n * pendingApprovals: ctx.pendingApprovals.length,\n * }\n * }\n * }\n *\n * // SSE emits: { type: 'state_update', channel: 'metrics', data: {...} }\n * // Client: eventSource.addEventListener('state_update', handler)\n * ```\n */\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst OBSERVABLE_CONFIG = Symbol.for('theokit:agents:observable')\n\nexport interface ObservableEntry {\n channel: string\n propertyKey: string | symbol\n}\n\nexport function Observable(channel: string): MethodDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const actualTarget = target.constructor\n const existing = getMeta<ObservableEntry[]>(OBSERVABLE_CONFIG, actualTarget) ?? []\n setMeta(OBSERVABLE_CONFIG, actualTarget, [...existing, { channel, propertyKey }])\n }\n}\n\nexport function getObservables(target: Function): ObservableEntry[] {\n return getMeta<ObservableEntry[]>(OBSERVABLE_CONFIG, target) ?? []\n}\n\nexport function getObservableByChannel(target: Function, channel: string): ObservableEntry | undefined {\n return getObservables(target).find((o) => o.channel === channel)\n}\n","/**\n * @Sandbox() — declares file/command permission scope for code assistant agents.\n *\n * Controls what the agent can read, write, and execute. The runtime enforces\n * these permissions BEFORE tool execution — a tool that tries to write to a\n * denied path gets a typed error, not a crash.\n *\n * Inspired by Claude Code's permission system (allow/deny per tool + path).\n *\n * @example\n * ```ts\n * @Agent({ name: 'coder', route: '/agents/coder' })\n * @Sandbox({\n * filesystem: {\n * read: ['src/**', 'tests/**', 'package.json'],\n * write: ['src/**', 'tests/**'],\n * deny: ['node_modules/**', '.env', '*.key'],\n * },\n * commands: {\n * allow: ['npm test', 'tsc --noEmit', 'git diff'],\n * deny: ['rm -rf', 'git push --force', 'npm publish'],\n * },\n * network: false,\n * })\n * class CoderAgent { ... }\n * ```\n */\nimport { resolve } from 'node:path'\n\nimport { setMeta, getMeta } from '../metadata/index.js'\n\nconst SANDBOX_CONFIG = Symbol.for('theokit:agents:sandbox')\n\nexport interface FilesystemPermissions {\n /** Glob patterns for allowed read paths. */\n read?: string[]\n /** Glob patterns for allowed write paths. */\n write?: string[]\n /** Glob patterns for DENIED paths (overrides read/write). */\n deny?: string[]\n}\n\nexport interface CommandPermissions {\n /** Command prefixes allowed to execute. */\n allow?: string[]\n /** Command prefixes denied (overrides allow). */\n deny?: string[]\n}\n\nexport interface SandboxOptions {\n /** Filesystem read/write permissions. */\n filesystem?: FilesystemPermissions\n /** Shell command execution permissions. */\n commands?: CommandPermissions\n /** Allow outbound network from tools (default: true). */\n network?: boolean\n /** Maximum execution time per command in ms (default: 120_000). */\n commandTimeout?: number\n /** Working directory root (default: process.cwd()). */\n cwd?: string\n}\n\nexport function Sandbox(options: SandboxOptions): ClassDecorator {\n return (target: Function) => {\n setMeta(SANDBOX_CONFIG, target, {\n network: true,\n commandTimeout: 120_000,\n ...options,\n })\n }\n}\n\nexport function getSandboxConfig(target: Function): SandboxOptions | undefined {\n return getMeta<SandboxOptions>(SANDBOX_CONFIG, target)\n}\n\n/**\n * Check if a file path is allowed for the given operation.\n * Deny patterns always win over allow patterns.\n *\n * Security: normalizes paths to prevent traversal (../) and rejects null bytes.\n */\nexport function isPathAllowed(\n sandbox: SandboxOptions,\n filePath: string,\n operation: 'read' | 'write',\n): boolean {\n // EC-2: null byte injection — reject before any processing\n if (filePath.includes('\\x00')) return false\n\n // Path traversal fix: normalize to remove ../ sequences\n const normalized = resolve('/', filePath).slice(1)\n\n const fs = sandbox.filesystem\n if (!fs) return true // no filesystem restrictions\n\n // Deny always wins\n if (fs.deny?.some((pattern) => matchGlob(pattern, normalized))) return false\n\n const allowList = operation === 'read' ? fs.read : fs.write\n if (!allowList) return true // no explicit allow = allow all (minus deny)\n\n return allowList.some((pattern) => matchGlob(pattern, normalized))\n}\n\n/**\n * Shell metacharacters that indicate injection attempts.\n * EC-1: includes redirect operators (>, <) and newlines (\\n, \\r).\n */\nconst SHELL_METACHARS = /[;|&$`(){}<>\\n\\r]/\n\n/**\n * Check if a command is allowed to execute.\n * Deny patterns always win. Rejects shell metacharacters.\n *\n * Security: tokenizes command to match binary name, not arbitrary prefix.\n */\nexport function isCommandAllowed(sandbox: SandboxOptions, command: string): boolean {\n const cmds = sandbox.commands\n if (!cmds) return true\n\n // Reject any command with shell metacharacters (injection prevention)\n if (SHELL_METACHARS.test(command)) return false\n\n // Extract binary name (first whitespace-delimited token)\n const binary = command.split(/\\s+/)[0]\n\n // Deny always wins — check both exact binary match and full command prefix\n if (cmds.deny?.some((d) => binary === d || command.startsWith(d + ' ') || command === d))\n return false\n\n if (!cmds.allow) return true\n\n // Allow: match exact binary or full command prefix\n return cmds.allow.some((a) => binary === a || command.startsWith(a + ' ') || command === a)\n}\n\n/**\n * Glob matcher — converts glob pattern to regex at call time.\n * Uses a pre-built RegExp from a sanitized pattern string.\n * Supports *, **, and ? glob characters.\n */\nfunction matchGlob(pattern: string, filePath: string): boolean {\n // Escape all regex specials except glob chars (* and ?)\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '\\0GLOBSTAR\\0')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\?/g, '[^/]')\n .replace(/\\0GLOBSTAR\\0/g, '.*')\n // Pre-compile regex outside of hot path (pattern is controlled by developer, not user input)\n const regex = buildGlobRegex(escaped)\n return regex.test(filePath)\n}\n\n/** Build a regex from a pre-escaped glob pattern string. */\nfunction buildGlobRegex(escapedPattern: string): RegExp {\n return RegExp(`^${escapedPattern}$`)\n}\n","/**\n * @EditFormat() — declares how a tool outputs file edits.\n *\n * Code assistants show DIFFS, not entire files. This decorator tells the\n * runtime which format the tool produces so the SSE stream emits the\n * correct `file_edit` event type.\n *\n * @example\n * ```ts\n * @Toolbox({ namespace: 'editor' })\n * class EditorTools {\n * @Tool({ name: 'edit', description: 'Edit file', input: editSchema })\n * @EditFormat('search-replace')\n * async edit(input: { file: string; search: string; replace: string }) {\n * return { file: input.file, search: input.search, replace: input.replace }\n * }\n *\n * @Tool({ name: 'write', description: 'Write file', input: writeSchema })\n * @EditFormat('full-file')\n * async write(input: { file: string; content: string }) {\n * return { file: input.file, content: input.content }\n * }\n * }\n * ```\n */\nimport { createDecorator } from '@theokit/http'\n\nexport type EditFormatType =\n | 'search-replace' // { file, search, replace } — Claude Code Edit pattern\n | 'unified-diff' // Standard unified diff format\n | 'full-file' // Complete file content (Write pattern)\n | 'line-range' // { file, startLine, endLine, content }\n\n/** Declare the edit format a tool produces. */\nexport const EditFormat = createDecorator<EditFormatType>()\n","/**\n * applyDecorators() — compose multiple decorators into a single reusable decorator.\n *\n * NestJS-compatible utility. Enables creating \"preset\" decorators that bundle\n * common configurations (auth + throttle + trace + memory + ...) into one decorator.\n *\n * @example\n * ```ts\n * // Create a reusable preset\n * const ProductionAgent = (name: string, route: string) => applyDecorators(\n * Agent({ name, route, model: 'claude-sonnet-4-5-20250929' }),\n * UseGuards(AuthGuard, TenantGuard),\n * Throttle({ limit: 30, ttl: 60_000 }),\n * Budget({ maxCostUsd: 5.00 }),\n * Trace(true),\n * )\n *\n * // Apply preset to any agent\n * @ProductionAgent('support', '/api/agents/support')\n * class SupportAgent {\n * @MainLoop()\n * async run() {}\n * }\n * ```\n */\n\ntype AnyDecorator = ClassDecorator | MethodDecorator | PropertyDecorator\n\n/**\n * Compose multiple decorators into a single decorator.\n * Works for both class-level and method-level decorators.\n */\nexport function applyDecorators(\n ...decorators: AnyDecorator[]\n): ClassDecorator & MethodDecorator {\n return (\n target: object | Function,\n propertyKey?: string | symbol,\n descriptor?: PropertyDescriptor,\n ) => {\n for (const decorator of decorators) {\n if (propertyKey !== undefined && descriptor !== undefined) {\n // Method-level\n ;(decorator as MethodDecorator)(target, propertyKey, descriptor)\n } else {\n // Class-level\n ;(decorator as ClassDecorator)(target as Function)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,SAASA,SAASC,UAA2B,CAAC,GAAC;AACpD,SAAO,CAACC,QAAgBC,gBAAAA;AACtB,UAAMC,eAAeF,OAAO;AAC5B,UAAMG,WAAWC,QAAsBC,iBAAiBH,YAAAA;AACxD,QAAIC,UAAU;AACZG,cAAQC,KACN,qBAAqBL,aAAaM,IAAI,sCAAsCC,OAAON,SAASF,WAAW,CAAA,wBAAyBQ,OAAOR,WAAAA,CAAAA,IAAgB;IAE3J;AACA,UAAMS,OAAqB;MACzBT;MACAU,UAAUZ,QAAQY,YAAY;MAC9BC,eAAeb,QAAQa;MACvBC,WAAWd,QAAQc;IACrB;AACAC,YAAQT,iBAAiBH,cAAcQ,IAAAA;EACzC;AACF;AAjBgBZ;AAmBT,SAASiB,YAAYf,QAAgB;AAC1C,SAAOI,QAAsBC,iBAAiBL,MAAAA;AAChD;AAFgBe;;;ACZhB,SAASC,eAAeC,WAAiB;AACvC,QAAMC,WAAWD,UAAUE,QAAQ,UAAU,EAAA;AAC7C,SAAOD,SACJC,QAAQ,sBAAsB,OAAA,EAC9BA,QAAQ,wBAAwB,OAAA,EAChCC,YAAW;AAChB;AANSJ;AAQF,SAASK,QAAQC,UAA0B,CAAC,GAAC;AAClD,SAAO,CAACC,WAAAA;AACN,UA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,cAAAA,GAAiB;AACrC;AAFSD;;;ACnIT,SAASG,mBAAAA,wBAAuB;AASzB,IAAMC,aAAaD,iBAAAA;;;ACFnB,SAASE,mBACXC,YAA0B;AAE7B,SAAO,CACLC,QACAC,aACAC,eAAAA;AAEA,eAAWC,aAAaJ,YAAY;AAClC,UAAIE,gBAAgBG,UAAaF,eAAeE,QAAW;;AAEvDD,kBAA8BH,QAAQC,aAAaC,UAAAA;MACvD,OAAO;;AAEHC,kBAA6BH,MAAAA;MACjC;IACF;EACF;AACF;AAlBgBF;","names":["MainLoop","options","target","propertyKey","actualTarget","existing","getMeta","AGENT_MAIN_LOOP","console","warn","name","String","meta","strategy","maxIterations","timeoutMs","setMeta","getMainLoop","inferNamespace","className","stripped","replace","toLowerCase","Toolbox","options","target","ns","namespace","name","setMeta","TOOLBOX_CONFIG","Tool","propertyKey","actualTarget","TOOL_CONFIG","existing","getMeta","TOOL_METHODS","getToolboxConfig","getToolMethods","getToolConfig","HOOKS_CONFIG","Symbol","for","Hook","point","target","propertyKey","actualTarget","existing","getMeta","setMeta","getHooks","getHooksByPoint","filter","h","createDecorator","Model","ARTIFACT_CONFIG","Symbol","for","Artifact","options","target","propertyKey","actualTarget","setMeta","streamable","maxSize","getArtifactConfig","getMeta","OBSERVABLE_CONFIG","Symbol","for","Observable","channel","target","propertyKey","actualTarget","existing","getMeta","setMeta","getObservables","getObservableByChannel","find","o","resolve","SANDBOX_CONFIG","Symbol","for","Sandbox","options","target","setMeta","network","commandTimeout","getSandboxConfig","getMeta","isPathAllowed","sandbox","filePath","operation","includes","normalized","resolve","slice","fs","filesystem","deny","some","pattern","matchGlob","allowList","read","write","SHELL_METACHARS","isCommandAllowed","command","cmds","commands","test","binary","split","d","startsWith","allow","a","escaped","replace","regex","buildGlobRegex","escapedPattern","RegExp","createDecorator","EditFormat","applyDecorators","decorators","target","propertyKey","descriptor","decorator","undefined"]}
|
package/dist/types-DVA4LQsA.d.ts
DELETED
|
@@ -1,313 +0,0 @@
|
|
|
1
|
-
import { SystemPromptResolver } from '@theokit/sdk';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Provider-agnostic extended-thinking knob (M1 reasoning-visibility). The common set autocompletes;
|
|
6
|
-
* `(string & {})` accepts provider-specific values forward-compat (mirrors `AgentRunErrorCode`) — the
|
|
7
|
-
* SDK validates the value against the model's catalog. Defined in this leaf module so every layer
|
|
8
|
-
* (`@Agent` config, compiler, runner, sdk-adapter) imports it without an import cycle.
|
|
9
|
-
*/
|
|
10
|
-
type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | (string & {});
|
|
11
|
-
/** Configuration stored by @Agent() decorator. */
|
|
12
|
-
interface AgentOptions {
|
|
13
|
-
/** Unique agent name (kebab-case). */
|
|
14
|
-
name: string;
|
|
15
|
-
/** HTTP route prefix (e.g., '/api/agents/support'). */
|
|
16
|
-
route: string;
|
|
17
|
-
/** LLM model identifier (e.g., 'claude-sonnet-4-5-20250929'). */
|
|
18
|
-
model?: string;
|
|
19
|
-
/** Extended-thinking effort; mapped to the SDK `ModelSelection.params` so the provider reasons. */
|
|
20
|
-
reasoningEffort?: ReasoningEffort;
|
|
21
|
-
/**
|
|
22
|
-
* Opt-in (default false): convert inline `<think>…</think>` in the text stream into `thinking`
|
|
23
|
-
* events (M2) — for models that emit reasoning as inline tags (qwen/deepseek) rather than via a
|
|
24
|
-
* native reasoning param. Off by default since a code assistant may emit literal `<think>` in text.
|
|
25
|
-
*/
|
|
26
|
-
parseThinkTags?: boolean;
|
|
27
|
-
/**
|
|
28
|
-
* Opt-in (default false): strip a leaked Hermes `<function=…></tool_call>` tool-call dialect out of
|
|
29
|
-
* the visible text (theocode#32) — for models (qwen/qwen3-coder) that intermittently emit tool calls
|
|
30
|
-
* as text instead of native `tool_calls`. Off by default since a code assistant may emit a literal
|
|
31
|
-
* `<function=` in answer/code text. Sibling of {@link parseThinkTags}.
|
|
32
|
-
*/
|
|
33
|
-
stripToolDialect?: boolean;
|
|
34
|
-
/**
|
|
35
|
-
* Opt-in (default false): recover a leaked Hermes `<function=…></tool_call>` tool-call dialect so the
|
|
36
|
-
* call actually EXECUTES (theokit#58 follow-up). Where {@link stripToolDialect} only hides the leaked
|
|
37
|
-
* block from the visible text, this enables the SDK's `extractToolCallsFromContent` on the chat route,
|
|
38
|
-
* so a `chat_completions` finish with ZERO native `tool_calls` has its text scanned for the dialect and
|
|
39
|
-
* any recovered calls are dispatched by the loop. For models (qwen/qwen3-coder via OpenRouter) that
|
|
40
|
-
* leak tool calls as text. Off by default (a code assistant may print a literal `<function=`); fail-open.
|
|
41
|
-
* Has effect only when {@link AgentOptions} routes a provider via `providers.routes`. Sibling of
|
|
42
|
-
* {@link stripToolDialect} — typically enabled together.
|
|
43
|
-
*/
|
|
44
|
-
recoverLeakedToolCalls?: boolean;
|
|
45
|
-
/** Enable SSE streaming (default: true). */
|
|
46
|
-
stream?: boolean;
|
|
47
|
-
/** Maximum loop iterations before forcing a terminal response. */
|
|
48
|
-
maxIterations?: number;
|
|
49
|
-
/** Timeout in milliseconds for the entire agent run. */
|
|
50
|
-
timeoutMs?: number;
|
|
51
|
-
/**
|
|
52
|
-
* System prompt for the agent. Either a static string OR a
|
|
53
|
-
* {@link SystemPromptResolver} computed per request (V4-L.1, Axis-B) — the SDK
|
|
54
|
-
* invokes the resolver each send with the run's `SystemPromptContext` (cwd, etc.).
|
|
55
|
-
*/
|
|
56
|
-
systemPrompt?: string | SystemPromptResolver;
|
|
57
|
-
}
|
|
58
|
-
/** Configuration stored by @MainLoop() decorator. */
|
|
59
|
-
interface MainLoopOptions {
|
|
60
|
-
/** Execution strategy. */
|
|
61
|
-
strategy?: 'simple-chat' | 'plan-act-reflect' | 'react';
|
|
62
|
-
/** Maximum iterations for this loop. */
|
|
63
|
-
maxIterations?: number;
|
|
64
|
-
/** Timeout in milliseconds. */
|
|
65
|
-
timeoutMs?: number;
|
|
66
|
-
}
|
|
67
|
-
/** Internal representation of a resolved @MainLoop. */
|
|
68
|
-
interface MainLoopMeta {
|
|
69
|
-
propertyKey: string | symbol;
|
|
70
|
-
strategy: 'simple-chat' | 'plan-act-reflect' | 'react';
|
|
71
|
-
maxIterations?: number;
|
|
72
|
-
timeoutMs?: number;
|
|
73
|
-
}
|
|
74
|
-
/** Configuration stored by @Toolbox() decorator. */
|
|
75
|
-
interface ToolboxOptions {
|
|
76
|
-
/** Namespace prefix for all tools in this toolbox (e.g., 'support'). */
|
|
77
|
-
namespace?: string;
|
|
78
|
-
}
|
|
79
|
-
/** Configuration stored by @Tool() decorator. */
|
|
80
|
-
interface ToolOptions {
|
|
81
|
-
/** Tool name (surfaced to LLM). */
|
|
82
|
-
name: string;
|
|
83
|
-
/** LLM-facing description. */
|
|
84
|
-
description: string;
|
|
85
|
-
/** Zod input schema — compiled to JSON Schema via defineTool(). */
|
|
86
|
-
input: z.ZodType;
|
|
87
|
-
/** Risk level (informational — feeds manifest + UI). */
|
|
88
|
-
risk?: 'low' | 'medium' | 'high';
|
|
89
|
-
}
|
|
90
|
-
/** Budget configuration for @Budget() decorator. */
|
|
91
|
-
interface BudgetOptions {
|
|
92
|
-
/** Maximum cost in USD for this scope. */
|
|
93
|
-
maxCostUsd: number;
|
|
94
|
-
/** Rolling window for budget tracking. */
|
|
95
|
-
window?: 'daily' | 'monthly';
|
|
96
|
-
}
|
|
97
|
-
/** Approval configuration for @RequiresApproval() decorator. */
|
|
98
|
-
interface ApprovalOptions {
|
|
99
|
-
/** Reason shown to the approver. */
|
|
100
|
-
reason: string;
|
|
101
|
-
}
|
|
102
|
-
/** Policy handler function type. */
|
|
103
|
-
type PolicyHandler = (user: {
|
|
104
|
-
roles: string[];
|
|
105
|
-
}) => boolean;
|
|
106
|
-
|
|
107
|
-
type CheckpointStrategy = 'after-tool-call' | 'after-iteration' | 'manual';
|
|
108
|
-
type CheckpointStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis';
|
|
109
|
-
interface CheckpointOptions {
|
|
110
|
-
/** Where to persist checkpoints. */
|
|
111
|
-
storage?: CheckpointStorage;
|
|
112
|
-
/** When to auto-checkpoint (default: 'after-tool-call'). */
|
|
113
|
-
strategy?: CheckpointStrategy;
|
|
114
|
-
/** Maximum checkpoints to retain per run (rolling window). */
|
|
115
|
-
maxCheckpoints?: number;
|
|
116
|
-
/** Time-to-live in ms before checkpoints expire (default: 3_600_000 = 1h). */
|
|
117
|
-
ttl?: number;
|
|
118
|
-
}
|
|
119
|
-
/** Serializable checkpoint state. */
|
|
120
|
-
interface CheckpointState {
|
|
121
|
-
id: string;
|
|
122
|
-
runId: string;
|
|
123
|
-
agentName: string;
|
|
124
|
-
step: number;
|
|
125
|
-
messages: unknown[];
|
|
126
|
-
toolResults: unknown[];
|
|
127
|
-
createdAt: number;
|
|
128
|
-
resumeToken: string;
|
|
129
|
-
}
|
|
130
|
-
declare function Checkpoint(options?: CheckpointOptions): ClassDecorator;
|
|
131
|
-
declare function getCheckpointConfig(target: Function): CheckpointOptions | undefined;
|
|
132
|
-
|
|
133
|
-
/** Stored `@Compaction` declaration (resolved + validated at `AgentRunner.build()`). */
|
|
134
|
-
interface CompactionDecoratorConfig {
|
|
135
|
-
/** Strategy name (e.g. `'token-budget'`). Validated at resolve time. */
|
|
136
|
-
name: string;
|
|
137
|
-
/** Token budget for `'token-budget'`. Required at resolve time (EC-2). */
|
|
138
|
-
keepTokens?: number;
|
|
139
|
-
}
|
|
140
|
-
declare function Compaction(name: string, options?: {
|
|
141
|
-
keepTokens?: number;
|
|
142
|
-
}): ClassDecorator;
|
|
143
|
-
declare function getCompactionConfig(target: Function): CompactionDecoratorConfig | undefined;
|
|
144
|
-
|
|
145
|
-
type ContextCompactionStrategy = 'truncate-oldest' | 'summarize-oldest' | 'sliding-window' | 'priority-based';
|
|
146
|
-
interface ContextWindowOptions {
|
|
147
|
-
/** Maximum tokens before compaction triggers. */
|
|
148
|
-
maxTokens?: number;
|
|
149
|
-
/** How to compact when maxTokens is exceeded. */
|
|
150
|
-
compactionStrategy?: ContextCompactionStrategy;
|
|
151
|
-
/** Always preserve the system prompt during compaction (default: true). */
|
|
152
|
-
preserveSystemPrompt?: boolean;
|
|
153
|
-
/** Number of recent messages to always keep intact (default: 10). */
|
|
154
|
-
preserveLastN?: number;
|
|
155
|
-
/** Keep all tool results even during compaction (default: true). */
|
|
156
|
-
preserveToolResults?: boolean;
|
|
157
|
-
}
|
|
158
|
-
declare function ContextWindow(options?: ContextWindowOptions): ClassDecorator;
|
|
159
|
-
declare function getContextWindowConfig(target: Function): ContextWindowOptions | undefined;
|
|
160
|
-
|
|
161
|
-
type PlatformName = 'telegram' | 'discord' | 'slack' | 'whatsapp' | 'teams' | 'email' | 'sms' | 'mattermost' | 'line' | 'matrix';
|
|
162
|
-
type SessionStrategy = 'per-user' | 'per-channel' | 'per-thread';
|
|
163
|
-
interface GatewayOptions {
|
|
164
|
-
/** Platform adapters this agent supports. */
|
|
165
|
-
platforms: PlatformName[];
|
|
166
|
-
/** How to resolve agentId from inbound events (default: 'per-user'). */
|
|
167
|
-
sessionStrategy?: SessionStrategy;
|
|
168
|
-
/** Auto-start typing indicator while agent processes (default: true). */
|
|
169
|
-
typing?: boolean;
|
|
170
|
-
}
|
|
171
|
-
declare function Gateway(options: GatewayOptions): ClassDecorator;
|
|
172
|
-
declare function getGatewayConfig(target: Function): GatewayOptions | undefined;
|
|
173
|
-
/**
|
|
174
|
-
* Resolve a stable agentId from a platform event based on the session strategy.
|
|
175
|
-
*
|
|
176
|
-
* Mirrors @theokit/gateway SessionRouter.defaultStrategy() but is configurable
|
|
177
|
-
* via the @Gateway decorator.
|
|
178
|
-
*/
|
|
179
|
-
declare function resolveSessionId(strategy: SessionStrategy, platform: string, sender: {
|
|
180
|
-
id: string;
|
|
181
|
-
}, channel: {
|
|
182
|
-
id: string;
|
|
183
|
-
type: 'dm' | 'group' | 'thread';
|
|
184
|
-
topicId?: string;
|
|
185
|
-
}): string;
|
|
186
|
-
|
|
187
|
-
type TimeoutAction = 'abort' | 'proceed' | 'retry';
|
|
188
|
-
interface HumanInTheLoopOptions {
|
|
189
|
-
/** Question shown to the human approver. */
|
|
190
|
-
question: string;
|
|
191
|
-
/** Timeout in milliseconds before onTimeout fires (default: 300_000 = 5 min). */
|
|
192
|
-
timeout?: number;
|
|
193
|
-
/** Action when timeout expires (default: 'abort'). */
|
|
194
|
-
onTimeout?: TimeoutAction;
|
|
195
|
-
/** Show the tool input to the approver (default: true). */
|
|
196
|
-
showInput?: boolean;
|
|
197
|
-
/**
|
|
198
|
-
* M20 — an optional JSON-schema descriptor of the custom payload the approver may attach (edited
|
|
199
|
-
* args, a review note). Carried into the `approval_required` event + `GET /approvals` so the UI
|
|
200
|
-
* knows what to collect. A plain JSON object, not a live Zod schema (keeps the wire serializable).
|
|
201
|
-
*/
|
|
202
|
-
payloadSchema?: Record<string, unknown>;
|
|
203
|
-
}
|
|
204
|
-
declare function HumanInTheLoop(options: HumanInTheLoopOptions): MethodDecorator;
|
|
205
|
-
declare function getHumanInTheLoopConfig(target: Function, propertyKey: string | symbol): HumanInTheLoopOptions | undefined;
|
|
206
|
-
|
|
207
|
-
interface McpServerConfig {
|
|
208
|
-
/** Command to start the MCP server. */
|
|
209
|
-
command: string;
|
|
210
|
-
/** Arguments passed to the command. */
|
|
211
|
-
args?: string[];
|
|
212
|
-
/** Environment variables for the server process. */
|
|
213
|
-
env?: Record<string, string>;
|
|
214
|
-
/** Working directory for the server process. */
|
|
215
|
-
cwd?: string;
|
|
216
|
-
}
|
|
217
|
-
type McpServersMap = Record<string, McpServerConfig>;
|
|
218
|
-
declare function MCP(servers: McpServersMap): ClassDecorator;
|
|
219
|
-
declare function getMcpConfig(target: Function): McpServersMap | undefined;
|
|
220
|
-
|
|
221
|
-
type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0';
|
|
222
|
-
type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global';
|
|
223
|
-
interface MemoryOptions {
|
|
224
|
-
/** Memory provider backend. */
|
|
225
|
-
provider?: MemoryProvider;
|
|
226
|
-
/** Enable semantic search via embeddings. */
|
|
227
|
-
embeddings?: boolean;
|
|
228
|
-
/** Enable full-text search (FTS5). */
|
|
229
|
-
fts?: boolean;
|
|
230
|
-
/** Memory isolation scope (default: 'per-user'). */
|
|
231
|
-
scope?: MemoryScope;
|
|
232
|
-
/** Maximum facts to retain per scope (0 = unlimited). */
|
|
233
|
-
maxFacts?: number;
|
|
234
|
-
}
|
|
235
|
-
declare function Memory(options?: MemoryOptions): ClassDecorator;
|
|
236
|
-
declare function getMemoryConfig(target: Function): MemoryOptions | undefined;
|
|
237
|
-
|
|
238
|
-
type IndexStrategy = 'tree-sitter' | 'regex' | 'none';
|
|
239
|
-
type RelevanceStrategy = 'git-history' | 'import-graph' | 'semantic' | 'manual';
|
|
240
|
-
interface ProjectContextOptions {
|
|
241
|
-
/** Files that mark the project root (searched upward from cwd). */
|
|
242
|
-
rootMarkers?: string[];
|
|
243
|
-
/** How to index the codebase for structural understanding. */
|
|
244
|
-
indexStrategy?: IndexStrategy;
|
|
245
|
-
/** Maximum files to include in context per request. */
|
|
246
|
-
maxFilesInContext?: number;
|
|
247
|
-
/** How to rank file relevance when selecting context. */
|
|
248
|
-
relevanceStrategy?: RelevanceStrategy;
|
|
249
|
-
/** Glob patterns to exclude from indexing and context. */
|
|
250
|
-
ignorePatterns?: string[];
|
|
251
|
-
/** File extensions to include in indexing (default: all text files). */
|
|
252
|
-
includeExtensions?: string[];
|
|
253
|
-
}
|
|
254
|
-
declare function ProjectContext(options?: ProjectContextOptions): ClassDecorator;
|
|
255
|
-
declare function getProjectContextConfig(target: Function): ProjectContextOptions | undefined;
|
|
256
|
-
|
|
257
|
-
interface SkillsOptions {
|
|
258
|
-
/** Skill names to include (resolved from .theokit/skills/<name>/SKILL.md). */
|
|
259
|
-
include: string[];
|
|
260
|
-
/** Auto-discover all skills in .theokit/skills/ (default: false). */
|
|
261
|
-
autoDiscover?: boolean;
|
|
262
|
-
}
|
|
263
|
-
declare function Skills(namesOrOptions: string[] | SkillsOptions): ClassDecorator;
|
|
264
|
-
declare function getSkillsConfig(target: Function): SkillsOptions | undefined;
|
|
265
|
-
|
|
266
|
-
/**
|
|
267
|
-
* M9 (theokit-ai-first) — guardrail contract + typed errors.
|
|
268
|
-
*
|
|
269
|
-
* ADR-0040 § D2: guardrails are a HOME/BOUNDARY concern (filter user input before the SDK,
|
|
270
|
-
* filter model output before the client). They REUSE the SDK runtime — this module makes zero
|
|
271
|
-
* LLM calls. A guard reports one of three actions; the pipeline (`pipeline.ts`) enforces them.
|
|
272
|
-
*/
|
|
273
|
-
/** What a guard decided for a piece of text. */
|
|
274
|
-
type GuardrailAction = 'allow' | 'block' | 'redact';
|
|
275
|
-
/**
|
|
276
|
-
* The result of a single guard check.
|
|
277
|
-
* - `allow` — text passes untouched.
|
|
278
|
-
* - `block` — the pipeline throws {@link GuardrailViolationError}; the run stops fail-fast.
|
|
279
|
-
* - `redact` — the pipeline replaces the text with {@link GuardrailResult.text} and continues.
|
|
280
|
-
*/
|
|
281
|
-
interface GuardrailResult {
|
|
282
|
-
action: GuardrailAction;
|
|
283
|
-
/** Human-readable reason — required in spirit for `block`, surfaced in the thrown error. */
|
|
284
|
-
reason?: string;
|
|
285
|
-
/** The transformed text — present (and used) only when `action === 'redact'`. */
|
|
286
|
-
text?: string;
|
|
287
|
-
}
|
|
288
|
-
/**
|
|
289
|
-
* A guardrail. A guard MAY inspect input (before the model), output (after the model), or both.
|
|
290
|
-
* A guard that omits a phase hook is skipped for that phase.
|
|
291
|
-
*/
|
|
292
|
-
interface Guardrail {
|
|
293
|
-
readonly name: string;
|
|
294
|
-
checkInput?(text: string): GuardrailResult | Promise<GuardrailResult>;
|
|
295
|
-
checkOutput?(text: string): GuardrailResult | Promise<GuardrailResult>;
|
|
296
|
-
}
|
|
297
|
-
/** Which boundary phase a violation happened in. */
|
|
298
|
-
type GuardrailPhase = 'input' | 'output';
|
|
299
|
-
/** Thrown (fail-fast) when a guard returns `action: 'block'`. Typed per error-handling.md. */
|
|
300
|
-
declare class GuardrailViolationError extends Error {
|
|
301
|
-
readonly guardName: string;
|
|
302
|
-
readonly phase: GuardrailPhase;
|
|
303
|
-
readonly reason: string;
|
|
304
|
-
constructor(guardName: string, phase: GuardrailPhase, reason: string);
|
|
305
|
-
}
|
|
306
|
-
/** Thrown when {@link costGuard}'s cumulative token budget is exceeded. */
|
|
307
|
-
declare class CostBudgetExceededError extends Error {
|
|
308
|
-
readonly usedTokens: number;
|
|
309
|
-
readonly maxTokens: number;
|
|
310
|
-
constructor(usedTokens: number, maxTokens: number);
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
export { getSkillsConfig as $, type AgentOptions as A, type BudgetOptions as B, CostBudgetExceededError as C, type MemoryProvider as D, type MemoryScope as E, type PlatformName as F, type Guardrail as G, type HumanInTheLoopOptions as H, type IndexStrategy as I, ProjectContext as J, type ProjectContextOptions as K, type RelevanceStrategy as L, type MainLoopMeta as M, Skills as N, type SkillsOptions as O, type PolicyHandler as P, getCheckpointConfig as Q, type ReasoningEffort as R, type SessionStrategy as S, type TimeoutAction as T, getCompactionConfig as U, getContextWindowConfig as V, getGatewayConfig as W, getHumanInTheLoopConfig as X, getMcpConfig as Y, getMemoryConfig as Z, getProjectContextConfig as _, type ApprovalOptions as a, resolveSessionId as a0, type GuardrailAction as b, type GuardrailPhase as c, type GuardrailResult as d, GuardrailViolationError as e, type MainLoopOptions as f, type ToolOptions as g, type ToolboxOptions as h, Checkpoint as i, type CheckpointOptions as j, type CheckpointState as k, type CheckpointStorage as l, type CheckpointStrategy as m, Compaction as n, type CompactionDecoratorConfig as o, type ContextCompactionStrategy as p, ContextWindow as q, type ContextWindowOptions as r, Gateway as s, type GatewayOptions as t, HumanInTheLoop as u, MCP as v, type McpServerConfig as w, type McpServersMap as x, Memory as y, type MemoryOptions as z };
|