agent-framework-js 0.1.1 → 0.2.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 +69 -0
- package/README.md +45 -0
- package/dist/agents/index.cjs +7 -7
- package/dist/agents/index.d.cts +4 -4
- package/dist/agents/index.d.ts +4 -4
- package/dist/agents/index.js +2 -2
- package/dist/{chunk-YKZJRE32.cjs → chunk-245NZAGV.cjs} +4 -4
- package/dist/{chunk-YKZJRE32.cjs.map → chunk-245NZAGV.cjs.map} +1 -1
- package/dist/{chunk-UVWQWOLO.js → chunk-7M3EAGCA.js} +41 -8
- package/dist/chunk-7M3EAGCA.js.map +1 -0
- package/dist/{chunk-XPXTXOYQ.js → chunk-E4VTVUYU.js} +4 -3
- package/dist/chunk-E4VTVUYU.js.map +1 -0
- package/dist/{chunk-V472N2PK.js → chunk-IGIFX6QO.js} +3 -3
- package/dist/{chunk-V472N2PK.js.map → chunk-IGIFX6QO.js.map} +1 -1
- package/dist/{chunk-LMN75W3W.cjs → chunk-ILBKDEEL.cjs} +4 -3
- package/dist/chunk-ILBKDEEL.cjs.map +1 -0
- package/dist/{chunk-YBFLWRO5.cjs → chunk-NURRGYIU.cjs} +18 -15
- package/dist/chunk-NURRGYIU.cjs.map +1 -0
- package/dist/{chunk-VLSVL5N2.js → chunk-S5776DOL.js} +3 -3
- package/dist/{chunk-VLSVL5N2.js.map → chunk-S5776DOL.js.map} +1 -1
- package/dist/{chunk-TLACSVEZ.cjs → chunk-U64OEHG6.cjs} +40 -6
- package/dist/chunk-U64OEHG6.cjs.map +1 -0
- package/dist/{chunk-QJ5XHA6S.cjs → chunk-UIXNKPLQ.cjs} +4 -4
- package/dist/{chunk-QJ5XHA6S.cjs.map → chunk-UIXNKPLQ.cjs.map} +1 -1
- package/dist/{chunk-RD5YUB2E.js → chunk-WEKU7735.js} +12 -9
- package/dist/chunk-WEKU7735.js.map +1 -0
- package/dist/declarative/index.cjs +4 -4
- package/dist/declarative/index.d.cts +4 -4
- package/dist/declarative/index.d.ts +4 -4
- package/dist/declarative/index.js +3 -3
- package/dist/{index-DdYZeNIu.d.cts → index-5eIhfrC1.d.cts} +5 -3
- package/dist/{index-D7-znzrc.d.ts → index-Dog-CyOK.d.ts} +5 -3
- package/dist/index.cjs +34 -30
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +6 -6
- package/dist/middleware/index.d.cts +5 -5
- package/dist/middleware/index.d.ts +5 -5
- package/dist/persistence/index.cjs +5 -5
- package/dist/persistence/index.d.cts +2 -2
- package/dist/persistence/index.d.ts +2 -2
- package/dist/persistence/index.js +2 -2
- package/dist/{provider-osAtfZ7x.d.ts → provider-C_rgZvmX.d.ts} +47 -2
- package/dist/{provider-CMAymr1b.d.cts → provider-IJnfNhCX.d.cts} +47 -2
- package/dist/providers/index.cjs +9 -5
- package/dist/providers/index.d.cts +32 -13
- package/dist/providers/index.d.ts +32 -13
- package/dist/providers/index.js +1 -1
- package/dist/{registry-D4fThGiN.d.cts → registry-B-hicOxp.d.cts} +1 -1
- package/dist/{registry-CpO0yH5v.d.ts → registry-KMWN0p4Z.d.ts} +1 -1
- package/dist/{thread-CWVzTyti.d.ts → thread-COV135Ja.d.ts} +4 -2
- package/dist/{thread-Dfo9LLf7.d.cts → thread-D3zaGK1Y.d.cts} +4 -2
- package/dist/tools/index.d.cts +2 -2
- package/dist/tools/index.d.ts +2 -2
- package/dist/workflows/index.d.cts +4 -4
- package/dist/workflows/index.d.ts +4 -4
- package/package.json +4 -4
- package/AGENT_USAGE.md +0 -207
- package/dist/chunk-LMN75W3W.cjs.map +0 -1
- package/dist/chunk-RD5YUB2E.js.map +0 -1
- package/dist/chunk-TLACSVEZ.cjs.map +0 -1
- package/dist/chunk-UVWQWOLO.js.map +0 -1
- package/dist/chunk-XPXTXOYQ.js.map +0 -1
- package/dist/chunk-YBFLWRO5.cjs.map +0 -1
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
var chunkWSMYH2IN_cjs = require('./chunk-WSMYH2IN.cjs');
|
|
4
4
|
var chunkTAMJ5HSR_cjs = require('./chunk-TAMJ5HSR.cjs');
|
|
5
5
|
var chunkFSDMBWQV_cjs = require('./chunk-FSDMBWQV.cjs');
|
|
6
|
-
var
|
|
6
|
+
var chunkILBKDEEL_cjs = require('./chunk-ILBKDEEL.cjs');
|
|
7
7
|
var chunkMQ2XTH3S_cjs = require('./chunk-MQ2XTH3S.cjs');
|
|
8
8
|
|
|
9
9
|
// src/agents/loop.ts
|
|
@@ -46,12 +46,12 @@ async function runLoop(generate, registry, messages, options) {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
function buildMessages(instructions, input) {
|
|
49
|
-
return [
|
|
49
|
+
return [chunkILBKDEEL_cjs.textMessage("system", instructions), ...input];
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
// src/agents/agent.ts
|
|
53
53
|
function normalizeInput(input) {
|
|
54
|
-
if (typeof input === "string") return [
|
|
54
|
+
if (typeof input === "string") return [chunkILBKDEEL_cjs.textMessage("user", input)];
|
|
55
55
|
return Array.isArray(input) ? input : [input];
|
|
56
56
|
}
|
|
57
57
|
function promptText(messages) {
|
|
@@ -61,8 +61,9 @@ function createAgent(config) {
|
|
|
61
61
|
const registry = new chunkTAMJ5HSR_cjs.ToolRegistry(config.tools ?? []);
|
|
62
62
|
const skillIndex = new chunkWSMYH2IN_cjs.SkillIndex(config.skills ?? []);
|
|
63
63
|
const middleware = config.middleware ?? [];
|
|
64
|
+
const modelCaps = () => config.provider.model(config.model);
|
|
64
65
|
function gateVision(messages) {
|
|
65
|
-
if (!
|
|
66
|
+
if (!modelCaps().supportsVision && messages.some(chunkILBKDEEL_cjs.hasImage)) {
|
|
66
67
|
throw new chunkMQ2XTH3S_cjs.ProviderError(
|
|
67
68
|
"Image input was provided but the configured model does not support vision",
|
|
68
69
|
"client"
|
|
@@ -74,7 +75,7 @@ function createAgent(config) {
|
|
|
74
75
|
const selected = skillIndex.select(promptText(userMessages));
|
|
75
76
|
if (selected.length === 0) return userMessages;
|
|
76
77
|
const contents = await Promise.all(selected.map((s) => skillIndex.load(s)));
|
|
77
|
-
const skillBlock =
|
|
78
|
+
const skillBlock = chunkILBKDEEL_cjs.textMessage(
|
|
78
79
|
"system",
|
|
79
80
|
`Relevant skill knowledge:
|
|
80
81
|
${contents.join("\n\n")}`
|
|
@@ -84,7 +85,7 @@ ${contents.join("\n\n")}`
|
|
|
84
85
|
async function callProvider(req) {
|
|
85
86
|
const ctx = {
|
|
86
87
|
agentName: config.name,
|
|
87
|
-
request: req
|
|
88
|
+
request: { ...req, model: req.model ?? config.model }
|
|
88
89
|
};
|
|
89
90
|
const pipeline = chunkFSDMBWQV_cjs.composeMiddleware(middleware, (c) => config.provider.generate(c.request));
|
|
90
91
|
return pipeline(ctx);
|
|
@@ -92,12 +93,13 @@ ${contents.join("\n\n")}`
|
|
|
92
93
|
async function prepare(input, opts) {
|
|
93
94
|
const userMessages = normalizeInput(input);
|
|
94
95
|
gateVision(userMessages);
|
|
95
|
-
const thread = opts?.thread ?? new
|
|
96
|
+
const thread = opts?.thread ?? new chunkILBKDEEL_cjs.Thread(void 0, [chunkILBKDEEL_cjs.textMessage("system", config.instructions)]);
|
|
96
97
|
const withSkills = await injectSkills(userMessages);
|
|
97
98
|
for (const m of withSkills) thread.add(m);
|
|
98
99
|
await thread.maybeCompact(config.provider, {
|
|
99
100
|
compactionThreshold: config.compactionThreshold,
|
|
100
|
-
compactionModel: config.compactionModel
|
|
101
|
+
compactionModel: config.compactionModel,
|
|
102
|
+
modelCapabilities: modelCaps()
|
|
101
103
|
});
|
|
102
104
|
return thread;
|
|
103
105
|
}
|
|
@@ -107,7 +109,7 @@ ${contents.join("\n\n")}`
|
|
|
107
109
|
thread = await prepare(input, opts);
|
|
108
110
|
} catch (e) {
|
|
109
111
|
if (e instanceof chunkMQ2XTH3S_cjs.ProviderError) {
|
|
110
|
-
return { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new
|
|
112
|
+
return { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new chunkILBKDEEL_cjs.Thread() };
|
|
111
113
|
}
|
|
112
114
|
throw e;
|
|
113
115
|
}
|
|
@@ -122,7 +124,7 @@ ${contents.join("\n\n")}`
|
|
|
122
124
|
}
|
|
123
125
|
return {
|
|
124
126
|
output: loop.final.text,
|
|
125
|
-
reasoning:
|
|
127
|
+
reasoning: modelCaps().supportsReasoning ? loop.final.reasoning : void 0,
|
|
126
128
|
status: loop.status,
|
|
127
129
|
partial: loop.status === "incomplete",
|
|
128
130
|
thread
|
|
@@ -140,7 +142,7 @@ ${contents.join("\n\n")}`
|
|
|
140
142
|
thread = await prepare(input, opts);
|
|
141
143
|
} catch (e) {
|
|
142
144
|
if (e instanceof chunkMQ2XTH3S_cjs.ProviderError) {
|
|
143
|
-
yield { type: "done", result: { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new
|
|
145
|
+
yield { type: "done", result: { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new chunkILBKDEEL_cjs.Thread() } };
|
|
144
146
|
return;
|
|
145
147
|
}
|
|
146
148
|
throw e;
|
|
@@ -151,12 +153,13 @@ ${contents.join("\n\n")}`
|
|
|
151
153
|
for await (const chunk of config.provider.generateStream({
|
|
152
154
|
messages: thread.messages,
|
|
153
155
|
tools: registry.specs(),
|
|
156
|
+
model: config.model,
|
|
154
157
|
signal: opts?.signal
|
|
155
158
|
})) {
|
|
156
159
|
if (chunk.type === "text") {
|
|
157
160
|
text += chunk.text;
|
|
158
161
|
yield { type: "text", text: chunk.text };
|
|
159
|
-
} else if (chunk.type === "reasoning" &&
|
|
162
|
+
} else if (chunk.type === "reasoning" && modelCaps().supportsReasoning) {
|
|
160
163
|
reasoning += chunk.text;
|
|
161
164
|
yield { type: "reasoning", text: chunk.text };
|
|
162
165
|
} else if (chunk.type === "done") {
|
|
@@ -177,7 +180,7 @@ ${contents.join("\n\n")}`
|
|
|
177
180
|
type: "done",
|
|
178
181
|
result: {
|
|
179
182
|
output: text,
|
|
180
|
-
reasoning:
|
|
183
|
+
reasoning: modelCaps().supportsReasoning ? reasoning || void 0 : void 0,
|
|
181
184
|
status: "completed",
|
|
182
185
|
partial: false,
|
|
183
186
|
thread
|
|
@@ -190,5 +193,5 @@ ${contents.join("\n\n")}`
|
|
|
190
193
|
exports.buildMessages = buildMessages;
|
|
191
194
|
exports.createAgent = createAgent;
|
|
192
195
|
exports.runLoop = runLoop;
|
|
193
|
-
//# sourceMappingURL=chunk-
|
|
194
|
-
//# sourceMappingURL=chunk-
|
|
196
|
+
//# sourceMappingURL=chunk-NURRGYIU.cjs.map
|
|
197
|
+
//# sourceMappingURL=chunk-NURRGYIU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/loop.ts","../src/agents/agent.ts"],"names":["textMessage","ToolRegistry","SkillIndex","hasImage","ProviderError","composeMiddleware","Thread"],"mappings":";;;;;;;;;AA4CA,eAAsB,OAAA,CACrB,QAAA,EACA,QAAA,EACA,QAAA,EACA,OAAA,EACsB;AACtB,EAAA,MAAM,aAAA,GAAgB,SAAS,aAAA,IAAiB,EAAA;AAChD,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,QAAQ,CAAA;AAC5B,EAAA,IAAI,SAAA,GAAY,CAAA;AAEhB,EAAA,WAAU;AACT,IAAA,IAAI,aAAA,KAAkB,EAAA,IAAM,SAAA,IAAa,aAAA,EAAe;AACvD,MAAA,OAAO;AAAA,QACN,QAAA,EAAU,OAAA;AAAA,QACV,KAAA,EAAO,EAAE,IAAA,EAAM,EAAA,EAAG;AAAA,QAClB,MAAA,EAAQ;AAAA,OACT;AAAA,IACD;AACA,IAAA,SAAA,EAAA;AAEA,IAAA,MAAM,KAAA,GAAQ,SAAS,KAAA,EAAM;AAC7B,IAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS;AAAA,MAC/B,QAAA,EAAU,OA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,MAAA;AAAA,MACN,MAAA,EAAQ;AAAA,QACP,MAAA,EAAQ,IAAA;AAAA,QACR,SAAA,EAAW,SAAA,EAAU,CAAE,iBAAA,GAAoB,aAAa,MAAA,GAAY,MAAA;AAAA,QACpE,MAAA,EAAQ,WAAA;AAAA,QACR,OAAA,EAAS,KAAA;AAAA,QACT;AAAA;AACD,KACD;AAAA,EACD;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,MAAA,CAAO,IAAA,EAAM,KAAK,SAAA,EAAU;AAC5C","file":"chunk-NURRGYIU.cjs","sourcesContent":["/**\n * The agent run loop: drives provider calls, executes requested tool calls,\n * feeds typed results (including errors, for self-correction) back to the model,\n * and stops on a final answer, the iteration cap, or an abort. (FR-011a, FR-012b)\n *\n * @packageDocumentation\n */\n\nimport type { Message } from \"../core/types.js\";\nimport { textMessage } from \"../core/types.js\";\nimport type { GenerateRequest, GenerateResponse } from \"../providers/provider.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\n\n/** Outcome status of a run. */\nexport type RunStatus = \"completed\" | \"failed\" | \"incomplete\" | \"limit-exceeded\";\n\n/** A function that produces a model response (optionally through middleware). */\nexport type GenerateFn = (req: GenerateRequest) => Promise<GenerateResponse>;\n\n/** Settings controlling the loop. */\nexport interface LoopOptions {\n\t/** Maximum iterations; -1 means unlimited. Default 10. (FR-012b) */\n\tmaxIterations?: number;\n\t/** Per-tool-call timeout in ms. (FR-012c) */\n\ttoolTimeoutMs?: number;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Result of running the loop. */\nexport interface LoopResult {\n\tmessages: Message[];\n\tfinal: GenerateResponse;\n\tstatus: RunStatus;\n}\n\n/**\n * Execute the tool-call loop against a generate function and tool registry.\n *\n * @param generate - Produces a model response (typically the middleware pipeline).\n * @param registry - Tools available to the agent (may be empty).\n * @param messages - Initial conversation (system + user, etc.).\n * @param options - Loop tuning.\n */\nexport async function runLoop(\n\tgenerate: GenerateFn,\n\tregistry: ToolRegistry,\n\tmessages: Message[],\n\toptions?: LoopOptions,\n): Promise<LoopResult> {\n\tconst maxIterations = options?.maxIterations ?? 10;\n\tconst working = [...messages];\n\tlet iteration = 0;\n\n\tfor (; ;) {\n\t\tif (maxIterations !== -1 && iteration >= maxIterations) {\n\t\t\treturn {\n\t\t\t\tmessages: working,\n\t\t\t\tfinal: { text: \"\" },\n\t\t\t\tstatus: \"limit-exceeded\",\n\t\t\t};\n\t\t}\n\t\titeration++;\n\n\t\tconst specs = registry.specs();\n\t\tconst response = await generate({\n\t\t\tmessages: working,\n\t\t\ttools: specs.length > 0 ? specs : undefined,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tif (!response.toolCalls || response.toolCalls.length === 0) {\n\t\t\treturn { messages: working, final: response, status: \"completed\" };\n\t\t}\n\n\t\t// Record the assistant's tool-call turn.\n\t\tworking.push({\n\t\t\trole: \"assistant\",\n\t\t\tparts: response.text ? [{ type: \"text\", text: response.text }] : [],\n\t\t});\n\n\t\t// Execute each requested tool and feed results (or typed errors) back.\n\t\tfor (const call of response.toolCalls) {\n\t\t\tconst result = await registry.invoke(call.name, call.arguments, options?.toolTimeoutMs);\n\t\t\tconst payload = result.error\n\t\t\t\t? `ERROR (${result.error.reason}): ${result.error.message}`\n\t\t\t\t: JSON.stringify(result.value ?? null);\n\t\t\tworking.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\tname: call.name,\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\tparts: [{ type: \"text\", text: payload }],\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Build the initial message list from instructions + input. */\nexport function buildMessages(instructions: string, input: Message[]): Message[] {\n\treturn [textMessage(\"system\", instructions), ...input];\n}\n","/**\n * The agent: a configured actor that runs against a provider, optionally using\n * tools and skills, with streaming, reasoning output, multimodal input gating,\n * conversation threads with compaction, and a middleware pipeline.\n *\n * @packageDocumentation\n */\n\nimport type { Message, ContentPart } from \"../core/types.js\";\nimport { hasImage, textMessage } from \"../core/types.js\";\nimport { ProviderError } from \"../core/errors.js\";\nimport type { Provider, GenerateResponse, GenerateRequest } from \"../providers/provider.js\";\nimport { ToolRegistry } from \"../tools/registry.js\";\nimport type { Tool } from \"../tools/tool.js\";\nimport type { Skill } from \"../skills/skill.js\";\nimport { SkillIndex } from \"../skills/index.js\";\nimport type { Middleware, MiddlewareContext } from \"../middleware/middleware.js\";\nimport { composeMiddleware } from \"../middleware/middleware.js\";\nimport { Thread, type ThreadOptions } from \"./thread.js\";\nimport { runLoop, type RunStatus } from \"./loop.js\";\n\n/** Configuration for {@link createAgent}. */\nexport interface AgentConfig {\n\tname: string;\n\tinstructions: string;\n\tprovider: Provider;\n\t/** Which of the provider's models to use; defaults to the provider's default model. */\n\tmodel?: string;\n\ttools?: Tool[];\n\tskills?: Skill[];\n\t/** Max tool-call iterations per run; -1 = unlimited. Default 10. (FR-012b) */\n\tmaxIterations?: number;\n\t/** Per-tool-call timeout in ms. (FR-012c) */\n\ttoolTimeoutMs?: number;\n\t/** Compaction threshold as a fraction of maxInputTokens. Default 0.9. (FR-004a) */\n\tcompactionThreshold?: number;\n\t/** Optional override model for compaction summaries. (FR-004b) */\n\tcompactionModel?: Provider;\n\t/** Middleware applied around provider calls. (FR-023) */\n\tmiddleware?: Middleware[];\n}\n\n/** Options for a single run. */\nexport interface RunOptions {\n\t/** Continue an existing conversation. (FR-004) */\n\tthread?: Thread;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** The result of a non-streaming run. */\nexport interface RunResult {\n\toutput: string;\n\t/** Reasoning content — only for reasoning-capable models. (FR-003a) */\n\treasoning?: string;\n\tstatus: RunStatus;\n\t/** True when the run was interrupted before completing. (FR-003b) */\n\tpartial: boolean;\n\terror?: ProviderError;\n\t/** The thread used/updated by this run. */\n\tthread: Thread;\n}\n\n/** Streamed run chunk. */\nexport type RunChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"reasoning\"; text: string }\n\t| { type: \"done\"; result: RunResult };\n\n/** Agent input: plain text or structured (multimodal) messages. (FR-002) */\nexport type AgentInput = string | Message | Message[];\n\n/** A runnable agent. */\nexport interface Agent {\n\treadonly name: string;\n\trun(input: AgentInput, opts?: RunOptions): Promise<RunResult>;\n\trunStream(input: AgentInput, opts?: RunOptions): AsyncIterable<RunChunk>;\n}\n\nfunction normalizeInput(input: AgentInput): Message[] {\n\tif (typeof input === \"string\") return [textMessage(\"user\", input)];\n\treturn Array.isArray(input) ? input : [input];\n}\n\nfunction promptText(messages: Message[]): string {\n\treturn messages\n\t\t.flatMap((m) => m.parts)\n\t\t.filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n\t\t.map((p) => p.text)\n\t\t.join(\" \");\n}\n\n/**\n * Create an agent.\n *\n * @example\n * ```ts\n * const agent = createAgent({ name: \"Helper\", instructions: \"Be concise.\", provider });\n * const res = await agent.run(\"Say hello.\");\n * console.log(res.status, res.output);\n * ```\n */\nexport function createAgent(config: AgentConfig): Agent {\n\tconst registry = new ToolRegistry(config.tools ?? []);\n\tconst skillIndex = new SkillIndex(config.skills ?? []);\n\tconst middleware = config.middleware ?? [];\n\t/** Capabilities of the model this agent uses (selected from the provider). */\n\tconst modelCaps = () => config.provider.model(config.model);\n\n\tfunction gateVision(messages: Message[]): void {\n\t\tif (!modelCaps().supportsVision && messages.some(hasImage)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t\"Image input was provided but the configured model does not support vision\",\n\t\t\t\t\"client\",\n\t\t\t);\n\t\t}\n\t}\n\n\tasync function injectSkills(userMessages: Message[]): Promise<Message[]> {\n\t\tif ((config.skills ?? []).length === 0) return userMessages;\n\t\tconst selected = skillIndex.select(promptText(userMessages));\n\t\tif (selected.length === 0) return userMessages;\n\t\tconst contents = await Promise.all(selected.map((s) => skillIndex.load(s)));\n\t\tconst skillBlock = textMessage(\n\t\t\t\"system\",\n\t\t\t`Relevant skill knowledge:\\n${contents.join(\"\\n\\n\")}`,\n\t\t);\n\t\treturn [skillBlock, ...userMessages];\n\t}\n\n\tasync function callProvider(req: GenerateRequest): Promise<GenerateResponse> {\n\t\tconst ctx: MiddlewareContext = {\n\t\t\tagentName: config.name,\n\t\t\trequest: { ...req, model: req.model ?? config.model },\n\t\t};\n\t\tconst pipeline = composeMiddleware(middleware, (c) => config.provider.generate(c.request));\n\t\treturn pipeline(ctx);\n\t}\n\n\tasync function prepare(input: AgentInput, opts?: RunOptions): Promise<Thread> {\n\t\tconst userMessages = normalizeInput(input);\n\t\tgateVision(userMessages);\n\t\tconst thread =\n\t\t\topts?.thread ??\n\t\t\tnew Thread(undefined, [textMessage(\"system\", config.instructions)]);\n\t\tconst withSkills = await injectSkills(userMessages);\n\t\tfor (const m of withSkills) thread.add(m);\n\t\tawait thread.maybeCompact(config.provider, {\n\t\t\tcompactionThreshold: config.compactionThreshold,\n\t\t\tcompactionModel: config.compactionModel,\n\t\t\tmodelCapabilities: modelCaps(),\n\t\t} satisfies ThreadOptions);\n\t\treturn thread;\n\t}\n\n\tasync function run(input: AgentInput, opts?: RunOptions): Promise<RunResult> {\n\t\tlet thread: Thread;\n\t\ttry {\n\t\t\tthread = await prepare(input, opts);\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\treturn { output: \"\", status: \"failed\", partial: false, error: e, thread: opts?.thread ?? new Thread() };\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\n\t\ttry {\n\t\t\tconst loop = await runLoop(callProvider, registry, thread.messages, {\n\t\t\t\tmaxIterations: config.maxIterations,\n\t\t\t\ttoolTimeoutMs: config.toolTimeoutMs,\n\t\t\t\tsignal: opts?.signal,\n\t\t\t});\n\t\t\tif (loop.final.text) {\n\t\t\t\tthread.add({ role: \"assistant\", parts: [{ type: \"text\", text: loop.final.text }] });\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: loop.final.text,\n\t\t\t\treasoning: modelCaps().supportsReasoning ? loop.final.reasoning : undefined,\n\t\t\t\tstatus: loop.status,\n\t\t\t\tpartial: loop.status === \"incomplete\",\n\t\t\t\tthread,\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\treturn { output: \"\", status: \"failed\", partial: false, error: e, thread };\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync function* runStream(input: AgentInput, opts?: RunOptions): AsyncIterable<RunChunk> {\n\t\t// Streaming path: single provider streaming call (tool loops use non-streaming\n\t\t// internally). Suitable for the common single-turn streaming case.\n\t\tlet thread: Thread;\n\t\ttry {\n\t\t\tthread = await prepare(input, opts);\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\tyield { type: \"done\", result: { output: \"\", status: \"failed\", partial: false, error: e, thread: opts?.thread ?? new Thread() } };\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\n\t\tlet text = \"\";\n\t\tlet reasoning = \"\";\n\t\ttry {\n\t\t\tfor await (const chunk of config.provider.generateStream({\n\t\t\t\tmessages: thread.messages,\n\t\t\t\ttools: registry.specs(),\n\t\t\t\tmodel: config.model,\n\t\t\t\tsignal: opts?.signal,\n\t\t\t})) {\n\t\t\t\tif (chunk.type === \"text\") {\n\t\t\t\t\ttext += chunk.text;\n\t\t\t\t\tyield { type: \"text\", text: chunk.text };\n\t\t\t\t} else if (chunk.type === \"reasoning\" && modelCaps().supportsReasoning) {\n\t\t\t\t\treasoning += chunk.text;\n\t\t\t\t\tyield { type: \"reasoning\", text: chunk.text };\n\t\t\t\t} else if (chunk.type === \"done\") {\n\t\t\t\t\ttext = chunk.response.text || text;\n\t\t\t\t\treasoning = chunk.response.reasoning || reasoning;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconst error = e instanceof ProviderError ? e : new ProviderError((e as Error).message, \"transient\");\n\t\t\tyield {\n\t\t\t\ttype: \"done\",\n\t\t\t\tresult: { output: text, status: \"incomplete\", partial: true, error, thread },\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\n\t\tif (text) thread.add({ role: \"assistant\", parts: [{ type: \"text\", text }] });\n\t\tyield {\n\t\t\ttype: \"done\",\n\t\t\tresult: {\n\t\t\t\toutput: text,\n\t\t\t\treasoning: modelCaps().supportsReasoning ? reasoning || undefined : undefined,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tpartial: false,\n\t\t\t\tthread,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { name: config.name, run, runStream };\n}\n\nexport type { ContentPart };\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createAgent } from './chunk-
|
|
1
|
+
import { createAgent } from './chunk-WEKU7735.js';
|
|
2
2
|
import { ValidationError } from './chunk-IXV4UIF5.js';
|
|
3
3
|
|
|
4
4
|
// src/declarative/loader.ts
|
|
@@ -44,5 +44,5 @@ async function loadAgentDefinition(source, deps) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export { loadAgentDefinition };
|
|
47
|
-
//# sourceMappingURL=chunk-
|
|
48
|
-
//# sourceMappingURL=chunk-
|
|
47
|
+
//# sourceMappingURL=chunk-S5776DOL.js.map
|
|
48
|
+
//# sourceMappingURL=chunk-S5776DOL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/declarative/loader.ts"],"names":[],"mappings":";;;;AA+CA,SAAS,cAAc,MAAA,EAAyB;AAC/C,EAAA,MAAM,CAAA,GAAI,OAAO,SAAA,EAAU;AAC3B,EAAA,OAAO,EAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,WAAW,GAAG,CAAA;AAC7C;AAEA,eAAe,MAAM,MAAA,EAAkC;AACtD,EAAA,IAAI,aAAA,CAAc,MAAM,CAAA,EAAG;AAC1B,IAAA,IAAI;AACH,MAAA,OAAO,IAAA,CAAK,MAAM,MAAM,CAAA;AAAA,IACzB,SAAS,CAAA,EAAG;AACX,MAAA,MAAM,IAAI,eAAA,CAAgB,CAAA,yBAAA,EAA6B,CAAA,CAAY,OAAO,CAAA,CAAE,C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DAA0D,CAAA;AAAA,EACrF;AACD;AAaA,eAAsB,mBAAA,CAAoB,QAAgB,IAAA,EAAkC;AAC3F,EAAA,MAAM,MAAA,GAAS,MAAM,KAAA,CAAM,MAAM,CAAA;AACjC,EAAA,gBAAA,CAAiB,MAAM,CAAA;AAEvB,EAAA,MAAM,WAAW,IAAA,CAAK,eAAA,CAAgB,MAAA,CAAO,QAAA,EAAU,KAAK,aAAa,CAAA;AACzE,EAAA,MAAM,SAAS,MAAA,CAAO,KAAA,IAAS,EAAC,EAC9B,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,KAAA,GAAQ,IAAI,CAAC,CAAA,CAChC,MAAA,CAAO,CAAC,CAAA,KAAiB,CAAC,CAAC,CAAC,CAAA;AAC9B,EAAA,MAAM,UAAU,MAAA,CAAO,MAAA,IAAU,EAAC,EAChC,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,MAAA,GAAS,IAAI,CAAC,CAAA,CACjC,MAAA,CAAO,CAAC,CAAA,KAAkB,CAAC,CAAC,CAAC,CAAA;AAE/B,EAAA,OAAO,WAAA,CAAY;AAAA,IAClB,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,QAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,eAAe,MAAA,CAAO;AAAA,GACtB,CAAA;AACF","file":"chunk-S5776DOL.js","sourcesContent":["/**\n * Declarative agent definitions. Agents can be defined in YAML or JSON against a\n * single shared schema; the loader auto-detects the format (the YAML parser is\n * lazy-loaded so JSON-only/browser use pays no cost) and builds an equivalent\n * runnable agent. Credentials are still injected via callback, never embedded.\n * (FR-027, FR-005a)\n *\n * @packageDocumentation\n */\n\nimport type { ModelCapabilities } from \"../core/types.js\";\nimport type { Provider } from \"../providers/provider.js\";\nimport type { Tool } from \"../tools/tool.js\";\nimport type { Skill } from \"../skills/skill.js\";\nimport { createAgent, type Agent } from \"../agents/agent.js\";\nimport { ValidationError } from \"../core/errors.js\";\n\n/** Provider section of a declarative definition. */\nexport interface ProviderDefinition extends ModelCapabilities {\n\ttype: \"copilot\" | \"openai-compatible\";\n\tbaseUrl?: string;\n}\n\n/** A declarative agent definition (shared by YAML and JSON). */\nexport interface AgentDefinition {\n\tname: string;\n\tinstructions: string;\n\tprovider: ProviderDefinition;\n\t/** Names referencing tools provided in `deps.tools`. */\n\ttools?: string[];\n\t/** Names referencing skills provided in `deps.skills`. */\n\tskills?: string[];\n\tmaxIterations?: number;\n}\n\n/** Dependencies the loader needs to construct a live agent. */\nexport interface LoaderDeps {\n\t/** Build a provider from the definition + injected credential. */\n\tproviderFactory: (def: ProviderDefinition, getCredential: () => string | Promise<string>) => Provider;\n\t/** Credential callback — never embedded in the definition. (FR-005a) */\n\tgetCredential: () => string | Promise<string>;\n\t/** Registered tools available for reference by name. */\n\ttools?: Record<string, Tool>;\n\t/** Registered skills available for reference by name. */\n\tskills?: Record<string, Skill>;\n}\n\nfunction looksLikeJson(source: string): boolean {\n\tconst t = source.trimStart();\n\treturn t.startsWith(\"{\") || t.startsWith(\"[\");\n}\n\nasync function parse(source: string): Promise<unknown> {\n\tif (looksLikeJson(source)) {\n\t\ttry {\n\t\t\treturn JSON.parse(source);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(`Invalid JSON definition: ${(e as Error).message}`);\n\t\t}\n\t}\n\t// Lazy-load the YAML parser only when needed. (FR-027)\n\tconst YAML = await import(\"yaml\");\n\ttry {\n\t\treturn YAML.parse(source);\n\t} catch (e) {\n\t\tthrow new ValidationError(`Invalid YAML definition: ${(e as Error).message}`);\n\t}\n}\n\nfunction assertDefinition(value: unknown): asserts value is AgentDefinition {\n\tconst d = value as Partial<AgentDefinition>;\n\tif (!d || typeof d.name !== \"string\" || typeof d.instructions !== \"string\" || !d.provider) {\n\t\tthrow new ValidationError(\"Definition must include name, instructions, and provider\");\n\t}\n}\n\n/**\n * Load an agent from a YAML or JSON definition string.\n *\n * @example\n * ```ts\n * const agent = await loadAgentDefinition(yamlOrJson, {\n * providerFactory,\n * getCredential: () => process.env.LMSTUDIO_KEY ?? \"\",\n * });\n * ```\n */\nexport async function loadAgentDefinition(source: string, deps: LoaderDeps): Promise<Agent> {\n\tconst parsed = await parse(source);\n\tassertDefinition(parsed);\n\n\tconst provider = deps.providerFactory(parsed.provider, deps.getCredential);\n\tconst tools = (parsed.tools ?? [])\n\t\t.map((name) => deps.tools?.[name])\n\t\t.filter((t): t is Tool => !!t);\n\tconst skills = (parsed.skills ?? [])\n\t\t.map((name) => deps.skills?.[name])\n\t\t.filter((s): s is Skill => !!s);\n\n\treturn createAgent({\n\t\tname: parsed.name,\n\t\tinstructions: parsed.instructions,\n\t\tprovider,\n\t\ttools,\n\t\tskills,\n\t\tmaxIterations: parsed.maxIterations,\n\t});\n}\n"]}
|
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
var chunkMQ2XTH3S_cjs = require('./chunk-MQ2XTH3S.cjs');
|
|
4
4
|
|
|
5
|
+
// src/providers/provider.ts
|
|
6
|
+
function resolveModels(options) {
|
|
7
|
+
const models = options.models ?? (options.capabilities ? [options.capabilities] : []);
|
|
8
|
+
if (models.length === 0) {
|
|
9
|
+
throw new chunkMQ2XTH3S_cjs.ValidationError("Provider requires at least one model (set `capabilities` or `models`)");
|
|
10
|
+
}
|
|
11
|
+
const defaultModel = options.defaultModel ? models.find((m) => m.model === options.defaultModel) : models[0];
|
|
12
|
+
if (!defaultModel) {
|
|
13
|
+
throw new chunkMQ2XTH3S_cjs.ValidationError(`defaultModel "${options.defaultModel}" is not present in models`);
|
|
14
|
+
}
|
|
15
|
+
const modelOf = (name) => {
|
|
16
|
+
if (!name) return defaultModel;
|
|
17
|
+
const found = models.find((m) => m.model === name);
|
|
18
|
+
if (!found) {
|
|
19
|
+
throw new chunkMQ2XTH3S_cjs.ValidationError(`Model "${name}" is not configured for this provider`);
|
|
20
|
+
}
|
|
21
|
+
return found;
|
|
22
|
+
};
|
|
23
|
+
return { models, defaultModel, modelOf };
|
|
24
|
+
}
|
|
25
|
+
|
|
5
26
|
// src/providers/retry.ts
|
|
6
27
|
var DEFAULTS = {
|
|
7
28
|
maxRetries: 3,
|
|
@@ -60,6 +81,7 @@ function toOpenAIMessages(messages) {
|
|
|
60
81
|
function createOpenAICompatibleProvider(options) {
|
|
61
82
|
const doFetch = options.fetchImpl ?? globalThis.fetch;
|
|
62
83
|
const url = `${options.baseUrl.replace(/\/$/, "")}/chat/completions`;
|
|
84
|
+
const { models, defaultModel, modelOf } = resolveModels(options);
|
|
63
85
|
async function authHeaders() {
|
|
64
86
|
const cred = await options.getCredential();
|
|
65
87
|
const headers = { "content-type": "application/json" };
|
|
@@ -68,7 +90,7 @@ function createOpenAICompatibleProvider(options) {
|
|
|
68
90
|
}
|
|
69
91
|
function body(req, stream) {
|
|
70
92
|
return JSON.stringify({
|
|
71
|
-
model:
|
|
93
|
+
model: modelOf(req.model).model,
|
|
72
94
|
messages: toOpenAIMessages(req.messages),
|
|
73
95
|
stream,
|
|
74
96
|
...req.tools && req.tools.length > 0 ? {
|
|
@@ -113,7 +135,7 @@ function createOpenAICompatibleProvider(options) {
|
|
|
113
135
|
const message = choice.message;
|
|
114
136
|
return {
|
|
115
137
|
text: message["content"] ?? "",
|
|
116
|
-
reasoning:
|
|
138
|
+
reasoning: modelOf(req.model).supportsReasoning ? message["reasoning"] ?? void 0 : void 0,
|
|
117
139
|
toolCalls: parseToolCalls(message)
|
|
118
140
|
};
|
|
119
141
|
}, options.retry);
|
|
@@ -154,7 +176,7 @@ function createOpenAICompatibleProvider(options) {
|
|
|
154
176
|
text += delta.content;
|
|
155
177
|
yield { type: "text", text: delta.content };
|
|
156
178
|
}
|
|
157
|
-
if (delta?.reasoning &&
|
|
179
|
+
if (delta?.reasoning && modelOf(req.model).supportsReasoning) {
|
|
158
180
|
reasoning += delta.reasoning;
|
|
159
181
|
yield { type: "reasoning", text: delta.reasoning };
|
|
160
182
|
}
|
|
@@ -165,7 +187,14 @@ function createOpenAICompatibleProvider(options) {
|
|
|
165
187
|
response: { text, reasoning: reasoning || void 0 }
|
|
166
188
|
};
|
|
167
189
|
}
|
|
168
|
-
return {
|
|
190
|
+
return {
|
|
191
|
+
name: "openai-compatible",
|
|
192
|
+
capabilities: defaultModel,
|
|
193
|
+
models,
|
|
194
|
+
model: modelOf,
|
|
195
|
+
generate,
|
|
196
|
+
generateStream
|
|
197
|
+
};
|
|
169
198
|
}
|
|
170
199
|
function safeJson(s) {
|
|
171
200
|
try {
|
|
@@ -182,12 +211,16 @@ function createCopilotProvider(options) {
|
|
|
182
211
|
baseUrl: options.baseUrl ?? DEFAULT_COPILOT_BASE_URL,
|
|
183
212
|
getCredential: options.getCredential,
|
|
184
213
|
capabilities: options.capabilities,
|
|
214
|
+
models: options.models,
|
|
215
|
+
defaultModel: options.defaultModel,
|
|
185
216
|
retry: options.retry,
|
|
186
217
|
fetchImpl: options.fetchImpl
|
|
187
218
|
});
|
|
188
219
|
return {
|
|
189
220
|
name: "copilot",
|
|
190
221
|
capabilities: inner.capabilities,
|
|
222
|
+
models: inner.models,
|
|
223
|
+
model: inner.model.bind(inner),
|
|
191
224
|
generate: inner.generate.bind(inner),
|
|
192
225
|
generateStream: inner.generateStream.bind(inner)
|
|
193
226
|
};
|
|
@@ -196,6 +229,7 @@ function createCopilotProvider(options) {
|
|
|
196
229
|
exports.createCopilotProvider = createCopilotProvider;
|
|
197
230
|
exports.createOpenAICompatibleProvider = createOpenAICompatibleProvider;
|
|
198
231
|
exports.providerErrorFromStatus = providerErrorFromStatus;
|
|
232
|
+
exports.resolveModels = resolveModels;
|
|
199
233
|
exports.withRetry = withRetry;
|
|
200
|
-
//# sourceMappingURL=chunk-
|
|
201
|
-
//# sourceMappingURL=chunk-
|
|
234
|
+
//# sourceMappingURL=chunk-U64OEHG6.cjs.map
|
|
235
|
+
//# sourceMappingURL=chunk-U64OEHG6.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/providers/provider.ts","../src/providers/retry.ts","../src/providers/openai-compatible.ts","../src/providers/copilot.ts"],"names":["ValidationError","ProviderError"],"mappings":";;;;;AA4DO,SAAS,cAAc,OAAA,EAAgD;AAC7E,EAAA,MAAM,MAAA,GAAS,QAAQ,MAAA,KAAW,OAAA,CAAQ,eAAe,CAAC,OAAA,CAAQ,YAAY,CAAA,GAAI,EAAC,CAAA;AACnF,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACxB,IAAA,MAAM,IAAIA,kCAAgB,uEAAuE,CAAA;AAAA,EAClG;AACA,EAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,YAAA,GAC1B,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,KAAA,KAAU,OAAA,CAAQ,YAAY,CAAA,GACnD,OAAO,CAAC,CAAA;AACX,EAAA,IAAI,CAAC,YAAA,EAAc;AAClB,IAAA,MAAM,IAAIA,iCAAA,CAAgB,CAAA,cAAA,EAAiB,OAAA,CAAQ,YAAY,CAAA,0BAAA,CAA4B,CAAA;AAAA,EAC5F;AACA,EAAA,MAAM,OAAA,GAAU,CAAC,IAAA,KAAqC;AACrD,IAAA,IAAI,CAAC,MAAM,OAAO,YAAA;AAClB,IAAA,MAAM,QAAQ,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,UAAU,IAAI,CAAA;AACjD,IAAA,IAAI,CAAC,KAAA,EAAO;AACX,MAAA,MAAM,IAAIA,iCAAA,CAAgB,CAAA,OAAA,EAAU,IAAI,CAAA,qCAAA,CAAuC,CAAA;AAAA,IAChF;AACA,IAAA,OAAO,KAAA;AAAA,EACR,CAAA;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,YAAA,EAAc,OAAA,EAAQ;AACxC;;;AC5DA,IAAM,QAAA,GAAmC;AAAA,EACxC,UAAA,EAAY,CAAA;AAAA,EACZ,WAAA,EAAa,GAAA;AAAA,EACb,UA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AAM,SAAA,EAAW,aAAa,MAAA;AAAU,KACrD;AAAA,EACD;AAEA,EAAA,OAAO;AAAA,IACN,IAAA,EAAM,mBAAA;AAAA,IACN,YAAA,EAAc,YAAA;AAAA,IACd,MAAA;AAAA,IACA,KAAA,EAAO,OAAA;AAAA,IACP,QAAA;AAAA,IACA;AAAA,GACD;AACD;AAEA,SAAS,SAAS,CAAA,EAAoB;AACrC,EAAA,IAAI;AACH,IAAA,OAAO,IAAA,CAAK,MAAM,CAAC,CAAA;AAAA,EACpB,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,MAAA;AAAA,EACR;AACD;;;ACvMA,IAAM,wBAAA,GAA2B,+BAAA;AAyC1B,SAAS,sBAAsB,OAAA,EAA2C;AAChF,EAAA,MAAM,QAAQ,8BAAA,CAA+B;AAAA,IAC5C,OAAA,EAAS,QAAQ,OAAA,IAAW,wBAAA;AAAA,IAC5B,eAAe,OAAA,CAAQ,aAAA;AAAA,IACvB,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,QAAQ,OAAA,CAAQ,MAAA;AAAA,IAChB,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,WAAW,OAAA,CAAQ;AAAA,GACnB,CAAA;AAED,EAAA,OAAO;AAAA,IACN,IAAA,EAAM,SAAA;AAAA,IACN,cAAc,KAAA,CAAM,YAAA;AAAA,IACpB,QAAQ,KAAA,CAAM,MAAA;AAAA,IACd,KAAA,EAAO,KAAA,CAAM,KAAA,CAAM,IAAA,CAAK,KAAK,CAAA;AAAA,IAC7B,QAAA,EAAU,KAAA,CAAM,QAAA,CAAS,IAAA,CAAK,KAAK,CAAA;AAAA,IACnC,cAAA,EAAgB,KAAA,CAAM,cAAA,CAAe,IAAA,CAAK,KAAK;AAAA,GAChD;AACD","file":"chunk-U64OEHG6.cjs","sourcesContent":["/**\n * LLM provider abstraction. Agents and workflows depend only on this interface,\n * never on a concrete provider, so new providers can be added without changing\n * agent/workflow code. (FR-007)\n *\n * Credentials are always obtained via a caller-supplied callback and are never\n * bundled, persisted, or logged by the framework. (FR-005a, FR-008)\n *\n * @packageDocumentation\n */\n\nimport type { Message, ModelCapabilities } from \"../core/types.js\";\nimport { ValidationError } from \"../core/errors.js\";\n\n/** A caller-supplied source of credentials. The framework never stores the value. */\nexport interface CredentialSource {\n\t/** Return the current credential (token/api key). May be async. */\n\tgetCredential(): string | Promise<string>;\n}\n\n/**\n * Model configuration for a provider. A provider may expose **one or more** models\n * (e.g. GitHub Copilot offers several; an OpenAI-compatible endpoint is usually one).\n * Supply either a single `capabilities` object or an array via `models`.\n */\nexport interface ModelSelectionOptions {\n\t/** Single-model shorthand. */\n\tcapabilities?: ModelCapabilities;\n\t/** One or more models this provider can use. */\n\tmodels?: ModelCapabilities[];\n\t/** Name of the default model (defaults to the first entry). */\n\tdefaultModel?: string;\n}\n\n/** Resolved model set with a default and a lookup helper. */\nexport interface ResolvedModels {\n\t/** All configured models (at least one). */\n\tmodels: ModelCapabilities[];\n\t/** The default model used when a request does not specify one. */\n\tdefaultModel: ModelCapabilities;\n\t/** Look up a model by name, or return the default when omitted. */\n\tmodelOf(name?: string): ModelCapabilities;\n}\n\n/**\n * Normalize {@link ModelSelectionOptions} into a model list, a default, and a\n * lookup helper. Throws {@link ValidationError} if no model is configured or a\n * named model is missing.\n *\n * @example\n * ```ts\n * const { defaultModel, modelOf } = resolveModels({\n * models: [\n * { model: \"gpt-4o\", maxInputTokens: 128000, maxOutputTokens: 16000 },\n * { model: \"o3-mini\", maxInputTokens: 200000, maxOutputTokens: 100000, supportsReasoning: true },\n * ],\n * defaultModel: \"gpt-4o\",\n * });\n * ```\n */\nexport function resolveModels(options: ModelSelectionOptions): ResolvedModels {\n\tconst models = options.models ?? (options.capabilities ? [options.capabilities] : []);\n\tif (models.length === 0) {\n\t\tthrow new ValidationError(\"Provider requires at least one model (set `capabilities` or `models`)\");\n\t}\n\tconst defaultModel = options.defaultModel\n\t\t? models.find((m) => m.model === options.defaultModel)\n\t\t: models[0];\n\tif (!defaultModel) {\n\t\tthrow new ValidationError(`defaultModel \"${options.defaultModel}\" is not present in models`);\n\t}\n\tconst modelOf = (name?: string): ModelCapabilities => {\n\t\tif (!name) return defaultModel;\n\t\tconst found = models.find((m) => m.model === name);\n\t\tif (!found) {\n\t\t\tthrow new ValidationError(`Model \"${name}\" is not configured for this provider`);\n\t\t}\n\t\treturn found;\n\t};\n\treturn { models, defaultModel, modelOf };\n}\n\n/** A tool description passed to the provider so the model can decide to call it. */\nexport interface ToolSpec {\n\tname: string;\n\tdescription: string;\n\tinputSchema: Record<string, unknown>;\n}\n\n/** A request to generate a model response. */\nexport interface GenerateRequest {\n\tmessages: Message[];\n\ttools?: ToolSpec[];\n\t/** Which configured model to use; defaults to the provider's default model. */\n\tmodel?: string;\n\t/** Abort signal to cancel an in-flight request. */\n\tsignal?: AbortSignal;\n}\n\n/** A tool call requested by the model. */\nexport interface ToolCall {\n\tid: string;\n\tname: string;\n\t/** Raw JSON arguments (validated by the tools module before invocation). */\n\targuments: unknown;\n}\n\n/** A complete (non-streaming) model response. */\nexport interface GenerateResponse {\n\t/** Final answer text. */\n\ttext: string;\n\t/** Reasoning/thinking content — only present for reasoning-capable models. (FR-003a) */\n\treasoning?: string;\n\t/** Tool calls the model wants to make, if any. */\n\ttoolCalls?: ToolCall[];\n\t/** Approximate token usage if reported by the provider. */\n\tusage?: { inputTokens?: number; outputTokens?: number };\n}\n\n/** An incremental streaming chunk. */\nexport type GenerateChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"reasoning\"; text: string }\n\t| { type: \"tool-call\"; toolCall: ToolCall }\n\t| { type: \"done\"; response: GenerateResponse };\n\n/**\n * An LLM backend. Implementations adapt a concrete API (Copilot, OpenAI-compatible)\n * onto this uniform surface.\n */\nexport interface Provider {\n\t/** Stable provider identifier, e.g. `\"openai-compatible\"`. */\n\treadonly name: string;\n\t/** The default model's capability configuration. (FR-007a) */\n\treadonly capabilities: ModelCapabilities;\n\t/** All models this provider is configured with (one or more). */\n\treadonly models: ModelCapabilities[];\n\t/** Look up a configured model by name, or the default when omitted. */\n\tmodel(name?: string): ModelCapabilities;\n\t/** Generate a complete response. */\n\tgenerate(req: GenerateRequest): Promise<GenerateResponse>;\n\t/** Generate a streamed response. */\n\tgenerateStream(req: GenerateRequest): AsyncIterable<GenerateChunk>;\n}\n","/**\n * Exponential-backoff retry for transient provider failures. Transient errors\n * (429 with Retry-After, 5xx, network/timeout) are retried; auth/4xx fail fast.\n * (FR-008a)\n *\n * @packageDocumentation\n */\n\nimport { ProviderError } from \"../core/errors.js\";\n\n/** Retry tuning. All fields have safe defaults. */\nexport interface RetryOptions {\n\t/** Maximum retry attempts after the first try. Default 3. */\n\tmaxRetries?: number;\n\t/** Base delay in ms for backoff. Default 250. */\n\tbaseDelayMs?: number;\n\t/** Maximum delay cap in ms. Default 8000. */\n\tmaxDelayMs?: number;\n}\n\nconst DEFAULTS: Required<RetryOptions> = {\n\tmaxRetries: 3,\n\tbaseDelayMs: 250,\n\tmaxDelayMs: 8000,\n};\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((r) => setTimeout(r, ms));\n}\n\n/**\n * Run `fn`, retrying transient {@link ProviderError}s with exponential backoff\n * and jitter. Non-transient errors are rethrown immediately (fail fast).\n *\n * @param fn - The operation to attempt. It should throw a {@link ProviderError}.\n * @param opts - Retry tuning.\n * @param retryAfterMs - Optional hook returning a server-specified delay (Retry-After).\n */\nexport async function withRetry<T>(\n\tfn: () => Promise<T>,\n\topts?: RetryOptions,\n\tretryAfterMs?: (err: ProviderError) => number | undefined,\n): Promise<T> {\n\tconst cfg = { ...DEFAULTS, ...opts };\n\tlet attempt = 0;\n\n\tfor (; ;) {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (err) {\n\t\t\tconst isRetryable = err instanceof ProviderError && err.retryable;\n\t\t\tif (!isRetryable || attempt >= cfg.maxRetries) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tconst serverDelay = retryAfterMs?.(err as ProviderError);\n\t\t\tconst backoff = Math.min(cfg.baseDelayMs * 2 ** attempt, cfg.maxDelayMs);\n\t\t\tconst jitter = Math.random() * cfg.baseDelayMs;\n\t\t\tawait sleep(serverDelay ?? backoff + jitter);\n\t\t\tattempt++;\n\t\t}\n\t}\n}\n\n/** Map an HTTP status to a {@link ProviderError} with the right retry semantics. */\nexport function providerErrorFromStatus(status: number, message: string): ProviderError {\n\tif (status === 429 || status >= 500) {\n\t\treturn new ProviderError(message, \"transient\", { status });\n\t}\n\tif (status === 401 || status === 403) {\n\t\treturn new ProviderError(message, \"auth\", { status });\n\t}\n\treturn new ProviderError(message, \"client\", { status });\n}\n","/**\n * OpenAI-compatible provider. Targets any endpoint speaking the OpenAI\n * `/chat/completions` API, including local servers such as LM Studio via a custom\n * `baseUrl`. (FR-006)\n *\n * @packageDocumentation\n */\n\nimport type { Message, ContentPart } from \"../core/types.js\";\nimport { ProviderError } from \"../core/errors.js\";\nimport type {\n\tProvider,\n\tCredentialSource,\n\tGenerateRequest,\n\tGenerateResponse,\n\tGenerateChunk,\n\tToolCall,\n} from \"./provider.js\";\nimport { resolveModels, type ModelSelectionOptions } from \"./provider.js\";\nimport { withRetry, providerErrorFromStatus, type RetryOptions } from \"./retry.js\";\n\n/**\n * Options for {@link createOpenAICompatibleProvider}.\n *\n * Supply a single model via `capabilities`, or multiple via `models` (most\n * OpenAI-compatible endpoints expose one model, but multiple are supported).\n */\nexport interface OpenAICompatibleProviderOptions extends CredentialSource, ModelSelectionOptions {\n\t/** Base URL of the OpenAI-compatible API, e.g. `http://localhost:1234/v1`. */\n\tbaseUrl: string;\n\t/** Retry tuning for transient failures. */\n\tretry?: RetryOptions;\n\t/** Optional custom fetch (for testing or non-standard runtimes). */\n\tfetchImpl?: typeof fetch;\n}\n\ninterface OpenAIMessage {\n\trole: string;\n\tcontent: unknown;\n\ttool_calls?: Array<{ id: string; type: \"function\"; function: { name: string; arguments: string } }>;\n\ttool_call_id?: string;\n\tname?: string;\n}\n\nfunction toOpenAIContent(parts: ContentPart[]): unknown {\n\tif (parts.every((p) => p.type === \"text\")) {\n\t\treturn parts.map((p) => (p as { text: string }).text).join(\"\");\n\t}\n\treturn parts.map((p) =>\n\t\tp.type === \"text\"\n\t\t\t? { type: \"text\", text: p.text }\n\t\t\t: { type: \"image_url\", image_url: { url: p.data } },\n\t);\n}\n\nfunction toOpenAIMessages(messages: Message[]): OpenAIMessage[] {\n\treturn messages.map((m) => {\n\t\tconst msg: OpenAIMessage = { role: m.role, content: toOpenAIContent(m.parts) };\n\t\tif (m.toolCallId) msg.tool_call_id = m.toolCallId;\n\t\tif (m.name) msg.name = m.name;\n\t\treturn msg;\n\t});\n}\n\n/**\n * Create an OpenAI-compatible provider (works with LM Studio, vLLM, etc.).\n *\n * @example\n * ```ts\n * const provider = createOpenAICompatibleProvider({\n * baseUrl: \"http://localhost:1234/v1\",\n * getCredential: () => process.env.LMSTUDIO_KEY ?? \"\",\n * capabilities: { model: \"local\", maxInputTokens: 262144, maxOutputTokens: 32000 },\n * });\n * ```\n */\nexport function createOpenAICompatibleProvider(\n\toptions: OpenAICompatibleProviderOptions,\n): Provider {\n\tconst doFetch = options.fetchImpl ?? globalThis.fetch;\n\tconst url = `${options.baseUrl.replace(/\\/$/, \"\")}/chat/completions`;\n\tconst { models, defaultModel, modelOf } = resolveModels(options);\n\n\tasync function authHeaders(): Promise<Record<string, string>> {\n\t\tconst cred = await options.getCredential();\n\t\tconst headers: Record<string, string> = { \"content-type\": \"application/json\" };\n\t\tif (cred) headers[\"authorization\"] = `Bearer ${cred}`;\n\t\treturn headers;\n\t}\n\n\tfunction body(req: GenerateRequest, stream: boolean): string {\n\t\treturn JSON.stringify({\n\t\t\tmodel: modelOf(req.model).model,\n\t\t\tmessages: toOpenAIMessages(req.messages),\n\t\t\tstream,\n\t\t\t...(req.tools && req.tools.length > 0\n\t\t\t\t? {\n\t\t\t\t\ttools: req.tools.map((t) => ({\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: t.name, description: t.description, parameters: t.inputSchema },\n\t\t\t\t\t})),\n\t\t\t\t}\n\t\t\t\t: {}),\n\t\t});\n\t}\n\n\tfunction parseToolCalls(raw: unknown): ToolCall[] | undefined {\n\t\tconst calls = (raw as { tool_calls?: Array<{ id: string; function: { name: string; arguments: string } }> })\n\t\t\t?.tool_calls;\n\t\tif (!calls || calls.length === 0) return undefined;\n\t\treturn calls.map((c) => ({\n\t\t\tid: c.id,\n\t\t\tname: c.function.name,\n\t\t\targuments: safeJson(c.function.arguments),\n\t\t}));\n\t}\n\n\tasync function generate(req: GenerateRequest): Promise<GenerateResponse> {\n\t\treturn withRetry(async () => {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await doFetch(url, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: await authHeaders(),\n\t\t\t\t\tbody: body(req, false),\n\t\t\t\t\tsignal: req.signal,\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ProviderError(`Network error: ${(e as Error).message}`, \"transient\");\n\t\t\t}\n\t\t\tif (!res.ok) throw providerErrorFromStatus(res.status, `Provider returned ${res.status}`);\n\n\t\t\tlet json: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tjson = (await res.json()) as Record<string, unknown>;\n\t\t\t} catch {\n\t\t\t\tthrow new ProviderError(\"Malformed provider response\", \"malformed\");\n\t\t\t}\n\t\t\tconst choice = (json[\"choices\"] as Array<{ message: Record<string, unknown> }>)?.[0];\n\t\t\tif (!choice) throw new ProviderError(\"Provider returned no choices\", \"malformed\");\n\t\t\tconst message = choice.message;\n\t\t\treturn {\n\t\t\t\ttext: (message[\"content\"] as string) ?? \"\",\n\t\t\t\treasoning: modelOf(req.model).supportsReasoning\n\t\t\t\t\t? ((message[\"reasoning\"] as string) ?? undefined)\n\t\t\t\t\t: undefined,\n\t\t\t\ttoolCalls: parseToolCalls(message),\n\t\t\t};\n\t\t}, options.retry);\n\t}\n\n\tasync function* generateStream(req: GenerateRequest): AsyncIterable<GenerateChunk> {\n\t\tlet res: Response;\n\t\ttry {\n\t\t\tres = await doFetch(url, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: await authHeaders(),\n\t\t\t\tbody: body(req, true),\n\t\t\t\tsignal: req.signal,\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tthrow new ProviderError(`Network error: ${(e as Error).message}`, \"transient\");\n\t\t}\n\t\tif (!res.ok) throw providerErrorFromStatus(res.status, `Provider returned ${res.status}`);\n\t\tif (!res.body) throw new ProviderError(\"Provider returned no stream body\", \"malformed\");\n\n\t\tconst reader = res.body.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\tlet buffer = \"\";\n\t\tlet text = \"\";\n\t\tlet reasoning = \"\";\n\n\t\tfor (; ;) {\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tconst trimmed = line.trim();\n\t\t\t\tif (!trimmed.startsWith(\"data:\")) continue;\n\t\t\t\tconst data = trimmed.slice(5).trim();\n\t\t\t\tif (data === \"[DONE]\") continue;\n\t\t\t\tconst parsed = safeJson(data) as\n\t\t\t\t\t| { choices?: Array<{ delta?: { content?: string; reasoning?: string } }> }\n\t\t\t\t\t| undefined;\n\t\t\t\tconst delta = parsed?.choices?.[0]?.delta;\n\t\t\t\tif (delta?.content) {\n\t\t\t\t\ttext += delta.content;\n\t\t\t\t\tyield { type: \"text\", text: delta.content };\n\t\t\t\t}\n\t\t\t\tif (delta?.reasoning && modelOf(req.model).supportsReasoning) {\n\t\t\t\t\treasoning += delta.reasoning;\n\t\t\t\t\tyield { type: \"reasoning\", text: delta.reasoning };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tyield {\n\t\t\ttype: \"done\",\n\t\t\tresponse: { text, reasoning: reasoning || undefined },\n\t\t};\n\t}\n\n\treturn {\n\t\tname: \"openai-compatible\",\n\t\tcapabilities: defaultModel,\n\t\tmodels,\n\t\tmodel: modelOf,\n\t\tgenerate,\n\t\tgenerateStream,\n\t};\n}\n\nfunction safeJson(s: string): unknown {\n\ttry {\n\t\treturn JSON.parse(s);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","/**\n * GitHub Copilot provider. (FR-005)\n *\n * Copilot's chat API is OpenAI-compatible, so this provider configures the shared\n * OpenAI-compatible transport with Copilot's endpoint and the caller-supplied\n * credential (a Copilot/GitHub token). The token is obtained via callback and is\n * never bundled, persisted, or logged. (FR-005a)\n *\n * In a frontend-only deployment the end user supplies their own token (it stays\n * client-side); in a backend deployment the developer may supply it, or the user\n * sends it per request over SSL/TLS and the backend must not log or persist it.\n *\n * @packageDocumentation\n */\n\nimport type { Provider, CredentialSource, ModelSelectionOptions } from \"./provider.js\";\nimport type { RetryOptions } from \"./retry.js\";\nimport { createOpenAICompatibleProvider } from \"./openai-compatible.js\";\n\n/** Default Copilot-compatible chat completions base URL. */\nconst DEFAULT_COPILOT_BASE_URL = \"https://api.githubcopilot.com\";\n\n/**\n * Options for {@link createCopilotProvider}.\n *\n * GitHub Copilot exposes several models, so configure them via `models` (with an\n * optional `defaultModel`). A single `capabilities` object is also accepted.\n */\nexport interface CopilotProviderOptions extends CredentialSource, ModelSelectionOptions {\n\t/** Override the Copilot base URL if needed. */\n\tbaseUrl?: string;\n\t/** Retry tuning for transient failures. */\n\tretry?: RetryOptions;\n\t/** Optional custom fetch (for testing or non-standard runtimes). */\n\tfetchImpl?: typeof fetch;\n}\n\n/**\n * Create a GitHub Copilot provider.\n *\n * @example Single model\n * ```ts\n * const provider = createCopilotProvider({\n * getCredential: () => myCopilotToken, // never logged or persisted\n * capabilities: { model: \"gpt-4o\", maxInputTokens: 128000, maxOutputTokens: 16000 },\n * });\n * ```\n *\n * @example Multiple models\n * ```ts\n * const provider = createCopilotProvider({\n * getCredential: () => myCopilotToken,\n * models: [\n * { model: \"gpt-4o\", maxInputTokens: 128000, maxOutputTokens: 16000, supportsVision: true },\n * { model: \"o3-mini\", maxInputTokens: 200000, maxOutputTokens: 100000, supportsReasoning: true },\n * ],\n * defaultModel: \"gpt-4o\",\n * });\n * // Pick a model per request: provider.generate({ messages, model: \"o3-mini\" })\n * ```\n */\nexport function createCopilotProvider(options: CopilotProviderOptions): Provider {\n\tconst inner = createOpenAICompatibleProvider({\n\t\tbaseUrl: options.baseUrl ?? DEFAULT_COPILOT_BASE_URL,\n\t\tgetCredential: options.getCredential,\n\t\tcapabilities: options.capabilities,\n\t\tmodels: options.models,\n\t\tdefaultModel: options.defaultModel,\n\t\tretry: options.retry,\n\t\tfetchImpl: options.fetchImpl,\n\t});\n\t// Preserve the provider contract but report the Copilot name.\n\treturn {\n\t\tname: \"copilot\",\n\t\tcapabilities: inner.capabilities,\n\t\tmodels: inner.models,\n\t\tmodel: inner.model.bind(inner),\n\t\tgenerate: inner.generate.bind(inner),\n\t\tgenerateStream: inner.generateStream.bind(inner),\n\t};\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkILBKDEEL_cjs = require('./chunk-ILBKDEEL.cjs');
|
|
4
4
|
var chunkFOTCUNP5_cjs = require('./chunk-FOTCUNP5.cjs');
|
|
5
5
|
|
|
6
6
|
// src/persistence/store.ts
|
|
@@ -12,7 +12,7 @@ var ThreadPersistence = {
|
|
|
12
12
|
/** Load and rehydrate a thread, or undefined if absent. */
|
|
13
13
|
async load(store, id) {
|
|
14
14
|
const data = await store.get(`thread:${id}`);
|
|
15
|
-
return data ?
|
|
15
|
+
return data ? chunkILBKDEEL_cjs.Thread.fromJSON(data) : void 0;
|
|
16
16
|
}
|
|
17
17
|
};
|
|
18
18
|
|
|
@@ -91,5 +91,5 @@ function indexedDbStore(ns) {
|
|
|
91
91
|
exports.ThreadPersistence = ThreadPersistence;
|
|
92
92
|
exports.createBrowserStore = createBrowserStore;
|
|
93
93
|
exports.createMemoryStore = createMemoryStore;
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-UIXNKPLQ.cjs.map
|
|
95
|
+
//# sourceMappingURL=chunk-UIXNKPLQ.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/persistence/store.ts","../src/persistence/memory.ts","../src/persistence/browser.ts"],"names":["Thread","requireCapability"],"mappings":";;;;;;AAkBO,IAAM,iBAAA,GAAoB;AAAA;AAAA,EAEhC,MAAM,IAAA,CAAK,KAAA,EAAc,MAAA,EAA+B;AACvD,IAAA,MAAM,KAAA,CAAM,IAAI,CAAA,OAAA,EAAU,MAAA,CAAO,EAAE,CAAA,CAAA,EAAI,MAAA,CAAO,QAAQ,CAAA;AAAA,EACvD,CAAA;AAAA;AAAA,EAEA,MAAM,IAAA,CAAK,KAAA,EAAc,EAAA,EAAyC;AACjE,IAAA,MAAM,OAAQ,MAAM,KAAA,CAAM,GAAA,CAAI,CAAA,OAAA,EAAU,EAAE,CAAA,CAAE,CAAA;AAG5C,IAAA,OAAO,IAAA,GAAOA,wBAAA,CAAY,QAAA,CAAS,IAAI,CAAA,GAAI,MAAA;AAAA,EAC5C;AACD;;;ACtBO,SAAS,iBAAA,GAA2B;AAC1C,EAAA,MAAM,GAAA,uBAAU,GAAA,EAAqB;AACrC,EAAA,OAAO;AAAA,IACN,MAAM,IAAI,GAAA,EAAK;AACd,MAAA,OAAO,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,IACnB,CAAA;AAAA,IACA,MAAM,GAAA,CAAI,GAAA,EAAK,KAAA,EAAO;AACrB,MAAA,GAAA,CAAI,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IACnB,CAAA;AAAA,IACA,MAAM,OAAO,GAAA,E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AAO,GAAG,CAAC,CAAA;AAAA,IAC/C,CAAA;AAAA,IACA,MAAM,OAAO,GAAA,EAAK;AACjB,MAAA,MAAM,GAAG,WAAA,EAAa,CAAC,MAAM,CAAA,CAAE,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,IAC3C;AAAA,GACD;AACD","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/persistence/store.ts","../src/persistence/memory.ts","../src/persistence/browser.ts"],"names":["Thread","requireCapability"],"mappings":";;;;;;AAkBO,IAAM,iBAAA,GAAoB;AAAA;AAAA,EAEhC,MAAM,IAAA,CAAK,KAAA,EAAc,MAAA,EAA+B;AACvD,IAAA,MAAM,KAAA,CAAM,IAAI,CAAA,OAAA,EAAU,MAAA,CAAO,EAAE,CAAA,CAAA,EAAI,MAAA,CAAO,QAAQ,CAAA;AAAA,EACvD,CAAA;AAAA;AAAA,EAEA,MAAM,IAAA,CAAK,KAAA,EAAc,EAAA,EAAyC;AACjE,IAAA,MAAM,OAAQ,MAAM,KAAA,CAAM,GAAA,CAAI,CAAA,OAAA,EAAU,EAAE,CAAA,CAAE,CAAA;AAG5C,IAAA,OAAO,IAAA,GAAOA,wBAAA,CAAY,QAAA,CAAS,IAAI,CAAA,GAAI,MAAA;AAAA,EAC5C;AACD;;;ACtBO,SAAS,iBAAA,GAA2B;AAC1C,EAAA,MAAM,GAAA,uBAAU,GAAA,EAAqB;AACrC,EAAA,OAAO;AAAA,IACN,MAAM,IAAI,GAAA,EAAK;AACd,MAAA,OAAO,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,IACnB,CAAA;AAAA,IACA,MAAM,GAAA,CAAI,GAAA,EAAK,KAAA,EAAO;AACrB,MAAA,GAAA,CAAI,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IACnB,CAAA;AAAA,IACA,MAAM,OAAO,GAAA,EAAK;AACjB,MAAA,GAAA,CAAI,OAAO,GAAG,CAAA;AAAA,IACf;AAAA,GACD;AACD;;;ACFO,SAAS,kBA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AM,GAAG,WAAA,EAAa,CAAC,MAAM,CAAA,CAAE,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,IAC3C;AAAA,GACD;AACD","file":"chunk-UIXNKPLQ.cjs","sourcesContent":["/**\n * Pluggable storage abstraction for persisting conversation/thread state in a\n * no-backend environment. No database server is assumed. (FR-024)\n *\n * @packageDocumentation\n */\n\nimport type { Thread } from \"../agents/thread.js\";\nimport { Thread as ThreadClass } from \"../agents/thread.js\";\n\n/** A minimal key/value store. */\nexport interface Store {\n\tget(key: string): Promise<unknown | undefined>;\n\tset(key: string, value: unknown): Promise<void>;\n\tdelete(key: string): Promise<void>;\n}\n\n/** Save and load threads via a {@link Store}. */\nexport const ThreadPersistence = {\n\t/** Persist a thread under the key `thread:<id>`. */\n\tasync save(store: Store, thread: Thread): Promise<void> {\n\t\tawait store.set(`thread:${thread.id}`, thread.toJSON());\n\t},\n\t/** Load and rehydrate a thread, or undefined if absent. */\n\tasync load(store: Store, id: string): Promise<Thread | undefined> {\n\t\tconst data = (await store.get(`thread:${id}`)) as\n\t\t\t| { id: string; messages: never[]; compacted?: boolean }\n\t\t\t| undefined;\n\t\treturn data ? ThreadClass.fromJSON(data) : undefined;\n\t},\n};\n","/**\n * In-memory store adapter. Works in every runtime; ideal as a default and for tests.\n * @packageDocumentation\n */\n\nimport type { Store } from \"./store.js\";\n\n/** Create an in-memory {@link Store}. */\nexport function createMemoryStore(): Store {\n\tconst map = new Map<string, unknown>();\n\treturn {\n\t\tasync get(key) {\n\t\t\treturn map.get(key);\n\t\t},\n\t\tasync set(key, value) {\n\t\t\tmap.set(key, value);\n\t\t},\n\t\tasync delete(key) {\n\t\t\tmap.delete(key);\n\t\t},\n\t};\n}\n","/**\n * Browser store adapters backed by `localStorage` or `IndexedDB`. Capability-gated\n * so a clear typed error is thrown if used where unavailable. (FR-024, FR-030a)\n *\n * @packageDocumentation\n */\n\nimport type { Store } from \"./store.js\";\nimport { requireCapability } from \"../core/runtime.js\";\n\n/** Options for {@link createBrowserStore}. */\nexport interface BrowserStoreOptions {\n\t/** Storage backend. Default \"local\". */\n\tbackend?: \"local\" | \"indexeddb\";\n\t/** Key namespace/prefix. Default \"afjs\". */\n\tnamespace?: string;\n}\n\n/** Create a browser-backed {@link Store}. */\nexport function createBrowserStore(options: BrowserStoreOptions = {}): Store {\n\tconst backend = options.backend ?? \"local\";\n\tconst ns = options.namespace ?? \"afjs\";\n\treturn backend === \"indexeddb\" ? indexedDbStore(ns) : localStorageStore(ns);\n}\n\nfunction localStorageStore(ns: string): Store {\n\trequireCapability(\"hasLocalStorage\", \"localStorage store\");\n\tconst ls = (globalThis as unknown as { localStorage: Storage }).localStorage;\n\tconst k = (key: string) => `${ns}:${key}`;\n\treturn {\n\t\tasync get(key) {\n\t\t\tconst raw = ls.getItem(k(key));\n\t\t\treturn raw == null ? undefined : JSON.parse(raw);\n\t\t},\n\t\tasync set(key, value) {\n\t\t\tls.setItem(k(key), JSON.stringify(value));\n\t\t},\n\t\tasync delete(key) {\n\t\t\tls.removeItem(k(key));\n\t\t},\n\t};\n}\n\nfunction indexedDbStore(ns: string): Store {\n\trequireCapability(\"hasIndexedDB\", \"IndexedDB store\");\n\tconst idb = (globalThis as unknown as { indexedDB: IDBFactory }).indexedDB;\n\n\tfunction open(): Promise<IDBDatabase> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst req = idb.open(ns, 1);\n\t\t\treq.onupgradeneeded = () => req.result.createObjectStore(\"kv\");\n\t\t\treq.onsuccess = () => resolve(req.result);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync function tx<T>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest): Promise<T> {\n\t\tconst db = await open();\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst store = db.transaction(\"kv\", mode).objectStore(\"kv\");\n\t\t\tconst req = fn(store);\n\t\t\treq.onsuccess = () => resolve(req.result as T);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\treturn {\n\t\tasync get(key) {\n\t\t\treturn tx<unknown>(\"readonly\", (s) => s.get(key));\n\t\t},\n\t\tasync set(key, value) {\n\t\t\tawait tx(\"readwrite\", (s) => s.put(value, key));\n\t\t},\n\t\tasync delete(key) {\n\t\t\tawait tx(\"readwrite\", (s) => s.delete(key));\n\t\t},\n\t};\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SkillIndex } from './chunk-YCBDEEAV.js';
|
|
2
2
|
import { ToolRegistry } from './chunk-HGEPXJDG.js';
|
|
3
3
|
import { composeMiddleware } from './chunk-7ZXUIHLH.js';
|
|
4
|
-
import { textMessage, Thread, hasImage } from './chunk-
|
|
4
|
+
import { textMessage, Thread, hasImage } from './chunk-E4VTVUYU.js';
|
|
5
5
|
import { ProviderError } from './chunk-IXV4UIF5.js';
|
|
6
6
|
|
|
7
7
|
// src/agents/loop.ts
|
|
@@ -59,8 +59,9 @@ function createAgent(config) {
|
|
|
59
59
|
const registry = new ToolRegistry(config.tools ?? []);
|
|
60
60
|
const skillIndex = new SkillIndex(config.skills ?? []);
|
|
61
61
|
const middleware = config.middleware ?? [];
|
|
62
|
+
const modelCaps = () => config.provider.model(config.model);
|
|
62
63
|
function gateVision(messages) {
|
|
63
|
-
if (!
|
|
64
|
+
if (!modelCaps().supportsVision && messages.some(hasImage)) {
|
|
64
65
|
throw new ProviderError(
|
|
65
66
|
"Image input was provided but the configured model does not support vision",
|
|
66
67
|
"client"
|
|
@@ -82,7 +83,7 @@ ${contents.join("\n\n")}`
|
|
|
82
83
|
async function callProvider(req) {
|
|
83
84
|
const ctx = {
|
|
84
85
|
agentName: config.name,
|
|
85
|
-
request: req
|
|
86
|
+
request: { ...req, model: req.model ?? config.model }
|
|
86
87
|
};
|
|
87
88
|
const pipeline = composeMiddleware(middleware, (c) => config.provider.generate(c.request));
|
|
88
89
|
return pipeline(ctx);
|
|
@@ -95,7 +96,8 @@ ${contents.join("\n\n")}`
|
|
|
95
96
|
for (const m of withSkills) thread.add(m);
|
|
96
97
|
await thread.maybeCompact(config.provider, {
|
|
97
98
|
compactionThreshold: config.compactionThreshold,
|
|
98
|
-
compactionModel: config.compactionModel
|
|
99
|
+
compactionModel: config.compactionModel,
|
|
100
|
+
modelCapabilities: modelCaps()
|
|
99
101
|
});
|
|
100
102
|
return thread;
|
|
101
103
|
}
|
|
@@ -120,7 +122,7 @@ ${contents.join("\n\n")}`
|
|
|
120
122
|
}
|
|
121
123
|
return {
|
|
122
124
|
output: loop.final.text,
|
|
123
|
-
reasoning:
|
|
125
|
+
reasoning: modelCaps().supportsReasoning ? loop.final.reasoning : void 0,
|
|
124
126
|
status: loop.status,
|
|
125
127
|
partial: loop.status === "incomplete",
|
|
126
128
|
thread
|
|
@@ -149,12 +151,13 @@ ${contents.join("\n\n")}`
|
|
|
149
151
|
for await (const chunk of config.provider.generateStream({
|
|
150
152
|
messages: thread.messages,
|
|
151
153
|
tools: registry.specs(),
|
|
154
|
+
model: config.model,
|
|
152
155
|
signal: opts?.signal
|
|
153
156
|
})) {
|
|
154
157
|
if (chunk.type === "text") {
|
|
155
158
|
text += chunk.text;
|
|
156
159
|
yield { type: "text", text: chunk.text };
|
|
157
|
-
} else if (chunk.type === "reasoning" &&
|
|
160
|
+
} else if (chunk.type === "reasoning" && modelCaps().supportsReasoning) {
|
|
158
161
|
reasoning += chunk.text;
|
|
159
162
|
yield { type: "reasoning", text: chunk.text };
|
|
160
163
|
} else if (chunk.type === "done") {
|
|
@@ -175,7 +178,7 @@ ${contents.join("\n\n")}`
|
|
|
175
178
|
type: "done",
|
|
176
179
|
result: {
|
|
177
180
|
output: text,
|
|
178
|
-
reasoning:
|
|
181
|
+
reasoning: modelCaps().supportsReasoning ? reasoning || void 0 : void 0,
|
|
179
182
|
status: "completed",
|
|
180
183
|
partial: false,
|
|
181
184
|
thread
|
|
@@ -186,5 +189,5 @@ ${contents.join("\n\n")}`
|
|
|
186
189
|
}
|
|
187
190
|
|
|
188
191
|
export { buildMessages, createAgent, runLoop };
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
190
|
-
//# sourceMappingURL=chunk-
|
|
192
|
+
//# sourceMappingURL=chunk-WEKU7735.js.map
|
|
193
|
+
//# sourceMappingURL=chunk-WEKU7735.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/loop.ts","../src/agents/agent.ts"],"names":[],"mappings":";;;;;;;AA4CA,eAAsB,OAAA,CACrB,QAAA,EACA,QAAA,EACA,QAAA,EACA,OAAA,EACsB;AACtB,EAAA,MAAM,aAAA,GAAgB,SAAS,aAAA,IAAiB,EAAA;AAChD,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,QAAQ,CAAA;AAC5B,EAAA,IAAI,SAAA,GAAY,CAAA;AAEhB,EAAA,WAAU;AACT,IAAA,IAAI,aAAA,KAAkB,EAAA,IAAM,SAAA,IAAa,aAAA,EAAe;AACvD,MAAA,OAAO;AAAA,QACN,QAAA,EAAU,OAAA;AAAA,QACV,KAAA,EAAO,EAAE,IAAA,EAAM,EAAA,EAAG;AAAA,QAClB,MAAA,EAAQ;AAAA,OACT;AAAA,IACD;AACA,IAAA,SAAA,EAAA;AAEA,IAAA,MAAM,KAAA,GAAQ,SAAS,KAAA,EAAM;AAC7B,IAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS;AAAA,MAC/B,QAAA,EAAU,OAAA;AAAA,MACV,KAAA,EAAO,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,MAAA;AAAA,MAClC,QAAQ,OAAA,EAAS;AAAA,KACjB,CAAA;AAED,IAAA,IAAI,CAAC,QAAA,CAAS,SAAA,IAAa,QAAA,CAAS,SAAA,CAAU,WAAW,CAAA,EAAG;AAC3D,MAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,KAAA,EAAO,QAAA,EAAU,QAAQ,WAAA,EAAY;AAAA,IAClE;AAGA,IAAA,OAAA,CAAQ,IAAA,C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ed results (including errors, for self-correction) back to the model,\n * and stops on a final answer, the iteration cap, or an abort. (FR-011a, FR-012b)\n *\n * @packageDocumentation\n */\n\nimport type { Message } from \"../core/types.js\";\nimport { textMessage } from \"../core/types.js\";\nimport type { GenerateRequest, GenerateResponse } from \"../providers/provider.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\n\n/** Outcome status of a run. */\nexport type RunStatus = \"completed\" | \"failed\" | \"incomplete\" | \"limit-exceeded\";\n\n/** A function that produces a model response (optionally through middleware). */\nexport type GenerateFn = (req: GenerateRequest) => Promise<GenerateResponse>;\n\n/** Settings controlling the loop. */\nexport interface LoopOptions {\n\t/** Maximum iterations; -1 means unlimited. Default 10. (FR-012b) */\n\tmaxIterations?: number;\n\t/** Per-tool-call timeout in ms. (FR-012c) */\n\ttoolTimeoutMs?: number;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Result of running the loop. */\nexport interface LoopResult {\n\tmessages: Message[];\n\tfinal: GenerateResponse;\n\tstatus: RunStatus;\n}\n\n/**\n * Execute the tool-call loop against a generate function and tool registry.\n *\n * @param generate - Produces a model response (typically the middleware pipeline).\n * @param registry - Tools available to the agent (may be empty).\n * @param messages - Initial conversation (system + user, etc.).\n * @param options - Loop tuning.\n */\nexport async function runLoop(\n\tgenerate: GenerateFn,\n\tregistry: ToolRegistry,\n\tmessages: Message[],\n\toptions?: LoopOptions,\n): Promise<LoopResult> {\n\tconst maxIterations = options?.maxIterations ?? 10;\n\tconst working = [...messages];\n\tlet iteration = 0;\n\n\tfor (; ;) {\n\t\tif (maxIterations !== -1 && iteration >= maxIterations) {\n\t\t\treturn {\n\t\t\t\tmessages: working,\n\t\t\t\tfinal: { text: \"\" },\n\t\t\t\tstatus: \"limit-exceeded\",\n\t\t\t};\n\t\t}\n\t\titeration++;\n\n\t\tconst specs = registry.specs();\n\t\tconst response = await generate({\n\t\t\tmessages: working,\n\t\t\ttools: specs.length > 0 ? specs : undefined,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tif (!response.toolCalls || response.toolCalls.length === 0) {\n\t\t\treturn { messages: working, final: response, status: \"completed\" };\n\t\t}\n\n\t\t// Record the assistant's tool-call turn.\n\t\tworking.push({\n\t\t\trole: \"assistant\",\n\t\t\tparts: response.text ? [{ type: \"text\", text: response.text }] : [],\n\t\t});\n\n\t\t// Execute each requested tool and feed results (or typed errors) back.\n\t\tfor (const call of response.toolCalls) {\n\t\t\tconst result = await registry.invoke(call.name, call.arguments, options?.toolTimeoutMs);\n\t\t\tconst payload = result.error\n\t\t\t\t? `ERROR (${result.error.reason}): ${result.error.message}`\n\t\t\t\t: JSON.stringify(result.value ?? null);\n\t\t\tworking.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\tname: call.name,\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\tparts: [{ type: \"text\", text: payload }],\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Build the initial message list from instructions + input. */\nexport function buildMessages(instructions: string, input: Message[]): Message[] {\n\treturn [textMessage(\"system\", instructions), ...input];\n}\n","/**\n * The agent: a configured actor that runs against a provider, optionally using\n * tools and skills, with streaming, reasoning output, multimodal input gating,\n * conversation threads with compaction, and a middleware pipeline.\n *\n * @packageDocumentation\n */\n\nimport type { Message, ContentPart } from \"../core/types.js\";\nimport { hasImage, textMessage } from \"../core/types.js\";\nimport { ProviderError } from \"../core/errors.js\";\nimport type { Provider, GenerateResponse, GenerateRequest } from \"../providers/provider.js\";\nimport { ToolRegistry } from \"../tools/registry.js\";\nimport type { Tool } from \"../tools/tool.js\";\nimport type { Skill } from \"../skills/skill.js\";\nimport { SkillIndex } from \"../skills/index.js\";\nimport type { Middleware, MiddlewareContext } from \"../middleware/middleware.js\";\nimport { composeMiddleware } from \"../middleware/middleware.js\";\nimport { Thread, type ThreadOptions } from \"./thread.js\";\nimport { runLoop, type RunStatus } from \"./loop.js\";\n\n/** Configuration for {@link createAgent}. */\nexport interface AgentConfig {\n\tname: string;\n\tinstructions: string;\n\tprovider: Provider;\n\t/** Which of the provider's models to use; defaults to the provider's default model. */\n\tmodel?: string;\n\ttools?: Tool[];\n\tskills?: Skill[];\n\t/** Max tool-call iterations per run; -1 = unlimited. Default 10. (FR-012b) */\n\tmaxIterations?: number;\n\t/** Per-tool-call timeout in ms. (FR-012c) */\n\ttoolTimeoutMs?: number;\n\t/** Compaction threshold as a fraction of maxInputTokens. Default 0.9. (FR-004a) */\n\tcompactionThreshold?: number;\n\t/** Optional override model for compaction summaries. (FR-004b) */\n\tcompactionModel?: Provider;\n\t/** Middleware applied around provider calls. (FR-023) */\n\tmiddleware?: Middleware[];\n}\n\n/** Options for a single run. */\nexport interface RunOptions {\n\t/** Continue an existing conversation. (FR-004) */\n\tthread?: Thread;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** The result of a non-streaming run. */\nexport interface RunResult {\n\toutput: string;\n\t/** Reasoning content — only for reasoning-capable models. (FR-003a) */\n\treasoning?: string;\n\tstatus: RunStatus;\n\t/** True when the run was interrupted before completing. (FR-003b) */\n\tpartial: boolean;\n\terror?: ProviderError;\n\t/** The thread used/updated by this run. */\n\tthread: Thread;\n}\n\n/** Streamed run chunk. */\nexport type RunChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"reasoning\"; text: string }\n\t| { type: \"done\"; result: RunResult };\n\n/** Agent input: plain text or structured (multimodal) messages. (FR-002) */\nexport type AgentInput = string | Message | Message[];\n\n/** A runnable agent. */\nexport interface Agent {\n\treadonly name: string;\n\trun(input: AgentInput, opts?: RunOptions): Promise<RunResult>;\n\trunStream(input: AgentInput, opts?: RunOptions): AsyncIterable<RunChunk>;\n}\n\nfunction normalizeInput(input: AgentInput): Message[] {\n\tif (typeof input === \"string\") return [textMessage(\"user\", input)];\n\treturn Array.isArray(input) ? input : [input];\n}\n\nfunction promptText(messages: Message[]): string {\n\treturn messages\n\t\t.flatMap((m) => m.parts)\n\t\t.filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n\t\t.map((p) => p.text)\n\t\t.join(\" \");\n}\n\n/**\n * Create an agent.\n *\n * @example\n * ```ts\n * const agent = createAgent({ name: \"Helper\", instructions: \"Be concise.\", provider });\n * const res = await agent.run(\"Say hello.\");\n * console.log(res.status, res.output);\n * ```\n */\nexport function createAgent(config: AgentConfig): Agent {\n\tconst registry = new ToolRegistry(config.tools ?? []);\n\tconst skillIndex = new SkillIndex(config.skills ?? []);\n\tconst middleware = config.middleware ?? [];\n\t/** Capabilities of the model this agent uses (selected from the provider). */\n\tconst modelCaps = () => config.provider.model(config.model);\n\n\tfunction gateVision(messages: Message[]): void {\n\t\tif (!modelCaps().supportsVision && messages.some(hasImage)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t\"Image input was provided but the configured model does not support vision\",\n\t\t\t\t\"client\",\n\t\t\t);\n\t\t}\n\t}\n\n\tasync function injectSkills(userMessages: Message[]): Promise<Message[]> {\n\t\tif ((config.skills ?? []).length === 0) return userMessages;\n\t\tconst selected = skillIndex.select(promptText(userMessages));\n\t\tif (selected.length === 0) return userMessages;\n\t\tconst contents = await Promise.all(selected.map((s) => skillIndex.load(s)));\n\t\tconst skillBlock = textMessage(\n\t\t\t\"system\",\n\t\t\t`Relevant skill knowledge:\\n${contents.join(\"\\n\\n\")}`,\n\t\t);\n\t\treturn [skillBlock, ...userMessages];\n\t}\n\n\tasync function callProvider(req: GenerateRequest): Promise<GenerateResponse> {\n\t\tconst ctx: MiddlewareContext = {\n\t\t\tagentName: config.name,\n\t\t\trequest: { ...req, model: req.model ?? config.model },\n\t\t};\n\t\tconst pipeline = composeMiddleware(middleware, (c) => config.provider.generate(c.request));\n\t\treturn pipeline(ctx);\n\t}\n\n\tasync function prepare(input: AgentInput, opts?: RunOptions): Promise<Thread> {\n\t\tconst userMessages = normalizeInput(input);\n\t\tgateVision(userMessages);\n\t\tconst thread =\n\t\t\topts?.thread ??\n\t\t\tnew Thread(undefined, [textMessage(\"system\", config.instructions)]);\n\t\tconst withSkills = await injectSkills(userMessages);\n\t\tfor (const m of withSkills) thread.add(m);\n\t\tawait thread.maybeCompact(config.provider, {\n\t\t\tcompactionThreshold: config.compactionThreshold,\n\t\t\tcompactionModel: config.compactionModel,\n\t\t\tmodelCapabilities: modelCaps(),\n\t\t} satisfies ThreadOptions);\n\t\treturn thread;\n\t}\n\n\tasync function run(input: AgentInput, opts?: RunOptions): Promise<RunResult> {\n\t\tlet thread: Thread;\n\t\ttry {\n\t\t\tthread = await prepare(input, opts);\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\treturn { output: \"\", status: \"failed\", partial: false, error: e, thread: opts?.thread ?? new Thread() };\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\n\t\ttry {\n\t\t\tconst loop = await runLoop(callProvider, registry, thread.messages, {\n\t\t\t\tmaxIterations: config.maxIterations,\n\t\t\t\ttoolTimeoutMs: config.toolTimeoutMs,\n\t\t\t\tsignal: opts?.signal,\n\t\t\t});\n\t\t\tif (loop.final.text) {\n\t\t\t\tthread.add({ role: \"assistant\", parts: [{ type: \"text\", text: loop.final.text }] });\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: loop.final.text,\n\t\t\t\treasoning: modelCaps().supportsReasoning ? loop.final.reasoning : undefined,\n\t\t\t\tstatus: loop.status,\n\t\t\t\tpartial: loop.status === \"incomplete\",\n\t\t\t\tthread,\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\treturn { output: \"\", status: \"failed\", partial: false, error: e, thread };\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync function* runStream(input: AgentInput, opts?: RunOptions): AsyncIterable<RunChunk> {\n\t\t// Streaming path: single provider streaming call (tool loops use non-streaming\n\t\t// internally). Suitable for the common single-turn streaming case.\n\t\tlet thread: Thread;\n\t\ttry {\n\t\t\tthread = await prepare(input, opts);\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\tyield { type: \"done\", result: { output: \"\", status: \"failed\", partial: false, error: e, thread: opts?.thread ?? new Thread() } };\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\n\t\tlet text = \"\";\n\t\tlet reasoning = \"\";\n\t\ttry {\n\t\t\tfor await (const chunk of config.provider.generateStream({\n\t\t\t\tmessages: thread.messages,\n\t\t\t\ttools: registry.specs(),\n\t\t\t\tmodel: config.model,\n\t\t\t\tsignal: opts?.signal,\n\t\t\t})) {\n\t\t\t\tif (chunk.type === \"text\") {\n\t\t\t\t\ttext += chunk.text;\n\t\t\t\t\tyield { type: \"text\", text: chunk.text };\n\t\t\t\t} else if (chunk.type === \"reasoning\" && modelCaps().supportsReasoning) {\n\t\t\t\t\treasoning += chunk.text;\n\t\t\t\t\tyield { type: \"reasoning\", text: chunk.text };\n\t\t\t\t} else if (chunk.type === \"done\") {\n\t\t\t\t\ttext = chunk.response.text || text;\n\t\t\t\t\treasoning = chunk.response.reasoning || reasoning;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconst error = e instanceof ProviderError ? e : new ProviderError((e as Error).message, \"transient\");\n\t\t\tyield {\n\t\t\t\ttype: \"done\",\n\t\t\t\tresult: { output: text, status: \"incomplete\", partial: true, error, thread },\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\n\t\tif (text) thread.add({ role: \"assistant\", parts: [{ type: \"text\", text }] });\n\t\tyield {\n\t\t\ttype: \"done\",\n\t\t\tresult: {\n\t\t\t\toutput: text,\n\t\t\t\treasoning: modelCaps().supportsReasoning ? reasoning || undefined : undefined,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tpartial: false,\n\t\t\t\tthread,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { name: config.name, run, runStream };\n}\n\nexport type { ContentPart };\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('../chunk-
|
|
3
|
+
var chunk245NZAGV_cjs = require('../chunk-245NZAGV.cjs');
|
|
4
|
+
require('../chunk-NURRGYIU.cjs');
|
|
5
5
|
require('../chunk-WSMYH2IN.cjs');
|
|
6
6
|
require('../chunk-TAMJ5HSR.cjs');
|
|
7
7
|
require('../chunk-FSDMBWQV.cjs');
|
|
8
|
-
require('../chunk-
|
|
8
|
+
require('../chunk-ILBKDEEL.cjs');
|
|
9
9
|
require('../chunk-MQ2XTH3S.cjs');
|
|
10
10
|
require('../chunk-IJASUMIQ.cjs');
|
|
11
11
|
|
|
@@ -13,7 +13,7 @@ require('../chunk-IJASUMIQ.cjs');
|
|
|
13
13
|
|
|
14
14
|
Object.defineProperty(exports, "loadAgentDefinition", {
|
|
15
15
|
enumerable: true,
|
|
16
|
-
get: function () { return
|
|
16
|
+
get: function () { return chunk245NZAGV_cjs.loadAgentDefinition; }
|
|
17
17
|
});
|
|
18
18
|
//# sourceMappingURL=index.cjs.map
|
|
19
19
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { a as ModelCapabilities } from '../types-Cn1g9Tg4.cjs';
|
|
2
|
-
import { P as Provider } from '../provider-
|
|
2
|
+
import { P as Provider } from '../provider-IJnfNhCX.cjs';
|
|
3
3
|
import { T as Tool } from '../tool-BZg_znMZ.cjs';
|
|
4
4
|
import { S as Skill } from '../skill-DfNChtJN.cjs';
|
|
5
|
-
import { A as Agent } from '../index-
|
|
5
|
+
import { A as Agent } from '../index-5eIhfrC1.cjs';
|
|
6
6
|
import '../errors-CjVz4W_5.cjs';
|
|
7
|
-
import '../thread-
|
|
8
|
-
import '../registry-
|
|
7
|
+
import '../thread-D3zaGK1Y.cjs';
|
|
8
|
+
import '../registry-B-hicOxp.cjs';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Declarative agent definitions. Agents can be defined in YAML or JSON against a
|