@dex-ai/sdk 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +308 -0
  2. package/dist/agent.d.ts +181 -0
  3. package/dist/agent.d.ts.map +1 -0
  4. package/dist/agent.js +41 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/context.d.ts +68 -0
  7. package/dist/context.d.ts.map +1 -0
  8. package/dist/context.js +8 -0
  9. package/dist/context.js.map +1 -0
  10. package/dist/create-agent.d.ts +7 -0
  11. package/dist/create-agent.d.ts.map +1 -0
  12. package/dist/create-agent.js +205 -0
  13. package/dist/create-agent.js.map +1 -0
  14. package/dist/extension.d.ts +162 -0
  15. package/dist/extension.d.ts.map +1 -0
  16. package/dist/extension.js +20 -0
  17. package/dist/extension.js.map +1 -0
  18. package/dist/generate.d.ts +10 -0
  19. package/dist/generate.d.ts.map +1 -0
  20. package/dist/generate.js +839 -0
  21. package/dist/generate.js.map +1 -0
  22. package/dist/index.d.ts +26 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +16 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/message.d.ts +89 -0
  27. package/dist/message.d.ts.map +1 -0
  28. package/dist/message.js +17 -0
  29. package/dist/message.js.map +1 -0
  30. package/dist/messages.d.ts +98 -0
  31. package/dist/messages.d.ts.map +1 -0
  32. package/dist/messages.js +339 -0
  33. package/dist/messages.js.map +1 -0
  34. package/dist/model.d.ts +39 -0
  35. package/dist/model.d.ts.map +1 -0
  36. package/dist/model.js +11 -0
  37. package/dist/model.js.map +1 -0
  38. package/dist/provider.d.ts +157 -0
  39. package/dist/provider.d.ts.map +1 -0
  40. package/dist/provider.js +39 -0
  41. package/dist/provider.js.map +1 -0
  42. package/dist/resolve-schema.d.ts +44 -0
  43. package/dist/resolve-schema.d.ts.map +1 -0
  44. package/dist/resolve-schema.js +367 -0
  45. package/dist/resolve-schema.js.map +1 -0
  46. package/dist/schema.d.ts +80 -0
  47. package/dist/schema.d.ts.map +1 -0
  48. package/dist/schema.js +90 -0
  49. package/dist/schema.js.map +1 -0
  50. package/dist/tool-dispatch.d.ts +24 -0
  51. package/dist/tool-dispatch.d.ts.map +1 -0
  52. package/dist/tool-dispatch.js +120 -0
  53. package/dist/tool-dispatch.js.map +1 -0
  54. package/dist/tool-result-cache.d.ts +43 -0
  55. package/dist/tool-result-cache.d.ts.map +1 -0
  56. package/dist/tool-result-cache.js +118 -0
  57. package/dist/tool-result-cache.js.map +1 -0
  58. package/dist/tool.d.ts +96 -0
  59. package/dist/tool.d.ts.map +1 -0
  60. package/dist/tool.js +29 -0
  61. package/dist/tool.js.map +1 -0
  62. package/dist/util.d.ts +26 -0
  63. package/dist/util.d.ts.map +1 -0
  64. package/dist/util.js +104 -0
  65. package/dist/util.js.map +1 -0
  66. package/package.json +41 -0
  67. package/src/agent.ts +235 -0
  68. package/src/context.ts +82 -0
  69. package/src/create-agent.ts +237 -0
  70. package/src/extension.ts +244 -0
  71. package/src/generate.ts +943 -0
  72. package/src/index.ts +113 -0
  73. package/src/message.ts +114 -0
  74. package/src/messages.test.ts +299 -0
  75. package/src/messages.ts +423 -0
  76. package/src/model.ts +43 -0
  77. package/src/provider.ts +187 -0
  78. package/src/resolve-schema.test.ts +351 -0
  79. package/src/resolve-schema.ts +426 -0
  80. package/src/schema.ts +131 -0
  81. package/src/tool-dispatch.ts +166 -0
  82. package/src/tool-result-cache.test.ts +182 -0
  83. package/src/tool-result-cache.ts +164 -0
  84. package/src/tool.ts +110 -0
  85. package/src/util.ts +110 -0
@@ -0,0 +1,120 @@
1
+ /** Dispatch one tool call: validate input → execute → return result. */
2
+ import { validateWithSchema } from "./util";
3
+ import { cacheIfLarge } from "./tool-result-cache";
4
+ const MAX_TOOL_OUTPUT_LINES = 1000;
5
+ const MAX_TOOL_OUTPUT_CHARS = 40_000;
6
+ /**
7
+ * Truncate tool output text to fit within limits.
8
+ * Keeps the tail (most recent output) and prepends a truncation notice.
9
+ */
10
+ function truncateText(text) {
11
+ const lines = text.split("\n");
12
+ let result = text;
13
+ let truncated = false;
14
+ if (lines.length > MAX_TOOL_OUTPUT_LINES) {
15
+ result = lines.slice(-MAX_TOOL_OUTPUT_LINES).join("\n");
16
+ truncated = true;
17
+ }
18
+ if (result.length > MAX_TOOL_OUTPUT_CHARS) {
19
+ result = result.slice(-MAX_TOOL_OUTPUT_CHARS);
20
+ truncated = true;
21
+ }
22
+ if (truncated) {
23
+ return ("[OUTPUT TRUNCATED — showing last portion only. " +
24
+ "Use more targeted commands to reduce output if needed.]\n" +
25
+ result);
26
+ }
27
+ return text;
28
+ }
29
+ /** Truncate a ToolOutput if it exceeds size limits. */
30
+ function truncateToolOutput(output) {
31
+ switch (output.type) {
32
+ case "text":
33
+ return { type: "text", value: truncateText(output.value) };
34
+ case "error-text":
35
+ return { type: "error-text", value: truncateText(output.value) };
36
+ case "json": {
37
+ const serialized = JSON.stringify(output.value, null, 2);
38
+ const truncatedStr = truncateText(serialized);
39
+ if (truncatedStr !== serialized) {
40
+ // Truncated JSON is no longer valid JSON — return as text
41
+ return { type: "text", value: truncatedStr };
42
+ }
43
+ return output;
44
+ }
45
+ case "content": {
46
+ const parts = output.value.map((part) => {
47
+ if (part.type === "text") {
48
+ return { ...part, text: truncateText(part.text) };
49
+ }
50
+ return part;
51
+ });
52
+ return { type: "content", value: parts };
53
+ }
54
+ default:
55
+ return output;
56
+ }
57
+ }
58
+ /** Wrap an execute() return value into a ToolOutput tagged variant. */
59
+ export function toToolOutput(result) {
60
+ if (typeof result === "object" && result !== null && "type" in result) {
61
+ const t = result.type;
62
+ if (t === "content" ||
63
+ t === "json" ||
64
+ t === "text" ||
65
+ t === "error-text" ||
66
+ t === "error-json") {
67
+ return result;
68
+ }
69
+ }
70
+ return { type: "json", value: result };
71
+ }
72
+ /**
73
+ * Validate and execute a tool call. Tool-start/tool-stop events are handled
74
+ * by the generate loop — this function only does validation + execution.
75
+ */
76
+ export async function dispatchTool(opts) {
77
+ const { call, tool, gctx, reportError } = opts;
78
+ // 1. Validate input against tool.parameters.
79
+ const validated = await validateWithSchema(tool.parameters, call.input);
80
+ if ("issues" in validated) {
81
+ const msg = validated.issues
82
+ .map((i) => (i.path?.length ? i.path.join(".") + ": " : "") + i.message)
83
+ .join("; ");
84
+ return {
85
+ result: {
86
+ toolCallId: call.toolCallId,
87
+ toolName: call.toolName,
88
+ output: { type: "error-text", value: "Invalid tool input: " + msg },
89
+ },
90
+ shortCircuited: false,
91
+ };
92
+ }
93
+ // 2. Execute.
94
+ let executeError;
95
+ let result;
96
+ try {
97
+ const raw = await tool.execute(validated.value, gctx);
98
+ let output = toToolOutput(raw);
99
+ // Cache large results before truncation — agent can explore via `read`
100
+ if (opts.cacheConfig) {
101
+ output = await cacheIfLarge(output, call.toolName, call.toolCallId, opts.cacheConfig);
102
+ }
103
+ output = truncateToolOutput(output);
104
+ result = { toolCallId: call.toolCallId, toolName: call.toolName, output };
105
+ }
106
+ catch (err) {
107
+ executeError = err;
108
+ await reportError(err, { kind: "tool", call });
109
+ result = {
110
+ toolCallId: call.toolCallId,
111
+ toolName: call.toolName,
112
+ output: {
113
+ type: "error-text",
114
+ value: err instanceof Error ? err.message : String(err),
115
+ },
116
+ };
117
+ }
118
+ return { result, shortCircuited: false, executeError };
119
+ }
120
+ //# sourceMappingURL=tool-dispatch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-dispatch.js","sourceRoot":"","sources":["../src/tool-dispatch.ts"],"names":[],"mappings":"AAAA,wEAAwE;AAYxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,EAAE,YAAY,EAA4B,MAAM,qBAAqB,CAAC;AAE7E,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAErC;;;GAGG;AACH,SAAS,YAAY,CAAC,IAAY;IACjC,MAAM,KAAK,GAAG,IAAI,CAAC,K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CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,YAAY,GAAG,GAAG,CAAC;QACnB,MAAM,WAAW,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC/C,MAAM,GAAG;YACR,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE;gBACP,IAAI,EAAE,YAAY;gBAClB,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;aACvD;SACD,CAAC;IACH,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;AACxD,CAAC"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Large Tool Result Caching
3
+ *
4
+ * When a tool result exceeds a character threshold, the full output is cached
5
+ * to disk and only the tail is sent to the model — with a header noting where
6
+ * the full output can be read.
7
+ *
8
+ * This reduces context consumption while allowing the agent to explore
9
+ * cached results via the existing `read` tool.
10
+ */
11
+ import type { ToolOutput } from "./message";
12
+ export interface ToolResultCacheConfig {
13
+ /** Character threshold above which results are cached. Default: 10_000 */
14
+ readonly threshold?: number;
15
+ /** Cache directory. Default: ~/.dex/cache */
16
+ readonly cacheDir?: string;
17
+ /** TTL in milliseconds for stale file cleanup. Default: 86_400_000 (24h) */
18
+ readonly ttlMs?: number;
19
+ /** Tool names excluded from caching. Default: ['read'] */
20
+ readonly excludedTools?: ReadonlyArray<string>;
21
+ }
22
+ /** Internal state key used to store the resolved config in AgentContext.state */
23
+ export declare const TOOL_RESULT_CACHE_KEY = "__toolResultCache";
24
+ export interface ResolvedCacheConfig {
25
+ readonly threshold: number;
26
+ readonly cacheDir: string;
27
+ readonly ttlMs: number;
28
+ readonly excludedTools: ReadonlyArray<string>;
29
+ }
30
+ export declare function resolveConfig(config?: ToolResultCacheConfig): ResolvedCacheConfig;
31
+ /**
32
+ * If the tool output exceeds the threshold, cache the full result to disk
33
+ * and return a truncated version with a header pointing to the cache file.
34
+ *
35
+ * Returns the original output unchanged if below threshold or excluded.
36
+ */
37
+ export declare function cacheIfLarge(output: ToolOutput, toolName: string, toolCallId: string, config: ResolvedCacheConfig): Promise<ToolOutput>;
38
+ /**
39
+ * Remove stale cache files older than TTL, then wipe the directory.
40
+ * Called on session start to ensure a clean slate.
41
+ */
42
+ export declare function cleanCacheDir(config: ResolvedCacheConfig): Promise<void>;
43
+ //# sourceMappingURL=tool-result-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-result-cache.d.ts","sourceRoot":"","sources":["../src/tool-result-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAM5C,MAAM,WAAW,qBAAqB;IACrC,0EAA0E;IAC1E,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,6CAA6C;IAC7C,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,4EAA4E;IAC5E,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,0DAA0D;IAC1D,QAAQ,CAAC,aAAa,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CAC/C;AAED,iFAAiF;AACjF,eAAO,MAAM,qBAAqB,sBAAsB,CAAC;AAWzD,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CAC9C;AAED,wBAAgB,aAAa,CAC5B,MAAM,CAAC,EAAE,qBAAqB,GAC5B,mBAAmB,CAOrB;AA6BD;;;;;GAKG;AACH,wBAAsB,YAAY,CACjC,MAAM,EAAE,UAAU,EAClB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,mBAAmB,GACzB,OAAO,CAAC,UAAU,CAAC,CA6BrB;AAMD;;;GAGG;AACH,wBAAsB,aAAa,CAClC,MAAM,EAAE,mBAAmB,GACzB,OAAO,CAAC,IAAI,CAAC,CAuBf"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Large Tool Result Caching
3
+ *
4
+ * When a tool result exceeds a character threshold, the full output is cached
5
+ * to disk and only the tail is sent to the model — with a header noting where
6
+ * the full output can be read.
7
+ *
8
+ * This reduces context consumption while allowing the agent to explore
9
+ * cached results via the existing `read` tool.
10
+ */
11
+ import { writeFile, mkdir, readdir, stat, unlink, rm } from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ import { homedir } from "node:os";
14
+ /** Internal state key used to store the resolved config in AgentContext.state */
15
+ export const TOOL_RESULT_CACHE_KEY = "__toolResultCache";
16
+ /* ------------------------------------------------------------------ */
17
+ /* Defaults */
18
+ /* ------------------------------------------------------------------ */
19
+ const DEFAULT_THRESHOLD = 10_000;
20
+ const DEFAULT_CACHE_DIR = join(homedir(), ".dex", "cache");
21
+ const DEFAULT_TTL_MS = 86_400_000; // 24 hours
22
+ const DEFAULT_EXCLUDED_TOOLS = ["read"];
23
+ export function resolveConfig(config) {
24
+ return {
25
+ threshold: config?.threshold ?? DEFAULT_THRESHOLD,
26
+ cacheDir: config?.cacheDir ?? DEFAULT_CACHE_DIR,
27
+ ttlMs: config?.ttlMs ?? DEFAULT_TTL_MS,
28
+ excludedTools: config?.excludedTools ?? DEFAULT_EXCLUDED_TOOLS,
29
+ };
30
+ }
31
+ /* ------------------------------------------------------------------ */
32
+ /* Text extraction */
33
+ /* ------------------------------------------------------------------ */
34
+ /** Extract the text content from a ToolOutput, or null if non-textual. */
35
+ function extractText(output) {
36
+ switch (output.type) {
37
+ case "text":
38
+ case "error-text":
39
+ return output.value;
40
+ case "json":
41
+ return JSON.stringify(output.value, null, 2);
42
+ case "content": {
43
+ const texts = output.value
44
+ .filter((p) => p.type === "text")
45
+ .map((p) => p.text);
46
+ return texts.length > 0 ? texts.join("\n") : null;
47
+ }
48
+ default:
49
+ return null;
50
+ }
51
+ }
52
+ /* ------------------------------------------------------------------ */
53
+ /* Core: cacheIfLarge */
54
+ /* ------------------------------------------------------------------ */
55
+ /**
56
+ * If the tool output exceeds the threshold, cache the full result to disk
57
+ * and return a truncated version with a header pointing to the cache file.
58
+ *
59
+ * Returns the original output unchanged if below threshold or excluded.
60
+ */
61
+ export async function cacheIfLarge(output, toolName, toolCallId, config) {
62
+ // Skip excluded tools
63
+ if (config.excludedTools.includes(toolName))
64
+ return output;
65
+ // Extract text content
66
+ const text = extractText(output);
67
+ if (!text || text.length <= config.threshold)
68
+ return output;
69
+ // Write full output to cache
70
+ const cachePath = join(config.cacheDir, toolCallId);
71
+ try {
72
+ await mkdir(config.cacheDir, { recursive: true });
73
+ await writeFile(cachePath, text, "utf-8");
74
+ }
75
+ catch {
76
+ // If caching fails (disk full, permissions), fall through to existing truncation
77
+ return output;
78
+ }
79
+ // Return tail with header
80
+ const tail = text.slice(-config.threshold);
81
+ const header = `[Tool output cached — showing last ${config.threshold.toLocaleString()} of ${text.length.toLocaleString()} chars. ` +
82
+ `Full output: ${cachePath}]\n`;
83
+ // Preserve the output type for error results
84
+ if (output.type === "error-text") {
85
+ return { type: "error-text", value: header + tail };
86
+ }
87
+ return { type: "text", value: header + tail };
88
+ }
89
+ /* ------------------------------------------------------------------ */
90
+ /* Cleanup */
91
+ /* ------------------------------------------------------------------ */
92
+ /**
93
+ * Remove stale cache files older than TTL, then wipe the directory.
94
+ * Called on session start to ensure a clean slate.
95
+ */
96
+ export async function cleanCacheDir(config) {
97
+ const { cacheDir, ttlMs } = config;
98
+ try {
99
+ // First pass: remove stale files (safety net for orphaned files from crashed sessions)
100
+ const entries = await readdir(cacheDir).catch(() => []);
101
+ const now = Date.now();
102
+ for (const entry of entries) {
103
+ const filePath = join(cacheDir, entry);
104
+ const fileStat = await stat(filePath).catch(() => null);
105
+ if (fileStat && now - fileStat.mtimeMs > ttlMs) {
106
+ await unlink(filePath).catch(() => { });
107
+ }
108
+ }
109
+ // Wipe the directory for a clean session start
110
+ await rm(cacheDir, { recursive: true, force: true });
111
+ }
112
+ catch {
113
+ // Non-fatal — directory may not exist yet
114
+ }
115
+ // Ensure directory exists for this session
116
+ await mkdir(cacheDir, { recursive: true });
117
+ }
118
+ //# sourceMappingURL=tool-result-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-result-cache.js","sourceRoot":"","sources":["../src/tool-result-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAC/E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAkBlC,iFAAiF;AACjF,MAAM,CAAC,MAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAEzD,wEAAwE;AACxE,yEAAyE;AACzE,wEAAwE;AAExE,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,MAAM,iBAAiB,GAAG,IAAI,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAC3D,MAAM,cAAc,GAAG,UAAU,CAAC,CAAC,WAAW;AAC9C,MAAM,sBAAsB,GAA0B,CAAC,MAAM,CAAC,CAAC;AAS/D,MAAM,UAAU,aAAa,CAC5B,MAA8B;IAE9B,OAAO;QACN,SAAS,EAAE,MAAM,EAAE,SAAS,IAAI,iBAAiB;QACjD,QAAQ,EAAE,MAAM,EAAE,QAAQ,IAAI,iBAAiB;QAC/C,KAAK,EAAE,MAAM,EAAE,KAAK,I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G,EAAE,CAAC;QACvB,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;YACvC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;YACxD,IAAI,QAAQ,IAAI,GAAG,GAAG,QAAQ,CAAC,OAAO,GAAG,KAAK,EAAE,CAAC;gBAChD,MAAM,MAAM,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACxC,CAAC;QACF,CAAC;QAED,+CAA+C;QAC/C,MAAM,EAAE,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACtD,CAAC;IAAC,MAAM,CAAC;QACR,0CAA0C;IAC3C,CAAC;IAED,2CAA2C;IAC3C,MAAM,KAAK,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAC5C,CAAC"}
package/dist/tool.d.ts ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Tool — an action a Provider may invoke.
3
+ *
4
+ * ai-sdk aligned:
5
+ * - parameters: Standard Schema for the input
6
+ * - execute: ({input}, gctx) => ToolOutput | value
7
+ * - outputSchema: optional Standard Schema for the output value
8
+ *
9
+ * Approval is NOT a first-class tool field. Use the onToolCall hook
10
+ * (see extension.ts) — a short-circuit-capable reducer. An approver
11
+ * extension returns a ToolResult to reject, a rewritten ToolCall to
12
+ * modify, or void to pass through. A rejection is data for the LLM:
13
+ * the tool-result message goes into history and the model decides to
14
+ * retry, call a different tool, or stop.
15
+ */
16
+ import type { StandardSchemaV1, InferInput } from "./schema";
17
+ import type { ToolOutput } from "./message";
18
+ import type { GenerateContext } from "./context";
19
+ /** A pending tool invocation parsed from the model. */
20
+ export interface ToolCall<Input = unknown> {
21
+ readonly toolCallId: string;
22
+ readonly toolName: string;
23
+ readonly input: Input;
24
+ }
25
+ /**
26
+ * The outcome of a tool invocation. Wraps a tagged ToolOutput so tools
27
+ * can return rich content, structured JSON, plain text, or errors
28
+ * uniformly.
29
+ */
30
+ export interface ToolResult {
31
+ readonly toolCallId: string;
32
+ readonly toolName: string;
33
+ readonly output: ToolOutput;
34
+ }
35
+ /**
36
+ * An execute function may return either:
37
+ * - a raw Output value (wrapped by the loop into a ToolOutput.json), or
38
+ * - a ToolOutput directly (for rich content / explicit error shapes).
39
+ */
40
+ export type ExecuteResult<Output> = Output | ToolOutput;
41
+ export interface Tool<Input = unknown, Output = unknown> {
42
+ readonly name: string;
43
+ readonly description?: string;
44
+ readonly parameters: StandardSchemaV1<Input>;
45
+ readonly outputSchema?: StandardSchemaV1<Output>;
46
+ /**
47
+ * Access level hint for permission systems.
48
+ * - 'read': tool only reads/queries data (no side effects)
49
+ * - 'write': tool modifies state (files, memory, shell, etc.)
50
+ *
51
+ * If omitted, defaults to 'write' (conservative — requires approval).
52
+ */
53
+ readonly access?: "read" | "write";
54
+ /**
55
+ * Human-friendly name for UI display.
56
+ * Falls back to `name` when omitted.
57
+ * Examples: "Read", "Update", "Search", "Remember"
58
+ */
59
+ readonly displayName?: string;
60
+ /**
61
+ * Whether the tool invocation should be rendered in the UI message stream.
62
+ * Defaults to `true`. Set to `false` for tools that have dedicated UI
63
+ * (e.g. task panel) or whose invocations aren't useful to show inline.
64
+ */
65
+ readonly visible?: boolean;
66
+ execute(input: Input, gctx: GenerateContext): Promise<ExecuteResult<Output>> | ExecuteResult<Output>;
67
+ /**
68
+ * Streaming alternative to execute. Yields Parts (tool-progress + tool-result).
69
+ * If present, the loop prefers stream() over execute().
70
+ * The loop stamps toolCallId on emitted parts.
71
+ */
72
+ stream?(input: Input, gctx: GenerateContext): AsyncIterable<ToolStreamPart>;
73
+ }
74
+ /** Parts a streaming tool can yield. */
75
+ export type ToolStreamPart = {
76
+ readonly type: "tool-progress";
77
+ readonly text: string;
78
+ } | {
79
+ readonly type: "tool-result";
80
+ readonly output: ToolOutput;
81
+ };
82
+ export type AnyTool = Tool<any, any>;
83
+ /**
84
+ * Tool namespace — identity-typed declaration helper.
85
+ *
86
+ * Use `Tool.define({...})` at author-time to get full contextual typing
87
+ * (tool input/output inference from the Standard Schema `parameters`).
88
+ * Runtime behavior: returns the argument unchanged.
89
+ */
90
+ export declare const Tool: {
91
+ define<ParamsSchema extends StandardSchemaV1<any, any>, Output>(tool: Omit<Tool<InferInput<ParamsSchema>, Output>, "parameters" | "outputSchema"> & {
92
+ readonly parameters: ParamsSchema;
93
+ readonly outputSchema?: StandardSchemaV1<Output>;
94
+ }): Tool<InferInput<ParamsSchema>, Output>;
95
+ };
96
+ //# sourceMappingURL=tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAEjD,uDAAuD;AACvD,MAAM,WAAW,QAAQ,CAAC,KAAK,GAAG,OAAO;IACxC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;CACtB;AAED;;;;GAIG;AACH,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;CAC5B;AAED;;;;GAIG;AACH,MAAM,MAAM,aA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C,EAAE,MAAM,QACvD,IAAI,CACT,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC,EACtC,YAAY,GAAG,cAAc,CAC7B,GAAG;QACH,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC;QAClC,QAAQ,CAAC,YAAY,CAAC,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;KACjD,GACC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAGzC,CAAC"}
package/dist/tool.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Tool — an action a Provider may invoke.
3
+ *
4
+ * ai-sdk aligned:
5
+ * - parameters: Standard Schema for the input
6
+ * - execute: ({input}, gctx) => ToolOutput | value
7
+ * - outputSchema: optional Standard Schema for the output value
8
+ *
9
+ * Approval is NOT a first-class tool field. Use the onToolCall hook
10
+ * (see extension.ts) — a short-circuit-capable reducer. An approver
11
+ * extension returns a ToolResult to reject, a rewritten ToolCall to
12
+ * modify, or void to pass through. A rejection is data for the LLM:
13
+ * the tool-result message goes into history and the model decides to
14
+ * retry, call a different tool, or stop.
15
+ */
16
+ /**
17
+ * Tool namespace — identity-typed declaration helper.
18
+ *
19
+ * Use `Tool.define({...})` at author-time to get full contextual typing
20
+ * (tool input/output inference from the Standard Schema `parameters`).
21
+ * Runtime behavior: returns the argument unchanged.
22
+ */
23
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
24
+ export const Tool = {
25
+ define(tool) {
26
+ return tool;
27
+ },
28
+ };
29
+ //# sourceMappingURL=tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA2EH;;;;;;GAMG;AACH,2DAA2D;AAC3D,MAAM,CAAC,MAAM,IAAI,GAAG;IACnB,MAAM,CACL,IAMC;QAED,OAAO,IAA8C,CAAC;IACvD,CAAC;CACD,CAAC"}
package/dist/util.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /** Small helpers used across the agent loop. */
2
+ import type { StandardSchemaV1 } from "./index";
3
+ /**
4
+ * Format an error with full stack trace for troubleshooting.
5
+ * Handles nested errors, non-Error throws, and provider metadata.
6
+ */
7
+ export declare function formatError(err: unknown): string;
8
+ /** Validate a value against a Standard Schema. Returns either { value } or { issues }. */
9
+ export declare function validateWithSchema<I, O>(schema: StandardSchemaV1<I, O>, value: unknown): Promise<import("./schema").Result<O>>;
10
+ /** Merge two optional AbortSignals into one AbortController.signal. */
11
+ export declare function mergeSignals(a?: AbortSignal, b?: AbortSignal): {
12
+ signal: AbortSignal;
13
+ dispose: () => void;
14
+ };
15
+ /** A queue-backed push channel that becomes an AsyncIterable. Used to fan out StreamParts to callers. */
16
+ export declare class PushStream<T> implements AsyncIterable<T> {
17
+ private buffer;
18
+ private resolvers;
19
+ private closed;
20
+ private failure;
21
+ push(v: T): void;
22
+ close(): void;
23
+ fail(err: unknown): void;
24
+ [Symbol.asyncIterator](): AsyncIterator<T>;
25
+ }
26
+ //# sourceMappingURL=util.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAEhD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEhD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAkChD;AAED,0FAA0F;AAC1F,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,CAAC,EAC5C,MAAM,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,EAC9B,KAAK,EAAE,OAAO,yCAId;AAED,uEAAuE;AACvE,wBAAgB,YAAY,CAC3B,CAAC,CAAC,EAAE,WAAW,EACf,CAAC,CAAC,EAAE,WAAW,GACb;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CAc9C;AAED,yGAAyG;AACzG,qBAAa,UAAU,CAAC,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IACrD,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,SAAS,CAA6C;IAC9D,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAiB;IAEhC,IAAI,CAAC,CAAC,EAAE,CAAC;IAMT,KAAK;IAKL,IAAI,CAAC,GAAG,EAAE,OAAO;IAIjB,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC;CAc1C"}
package/dist/util.js ADDED
@@ -0,0 +1,104 @@
1
+ /** Small helpers used across the agent loop. */
2
+ /**
3
+ * Format an error with full stack trace for troubleshooting.
4
+ * Handles nested errors, non-Error throws, and provider metadata.
5
+ */
6
+ export function formatError(err) {
7
+ if (!(err instanceof Error)) {
8
+ return `Non-Error thrown: ${JSON.stringify(err)}`;
9
+ }
10
+ const parts = [];
11
+ parts.push(`${err.name}: ${err.message}`);
12
+ // Include stack trace
13
+ if (err.stack) {
14
+ // Strip the first line (it's the message, already shown)
15
+ const stackLines = err.stack.split("\n").slice(1);
16
+ if (stackLines.length > 0) {
17
+ parts.push(stackLines.slice(0, 15).join("\n"));
18
+ if (stackLines.length > 15) {
19
+ parts.push(` ... ${stackLines.length - 15} more frames`);
20
+ }
21
+ }
22
+ }
23
+ // Provider-specific metadata (e.g. HTTP status, response body)
24
+ const meta = err.status ?? err.statusCode;
25
+ if (meta)
26
+ parts.push(` HTTP status: ${meta}`);
27
+ const code = err.code;
28
+ if (code)
29
+ parts.push(` code: ${code}`);
30
+ const type = err.type;
31
+ if (type)
32
+ parts.push(` type: ${type}`);
33
+ // Nested cause (Error.cause)
34
+ if (err.cause) {
35
+ parts.push(` caused by: ${formatError(err.cause)}`);
36
+ }
37
+ return parts.join("\n");
38
+ }
39
+ /** Validate a value against a Standard Schema. Returns either { value } or { issues }. */
40
+ export async function validateWithSchema(schema, value) {
41
+ const res = await schema["~standard"].validate(value);
42
+ return res;
43
+ }
44
+ /** Merge two optional AbortSignals into one AbortController.signal. */
45
+ export function mergeSignals(a, b) {
46
+ const ctrl = new AbortController();
47
+ const relay = (reason) => ctrl.abort(reason);
48
+ const la = a && (() => relay(a.reason));
49
+ const lb = b && (() => relay(b.reason));
50
+ if (a?.aborted)
51
+ ctrl.abort(a.reason);
52
+ else if (b?.aborted)
53
+ ctrl.abort(b.reason);
54
+ if (la)
55
+ a.addEventListener("abort", la, { once: true });
56
+ if (lb)
57
+ b.addEventListener("abort", lb, { once: true });
58
+ const dispose = () => {
59
+ if (la)
60
+ a.removeEventListener("abort", la);
61
+ if (lb)
62
+ b.removeEventListener("abort", lb);
63
+ };
64
+ return { signal: ctrl.signal, dispose };
65
+ }
66
+ /** A queue-backed push channel that becomes an AsyncIterable. Used to fan out StreamParts to callers. */
67
+ export class PushStream {
68
+ buffer = [];
69
+ resolvers = [];
70
+ closed = false;
71
+ failure = null;
72
+ push(v) {
73
+ if (this.closed)
74
+ return;
75
+ const r = this.resolvers.shift();
76
+ if (r)
77
+ r({ value: v, done: false });
78
+ else
79
+ this.buffer.push(v);
80
+ }
81
+ close() {
82
+ this.closed = true;
83
+ while (this.resolvers.length)
84
+ this.resolvers.shift()({ value: undefined, done: true });
85
+ }
86
+ fail(err) {
87
+ this.failure = err;
88
+ this.close();
89
+ }
90
+ [Symbol.asyncIterator]() {
91
+ return {
92
+ next: () => {
93
+ if (this.buffer.length)
94
+ return Promise.resolve({ value: this.buffer.shift(), done: false });
95
+ if (this.failure)
96
+ return Promise.reject(this.failure);
97
+ if (this.closed)
98
+ return Promise.resolve({ value: undefined, done: true });
99
+ return new Promise((resolve) => this.resolvers.push(resolve));
100
+ },
101
+ };
102
+ }
103
+ }
104
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAIh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AAO;YACN,IAAI,EAAE,GAAG,EAAE;gBACV,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM;oBACrB,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;gBACtE,IAAI,IAAI,CAAC,OAAO;oBAAE,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACtD,IAAI,IAAI,CAAC,MAAM;oBACd,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,SAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;gBACjE,OAAO,IAAI,OAAO,CAAoB,CAAC,OAAO,EAAE,EAAE,CACjD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAC5B,CAAC;YACH,CAAC;SACD,CAAC;IACH,CAAC;CACD"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@dex-ai/sdk",
3
+ "version": "0.1.30",
4
+ "description": "Agent SDK: interfaces + createAgent() + generate loop. One package.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.ts",
9
+ "default": "./src/index.ts"
10
+ }
11
+ },
12
+ "files": [
13
+ "src",
14
+ "dist"
15
+ ],
16
+ "workspaces": [
17
+ "examples"
18
+ ],
19
+ "scripts": {
20
+ "typecheck": "tsc --noEmit",
21
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
22
+ "changeset": "changeset",
23
+ "version": "changeset version",
24
+ "release": "changeset publish",
25
+ "prepublishOnly": "bun run build"
26
+ },
27
+ "devDependencies": {
28
+ "@types/bun": "latest",
29
+ "bun-types": "^1.3.14",
30
+ "typescript": "^5.6.3",
31
+ "@changesets/cli": "^2.29.0"
32
+ },
33
+ "engines": {
34
+ "bun": ">=1.1.0"
35
+ },
36
+ "sideEffects": false,
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "registry": "https://registry.npmjs.org/"
40
+ }
41
+ }