@dudko.dev/agent-web 0.0.37 → 0.0.38
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/README.md +156 -4
- package/dist/agent-web.js +270 -110
- package/dist/agent-web.js.map +1 -1
- package/dist/chunk-AY2BZYZY.js +573 -0
- package/dist/chunk-AY2BZYZY.js.map +1 -0
- package/dist/chunk-CTXDKSDD.js +39 -0
- package/dist/chunk-CTXDKSDD.js.map +1 -0
- package/dist/{chunk-CPSDKXO6.js → chunk-T6LZW7ML.js} +27 -35
- package/dist/chunk-T6LZW7ML.js.map +1 -0
- package/dist/chunk-V3JOK7EW.js +929 -0
- package/dist/chunk-V3JOK7EW.js.map +1 -0
- package/dist/index.cjs +5980 -3627
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +363 -3
- package/dist/index.d.ts +363 -3
- package/dist/index.js +1183 -583
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +879 -13
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +372 -13
- package/dist/mcp.d.ts +372 -13
- package/dist/mcp.js +857 -15
- package/dist/mcp.js.map +1 -1
- package/dist/sandbox-AMO2SA4X.js +269 -0
- package/dist/sandbox-AMO2SA4X.js.map +1 -0
- package/dist/sandbox-worker.cjs +745 -0
- package/dist/sandbox-worker.cjs.map +1 -0
- package/dist/sandbox-worker.d.cts +37 -0
- package/dist/sandbox-worker.d.ts +37 -0
- package/dist/sandbox-worker.js +27 -0
- package/dist/sandbox-worker.js.map +1 -0
- package/package.json +23 -4
- package/dist/chunk-CPSDKXO6.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
|
-
FILES_STORE,
|
|
3
2
|
IndexedDBVault,
|
|
4
|
-
|
|
5
|
-
RUNS_STORE,
|
|
6
|
-
SECRETS_STORE,
|
|
7
|
-
SESSIONS_STORE,
|
|
3
|
+
createLogger,
|
|
8
4
|
decryptJSON,
|
|
9
5
|
encryptJSON,
|
|
10
|
-
getOrCreateVaultKey
|
|
11
|
-
|
|
12
|
-
} from "./chunk-CPSDKXO6.js";
|
|
6
|
+
getOrCreateVaultKey
|
|
7
|
+
} from "./chunk-T6LZW7ML.js";
|
|
13
8
|
import {
|
|
14
9
|
AttachmentsNotSupportedError,
|
|
15
10
|
ContextWindowExceededError,
|
|
@@ -51,6 +46,38 @@ import {
|
|
|
51
46
|
webLLMContextWindow,
|
|
52
47
|
withWebLLMContextWindow
|
|
53
48
|
} from "./chunk-Y7OGKYE5.js";
|
|
49
|
+
import {
|
|
50
|
+
TOOL_APPROVAL_MODES,
|
|
51
|
+
ToolBudgetError,
|
|
52
|
+
ToolDeniedError,
|
|
53
|
+
VirtualFileSystem,
|
|
54
|
+
bytesToBase64,
|
|
55
|
+
checkLimits,
|
|
56
|
+
createApprovalState,
|
|
57
|
+
createCallCounter,
|
|
58
|
+
createFileTools,
|
|
59
|
+
decideToolPermission,
|
|
60
|
+
fileToolBindingOf,
|
|
61
|
+
isReadOnlyTool,
|
|
62
|
+
isTextMime,
|
|
63
|
+
limitModelOutput,
|
|
64
|
+
markReadOnly,
|
|
65
|
+
matchRule,
|
|
66
|
+
mimeFromPath,
|
|
67
|
+
normalizePath,
|
|
68
|
+
promptHintOf,
|
|
69
|
+
schemaHintOf,
|
|
70
|
+
toolRunContextOf,
|
|
71
|
+
wrapToolsForRun
|
|
72
|
+
} from "./chunk-AY2BZYZY.js";
|
|
73
|
+
import {
|
|
74
|
+
FILES_STORE,
|
|
75
|
+
KEYS_STORE,
|
|
76
|
+
RUNS_STORE,
|
|
77
|
+
SECRETS_STORE,
|
|
78
|
+
SESSIONS_STORE,
|
|
79
|
+
openAgentWebDB
|
|
80
|
+
} from "./chunk-CTXDKSDD.js";
|
|
54
81
|
|
|
55
82
|
// src/caching.ts
|
|
56
83
|
var resolveCaching = (s) => {
|
|
@@ -135,40 +162,6 @@ var resolveConfig = (c) => ({
|
|
|
135
162
|
logLevel: c.logLevel ?? "warn"
|
|
136
163
|
});
|
|
137
164
|
|
|
138
|
-
// src/limits.ts
|
|
139
|
-
var over = (value, cap) => typeof cap === "number" && cap > 0 && (value ?? 0) >= cap;
|
|
140
|
-
var checkLimits = (usage, limits) => {
|
|
141
|
-
if (!limits) return void 0;
|
|
142
|
-
if (over(usage.totalTokens, limits.maxTotalTokens)) {
|
|
143
|
-
return { kind: "total", tokens: usage.totalTokens, cap: limits.maxTotalTokens };
|
|
144
|
-
}
|
|
145
|
-
if (over(usage.inputTokens, limits.maxInputTokens)) {
|
|
146
|
-
return { kind: "input", tokens: usage.inputTokens, cap: limits.maxInputTokens };
|
|
147
|
-
}
|
|
148
|
-
if (over(usage.outputTokens, limits.maxOutputTokens)) {
|
|
149
|
-
return { kind: "output", tokens: usage.outputTokens, cap: limits.maxOutputTokens };
|
|
150
|
-
}
|
|
151
|
-
if (over(usage.reasoningTokens, limits.maxReasoningTokens)) {
|
|
152
|
-
return {
|
|
153
|
-
kind: "reasoning",
|
|
154
|
-
tokens: usage.reasoningTokens ?? 0,
|
|
155
|
-
cap: limits.maxReasoningTokens
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
return void 0;
|
|
159
|
-
};
|
|
160
|
-
var ToolBudgetError = class extends Error {
|
|
161
|
-
constructor(cap) {
|
|
162
|
-
super(
|
|
163
|
-
`Tool-call budget exhausted (${cap} per run). Do not call more tools; report what you have.`
|
|
164
|
-
);
|
|
165
|
-
this.name = "ToolBudgetError";
|
|
166
|
-
}
|
|
167
|
-
toJSON() {
|
|
168
|
-
return this.message;
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
|
|
172
165
|
// src/providers/types.ts
|
|
173
166
|
var isDirectModel = (m) => typeof m === "string" || typeof m === "object" && m !== null && "specificationVersion" in m;
|
|
174
167
|
var isProviderSpec = (m) => typeof m === "object" && m !== null && !isDirectModel(m) && typeof m.providerType === "string";
|
|
@@ -527,283 +520,6 @@ var defineTool = (config) => {
|
|
|
527
520
|
return t;
|
|
528
521
|
};
|
|
529
522
|
|
|
530
|
-
// src/tools/wrap.ts
|
|
531
|
-
import { asSchema } from "ai";
|
|
532
|
-
|
|
533
|
-
// src/tools/approval.ts
|
|
534
|
-
var TOOL_APPROVAL_MODES = [
|
|
535
|
-
"autopilot",
|
|
536
|
-
"ask-writes",
|
|
537
|
-
"ask-all",
|
|
538
|
-
"read-only"
|
|
539
|
-
];
|
|
540
|
-
var ToolDeniedError = class extends Error {
|
|
541
|
-
constructor(reason) {
|
|
542
|
-
super(
|
|
543
|
-
`Tool call denied by the user${reason ? `: ${reason}` : ""}. Do not retry it; continue without it, or report what is blocked.`
|
|
544
|
-
);
|
|
545
|
-
this.name = "ToolDeniedError";
|
|
546
|
-
}
|
|
547
|
-
toJSON() {
|
|
548
|
-
return this.message;
|
|
549
|
-
}
|
|
550
|
-
};
|
|
551
|
-
var markReadOnly = (tool6, readOnly = true) => {
|
|
552
|
-
;
|
|
553
|
-
tool6.readOnly = readOnly;
|
|
554
|
-
return tool6;
|
|
555
|
-
};
|
|
556
|
-
var isReadOnlyTool = (tool6) => tool6?.readOnly === true;
|
|
557
|
-
var globToRegExp = (glob) => new RegExp(
|
|
558
|
-
`^${glob.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`
|
|
559
|
-
);
|
|
560
|
-
var matchRule = (rules, toolName) => {
|
|
561
|
-
if (!rules) return void 0;
|
|
562
|
-
if (Object.hasOwn(rules, toolName)) return rules[toolName];
|
|
563
|
-
let best;
|
|
564
|
-
for (const [pattern, perm] of Object.entries(rules)) {
|
|
565
|
-
if (!pattern.includes("*")) continue;
|
|
566
|
-
if (!globToRegExp(pattern).test(toolName)) continue;
|
|
567
|
-
const len = pattern.replace(/\*/g, "").length;
|
|
568
|
-
if (!best || len > best.len) best = { len, perm };
|
|
569
|
-
}
|
|
570
|
-
return best?.perm;
|
|
571
|
-
};
|
|
572
|
-
var decideToolPermission = (opts) => {
|
|
573
|
-
if (opts.remembered?.has(opts.toolName)) return "allow";
|
|
574
|
-
const rule = matchRule(opts.rules, opts.toolName);
|
|
575
|
-
if (rule) return rule;
|
|
576
|
-
switch (opts.mode) {
|
|
577
|
-
case "autopilot":
|
|
578
|
-
return "allow";
|
|
579
|
-
case "read-only":
|
|
580
|
-
return opts.readOnly ? "allow" : "deny";
|
|
581
|
-
case "ask-writes":
|
|
582
|
-
return opts.readOnly ? "allow" : "ask";
|
|
583
|
-
case "ask-all":
|
|
584
|
-
return "ask";
|
|
585
|
-
}
|
|
586
|
-
};
|
|
587
|
-
var normalizeDecision = (d) => typeof d === "boolean" ? { approved: d } : { approved: Boolean(d?.approved), reason: d?.reason, remember: d?.remember };
|
|
588
|
-
var createApprovalState = (config) => ({
|
|
589
|
-
mode: config?.mode ?? "autopilot",
|
|
590
|
-
config: config ?? {},
|
|
591
|
-
remembered: /* @__PURE__ */ new Set()
|
|
592
|
-
});
|
|
593
|
-
var seq = 0;
|
|
594
|
-
var gateToolCall = async (state, call, events, signal) => {
|
|
595
|
-
const permission = decideToolPermission({
|
|
596
|
-
toolName: call.toolName,
|
|
597
|
-
readOnly: call.readOnly,
|
|
598
|
-
mode: state.mode,
|
|
599
|
-
rules: state.config.rules,
|
|
600
|
-
remembered: state.remembered
|
|
601
|
-
});
|
|
602
|
-
if (permission === "allow") return;
|
|
603
|
-
const id = `approval-${Date.now().toString(36)}-${seq += 1}`;
|
|
604
|
-
if (permission === "deny") {
|
|
605
|
-
const reason = state.mode === "read-only" && !matchRule(state.config.rules, call.toolName) ? "the agent is in read-only mode" : "blocked by policy";
|
|
606
|
-
events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true });
|
|
607
|
-
throw new ToolDeniedError(reason);
|
|
608
|
-
}
|
|
609
|
-
const onRequest = state.config.onRequest;
|
|
610
|
-
if (!onRequest) {
|
|
611
|
-
const reason = "no approval handler configured";
|
|
612
|
-
events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true });
|
|
613
|
-
throw new ToolDeniedError(reason);
|
|
614
|
-
}
|
|
615
|
-
const req = { id, ...call };
|
|
616
|
-
events.requested(req);
|
|
617
|
-
let decision;
|
|
618
|
-
try {
|
|
619
|
-
decision = normalizeDecision(
|
|
620
|
-
await withDeadline(Promise.resolve(onRequest(req)), state.config.timeoutMs, signal)
|
|
621
|
-
);
|
|
622
|
-
} catch (err) {
|
|
623
|
-
const reason = err instanceof Error ? err.message : String(err);
|
|
624
|
-
events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true });
|
|
625
|
-
throw new ToolDeniedError(reason);
|
|
626
|
-
}
|
|
627
|
-
if (decision.approved && decision.remember) state.remembered.add(call.toolName);
|
|
628
|
-
events.resolved({
|
|
629
|
-
id,
|
|
630
|
-
name: call.toolName,
|
|
631
|
-
approved: decision.approved,
|
|
632
|
-
reason: decision.reason,
|
|
633
|
-
automatic: false
|
|
634
|
-
});
|
|
635
|
-
if (!decision.approved) throw new ToolDeniedError(decision.reason);
|
|
636
|
-
};
|
|
637
|
-
var withDeadline = (p, timeoutMs, signal) => {
|
|
638
|
-
if ((!timeoutMs || timeoutMs <= 0) && !signal) return p;
|
|
639
|
-
return new Promise((resolve, reject) => {
|
|
640
|
-
let timer;
|
|
641
|
-
const done = () => {
|
|
642
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
643
|
-
signal?.removeEventListener("abort", onAbort);
|
|
644
|
-
};
|
|
645
|
-
const onAbort = () => {
|
|
646
|
-
done();
|
|
647
|
-
reject(new Error("the run was stopped while waiting for approval"));
|
|
648
|
-
};
|
|
649
|
-
if (signal?.aborted) return onAbort();
|
|
650
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
651
|
-
if (timeoutMs && timeoutMs > 0) {
|
|
652
|
-
timer = setTimeout(() => {
|
|
653
|
-
done();
|
|
654
|
-
reject(new Error(`no approval decision within ${timeoutMs} ms`));
|
|
655
|
-
}, timeoutMs);
|
|
656
|
-
}
|
|
657
|
-
p.then(
|
|
658
|
-
(v) => {
|
|
659
|
-
done();
|
|
660
|
-
resolve(v);
|
|
661
|
-
},
|
|
662
|
-
(e) => {
|
|
663
|
-
done();
|
|
664
|
-
reject(e);
|
|
665
|
-
}
|
|
666
|
-
);
|
|
667
|
-
});
|
|
668
|
-
};
|
|
669
|
-
|
|
670
|
-
// src/tools/types.ts
|
|
671
|
-
var promptHintOf = (tool6) => typeof tool6.promptHint === "string" ? tool6.promptHint : void 0;
|
|
672
|
-
|
|
673
|
-
// src/tools/wrap.ts
|
|
674
|
-
var toolRunContextOf = (options) => options?.agentRun;
|
|
675
|
-
var truncated = (s, max) => s.length > max ? `${s.slice(0, max)}\u2026 [truncated ${s.length - max} chars]` : s;
|
|
676
|
-
var toText = (v) => {
|
|
677
|
-
if (typeof v === "string") return v;
|
|
678
|
-
try {
|
|
679
|
-
return JSON.stringify(v) ?? String(v);
|
|
680
|
-
} catch {
|
|
681
|
-
return String(v);
|
|
682
|
-
}
|
|
683
|
-
};
|
|
684
|
-
var limitModelOutput = (original, maxChars) => (async (opts) => {
|
|
685
|
-
const base = original ? await original(opts) : typeof opts.output === "string" ? { type: "text", value: opts.output } : { type: "json", value: opts.output ?? null };
|
|
686
|
-
if (base.type === "text" || base.type === "error-text") {
|
|
687
|
-
return { ...base, value: truncated(base.value, maxChars) };
|
|
688
|
-
}
|
|
689
|
-
if (base.type === "json" || base.type === "error-json") {
|
|
690
|
-
const text = toText(base.value);
|
|
691
|
-
if (text.length <= maxChars) return base;
|
|
692
|
-
return {
|
|
693
|
-
type: base.type === "json" ? "text" : "error-text",
|
|
694
|
-
value: truncated(text, maxChars)
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
return base;
|
|
698
|
-
});
|
|
699
|
-
var wrapToolsForRun = (tools, o) => {
|
|
700
|
-
const out = {};
|
|
701
|
-
const gate = (toolName, input, readOnly, signal) => gateToolCall(
|
|
702
|
-
o.approval,
|
|
703
|
-
{ toolName, input, readOnly, step: o.step() },
|
|
704
|
-
{
|
|
705
|
-
requested: (req) => o.emit({
|
|
706
|
-
type: "tool.approval-requested",
|
|
707
|
-
id: req.id,
|
|
708
|
-
name: req.toolName,
|
|
709
|
-
input: req.input,
|
|
710
|
-
readOnly: req.readOnly,
|
|
711
|
-
step: req.step
|
|
712
|
-
}),
|
|
713
|
-
resolved: (r) => o.emit({ type: "tool.approval-resolved", ...r })
|
|
714
|
-
},
|
|
715
|
-
signal ?? o.signal
|
|
716
|
-
);
|
|
717
|
-
for (const [name, t] of Object.entries(tools)) {
|
|
718
|
-
const execute = t.execute;
|
|
719
|
-
const builtin = o.builtins.has(name);
|
|
720
|
-
const readOnly = builtin || isReadOnlyTool(t);
|
|
721
|
-
const wrapped = { ...t };
|
|
722
|
-
if (o.maxToolOutputChars > 0) {
|
|
723
|
-
wrapped.toModelOutput = limitModelOutput(t.toModelOutput, o.maxToolOutputChars);
|
|
724
|
-
}
|
|
725
|
-
if (typeof execute === "function") {
|
|
726
|
-
wrapped.execute = (input, options) => {
|
|
727
|
-
const run = () => {
|
|
728
|
-
if (!builtin) o.countCall();
|
|
729
|
-
const agentRun = {
|
|
730
|
-
emit: o.emit,
|
|
731
|
-
step: o.step(),
|
|
732
|
-
signal: o.signal,
|
|
733
|
-
addUsage: o.addUsage,
|
|
734
|
-
approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),
|
|
735
|
-
...o.control ? { control: o.control } : {},
|
|
736
|
-
...o.runId ? { runId: o.runId } : {},
|
|
737
|
-
...o.fetched ? { fetched: o.fetched } : {}
|
|
738
|
-
};
|
|
739
|
-
return execute.call(t, input, { ...options, agentRun });
|
|
740
|
-
};
|
|
741
|
-
if (builtin) return run();
|
|
742
|
-
const permission = decideToolPermission({
|
|
743
|
-
toolName: name,
|
|
744
|
-
readOnly,
|
|
745
|
-
mode: o.approval.mode,
|
|
746
|
-
rules: o.approval.config.rules,
|
|
747
|
-
remembered: o.approval.remembered
|
|
748
|
-
});
|
|
749
|
-
if (permission === "allow") return run();
|
|
750
|
-
return gate(
|
|
751
|
-
name,
|
|
752
|
-
input,
|
|
753
|
-
readOnly,
|
|
754
|
-
options?.abortSignal
|
|
755
|
-
).then(run);
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
out[name] = wrapped;
|
|
759
|
-
}
|
|
760
|
-
return out;
|
|
761
|
-
};
|
|
762
|
-
var createCallCounter = (cap, initial = 0) => {
|
|
763
|
-
let calls = Math.max(0, Math.floor(initial));
|
|
764
|
-
return {
|
|
765
|
-
count: () => {
|
|
766
|
-
if (cap && cap > 0 && calls >= cap) throw new ToolBudgetError(cap);
|
|
767
|
-
calls += 1;
|
|
768
|
-
},
|
|
769
|
-
get calls() {
|
|
770
|
-
return calls;
|
|
771
|
-
},
|
|
772
|
-
get exhausted() {
|
|
773
|
-
return Boolean(cap && cap > 0 && calls >= cap);
|
|
774
|
-
}
|
|
775
|
-
};
|
|
776
|
-
};
|
|
777
|
-
var typeHint = (s, depth) => {
|
|
778
|
-
if (!s) return "any";
|
|
779
|
-
if (Array.isArray(s.enum) && s.enum.length > 0 && s.enum.length <= 8) {
|
|
780
|
-
return s.enum.map((v) => JSON.stringify(v)).join(" | ");
|
|
781
|
-
}
|
|
782
|
-
const type = Array.isArray(s.type) ? s.type.find((x) => x !== "null") : s.type;
|
|
783
|
-
if (type === "array") return `${typeHint(s.items, depth)}[]`;
|
|
784
|
-
if (type === "object" || s.properties) {
|
|
785
|
-
if (depth > 1 || !s.properties) return "object";
|
|
786
|
-
return objectHint(s, depth + 1);
|
|
787
|
-
}
|
|
788
|
-
return type ?? "any";
|
|
789
|
-
};
|
|
790
|
-
var objectHint = (s, depth = 0) => {
|
|
791
|
-
const required = new Set(s.required ?? []);
|
|
792
|
-
const props = Object.entries(s.properties ?? {});
|
|
793
|
-
if (props.length === 0) return "{}";
|
|
794
|
-
return `{ ${props.slice(0, 12).map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${typeHint(v, depth)}`).join(", ")}${props.length > 12 ? ", \u2026" : ""} }`;
|
|
795
|
-
};
|
|
796
|
-
var schemaHintOf = async (t) => {
|
|
797
|
-
const own = promptHintOf(t);
|
|
798
|
-
if (own) return own;
|
|
799
|
-
try {
|
|
800
|
-
const schema = await asSchema(t.inputSchema).jsonSchema;
|
|
801
|
-
return schema && typeof schema === "object" ? objectHint(schema) : void 0;
|
|
802
|
-
} catch {
|
|
803
|
-
return void 0;
|
|
804
|
-
}
|
|
805
|
-
};
|
|
806
|
-
|
|
807
523
|
// src/learning.ts
|
|
808
524
|
var SAVE_SKILL_TOOL = "save_skill";
|
|
809
525
|
var FORGET_SKILL_TOOL = "forget_skill";
|
|
@@ -1132,14 +848,16 @@ var SYNTHESIZER_SYSTEM = `You are the SYNTHESIZER. Answer the user's goal from w
|
|
|
1132
848
|
- Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON, no code.`;
|
|
1133
849
|
var defaultPrompts = {
|
|
1134
850
|
planner: (ctx) => ({
|
|
1135
|
-
system: (ctx.mode === "prompted" ? PLANNER_PROMPTED : PLANNER_NATIVE) + (ctx.skills ? PLANNER_SKILLS : "") + (ctx.searchMode ? PLANNER_SEARCH : "") +
|
|
851
|
+
system: (ctx.mode === "prompted" ? PLANNER_PROMPTED : PLANNER_NATIVE) + (ctx.skills ? PLANNER_SKILLS : "") + (ctx.searchMode ? PLANNER_SEARCH : "") + (ctx.sandbox ? `
|
|
852
|
+
${ctx.sandbox}` : "") + section("SKILLS", ctx.skills) + `
|
|
1136
853
|
|
|
1137
854
|
TOOLS:
|
|
1138
855
|
${ctx.toolCatalog}`,
|
|
1139
856
|
prompt: `GOAL: ${ctx.goal}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
|
|
1140
857
|
}),
|
|
1141
858
|
executor: (ctx) => ({
|
|
1142
|
-
system: (ctx.mode === "prompted" ? EXECUTOR_PROMPTED : EXECUTOR_NATIVE) + (ctx.searchMode ? EXECUTOR_SEARCH : "") + (ctx.skills ? EXECUTOR_SKILLS : "") + (ctx.learning ? executorLearning(ctx.learning.fetch) : "") +
|
|
859
|
+
system: (ctx.mode === "prompted" ? EXECUTOR_PROMPTED : EXECUTOR_NATIVE) + (ctx.searchMode ? EXECUTOR_SEARCH : "") + (ctx.skills ? EXECUTOR_SKILLS : "") + (ctx.learning ? executorLearning(ctx.learning.fetch) : "") + (ctx.sandbox ? `
|
|
860
|
+
- ${ctx.sandbox}` : "") + section("SKILLS", ctx.skills) + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
|
|
1143
861
|
prompt: [
|
|
1144
862
|
`GOAL: ${ctx.goal}`,
|
|
1145
863
|
stateBlock(ctx.state).trimStart(),
|
|
@@ -1165,7 +883,8 @@ ${numbered(ctx.remaining, "(none)")}`,
|
|
|
1165
883
|
].filter(Boolean).join("\n\n")
|
|
1166
884
|
}),
|
|
1167
885
|
synthesizer: (ctx) => ({
|
|
1168
|
-
system: SYNTHESIZER_SYSTEM +
|
|
886
|
+
system: SYNTHESIZER_SYSTEM + (ctx.sandbox ? `
|
|
887
|
+
- ${ctx.sandbox}` : "") + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
|
|
1169
888
|
prompt: [
|
|
1170
889
|
`GOAL: ${ctx.goal}`,
|
|
1171
890
|
stateBlock(ctx.state).trimStart(),
|
|
@@ -1893,7 +1612,7 @@ var portOf = (control) => {
|
|
|
1893
1612
|
return port;
|
|
1894
1613
|
};
|
|
1895
1614
|
var createRunControl = () => {
|
|
1896
|
-
let
|
|
1615
|
+
let seq2 = 0;
|
|
1897
1616
|
let queue = [];
|
|
1898
1617
|
let emit;
|
|
1899
1618
|
let ended = false;
|
|
@@ -1902,7 +1621,7 @@ var createRunControl = () => {
|
|
|
1902
1621
|
send(text) {
|
|
1903
1622
|
const clean = typeof text === "string" ? text.trim() : "";
|
|
1904
1623
|
if (!clean || ended) return false;
|
|
1905
|
-
const message = { id: `msg-${
|
|
1624
|
+
const message = { id: `msg-${seq2 += 1}`, text: clean };
|
|
1906
1625
|
queue.push(message);
|
|
1907
1626
|
emit?.({ type: "message.queued", id: message.id, text: message.text });
|
|
1908
1627
|
return true;
|
|
@@ -2478,7 +2197,8 @@ var executeStep = async (ctx, goal, step, index, total, done) => {
|
|
|
2478
2197
|
activeSkills: active.length ? renderActiveSkills(active) : void 0,
|
|
2479
2198
|
searchMode: searchMode && Boolean(ctx.tools[FIND_TOOLS_NAME]),
|
|
2480
2199
|
updates: ctx.userUpdates?.(),
|
|
2481
|
-
...ctx.learning?.nudge ? { learning: { fetch: Boolean(ctx.tools[WEB_FETCH_TOOL]) } } : {}
|
|
2200
|
+
...ctx.learning?.nudge ? { learning: { fetch: Boolean(ctx.tools[WEB_FETCH_TOOL]) } } : {},
|
|
2201
|
+
...ctx.sandbox ? { sandbox: ctx.sandbox.executor } : {}
|
|
2482
2202
|
});
|
|
2483
2203
|
const loop = await runToolLoop(ctx.executorModel, {
|
|
2484
2204
|
mode: ctx.executorMode,
|
|
@@ -2650,7 +2370,8 @@ ${nudge}` : goal;
|
|
|
2650
2370
|
mode,
|
|
2651
2371
|
history: ctx.history,
|
|
2652
2372
|
skills: skillIndex,
|
|
2653
|
-
searchMode: ctx.strategy === "search"
|
|
2373
|
+
searchMode: ctx.strategy === "search",
|
|
2374
|
+
...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {}
|
|
2654
2375
|
});
|
|
2655
2376
|
return {
|
|
2656
2377
|
...stageCall(ctx, "planner", parts.system),
|
|
@@ -2776,7 +2497,8 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
|
2776
2497
|
done,
|
|
2777
2498
|
findings,
|
|
2778
2499
|
activeSkills: active.length ? renderActiveSkills(active) : void 0,
|
|
2779
|
-
updates: ctx.userUpdates?.()
|
|
2500
|
+
updates: ctx.userUpdates?.(),
|
|
2501
|
+
...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {}
|
|
2780
2502
|
});
|
|
2781
2503
|
const result = stream(ctx.synthesizerModel, {
|
|
2782
2504
|
...stageCall(ctx, "synthesizer", parts.system),
|
|
@@ -2820,27 +2542,6 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
|
2820
2542
|
};
|
|
2821
2543
|
};
|
|
2822
2544
|
|
|
2823
|
-
// src/logger.ts
|
|
2824
|
-
var WEIGHT = {
|
|
2825
|
-
silent: 0,
|
|
2826
|
-
error: 1,
|
|
2827
|
-
warn: 2,
|
|
2828
|
-
info: 3,
|
|
2829
|
-
debug: 4
|
|
2830
|
-
};
|
|
2831
|
-
var PREFIX = "[agent-web]";
|
|
2832
|
-
var noop = () => void 0;
|
|
2833
|
-
var createLogger = (level = "warn", sink = console) => {
|
|
2834
|
-
const at = (min, fn) => WEIGHT[level] >= WEIGHT[min] ? (...args) => fn.call(sink, PREFIX, ...args) : noop;
|
|
2835
|
-
return {
|
|
2836
|
-
level,
|
|
2837
|
-
error: at("error", sink.error),
|
|
2838
|
-
warn: at("warn", sink.warn),
|
|
2839
|
-
info: at("info", sink.info),
|
|
2840
|
-
debug: at("debug", sink.debug)
|
|
2841
|
-
};
|
|
2842
|
-
};
|
|
2843
|
-
|
|
2844
2545
|
// src/providers/capabilities.ts
|
|
2845
2546
|
var CLOUD = /* @__PURE__ */ new Set([
|
|
2846
2547
|
"openai",
|
|
@@ -2933,13 +2634,20 @@ var createAgent = async (config) => {
|
|
|
2933
2634
|
(m) => log.warn(m)
|
|
2934
2635
|
) : void 0;
|
|
2935
2636
|
const hasSkill = (name) => skills.some((s) => s.name === name);
|
|
2936
|
-
const
|
|
2637
|
+
const hostTools = filterTools(
|
|
2937
2638
|
// What `egress` switches on (web_fetch) and the notebook's tools; a tool of the same name in
|
|
2938
2639
|
// `tools` wins.
|
|
2939
2640
|
{ ...createEgressTools(config.egress), ...learning?.tools, ...config.tools },
|
|
2940
2641
|
config.availableTools,
|
|
2941
2642
|
config.excludedTools
|
|
2942
2643
|
);
|
|
2644
|
+
const sandbox = config.sandbox ? (await import("./sandbox-AMO2SA4X.js")).createSandbox(
|
|
2645
|
+
config.sandbox === true ? {} : config.sandbox,
|
|
2646
|
+
hostTools,
|
|
2647
|
+
(m) => log.warn(m)
|
|
2648
|
+
) : void 0;
|
|
2649
|
+
const baseTools = sandbox ? { ...filterTools(sandbox.tools, config.availableTools, config.excludedTools), ...hostTools } : hostTools;
|
|
2650
|
+
const sandboxNotes = sandbox && baseTools.run_js === sandbox.tools.run_js ? sandbox.notes : void 0;
|
|
2943
2651
|
const catalog = toolCatalogOf(baseTools);
|
|
2944
2652
|
const toolDefTokens = await toolDefinitionTokens(baseTools);
|
|
2945
2653
|
const toolTokens = cfg.toolSelectionStrategy === "auto" ? toolDefTokens : 0;
|
|
@@ -3188,6 +2896,7 @@ ${renderActiveSkills(active)}`
|
|
|
3188
2896
|
tools: Object.keys(learning.tools)
|
|
3189
2897
|
}
|
|
3190
2898
|
} : {},
|
|
2899
|
+
...sandboxNotes ? { sandbox: sandboxNotes } : {},
|
|
3191
2900
|
discovered: () => discovered,
|
|
3192
2901
|
builtinTools,
|
|
3193
2902
|
toolHint,
|
|
@@ -3566,8 +3275,1113 @@ ${renderActiveSkills(active)}`
|
|
|
3566
3275
|
};
|
|
3567
3276
|
};
|
|
3568
3277
|
|
|
3278
|
+
// src/pipeline/index.ts
|
|
3279
|
+
import { z as z4 } from "zod";
|
|
3280
|
+
|
|
3281
|
+
// src/pipeline/engine.ts
|
|
3282
|
+
var PIPELINE_LIMITS = {
|
|
3283
|
+
// Defaults of `limits`.
|
|
3284
|
+
maxNodeVisits: 3,
|
|
3285
|
+
maxRuns: 25,
|
|
3286
|
+
// The largest values `limits` accepts (the smallest is 1).
|
|
3287
|
+
maxNodeVisitsCeiling: 100,
|
|
3288
|
+
maxRunsCeiling: 1e3,
|
|
3289
|
+
// The size of a definition.
|
|
3290
|
+
maxNodes: 200,
|
|
3291
|
+
maxEdges: 1e3,
|
|
3292
|
+
maxRoutes: 20,
|
|
3293
|
+
// `matches`: the longest pattern, and the largest compiled program (what `a{50}` grows into).
|
|
3294
|
+
maxPatternLength: 500,
|
|
3295
|
+
maxPatternProgram: 1e3,
|
|
3296
|
+
// `contains` and `matches` look at this many leading characters of an output.
|
|
3297
|
+
conditionInputChars: 5e4
|
|
3298
|
+
};
|
|
3299
|
+
var PipelineValidationError = class extends Error {
|
|
3300
|
+
errors;
|
|
3301
|
+
constructor(errors) {
|
|
3302
|
+
super(`Invalid pipeline: ${errors.map((e) => e.message).join("; ")}`);
|
|
3303
|
+
this.name = "PipelineValidationError";
|
|
3304
|
+
this.errors = errors;
|
|
3305
|
+
}
|
|
3306
|
+
};
|
|
3307
|
+
var PipelineNodeError = class extends Error {
|
|
3308
|
+
nodeId;
|
|
3309
|
+
visit;
|
|
3310
|
+
constructor(nodeId, visit, cause) {
|
|
3311
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
3312
|
+
super(`Pipeline node "${nodeId}" failed (visit ${visit}): ${reason}`, { cause });
|
|
3313
|
+
this.name = "PipelineNodeError";
|
|
3314
|
+
this.nodeId = nodeId;
|
|
3315
|
+
this.visit = visit;
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
var cp = (s) => s.codePointAt(0);
|
|
3319
|
+
var DIGIT = [48, 57];
|
|
3320
|
+
var WORD = [48, 57, 65, 90, 95, 95, 97, 122];
|
|
3321
|
+
var SPACE = [
|
|
3322
|
+
9,
|
|
3323
|
+
13,
|
|
3324
|
+
32,
|
|
3325
|
+
32,
|
|
3326
|
+
160,
|
|
3327
|
+
160,
|
|
3328
|
+
5760,
|
|
3329
|
+
5760,
|
|
3330
|
+
8192,
|
|
3331
|
+
8202,
|
|
3332
|
+
8232,
|
|
3333
|
+
8233,
|
|
3334
|
+
8239,
|
|
3335
|
+
8239,
|
|
3336
|
+
8287,
|
|
3337
|
+
8287,
|
|
3338
|
+
12288,
|
|
3339
|
+
12288,
|
|
3340
|
+
65279,
|
|
3341
|
+
65279
|
|
3342
|
+
];
|
|
3343
|
+
var MAX_CODE_POINT = 1114111;
|
|
3344
|
+
var MAX_REPEAT = 1e3;
|
|
3345
|
+
var inRanges = (r, c) => {
|
|
3346
|
+
for (let i = 0; i < r.length; i += 2) {
|
|
3347
|
+
if (c >= r[i] && c <= r[i + 1]) return true;
|
|
3348
|
+
}
|
|
3349
|
+
return false;
|
|
3350
|
+
};
|
|
3351
|
+
var complement = (r) => {
|
|
3352
|
+
const pairs = [];
|
|
3353
|
+
for (let i = 0; i < r.length; i += 2) pairs.push([r[i], r[i + 1]]);
|
|
3354
|
+
pairs.sort((a, b) => a[0] - b[0]);
|
|
3355
|
+
const out = [];
|
|
3356
|
+
let next = 0;
|
|
3357
|
+
for (const [lo, hi] of pairs) {
|
|
3358
|
+
if (lo > next) out.push(next, lo - 1);
|
|
3359
|
+
next = Math.max(next, hi + 1);
|
|
3360
|
+
}
|
|
3361
|
+
if (next <= MAX_CODE_POINT) out.push(next, MAX_CODE_POINT);
|
|
3362
|
+
return out;
|
|
3363
|
+
};
|
|
3364
|
+
var isLineEnd = (c) => c === 10 || c === 13 || c === 8232 || c === 8233;
|
|
3365
|
+
var isWordChar = (c) => c !== void 0 && inRanges(WORD, c);
|
|
3366
|
+
var isHex = (c) => c !== void 0 && /^[0-9a-fA-F]$/.test(String.fromCodePoint(c));
|
|
3367
|
+
var isDigit = (c) => c !== void 0 && c >= 48 && c <= 57;
|
|
3368
|
+
var parsePattern = (pattern) => {
|
|
3369
|
+
const src = Array.from(pattern, cp);
|
|
3370
|
+
let i = 0;
|
|
3371
|
+
const peek = (offset = 0) => src[i + offset];
|
|
3372
|
+
const is = (ch, offset = 0) => src[i + offset] === cp(ch);
|
|
3373
|
+
const fail = (message) => {
|
|
3374
|
+
throw new Error(`${message} (at ${i})`);
|
|
3375
|
+
};
|
|
3376
|
+
const hex = (digits) => {
|
|
3377
|
+
let value = 0;
|
|
3378
|
+
for (let n = 0; n < digits; n++) {
|
|
3379
|
+
if (!isHex(peek())) fail("a bad hexadecimal escape");
|
|
3380
|
+
value = value * 16 + parseInt(String.fromCodePoint(src[i++]), 16);
|
|
3381
|
+
}
|
|
3382
|
+
return value;
|
|
3383
|
+
};
|
|
3384
|
+
const escape = (inClass) => {
|
|
3385
|
+
const c = peek();
|
|
3386
|
+
if (c === void 0) return fail("a pattern cannot end with a backslash");
|
|
3387
|
+
i++;
|
|
3388
|
+
const ch = String.fromCodePoint(c);
|
|
3389
|
+
switch (ch) {
|
|
3390
|
+
case "d":
|
|
3391
|
+
return { r: DIGIT };
|
|
3392
|
+
case "D":
|
|
3393
|
+
return { r: complement(DIGIT) };
|
|
3394
|
+
case "w":
|
|
3395
|
+
return { r: WORD };
|
|
3396
|
+
case "W":
|
|
3397
|
+
return { r: complement(WORD) };
|
|
3398
|
+
case "s":
|
|
3399
|
+
return { r: SPACE };
|
|
3400
|
+
case "S":
|
|
3401
|
+
return { r: complement(SPACE) };
|
|
3402
|
+
case "b":
|
|
3403
|
+
return inClass ? { c: 8 } : { k: "word" };
|
|
3404
|
+
case "B":
|
|
3405
|
+
return inClass ? fail("\\B is not allowed in a class") : { k: "not-word" };
|
|
3406
|
+
case "n":
|
|
3407
|
+
return { c: 10 };
|
|
3408
|
+
case "r":
|
|
3409
|
+
return { c: 13 };
|
|
3410
|
+
case "t":
|
|
3411
|
+
return { c: 9 };
|
|
3412
|
+
case "f":
|
|
3413
|
+
return { c: 12 };
|
|
3414
|
+
case "v":
|
|
3415
|
+
return { c: 11 };
|
|
3416
|
+
case "0":
|
|
3417
|
+
return isDigit(peek()) ? fail("octal escapes are not supported") : { c: 0 };
|
|
3418
|
+
case "x":
|
|
3419
|
+
return { c: hex(2) };
|
|
3420
|
+
case "u": {
|
|
3421
|
+
if (!is("{")) return { c: hex(4) };
|
|
3422
|
+
i++;
|
|
3423
|
+
let value = 0;
|
|
3424
|
+
let digits = 0;
|
|
3425
|
+
while (isHex(peek())) {
|
|
3426
|
+
value = value * 16 + parseInt(String.fromCodePoint(src[i++]), 16);
|
|
3427
|
+
digits++;
|
|
3428
|
+
if (value > MAX_CODE_POINT) fail("a code point out of range");
|
|
3429
|
+
}
|
|
3430
|
+
if (!digits || !is("}")) fail("a bad \\u{...} escape");
|
|
3431
|
+
i++;
|
|
3432
|
+
return { c: value };
|
|
3433
|
+
}
|
|
3434
|
+
case "k":
|
|
3435
|
+
return fail("backreferences are not supported");
|
|
3436
|
+
case "p":
|
|
3437
|
+
case "P":
|
|
3438
|
+
return fail("\\p{...} is not supported");
|
|
3439
|
+
case "c":
|
|
3440
|
+
return fail("\\c control escapes are not supported");
|
|
3441
|
+
default:
|
|
3442
|
+
if (isDigit(c)) return fail("backreferences are not supported");
|
|
3443
|
+
if (/^[a-zA-Z]$/.test(ch)) return fail(`unknown escape \\${ch}`);
|
|
3444
|
+
return { c };
|
|
3445
|
+
}
|
|
3446
|
+
};
|
|
3447
|
+
const klass = () => {
|
|
3448
|
+
const neg = is("^");
|
|
3449
|
+
if (neg) i++;
|
|
3450
|
+
const r = [];
|
|
3451
|
+
for (; ; ) {
|
|
3452
|
+
const c = peek();
|
|
3453
|
+
if (c === void 0) return fail("an unterminated class");
|
|
3454
|
+
if (is("]")) {
|
|
3455
|
+
i++;
|
|
3456
|
+
break;
|
|
3457
|
+
}
|
|
3458
|
+
i++;
|
|
3459
|
+
let lo;
|
|
3460
|
+
if (c === cp("\\")) {
|
|
3461
|
+
const e = escape(true);
|
|
3462
|
+
if ("r" in e) {
|
|
3463
|
+
r.push(...e.r);
|
|
3464
|
+
continue;
|
|
3465
|
+
}
|
|
3466
|
+
lo = e.c;
|
|
3467
|
+
} else {
|
|
3468
|
+
lo = c;
|
|
3469
|
+
}
|
|
3470
|
+
if (is("-") && peek(1) !== void 0 && !is("]", 1)) {
|
|
3471
|
+
i++;
|
|
3472
|
+
let hi = src[i++];
|
|
3473
|
+
if (hi === cp("\\")) {
|
|
3474
|
+
const e = escape(true);
|
|
3475
|
+
if (!("c" in e)) return fail("a bad range in a class");
|
|
3476
|
+
hi = e.c;
|
|
3477
|
+
}
|
|
3478
|
+
if (hi < lo) fail("a range out of order in a class");
|
|
3479
|
+
r.push(lo, hi);
|
|
3480
|
+
} else {
|
|
3481
|
+
r.push(lo, lo);
|
|
3482
|
+
}
|
|
3483
|
+
}
|
|
3484
|
+
return { t: "set", r, neg };
|
|
3485
|
+
};
|
|
3486
|
+
const braces = () => {
|
|
3487
|
+
let j = i + 1;
|
|
3488
|
+
const number = () => {
|
|
3489
|
+
const start = j;
|
|
3490
|
+
while (isDigit(src[j])) j++;
|
|
3491
|
+
return j > start ? Number(String.fromCodePoint(...src.slice(start, j))) : void 0;
|
|
3492
|
+
};
|
|
3493
|
+
const min = number();
|
|
3494
|
+
if (min === void 0) return void 0;
|
|
3495
|
+
let max = min;
|
|
3496
|
+
if (src[j] === cp(",")) {
|
|
3497
|
+
j++;
|
|
3498
|
+
max = number() ?? Infinity;
|
|
3499
|
+
}
|
|
3500
|
+
if (src[j] !== cp("}")) return void 0;
|
|
3501
|
+
i = j + 1;
|
|
3502
|
+
if (max < min) fail("a quantifier out of order");
|
|
3503
|
+
if (min > MAX_REPEAT || max !== Infinity && max > MAX_REPEAT) {
|
|
3504
|
+
fail(`a repeat count above ${MAX_REPEAT}`);
|
|
3505
|
+
}
|
|
3506
|
+
return { min, max };
|
|
3507
|
+
};
|
|
3508
|
+
const atom = () => {
|
|
3509
|
+
const c = src[i++];
|
|
3510
|
+
switch (String.fromCodePoint(c)) {
|
|
3511
|
+
case "(": {
|
|
3512
|
+
if (is("?")) {
|
|
3513
|
+
if (is(":", 1)) {
|
|
3514
|
+
i += 2;
|
|
3515
|
+
} else if (is("<", 1) && !is("=", 2) && !is("!", 2)) {
|
|
3516
|
+
while (peek() !== void 0 && !is(">")) i++;
|
|
3517
|
+
if (peek() === void 0) fail("an unterminated group name");
|
|
3518
|
+
i++;
|
|
3519
|
+
} else {
|
|
3520
|
+
fail("lookaround is not supported");
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
const inner = alternation();
|
|
3524
|
+
if (!is(")")) fail("an unterminated group");
|
|
3525
|
+
i++;
|
|
3526
|
+
return inner;
|
|
3527
|
+
}
|
|
3528
|
+
case "[":
|
|
3529
|
+
return klass();
|
|
3530
|
+
case ".":
|
|
3531
|
+
return { t: "any" };
|
|
3532
|
+
case "^":
|
|
3533
|
+
return { t: "assert", k: "start" };
|
|
3534
|
+
case "$":
|
|
3535
|
+
return { t: "assert", k: "end" };
|
|
3536
|
+
case "\\": {
|
|
3537
|
+
const e = escape(false);
|
|
3538
|
+
if ("k" in e) return { t: "assert", k: e.k };
|
|
3539
|
+
return "r" in e ? { t: "set", r: e.r, neg: false } : { t: "char", c: e.c };
|
|
3540
|
+
}
|
|
3541
|
+
case "*":
|
|
3542
|
+
case "+":
|
|
3543
|
+
case "?":
|
|
3544
|
+
return fail("nothing to repeat");
|
|
3545
|
+
case "{":
|
|
3546
|
+
i--;
|
|
3547
|
+
if (braces()) fail("nothing to repeat");
|
|
3548
|
+
i++;
|
|
3549
|
+
return { t: "char", c };
|
|
3550
|
+
default:
|
|
3551
|
+
return { t: "char", c };
|
|
3552
|
+
}
|
|
3553
|
+
};
|
|
3554
|
+
const repetition = () => {
|
|
3555
|
+
let item = atom();
|
|
3556
|
+
for (; ; ) {
|
|
3557
|
+
let q;
|
|
3558
|
+
if (is("*")) q = { min: 0, max: Infinity };
|
|
3559
|
+
else if (is("+")) q = { min: 1, max: Infinity };
|
|
3560
|
+
else if (is("?")) q = { min: 0, max: 1 };
|
|
3561
|
+
if (q) i++;
|
|
3562
|
+
else if (is("{")) q = braces();
|
|
3563
|
+
if (!q) return item;
|
|
3564
|
+
if (item.t === "assert") fail("nothing to repeat");
|
|
3565
|
+
if (is("?")) i++;
|
|
3566
|
+
item = { t: "rep", item, min: q.min, max: q.max };
|
|
3567
|
+
}
|
|
3568
|
+
};
|
|
3569
|
+
const sequence = () => {
|
|
3570
|
+
const items = [];
|
|
3571
|
+
while (peek() !== void 0 && !is("|") && !is(")")) items.push(repetition());
|
|
3572
|
+
return items.length === 1 ? items[0] : { t: "cat", items };
|
|
3573
|
+
};
|
|
3574
|
+
function alternation() {
|
|
3575
|
+
const items = [sequence()];
|
|
3576
|
+
while (is("|")) {
|
|
3577
|
+
i++;
|
|
3578
|
+
items.push(sequence());
|
|
3579
|
+
}
|
|
3580
|
+
return items.length === 1 ? items[0] : { t: "alt", items };
|
|
3581
|
+
}
|
|
3582
|
+
const ast = alternation();
|
|
3583
|
+
if (i < src.length) fail("an unmatched )");
|
|
3584
|
+
return ast;
|
|
3585
|
+
};
|
|
3586
|
+
var compileAst = (ast) => {
|
|
3587
|
+
const prog = [];
|
|
3588
|
+
const push = (inst) => {
|
|
3589
|
+
if (prog.length >= PIPELINE_LIMITS.maxPatternProgram) {
|
|
3590
|
+
throw new Error(
|
|
3591
|
+
`the pattern is too complex (more than ${PIPELINE_LIMITS.maxPatternProgram} steps once its repeats are unrolled)`
|
|
3592
|
+
);
|
|
3593
|
+
}
|
|
3594
|
+
prog.push(inst);
|
|
3595
|
+
return prog.length - 1;
|
|
3596
|
+
};
|
|
3597
|
+
const emit = (node) => {
|
|
3598
|
+
switch (node.t) {
|
|
3599
|
+
case "char":
|
|
3600
|
+
push({ op: "char", c: node.c });
|
|
3601
|
+
return;
|
|
3602
|
+
case "any":
|
|
3603
|
+
push({ op: "any" });
|
|
3604
|
+
return;
|
|
3605
|
+
case "set":
|
|
3606
|
+
push({ op: "set", r: node.r, neg: node.neg });
|
|
3607
|
+
return;
|
|
3608
|
+
case "assert":
|
|
3609
|
+
push({ op: "assert", k: node.k });
|
|
3610
|
+
return;
|
|
3611
|
+
case "cat":
|
|
3612
|
+
for (const item of node.items) emit(item);
|
|
3613
|
+
return;
|
|
3614
|
+
case "alt": {
|
|
3615
|
+
const exits = [];
|
|
3616
|
+
node.items.forEach((item, index) => {
|
|
3617
|
+
if (index === node.items.length - 1) {
|
|
3618
|
+
emit(item);
|
|
3619
|
+
return;
|
|
3620
|
+
}
|
|
3621
|
+
const split = { op: "split", x: 0, y: 0 };
|
|
3622
|
+
split.x = push(split) + 1;
|
|
3623
|
+
emit(item);
|
|
3624
|
+
const exit = { op: "jmp", x: 0 };
|
|
3625
|
+
push(exit);
|
|
3626
|
+
exits.push(exit);
|
|
3627
|
+
split.y = prog.length;
|
|
3628
|
+
});
|
|
3629
|
+
for (const exit of exits) exit.x = prog.length;
|
|
3630
|
+
return;
|
|
3631
|
+
}
|
|
3632
|
+
case "rep": {
|
|
3633
|
+
for (let n = 0; n < node.min; n++) emit(node.item);
|
|
3634
|
+
if (node.max === Infinity) {
|
|
3635
|
+
const split = { op: "split", x: 0, y: 0 };
|
|
3636
|
+
const at = push(split);
|
|
3637
|
+
split.x = at + 1;
|
|
3638
|
+
emit(node.item);
|
|
3639
|
+
push({ op: "jmp", x: at });
|
|
3640
|
+
split.y = prog.length;
|
|
3641
|
+
return;
|
|
3642
|
+
}
|
|
3643
|
+
const skips = [];
|
|
3644
|
+
for (let n = node.min; n < node.max; n++) {
|
|
3645
|
+
const split = { op: "split", x: 0, y: 0 };
|
|
3646
|
+
split.x = push(split) + 1;
|
|
3647
|
+
skips.push(split);
|
|
3648
|
+
emit(node.item);
|
|
3649
|
+
}
|
|
3650
|
+
for (const split of skips) split.y = prog.length;
|
|
3651
|
+
return;
|
|
3652
|
+
}
|
|
3653
|
+
}
|
|
3654
|
+
};
|
|
3655
|
+
emit(ast);
|
|
3656
|
+
push({ op: "match" });
|
|
3657
|
+
return prog;
|
|
3658
|
+
};
|
|
3659
|
+
var ALLOWED_FLAGS = "imsu";
|
|
3660
|
+
var compileMatcher = (pattern, flags = "") => {
|
|
3661
|
+
if (typeof pattern !== "string" || pattern.length === 0) {
|
|
3662
|
+
throw new Error("the pattern is empty");
|
|
3663
|
+
}
|
|
3664
|
+
if (pattern.length > PIPELINE_LIMITS.maxPatternLength) {
|
|
3665
|
+
throw new Error(`the pattern is longer than ${PIPELINE_LIMITS.maxPatternLength} characters`);
|
|
3666
|
+
}
|
|
3667
|
+
if (typeof flags !== "string") throw new Error("flags must be a string");
|
|
3668
|
+
for (const flag of flags) {
|
|
3669
|
+
if (!ALLOWED_FLAGS.includes(flag)) {
|
|
3670
|
+
throw new Error(`flag "${flag}" is not allowed (allowed: ${ALLOWED_FLAGS})`);
|
|
3671
|
+
}
|
|
3672
|
+
}
|
|
3673
|
+
if (new Set(flags).size !== flags.length) throw new Error("a flag is repeated");
|
|
3674
|
+
try {
|
|
3675
|
+
new RegExp(pattern, flags);
|
|
3676
|
+
} catch (err) {
|
|
3677
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
3678
|
+
}
|
|
3679
|
+
const prog = compileAst(parsePattern(pattern));
|
|
3680
|
+
const ignoreCase = flags.includes("i");
|
|
3681
|
+
const multiline = flags.includes("m");
|
|
3682
|
+
const dotAll = flags.includes("s");
|
|
3683
|
+
const single = (c, mapped) => mapped.length === String.fromCodePoint(cp(mapped)).length ? cp(mapped) : c;
|
|
3684
|
+
const lower = (c) => single(c, String.fromCodePoint(c).toLowerCase());
|
|
3685
|
+
const upper = (c) => single(c, String.fromCodePoint(c).toUpperCase());
|
|
3686
|
+
return (text) => {
|
|
3687
|
+
const input = Array.from(text.slice(0, PIPELINE_LIMITS.conditionInputChars), cp);
|
|
3688
|
+
const n = input.length;
|
|
3689
|
+
const mark = new Int32Array(prog.length);
|
|
3690
|
+
let generation = 0;
|
|
3691
|
+
let matched = false;
|
|
3692
|
+
const stack = [];
|
|
3693
|
+
const holds = (k, pos) => {
|
|
3694
|
+
switch (k) {
|
|
3695
|
+
case "start":
|
|
3696
|
+
return pos === 0 || multiline && isLineEnd(input[pos - 1]);
|
|
3697
|
+
case "end":
|
|
3698
|
+
return pos === n || multiline && isLineEnd(input[pos]);
|
|
3699
|
+
case "word":
|
|
3700
|
+
return isWordChar(input[pos - 1]) !== isWordChar(input[pos]);
|
|
3701
|
+
case "not-word":
|
|
3702
|
+
return isWordChar(input[pos - 1]) === isWordChar(input[pos]);
|
|
3703
|
+
}
|
|
3704
|
+
};
|
|
3705
|
+
const add = (list, start, pos) => {
|
|
3706
|
+
stack.push(start);
|
|
3707
|
+
while (stack.length) {
|
|
3708
|
+
const pc = stack.pop();
|
|
3709
|
+
if (mark[pc] === generation) continue;
|
|
3710
|
+
mark[pc] = generation;
|
|
3711
|
+
const inst = prog[pc];
|
|
3712
|
+
switch (inst.op) {
|
|
3713
|
+
case "jmp":
|
|
3714
|
+
stack.push(inst.x);
|
|
3715
|
+
break;
|
|
3716
|
+
case "split":
|
|
3717
|
+
stack.push(inst.y, inst.x);
|
|
3718
|
+
break;
|
|
3719
|
+
case "assert":
|
|
3720
|
+
if (holds(inst.k, pos)) stack.push(pc + 1);
|
|
3721
|
+
break;
|
|
3722
|
+
case "match":
|
|
3723
|
+
matched = true;
|
|
3724
|
+
break;
|
|
3725
|
+
default:
|
|
3726
|
+
list.push(pc);
|
|
3727
|
+
}
|
|
3728
|
+
}
|
|
3729
|
+
};
|
|
3730
|
+
let current = [];
|
|
3731
|
+
let next = [];
|
|
3732
|
+
generation++;
|
|
3733
|
+
add(current, 0, 0);
|
|
3734
|
+
for (let pos = 0; pos < n && !matched; pos++) {
|
|
3735
|
+
const c = input[pos];
|
|
3736
|
+
const lo = ignoreCase ? lower(c) : c;
|
|
3737
|
+
const up = ignoreCase ? upper(c) : c;
|
|
3738
|
+
generation++;
|
|
3739
|
+
for (const pc of current) {
|
|
3740
|
+
const inst = prog[pc];
|
|
3741
|
+
let ok = false;
|
|
3742
|
+
if (inst.op === "char") {
|
|
3743
|
+
ok = inst.c === c || ignoreCase && (inst.c === lo || inst.c === up || lower(inst.c) === lo);
|
|
3744
|
+
} else if (inst.op === "any") {
|
|
3745
|
+
ok = dotAll || !isLineEnd(c);
|
|
3746
|
+
} else if (inst.op === "set") {
|
|
3747
|
+
const inside = inRanges(inst.r, c) || ignoreCase && (inRanges(inst.r, lo) || inRanges(inst.r, up));
|
|
3748
|
+
ok = inside !== inst.neg;
|
|
3749
|
+
}
|
|
3750
|
+
if (ok) add(next, pc + 1, pos + 1);
|
|
3751
|
+
}
|
|
3752
|
+
add(next, 0, pos + 1);
|
|
3753
|
+
current = next;
|
|
3754
|
+
next = [];
|
|
3755
|
+
}
|
|
3756
|
+
return matched;
|
|
3757
|
+
};
|
|
3758
|
+
};
|
|
3759
|
+
var CONDITION_KINDS = ["always", "contains", "matches", "route", "otherwise"];
|
|
3760
|
+
var testPipelineCondition = (when, output, matcher) => {
|
|
3761
|
+
if (!when || when.kind === "always") return true;
|
|
3762
|
+
switch (when.kind) {
|
|
3763
|
+
case "contains": {
|
|
3764
|
+
const text = output.text.slice(0, PIPELINE_LIMITS.conditionInputChars);
|
|
3765
|
+
return when.caseSensitive ? text.includes(when.text) : text.toLowerCase().includes(when.text.toLowerCase());
|
|
3766
|
+
}
|
|
3767
|
+
case "matches":
|
|
3768
|
+
return (matcher ?? compileMatcher(when.pattern, when.flags))(output.text);
|
|
3769
|
+
case "route":
|
|
3770
|
+
return output.route !== void 0 && output.route === when.label;
|
|
3771
|
+
default:
|
|
3772
|
+
return false;
|
|
3773
|
+
}
|
|
3774
|
+
};
|
|
3775
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3776
|
+
var isId = (v) => typeof v === "string" && v.trim().length > 0;
|
|
3777
|
+
var edgeIdOf = (edge, index) => isRecord(edge) && isId(edge.id) ? edge.id : `e${index}`;
|
|
3778
|
+
var edgeRef = (edge, index) => ({
|
|
3779
|
+
edgeId: edgeIdOf(edge, index),
|
|
3780
|
+
edgeIndex: index
|
|
3781
|
+
});
|
|
3782
|
+
var normalizePipeline = (definition) => {
|
|
3783
|
+
const def = JSON.parse(JSON.stringify(definition));
|
|
3784
|
+
if (isRecord(def) && Array.isArray(def.edges)) {
|
|
3785
|
+
def.edges.forEach((edge, index) => {
|
|
3786
|
+
if (isRecord(edge)) edge.id = edgeIdOf(edge, index);
|
|
3787
|
+
});
|
|
3788
|
+
}
|
|
3789
|
+
return def;
|
|
3790
|
+
};
|
|
3791
|
+
var inRange2 = (v, max) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= max;
|
|
3792
|
+
var validatePipeline = (definition) => {
|
|
3793
|
+
const errors = [];
|
|
3794
|
+
const warnings = [];
|
|
3795
|
+
const error = (code, message, at = {}) => {
|
|
3796
|
+
errors.push({ code, message, ...at });
|
|
3797
|
+
};
|
|
3798
|
+
const done = () => ({ ok: errors.length === 0, errors, warnings });
|
|
3799
|
+
const def = definition;
|
|
3800
|
+
if (!isRecord(def)) {
|
|
3801
|
+
error("definition", "a pipeline definition must be an object");
|
|
3802
|
+
return done();
|
|
3803
|
+
}
|
|
3804
|
+
if (def.version !== 1) {
|
|
3805
|
+
error("version", `unsupported pipeline version ${JSON.stringify(def.version)} (expected 1)`);
|
|
3806
|
+
}
|
|
3807
|
+
const nodes = Array.isArray(def.nodes) ? def.nodes : void 0;
|
|
3808
|
+
const edges = Array.isArray(def.edges) ? def.edges : void 0;
|
|
3809
|
+
if (!nodes || nodes.length === 0) error("nodes", "a pipeline needs at least one node");
|
|
3810
|
+
if (!edges) error("edges", "`edges` must be an array");
|
|
3811
|
+
if (nodes && nodes.length > PIPELINE_LIMITS.maxNodes) {
|
|
3812
|
+
error("nodes", `more than ${PIPELINE_LIMITS.maxNodes} nodes`);
|
|
3813
|
+
}
|
|
3814
|
+
if (edges && edges.length > PIPELINE_LIMITS.maxEdges) {
|
|
3815
|
+
error("edges", `more than ${PIPELINE_LIMITS.maxEdges} edges`);
|
|
3816
|
+
}
|
|
3817
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3818
|
+
const routesOf = /* @__PURE__ */ new Map();
|
|
3819
|
+
for (const [index, node] of (nodes ?? []).entries()) {
|
|
3820
|
+
if (!isRecord(node) || !isId(node.id)) {
|
|
3821
|
+
error("node.id", `node #${index + 1} has no id`);
|
|
3822
|
+
continue;
|
|
3823
|
+
}
|
|
3824
|
+
const nodeId = node.id;
|
|
3825
|
+
if (ids.has(nodeId)) {
|
|
3826
|
+
error("node.duplicate", `duplicate node id "${nodeId}"`, { nodeId });
|
|
3827
|
+
continue;
|
|
3828
|
+
}
|
|
3829
|
+
ids.add(nodeId);
|
|
3830
|
+
if (node.join !== void 0 && node.join !== "all" && node.join !== "any") {
|
|
3831
|
+
error("node.join", `node "${nodeId}": join must be "all" or "any"`, { nodeId });
|
|
3832
|
+
}
|
|
3833
|
+
const labels = [];
|
|
3834
|
+
if (node.routes !== void 0) {
|
|
3835
|
+
if (!Array.isArray(node.routes) || node.routes.length > PIPELINE_LIMITS.maxRoutes) {
|
|
3836
|
+
error(
|
|
3837
|
+
"node.routes",
|
|
3838
|
+
`node "${nodeId}": routes must be a list of at most ${PIPELINE_LIMITS.maxRoutes}`,
|
|
3839
|
+
{ nodeId }
|
|
3840
|
+
);
|
|
3841
|
+
} else {
|
|
3842
|
+
for (const route of node.routes) {
|
|
3843
|
+
if (!isRecord(route) || !isId(route.label)) {
|
|
3844
|
+
error("node.routes", `node "${nodeId}": a route has no label`, { nodeId });
|
|
3845
|
+
} else if (labels.includes(route.label)) {
|
|
3846
|
+
error("node.routes", `node "${nodeId}": duplicate route "${route.label}"`, { nodeId });
|
|
3847
|
+
} else {
|
|
3848
|
+
labels.push(route.label);
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
routesOf.set(nodeId, labels);
|
|
3854
|
+
}
|
|
3855
|
+
if (!isId(def.entry)) {
|
|
3856
|
+
error("entry", "the pipeline has no entry node");
|
|
3857
|
+
} else if (!ids.has(def.entry)) {
|
|
3858
|
+
error("entry", `the entry node "${def.entry}" does not exist`);
|
|
3859
|
+
}
|
|
3860
|
+
const out = /* @__PURE__ */ new Map();
|
|
3861
|
+
const edgeIds = /* @__PURE__ */ new Set();
|
|
3862
|
+
const otherwise = /* @__PURE__ */ new Set();
|
|
3863
|
+
const routed = /* @__PURE__ */ new Set();
|
|
3864
|
+
for (const [index, edge] of (edges ?? []).entries()) {
|
|
3865
|
+
const at = edgeRef(edge, index);
|
|
3866
|
+
const label = `edge "${at.edgeId}"`;
|
|
3867
|
+
if (!isRecord(edge)) {
|
|
3868
|
+
error("edge", `${label} is not an object`, at);
|
|
3869
|
+
continue;
|
|
3870
|
+
}
|
|
3871
|
+
if (edge.id !== void 0 && !isId(edge.id)) error("edge.id", `${label} has an empty id`, at);
|
|
3872
|
+
if (edgeIds.has(at.edgeId)) error("edge.duplicate", `duplicate edge id "${at.edgeId}"`, at);
|
|
3873
|
+
edgeIds.add(at.edgeId);
|
|
3874
|
+
const from = edge.from;
|
|
3875
|
+
const to = edge.to;
|
|
3876
|
+
const fromOk = isId(from) && ids.has(from);
|
|
3877
|
+
const toOk = isId(to) && ids.has(to);
|
|
3878
|
+
if (!fromOk)
|
|
3879
|
+
error("edge.from", `${label} starts at an unknown node ${JSON.stringify(from)}`, at);
|
|
3880
|
+
if (!toOk) error("edge.to", `${label} leads to an unknown node ${JSON.stringify(to)}`, at);
|
|
3881
|
+
if (fromOk && toOk) out.set(from, [...out.get(from) ?? [], to]);
|
|
3882
|
+
const when = edge.when;
|
|
3883
|
+
if (when === void 0) continue;
|
|
3884
|
+
if (!isRecord(when) || !CONDITION_KINDS.includes(when.kind)) {
|
|
3885
|
+
error("edge.when", `${label} has an unknown condition`, at);
|
|
3886
|
+
continue;
|
|
3887
|
+
}
|
|
3888
|
+
switch (when.kind) {
|
|
3889
|
+
case "contains":
|
|
3890
|
+
if (typeof when.text !== "string" || when.text.length === 0) {
|
|
3891
|
+
error("edge.when", `${label}: "contains" needs a text`, at);
|
|
3892
|
+
}
|
|
3893
|
+
break;
|
|
3894
|
+
case "matches":
|
|
3895
|
+
try {
|
|
3896
|
+
compileMatcher(when.pattern, when.flags ?? "");
|
|
3897
|
+
} catch (err) {
|
|
3898
|
+
error("edge.pattern", `${label}: ${err.message}`, at);
|
|
3899
|
+
}
|
|
3900
|
+
break;
|
|
3901
|
+
case "route":
|
|
3902
|
+
if (fromOk) routed.add(from);
|
|
3903
|
+
if (!isId(when.label)) {
|
|
3904
|
+
error("edge.route", `${label}: "route" needs a label`, at);
|
|
3905
|
+
} else if (fromOk && !(routesOf.get(from) ?? []).includes(when.label)) {
|
|
3906
|
+
error(
|
|
3907
|
+
"edge.route",
|
|
3908
|
+
`${label}: node "${from}" has no route "${when.label}"`,
|
|
3909
|
+
fromOk ? { ...at, nodeId: from } : at
|
|
3910
|
+
);
|
|
3911
|
+
}
|
|
3912
|
+
break;
|
|
3913
|
+
case "otherwise":
|
|
3914
|
+
if (fromOk) {
|
|
3915
|
+
if (otherwise.has(from)) {
|
|
3916
|
+
error("edge.otherwise", `node "${from}" has more than one "otherwise" edge`, {
|
|
3917
|
+
...at,
|
|
3918
|
+
nodeId: from
|
|
3919
|
+
});
|
|
3920
|
+
}
|
|
3921
|
+
otherwise.add(from);
|
|
3922
|
+
}
|
|
3923
|
+
break;
|
|
3924
|
+
}
|
|
3925
|
+
}
|
|
3926
|
+
if (def.limits !== void 0) {
|
|
3927
|
+
if (!isRecord(def.limits)) {
|
|
3928
|
+
error("limits", "`limits` must be an object");
|
|
3929
|
+
} else {
|
|
3930
|
+
const { maxNodeVisits, maxRuns } = def.limits;
|
|
3931
|
+
if (maxNodeVisits !== void 0 && !inRange2(maxNodeVisits, PIPELINE_LIMITS.maxNodeVisitsCeiling)) {
|
|
3932
|
+
error(
|
|
3933
|
+
"limits",
|
|
3934
|
+
`limits.maxNodeVisits must be a whole number from 1 to ${PIPELINE_LIMITS.maxNodeVisitsCeiling}`
|
|
3935
|
+
);
|
|
3936
|
+
}
|
|
3937
|
+
if (maxRuns !== void 0 && !inRange2(maxRuns, PIPELINE_LIMITS.maxRunsCeiling)) {
|
|
3938
|
+
error(
|
|
3939
|
+
"limits",
|
|
3940
|
+
`limits.maxRuns must be a whole number from 1 to ${PIPELINE_LIMITS.maxRunsCeiling}`
|
|
3941
|
+
);
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
}
|
|
3945
|
+
if (errors.length > 0 || !isId(def.entry)) return done();
|
|
3946
|
+
const reached = /* @__PURE__ */ new Set([def.entry]);
|
|
3947
|
+
const queue = [def.entry];
|
|
3948
|
+
while (queue.length) {
|
|
3949
|
+
for (const to of out.get(queue.pop()) ?? []) {
|
|
3950
|
+
if (!reached.has(to)) {
|
|
3951
|
+
reached.add(to);
|
|
3952
|
+
queue.push(to);
|
|
3953
|
+
}
|
|
3954
|
+
}
|
|
3955
|
+
}
|
|
3956
|
+
for (const nodeId of ids) {
|
|
3957
|
+
if (!reached.has(nodeId)) {
|
|
3958
|
+
warnings.push({
|
|
3959
|
+
code: "unreachable",
|
|
3960
|
+
message: `node "${nodeId}" cannot be reached from the entry node`,
|
|
3961
|
+
nodeId
|
|
3962
|
+
});
|
|
3963
|
+
}
|
|
3964
|
+
if ((routesOf.get(nodeId) ?? []).length > 0 && !routed.has(nodeId)) {
|
|
3965
|
+
warnings.push({
|
|
3966
|
+
code: "routes.unused",
|
|
3967
|
+
message: `node "${nodeId}" has routes but no edge with a "route" condition`,
|
|
3968
|
+
nodeId
|
|
3969
|
+
});
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
const state = /* @__PURE__ */ new Map();
|
|
3973
|
+
const path = [];
|
|
3974
|
+
const findCycle = (nodeId) => {
|
|
3975
|
+
state.set(nodeId, "open");
|
|
3976
|
+
path.push(nodeId);
|
|
3977
|
+
for (const to of out.get(nodeId) ?? []) {
|
|
3978
|
+
if (state.get(to) === "open") return [...path.slice(path.indexOf(to)), to];
|
|
3979
|
+
if (!state.has(to)) {
|
|
3980
|
+
const found = findCycle(to);
|
|
3981
|
+
if (found) return found;
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
path.pop();
|
|
3985
|
+
state.set(nodeId, "closed");
|
|
3986
|
+
return void 0;
|
|
3987
|
+
};
|
|
3988
|
+
const cycle = findCycle(def.entry);
|
|
3989
|
+
if (cycle) {
|
|
3990
|
+
warnings.push({
|
|
3991
|
+
code: "cycle",
|
|
3992
|
+
message: `the pipeline has a loop (${cycle.join(" \u2192 ")}); limits.maxNodeVisits and limits.maxRuns bound it`,
|
|
3993
|
+
nodeId: cycle[0]
|
|
3994
|
+
});
|
|
3995
|
+
}
|
|
3996
|
+
return done();
|
|
3997
|
+
};
|
|
3998
|
+
var titleOf = (source) => source.name || source.nodeId;
|
|
3999
|
+
var renderPipelineNodeInput = (input) => {
|
|
4000
|
+
if (input.from.length === 0 && input.visit <= 1) return input.request;
|
|
4001
|
+
const parts = [`Request:
|
|
4002
|
+
${input.request}`];
|
|
4003
|
+
for (const source of input.from) {
|
|
4004
|
+
parts.push(`Output of "${titleOf(source)}":
|
|
4005
|
+
${source.text}`);
|
|
4006
|
+
}
|
|
4007
|
+
if (input.visit > 1) parts.push(`(This is visit ${input.visit} of this step.)`);
|
|
4008
|
+
return parts.join("\n\n");
|
|
4009
|
+
};
|
|
4010
|
+
var PIPELINE_ROUTER_SYSTEM = "You are the Router of one step in a pipeline of agents. The step has answered. Pick the ONE route label that fits its answer, from the list you are given. Answer with a label exactly as it is written in the list, and nothing else.";
|
|
4011
|
+
var ROUTER_HEAD_CHARS = 2e3;
|
|
4012
|
+
var ROUTER_TAIL_CHARS = 6e3;
|
|
4013
|
+
var renderPipelineRoutePrompt = (node, text) => {
|
|
4014
|
+
const routes = (node.routes ?? []).map((r) => `- ${r.label}${r.description ? `: ${r.description}` : ""}`).join("\n");
|
|
4015
|
+
const answer = text.length > ROUTER_HEAD_CHARS + ROUTER_TAIL_CHARS ? `${text.slice(0, ROUTER_HEAD_CHARS)}
|
|
4016
|
+
[...]
|
|
4017
|
+
${text.slice(-ROUTER_TAIL_CHARS)}` : text;
|
|
4018
|
+
return [
|
|
4019
|
+
`Step: ${titleOf({ nodeId: node.id, name: node.name })}`,
|
|
4020
|
+
node.instructions ? `Its role:
|
|
4021
|
+
${node.instructions}` : "",
|
|
4022
|
+
`Routes:
|
|
4023
|
+
${routes}`,
|
|
4024
|
+
`The step's answer:
|
|
4025
|
+
${answer}`,
|
|
4026
|
+
"Which route? Answer with one label from the list."
|
|
4027
|
+
].filter(Boolean).join("\n\n");
|
|
4028
|
+
};
|
|
4029
|
+
var matchPipelineRoute = (node, answer) => {
|
|
4030
|
+
const labels = (node.routes ?? []).map((r) => r.label);
|
|
4031
|
+
let value = answer;
|
|
4032
|
+
if (typeof value === "string") {
|
|
4033
|
+
const text = value.trim();
|
|
4034
|
+
if (text.startsWith("{")) {
|
|
4035
|
+
try {
|
|
4036
|
+
value = JSON.parse(text);
|
|
4037
|
+
} catch {
|
|
4038
|
+
value = text;
|
|
4039
|
+
}
|
|
4040
|
+
} else {
|
|
4041
|
+
value = text;
|
|
4042
|
+
}
|
|
4043
|
+
}
|
|
4044
|
+
if (isRecord(value)) value = value.route;
|
|
4045
|
+
if (typeof value !== "string") return void 0;
|
|
4046
|
+
const wanted = value.trim().replace(/^["'`]+|["'`.]+$/g, "").toLowerCase();
|
|
4047
|
+
return labels.find((label) => label.toLowerCase() === wanted);
|
|
4048
|
+
};
|
|
4049
|
+
var preparePipeline = (definition) => {
|
|
4050
|
+
const { errors } = validatePipeline(definition);
|
|
4051
|
+
if (errors.length > 0) throw new PipelineValidationError(errors);
|
|
4052
|
+
const def = normalizePipeline(definition);
|
|
4053
|
+
const nodes = new Map(def.nodes.map((n) => [n.id, n]));
|
|
4054
|
+
const outgoing = new Map(def.nodes.map((n) => [n.id, []]));
|
|
4055
|
+
for (const edge of def.edges) {
|
|
4056
|
+
const planned = { edge };
|
|
4057
|
+
if (edge.when?.kind === "matches") {
|
|
4058
|
+
planned.matcher = compileMatcher(edge.when.pattern, edge.when.flags);
|
|
4059
|
+
}
|
|
4060
|
+
outgoing.get(edge.from)?.push(planned);
|
|
4061
|
+
}
|
|
4062
|
+
const closure = /* @__PURE__ */ new Map();
|
|
4063
|
+
const descendants = (from) => {
|
|
4064
|
+
let seen = closure.get(from);
|
|
4065
|
+
if (!seen) {
|
|
4066
|
+
seen = /* @__PURE__ */ new Set();
|
|
4067
|
+
const queue = [from];
|
|
4068
|
+
while (queue.length) {
|
|
4069
|
+
for (const { edge } of outgoing.get(queue.pop()) ?? []) {
|
|
4070
|
+
if (!seen.has(edge.to)) {
|
|
4071
|
+
seen.add(edge.to);
|
|
4072
|
+
queue.push(edge.to);
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
}
|
|
4076
|
+
closure.set(from, seen);
|
|
4077
|
+
}
|
|
4078
|
+
return seen;
|
|
4079
|
+
};
|
|
4080
|
+
return {
|
|
4081
|
+
definition: def,
|
|
4082
|
+
nodes,
|
|
4083
|
+
outgoing,
|
|
4084
|
+
maxNodeVisits: def.limits?.maxNodeVisits ?? PIPELINE_LIMITS.maxNodeVisits,
|
|
4085
|
+
maxRuns: def.limits?.maxRuns ?? PIPELINE_LIMITS.maxRuns,
|
|
4086
|
+
reaches: (from, to) => descendants(from).has(to)
|
|
4087
|
+
};
|
|
4088
|
+
};
|
|
4089
|
+
var abortError = () => new DOMException("Aborted", "AbortError");
|
|
4090
|
+
var addUsage2 = (into, usage) => {
|
|
4091
|
+
if (!usage) return;
|
|
4092
|
+
const sum = into;
|
|
4093
|
+
for (const [key, value] of Object.entries(usage)) {
|
|
4094
|
+
if (typeof value === "number" && Number.isFinite(value)) sum[key] = (sum[key] ?? 0) + value;
|
|
4095
|
+
}
|
|
4096
|
+
};
|
|
4097
|
+
var runPipelineGraph = async (plan, runNode, options, onAbort) => {
|
|
4098
|
+
const { definition } = plan;
|
|
4099
|
+
const controller = new AbortController();
|
|
4100
|
+
let halted;
|
|
4101
|
+
let halt = () => {
|
|
4102
|
+
};
|
|
4103
|
+
const haltPromise = new Promise((_, reject) => {
|
|
4104
|
+
halt = reject;
|
|
4105
|
+
});
|
|
4106
|
+
haltPromise.catch(() => {
|
|
4107
|
+
});
|
|
4108
|
+
const emit = (event) => {
|
|
4109
|
+
try {
|
|
4110
|
+
options.onEvent?.(event);
|
|
4111
|
+
} catch {
|
|
4112
|
+
}
|
|
4113
|
+
};
|
|
4114
|
+
const visits = /* @__PURE__ */ new Map();
|
|
4115
|
+
const usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
4116
|
+
const outputs = {};
|
|
4117
|
+
const trace = [];
|
|
4118
|
+
const terminals = [];
|
|
4119
|
+
const capped = /* @__PURE__ */ new Set();
|
|
4120
|
+
let runs = 0;
|
|
4121
|
+
let wave = 0;
|
|
4122
|
+
const pending = /* @__PURE__ */ new Map([[definition.entry, []]]);
|
|
4123
|
+
const result = (stoppedBy2) => {
|
|
4124
|
+
const lastWave = Math.max(-1, ...terminals.map((t) => t.wave));
|
|
4125
|
+
const last = terminals.filter((t) => t.wave === lastWave);
|
|
4126
|
+
const text = last.length === 1 ? last[0].text : last.map((t) => `## ${titleOf(t)}
|
|
4127
|
+
|
|
4128
|
+
${t.text}`).join("\n\n");
|
|
4129
|
+
return { text, outputs, trace, usage, ...stoppedBy2 ? { stoppedBy: stoppedBy2 } : {}, runs };
|
|
4130
|
+
};
|
|
4131
|
+
const onOuterAbort = () => {
|
|
4132
|
+
if (halted) return;
|
|
4133
|
+
halted = "aborted";
|
|
4134
|
+
controller.abort();
|
|
4135
|
+
halt(abortError());
|
|
4136
|
+
};
|
|
4137
|
+
const visit = async (nodeId, activations) => {
|
|
4138
|
+
const node = plan.nodes.get(nodeId);
|
|
4139
|
+
const number = (visits.get(nodeId) ?? 0) + 1;
|
|
4140
|
+
visits.set(nodeId, number);
|
|
4141
|
+
runs++;
|
|
4142
|
+
const from = activations.map((a) => a.source.nodeId);
|
|
4143
|
+
emit({ type: "pipeline.node.started", nodeId, visit: number, from });
|
|
4144
|
+
let output;
|
|
4145
|
+
try {
|
|
4146
|
+
output = await runNode(
|
|
4147
|
+
node,
|
|
4148
|
+
{ request: options.input, from: activations.map((a) => ({ ...a.source })), visit: number },
|
|
4149
|
+
{
|
|
4150
|
+
signal: controller.signal,
|
|
4151
|
+
pipeline: definition,
|
|
4152
|
+
emit: (event) => {
|
|
4153
|
+
if (!halted) emit({ ...event, nodeId, visit: number });
|
|
4154
|
+
}
|
|
4155
|
+
}
|
|
4156
|
+
);
|
|
4157
|
+
} catch (err) {
|
|
4158
|
+
if (halted) return;
|
|
4159
|
+
halted = "failed";
|
|
4160
|
+
const failure = new PipelineNodeError(nodeId, number, err);
|
|
4161
|
+
emit({
|
|
4162
|
+
type: "pipeline.node.failed",
|
|
4163
|
+
nodeId,
|
|
4164
|
+
visit: number,
|
|
4165
|
+
error: err instanceof Error ? err.message : String(err)
|
|
4166
|
+
});
|
|
4167
|
+
controller.abort();
|
|
4168
|
+
halt(failure);
|
|
4169
|
+
return;
|
|
4170
|
+
}
|
|
4171
|
+
if (halted) return;
|
|
4172
|
+
const text = typeof output?.text === "string" ? output.text : "";
|
|
4173
|
+
const route = (node.routes ?? []).some((r) => r.label === output?.route) ? output.route : void 0;
|
|
4174
|
+
addUsage2(usage, output?.usage);
|
|
4175
|
+
const optional = {
|
|
4176
|
+
...route !== void 0 ? { route } : {},
|
|
4177
|
+
...output?.usage ? { usage: output.usage } : {}
|
|
4178
|
+
};
|
|
4179
|
+
(outputs[nodeId] ??= []).push({
|
|
4180
|
+
visit: number,
|
|
4181
|
+
text,
|
|
4182
|
+
...route !== void 0 ? { route } : {}
|
|
4183
|
+
});
|
|
4184
|
+
trace.push({ type: "node", nodeId, visit: number, wave, from, text, ...optional });
|
|
4185
|
+
emit({ type: "pipeline.node.finished", nodeId, visit: number, text, ...optional });
|
|
4186
|
+
const edges = plan.outgoing.get(nodeId) ?? [];
|
|
4187
|
+
const fired = edges.map(
|
|
4188
|
+
({ edge, matcher }) => testPipelineCondition(edge.when, { text, route }, matcher)
|
|
4189
|
+
);
|
|
4190
|
+
const anyFired = fired.some(Boolean);
|
|
4191
|
+
const record = { nodeId, name: node.name, text, wave, live: 0 };
|
|
4192
|
+
const targets = /* @__PURE__ */ new Set();
|
|
4193
|
+
edges.forEach(({ edge }, index) => {
|
|
4194
|
+
const fires = edge.when?.kind === "otherwise" ? !anyFired : fired[index];
|
|
4195
|
+
const decision = {
|
|
4196
|
+
from: nodeId,
|
|
4197
|
+
to: edge.to,
|
|
4198
|
+
edgeId: edge.id,
|
|
4199
|
+
visit: number,
|
|
4200
|
+
fired: fires
|
|
4201
|
+
};
|
|
4202
|
+
trace.push({ type: "edge", ...decision });
|
|
4203
|
+
emit({ type: "pipeline.edge", ...decision });
|
|
4204
|
+
if (!fires || targets.has(edge.to)) return;
|
|
4205
|
+
targets.add(edge.to);
|
|
4206
|
+
const waiting = pending.get(edge.to) ?? [];
|
|
4207
|
+
waiting.push({ source: { nodeId, ...node.name ? { name: node.name } : {}, text }, record });
|
|
4208
|
+
pending.set(edge.to, waiting);
|
|
4209
|
+
});
|
|
4210
|
+
record.live = targets.size;
|
|
4211
|
+
if (record.live === 0) terminals.push(record);
|
|
4212
|
+
};
|
|
4213
|
+
const drop = (nodeId, activations, reason) => {
|
|
4214
|
+
capped.add(reason);
|
|
4215
|
+
const from = activations.map((a) => a.source.nodeId);
|
|
4216
|
+
trace.push({ type: "dropped", nodeId, from, reason });
|
|
4217
|
+
emit({ type: "pipeline.node.skipped", nodeId, from, reason });
|
|
4218
|
+
for (const { record } of activations) {
|
|
4219
|
+
record.live--;
|
|
4220
|
+
if (record.live === 0) terminals.push(record);
|
|
4221
|
+
}
|
|
4222
|
+
};
|
|
4223
|
+
const deferred = (nodeId, all) => (plan.nodes.get(nodeId)?.join ?? "all") === "all" && all.some((other) => other !== nodeId && plan.reaches(other, nodeId));
|
|
4224
|
+
emit({ type: "pipeline.started", ...definition.name ? { pipeline: definition.name } : {} });
|
|
4225
|
+
options.signal?.addEventListener("abort", onOuterAbort, { once: true });
|
|
4226
|
+
try {
|
|
4227
|
+
if (options.signal?.aborted) onOuterAbort();
|
|
4228
|
+
while (pending.size > 0 && !halted) {
|
|
4229
|
+
const waiting = [...pending.keys()];
|
|
4230
|
+
let ready = waiting.filter((nodeId) => !deferred(nodeId, waiting));
|
|
4231
|
+
if (ready.length === 0) ready = waiting;
|
|
4232
|
+
const starting = [];
|
|
4233
|
+
for (const nodeId of ready) {
|
|
4234
|
+
const activations = pending.get(nodeId);
|
|
4235
|
+
pending.delete(nodeId);
|
|
4236
|
+
if ((visits.get(nodeId) ?? 0) >= plan.maxNodeVisits) {
|
|
4237
|
+
drop(nodeId, activations, "maxNodeVisits");
|
|
4238
|
+
} else if (runs >= plan.maxRuns) {
|
|
4239
|
+
drop(nodeId, activations, "maxRuns");
|
|
4240
|
+
} else {
|
|
4241
|
+
starting.push(visit(nodeId, activations));
|
|
4242
|
+
}
|
|
4243
|
+
}
|
|
4244
|
+
if (starting.length === 0) continue;
|
|
4245
|
+
await Promise.race([Promise.all(starting), haltPromise]);
|
|
4246
|
+
wave++;
|
|
4247
|
+
}
|
|
4248
|
+
if (halted) await haltPromise;
|
|
4249
|
+
} catch (err) {
|
|
4250
|
+
if (halted !== "aborted") throw err;
|
|
4251
|
+
emit({ type: "pipeline.finished", stoppedBy: "aborted", runs });
|
|
4252
|
+
if (onAbort === "reject") throw err;
|
|
4253
|
+
return result("aborted");
|
|
4254
|
+
} finally {
|
|
4255
|
+
options.signal?.removeEventListener("abort", onOuterAbort);
|
|
4256
|
+
}
|
|
4257
|
+
const stoppedBy = capped.has("maxRuns") ? "maxRuns" : capped.has("maxNodeVisits") ? "maxNodeVisits" : void 0;
|
|
4258
|
+
emit({ type: "pipeline.finished", ...stoppedBy ? { stoppedBy } : {}, runs });
|
|
4259
|
+
return result(stoppedBy);
|
|
4260
|
+
};
|
|
4261
|
+
|
|
4262
|
+
// src/pipeline/index.ts
|
|
4263
|
+
var aborted = () => new DOMException("Aborted", "AbortError");
|
|
4264
|
+
var pickRoute = async ({ agent, config }, node, text, signal) => {
|
|
4265
|
+
const cfg = resolveConfig(config);
|
|
4266
|
+
const labels = (node.routes ?? []).map((r) => r.label);
|
|
4267
|
+
const call = {
|
|
4268
|
+
system: PIPELINE_ROUTER_SYSTEM,
|
|
4269
|
+
prompt: renderPipelineRoutePrompt(node, text),
|
|
4270
|
+
maxOutputTokens: cfg.budgets.replanner,
|
|
4271
|
+
temperature: cfg.temperature,
|
|
4272
|
+
abortSignal: signal,
|
|
4273
|
+
timeoutMs: cfg.chatTimeoutMs
|
|
4274
|
+
};
|
|
4275
|
+
let wasted = normalizeUsage();
|
|
4276
|
+
try {
|
|
4277
|
+
const schema = z4.object({
|
|
4278
|
+
route: z4.enum(labels).describe("The label of the chosen route")
|
|
4279
|
+
});
|
|
4280
|
+
const r = await generateStructured(agent.models.planner, schema, call);
|
|
4281
|
+
return { route: matchPipelineRoute(node, r.object), usage: normalizeUsage(r.usage) };
|
|
4282
|
+
} catch (err) {
|
|
4283
|
+
if (signal.aborted) throw aborted();
|
|
4284
|
+
wasted = usageOfError(err);
|
|
4285
|
+
}
|
|
4286
|
+
try {
|
|
4287
|
+
const r = await generate(agent.models.planner, call);
|
|
4288
|
+
return {
|
|
4289
|
+
route: matchPipelineRoute(node, r.text),
|
|
4290
|
+
usage: addUsage(wasted, normalizeUsage(r.usage))
|
|
4291
|
+
};
|
|
4292
|
+
} catch {
|
|
4293
|
+
if (signal.aborted) throw aborted();
|
|
4294
|
+
return { usage: wasted };
|
|
4295
|
+
}
|
|
4296
|
+
};
|
|
4297
|
+
var createPipeline = (definition, options) => {
|
|
4298
|
+
const plan = preparePipeline(definition);
|
|
4299
|
+
const { resolveNode } = options;
|
|
4300
|
+
if (!options.runNode && !resolveNode) {
|
|
4301
|
+
throw new Error("createPipeline needs `resolveNode` (or `runNode`)");
|
|
4302
|
+
}
|
|
4303
|
+
const agents = /* @__PURE__ */ new Map();
|
|
4304
|
+
const agentOf = (node) => {
|
|
4305
|
+
let entry = agents.get(node.id);
|
|
4306
|
+
if (!entry) {
|
|
4307
|
+
entry = (async () => {
|
|
4308
|
+
const resolved = await resolveNode(node);
|
|
4309
|
+
const systemPrompt = [resolved.systemPrompt, node.instructions].filter(Boolean).join("\n\n");
|
|
4310
|
+
const config = { ...resolved, ...systemPrompt ? { systemPrompt } : {} };
|
|
4311
|
+
return { agent: await createAgent(config), config };
|
|
4312
|
+
})();
|
|
4313
|
+
agents.set(node.id, entry);
|
|
4314
|
+
entry.catch(() => agents.delete(node.id));
|
|
4315
|
+
}
|
|
4316
|
+
return entry;
|
|
4317
|
+
};
|
|
4318
|
+
const runWithAgent = async (node, input, ctx) => {
|
|
4319
|
+
const entry = await agentOf(node);
|
|
4320
|
+
let failure;
|
|
4321
|
+
const result = await entry.agent.run(renderPipelineNodeInput(input), {
|
|
4322
|
+
signal: ctx.signal,
|
|
4323
|
+
onEvent: (event) => {
|
|
4324
|
+
if (event.type === "error" && event.phase === "run") failure = event.error;
|
|
4325
|
+
ctx.emit(event);
|
|
4326
|
+
}
|
|
4327
|
+
});
|
|
4328
|
+
if (result.stopped || ctx.signal.aborted) throw aborted();
|
|
4329
|
+
if (failure !== void 0) throw new Error(failure);
|
|
4330
|
+
if (!node.routes?.length) return { text: result.final, usage: result.usage };
|
|
4331
|
+
const picked = await pickRoute(entry, node, result.final, ctx.signal);
|
|
4332
|
+
return {
|
|
4333
|
+
text: result.final,
|
|
4334
|
+
usage: addUsage(result.usage, picked.usage),
|
|
4335
|
+
...picked.route ? { route: picked.route } : {}
|
|
4336
|
+
};
|
|
4337
|
+
};
|
|
4338
|
+
return {
|
|
4339
|
+
definition: plan.definition,
|
|
4340
|
+
run: (run) => runPipelineGraph(
|
|
4341
|
+
plan,
|
|
4342
|
+
options.runNode ?? runWithAgent,
|
|
4343
|
+
{ input: run.input, signal: run.signal, onEvent: run.onEvent },
|
|
4344
|
+
"resolve"
|
|
4345
|
+
),
|
|
4346
|
+
close: async () => {
|
|
4347
|
+
agents.clear();
|
|
4348
|
+
}
|
|
4349
|
+
};
|
|
4350
|
+
};
|
|
4351
|
+
var lookup = (node, kind, registry, key) => {
|
|
4352
|
+
if (!registry || !Object.prototype.hasOwnProperty.call(registry, key)) {
|
|
4353
|
+
const known = Object.keys(registry ?? {});
|
|
4354
|
+
throw new Error(
|
|
4355
|
+
`Pipeline node "${node.id}": unknown ${kind} "${key}" (registered: ${known.length ? known.join(", ") : "none"})`
|
|
4356
|
+
);
|
|
4357
|
+
}
|
|
4358
|
+
return registry[key];
|
|
4359
|
+
};
|
|
4360
|
+
var nodeResolver = (options) => async (node) => {
|
|
4361
|
+
let config = { ...options.base };
|
|
4362
|
+
if (node.model !== void 0) {
|
|
4363
|
+
const { planner, synthesizer, ...rest } = config;
|
|
4364
|
+
void [planner, synthesizer];
|
|
4365
|
+
config = { ...rest, model: lookup(node, "model", options.models, node.model) };
|
|
4366
|
+
}
|
|
4367
|
+
if (node.skills?.length) {
|
|
4368
|
+
const named = node.skills.map((key) => lookup(node, "skill", options.skills, key));
|
|
4369
|
+
const names = new Set(named.map((s) => s.name));
|
|
4370
|
+
config.skills = [...(config.skills ?? []).filter((s) => !names.has(s.name)), ...named];
|
|
4371
|
+
}
|
|
4372
|
+
const groups = [
|
|
4373
|
+
...(node.tools ?? []).map((key) => lookup(node, "tool group", options.tools, key)),
|
|
4374
|
+
...(node.mcpServers ?? []).map(
|
|
4375
|
+
(key) => lookup(node, "MCP server", options.mcpServers, key).tools
|
|
4376
|
+
)
|
|
4377
|
+
];
|
|
4378
|
+
if (groups.length) config.tools = Object.assign({ ...config.tools }, ...groups);
|
|
4379
|
+
if (config.memory) config.sessionId = `${config.sessionId ?? "default"}:${node.id}`;
|
|
4380
|
+
return options.configure ? options.configure(config, node) : config;
|
|
4381
|
+
};
|
|
4382
|
+
|
|
3569
4383
|
// src/subagent/tool.ts
|
|
3570
|
-
import { asSchema
|
|
4384
|
+
import { asSchema, jsonSchema as jsonSchema3, tool as tool4 } from "ai";
|
|
3571
4385
|
|
|
3572
4386
|
// src/subagent/protocol.ts
|
|
3573
4387
|
var toCloneable = (value) => {
|
|
@@ -3588,7 +4402,7 @@ var safePost = (target, message) => {
|
|
|
3588
4402
|
};
|
|
3589
4403
|
|
|
3590
4404
|
// src/subagent/tool.ts
|
|
3591
|
-
var
|
|
4405
|
+
var abortError2 = () => {
|
|
3592
4406
|
const e = new Error("The subagent was aborted");
|
|
3593
4407
|
e.name = "AbortError";
|
|
3594
4408
|
return e;
|
|
@@ -3606,7 +4420,7 @@ var createSemaphore = (size) => {
|
|
|
3606
4420
|
const onAbort = () => {
|
|
3607
4421
|
const i = queue.indexOf(go);
|
|
3608
4422
|
if (i >= 0) queue.splice(i, 1);
|
|
3609
|
-
reject(
|
|
4423
|
+
reject(abortError2());
|
|
3610
4424
|
};
|
|
3611
4425
|
queue.push(go);
|
|
3612
4426
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -3622,7 +4436,7 @@ var createSemaphore = (size) => {
|
|
|
3622
4436
|
};
|
|
3623
4437
|
};
|
|
3624
4438
|
};
|
|
3625
|
-
var
|
|
4439
|
+
var seq = 0;
|
|
3626
4440
|
var createSubagentTool = (opts) => {
|
|
3627
4441
|
if (!opts.config === !opts.worker) {
|
|
3628
4442
|
throw new Error(
|
|
@@ -3690,7 +4504,7 @@ var createSubagentTool = (opts) => {
|
|
|
3690
4504
|
forward(e);
|
|
3691
4505
|
}
|
|
3692
4506
|
});
|
|
3693
|
-
if (result.stopped) throw
|
|
4507
|
+
if (result.stopped) throw abortError2();
|
|
3694
4508
|
if (runError) throw new Error(runError);
|
|
3695
4509
|
return { text: result.final, usage: result.usage };
|
|
3696
4510
|
};
|
|
@@ -3698,7 +4512,7 @@ var createSubagentTool = (opts) => {
|
|
|
3698
4512
|
Object.entries(opts.tools ?? {}).map(async ([name, t2]) => ({
|
|
3699
4513
|
name,
|
|
3700
4514
|
description: typeof t2.description === "string" ? t2.description : "",
|
|
3701
|
-
inputSchema: toCloneable(await
|
|
4515
|
+
inputSchema: toCloneable(await asSchema(t2.inputSchema).jsonSchema),
|
|
3702
4516
|
readOnly: isReadOnlyTool(t2)
|
|
3703
4517
|
}))
|
|
3704
4518
|
);
|
|
@@ -3714,9 +4528,9 @@ var createSubagentTool = (opts) => {
|
|
|
3714
4528
|
return toCloneable({ ...cfg, model });
|
|
3715
4529
|
};
|
|
3716
4530
|
const runInWorker = async (task, signal, forward, hostTools, profile) => {
|
|
3717
|
-
if (signal?.aborted) throw
|
|
4531
|
+
if (signal?.aborted) throw abortError2();
|
|
3718
4532
|
const [config, proxied] = await Promise.all([workerConfigFor(profile), proxiedSpecs()]);
|
|
3719
|
-
if (signal?.aborted) throw
|
|
4533
|
+
if (signal?.aborted) throw abortError2();
|
|
3720
4534
|
const worker = opts.worker();
|
|
3721
4535
|
return new Promise((resolve, reject) => {
|
|
3722
4536
|
let settled = false;
|
|
@@ -3731,7 +4545,7 @@ var createSubagentTool = (opts) => {
|
|
|
3731
4545
|
};
|
|
3732
4546
|
const onAbort = () => {
|
|
3733
4547
|
safePost(worker, { type: "abort" });
|
|
3734
|
-
finish(() => reject(
|
|
4548
|
+
finish(() => reject(abortError2()));
|
|
3735
4549
|
};
|
|
3736
4550
|
const onError = (ev) => finish(() => reject(new Error(`subagent worker failed: ${ev?.message ?? "unknown error"}`)));
|
|
3737
4551
|
const callHostTool = async (callId, name, input) => {
|
|
@@ -3800,7 +4614,7 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
|
|
|
3800
4614
|
const profile = pickProfile(profileName);
|
|
3801
4615
|
const runCtx = toolRunContextOf(options);
|
|
3802
4616
|
const parentSignal = options?.abortSignal ?? runCtx?.signal;
|
|
3803
|
-
const id = `${opts.name}-${
|
|
4617
|
+
const id = `${opts.name}-${seq += 1}`;
|
|
3804
4618
|
const release = await acquire(parentSignal);
|
|
3805
4619
|
const emit = (e) => runCtx?.emit(e);
|
|
3806
4620
|
const controller = new AbortController();
|
|
@@ -4004,230 +4818,6 @@ var serveSubagentWorker = (opts = {}) => {
|
|
|
4004
4818
|
});
|
|
4005
4819
|
};
|
|
4006
4820
|
|
|
4007
|
-
// src/files/vfs.ts
|
|
4008
|
-
var MIME = {
|
|
4009
|
-
txt: "text/plain",
|
|
4010
|
-
md: "text/markdown",
|
|
4011
|
-
json: "application/json",
|
|
4012
|
-
csv: "text/csv",
|
|
4013
|
-
html: "text/html",
|
|
4014
|
-
css: "text/css",
|
|
4015
|
-
js: "text/javascript",
|
|
4016
|
-
ts: "text/typescript",
|
|
4017
|
-
svg: "image/svg+xml",
|
|
4018
|
-
png: "image/png",
|
|
4019
|
-
jpg: "image/jpeg",
|
|
4020
|
-
jpeg: "image/jpeg",
|
|
4021
|
-
gif: "image/gif",
|
|
4022
|
-
webp: "image/webp",
|
|
4023
|
-
pdf: "application/pdf",
|
|
4024
|
-
xml: "application/xml",
|
|
4025
|
-
yaml: "text/yaml",
|
|
4026
|
-
yml: "text/yaml"
|
|
4027
|
-
};
|
|
4028
|
-
var mimeFromPath = (path) => MIME[path.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
|
|
4029
|
-
var isTextMime = (mime) => /^text\/|json|xml|yaml|javascript|typescript|svg/.test(mime);
|
|
4030
|
-
var normalizePath = (input) => {
|
|
4031
|
-
const parts = [];
|
|
4032
|
-
for (const seg of String(input ?? "").replace(/\\/g, "/").split("/")) {
|
|
4033
|
-
if (!seg || seg === ".") continue;
|
|
4034
|
-
if (seg === "..") {
|
|
4035
|
-
if (parts.length === 0) throw new Error(`path "${input}" escapes the root`);
|
|
4036
|
-
parts.pop();
|
|
4037
|
-
continue;
|
|
4038
|
-
}
|
|
4039
|
-
parts.push(seg);
|
|
4040
|
-
}
|
|
4041
|
-
if (parts.length === 0) throw new Error("a file path is required");
|
|
4042
|
-
return `/${parts.join("/")}`;
|
|
4043
|
-
};
|
|
4044
|
-
var byteLength = (content, encoding) => encoding === "base64" ? Math.floor(content.replace(/=+$/, "").length * 3 / 4) : new TextEncoder().encode(content).length;
|
|
4045
|
-
var bytesToBase64 = (bytes) => {
|
|
4046
|
-
let bin = "";
|
|
4047
|
-
for (let i = 0; i < bytes.length; i += 32768) {
|
|
4048
|
-
bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
4049
|
-
}
|
|
4050
|
-
return btoa(bin);
|
|
4051
|
-
};
|
|
4052
|
-
var VirtualFileSystem = class {
|
|
4053
|
-
memory;
|
|
4054
|
-
dbName;
|
|
4055
|
-
ns;
|
|
4056
|
-
maxFileBytes;
|
|
4057
|
-
listeners = /* @__PURE__ */ new Set();
|
|
4058
|
-
constructor(opts = {}) {
|
|
4059
|
-
if (opts.memory) this.memory = /* @__PURE__ */ new Map();
|
|
4060
|
-
this.dbName = opts.dbName;
|
|
4061
|
-
this.ns = opts.namespace ?? "default";
|
|
4062
|
-
this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024;
|
|
4063
|
-
}
|
|
4064
|
-
key(path) {
|
|
4065
|
-
return `${this.ns}:${path}`;
|
|
4066
|
-
}
|
|
4067
|
-
/** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
|
|
4068
|
-
onChange(listener) {
|
|
4069
|
-
this.listeners.add(listener);
|
|
4070
|
-
return () => this.listeners.delete(listener);
|
|
4071
|
-
}
|
|
4072
|
-
notify(type, path) {
|
|
4073
|
-
for (const l of this.listeners) {
|
|
4074
|
-
try {
|
|
4075
|
-
l({ type, path });
|
|
4076
|
-
} catch {
|
|
4077
|
-
}
|
|
4078
|
-
}
|
|
4079
|
-
}
|
|
4080
|
-
async write(path, content, opts = {}) {
|
|
4081
|
-
const p = normalizePath(path);
|
|
4082
|
-
const binary = content instanceof Uint8Array;
|
|
4083
|
-
const encoding = binary ? "base64" : opts.encoding ?? "utf8";
|
|
4084
|
-
const text = binary ? bytesToBase64(content) : content;
|
|
4085
|
-
const size = binary ? content.length : byteLength(text, encoding);
|
|
4086
|
-
if (size > this.maxFileBytes) {
|
|
4087
|
-
throw new Error(`"${p}" is ${size} bytes; the limit is ${this.maxFileBytes}`);
|
|
4088
|
-
}
|
|
4089
|
-
const file = {
|
|
4090
|
-
path: p,
|
|
4091
|
-
content: text,
|
|
4092
|
-
encoding,
|
|
4093
|
-
mimeType: opts.mimeType ?? mimeFromPath(p),
|
|
4094
|
-
size,
|
|
4095
|
-
updatedAt: Date.now()
|
|
4096
|
-
};
|
|
4097
|
-
if (this.memory) this.memory.set(p, file);
|
|
4098
|
-
else {
|
|
4099
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4100
|
-
await db.put(FILES_STORE, file, this.key(p));
|
|
4101
|
-
}
|
|
4102
|
-
this.notify("write", p);
|
|
4103
|
-
const { content: _drop, ...info } = file;
|
|
4104
|
-
return info;
|
|
4105
|
-
}
|
|
4106
|
-
/** Store a data URL ("data:image/png;base64,…") as a file. */
|
|
4107
|
-
async writeDataUrl(path, dataUrl) {
|
|
4108
|
-
const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(dataUrl);
|
|
4109
|
-
if (!m) throw new Error("not a data URL");
|
|
4110
|
-
const mimeType = m[1] ?? "application/octet-stream";
|
|
4111
|
-
return m[2] ? this.write(path, m[3], { mimeType, encoding: "base64" }) : this.write(path, decodeURIComponent(m[3]), { mimeType });
|
|
4112
|
-
}
|
|
4113
|
-
async read(path) {
|
|
4114
|
-
const p = normalizePath(path);
|
|
4115
|
-
if (this.memory) return this.memory.get(p);
|
|
4116
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4117
|
-
return await db.get(FILES_STORE, this.key(p));
|
|
4118
|
-
}
|
|
4119
|
-
/** The file as a data URL (for <img src>, downloads). */
|
|
4120
|
-
async readDataUrl(path) {
|
|
4121
|
-
const f = await this.read(path);
|
|
4122
|
-
if (!f) return void 0;
|
|
4123
|
-
return f.encoding === "base64" ? `data:${f.mimeType};base64,${f.content}` : `data:${f.mimeType};charset=utf-8,${encodeURIComponent(f.content)}`;
|
|
4124
|
-
}
|
|
4125
|
-
async delete(path) {
|
|
4126
|
-
const p = normalizePath(path);
|
|
4127
|
-
let existed;
|
|
4128
|
-
if (this.memory) existed = this.memory.delete(p);
|
|
4129
|
-
else {
|
|
4130
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4131
|
-
existed = await db.get(FILES_STORE, this.key(p)) !== void 0;
|
|
4132
|
-
await db.delete(FILES_STORE, this.key(p));
|
|
4133
|
-
}
|
|
4134
|
-
if (existed) this.notify("delete", p);
|
|
4135
|
-
return existed;
|
|
4136
|
-
}
|
|
4137
|
-
/** Files under a prefix ("/" = all), sorted by path. */
|
|
4138
|
-
async list(prefix = "/") {
|
|
4139
|
-
const dir = prefix === "/" ? "/" : `${normalizePath(prefix)}/`;
|
|
4140
|
-
let files;
|
|
4141
|
-
if (this.memory) files = [...this.memory.values()];
|
|
4142
|
-
else {
|
|
4143
|
-
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4144
|
-
const range = IDBKeyRange.bound(`${this.ns}:`, `${this.ns}:\uFFFF`);
|
|
4145
|
-
files = await db.getAll(FILES_STORE, range);
|
|
4146
|
-
}
|
|
4147
|
-
return files.filter((f) => dir === "/" || f.path.startsWith(dir)).map(({ content: _drop, ...info }) => info).sort((a, b) => a.path.localeCompare(b.path));
|
|
4148
|
-
}
|
|
4149
|
-
/** Remove every file (of this namespace). */
|
|
4150
|
-
async clear() {
|
|
4151
|
-
for (const f of await this.list()) await this.delete(f.path);
|
|
4152
|
-
}
|
|
4153
|
-
};
|
|
4154
|
-
|
|
4155
|
-
// src/files/tools.ts
|
|
4156
|
-
import { jsonSchema as jsonSchema5, tool as tool5 } from "ai";
|
|
4157
|
-
var createFileTools = (vfs, opts = {}) => {
|
|
4158
|
-
const p = opts.prefix ?? "fs_";
|
|
4159
|
-
const maxRead = opts.maxReadChars ?? 5e4;
|
|
4160
|
-
const tools = {
|
|
4161
|
-
[`${p}list`]: markReadOnly(
|
|
4162
|
-
tool5({
|
|
4163
|
-
description: "List the files in the workspace (attachments the user added, files you wrote). Optionally only under a directory prefix.",
|
|
4164
|
-
inputSchema: jsonSchema5({
|
|
4165
|
-
type: "object",
|
|
4166
|
-
properties: { prefix: { type: "string", description: 'Directory prefix, e.g. "/docs"' } },
|
|
4167
|
-
additionalProperties: false
|
|
4168
|
-
}),
|
|
4169
|
-
execute: async ({ prefix }) => (await vfs.list(prefix || "/")).map((f) => ({
|
|
4170
|
-
path: f.path,
|
|
4171
|
-
mimeType: f.mimeType,
|
|
4172
|
-
size: f.size
|
|
4173
|
-
}))
|
|
4174
|
-
})
|
|
4175
|
-
),
|
|
4176
|
-
[`${p}read`]: markReadOnly(
|
|
4177
|
-
tool5({
|
|
4178
|
-
description: "Read a text file from the workspace by its path.",
|
|
4179
|
-
inputSchema: jsonSchema5({
|
|
4180
|
-
type: "object",
|
|
4181
|
-
properties: { path: { type: "string", description: 'Absolute path, e.g. "/notes.md"' } },
|
|
4182
|
-
required: ["path"],
|
|
4183
|
-
additionalProperties: false
|
|
4184
|
-
}),
|
|
4185
|
-
execute: async ({ path }) => {
|
|
4186
|
-
const f = await vfs.read(path);
|
|
4187
|
-
if (!f) {
|
|
4188
|
-
const known = (await vfs.list()).map((x) => x.path).slice(0, 30);
|
|
4189
|
-
throw new Error(`no file "${path}"; files: ${known.join(", ") || "none"}`);
|
|
4190
|
-
}
|
|
4191
|
-
if (f.encoding === "base64" && !isTextMime(f.mimeType)) {
|
|
4192
|
-
return `"${f.path}" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`;
|
|
4193
|
-
}
|
|
4194
|
-
const text = f.encoding === "base64" ? atob(f.content) : f.content;
|
|
4195
|
-
return text.length > maxRead ? `${text.slice(0, maxRead)}\u2026 [truncated ${text.length - maxRead} chars]` : text;
|
|
4196
|
-
}
|
|
4197
|
-
})
|
|
4198
|
-
)
|
|
4199
|
-
};
|
|
4200
|
-
if (opts.readOnly) return tools;
|
|
4201
|
-
tools[`${p}write`] = tool5({
|
|
4202
|
-
description: "Write a text file to the workspace (creates or replaces it). Use it for reports, drafts, data the user should be able to open.",
|
|
4203
|
-
inputSchema: jsonSchema5({
|
|
4204
|
-
type: "object",
|
|
4205
|
-
properties: {
|
|
4206
|
-
path: { type: "string", description: 'Absolute path, e.g. "/reports/summary.md"' },
|
|
4207
|
-
content: { type: "string", description: "The full file content" },
|
|
4208
|
-
mimeType: { type: "string", description: "Optional MIME type (guessed from the name)" }
|
|
4209
|
-
},
|
|
4210
|
-
required: ["path", "content"],
|
|
4211
|
-
additionalProperties: false
|
|
4212
|
-
}),
|
|
4213
|
-
execute: async ({ path, content, mimeType }) => {
|
|
4214
|
-
const info = await vfs.write(path, content, mimeType ? { mimeType } : {});
|
|
4215
|
-
return { written: info.path, size: info.size };
|
|
4216
|
-
}
|
|
4217
|
-
});
|
|
4218
|
-
tools[`${p}delete`] = tool5({
|
|
4219
|
-
description: "Delete a file from the workspace.",
|
|
4220
|
-
inputSchema: jsonSchema5({
|
|
4221
|
-
type: "object",
|
|
4222
|
-
properties: { path: { type: "string" } },
|
|
4223
|
-
required: ["path"],
|
|
4224
|
-
additionalProperties: false
|
|
4225
|
-
}),
|
|
4226
|
-
execute: async ({ path }) => ({ deleted: await vfs.delete(path) })
|
|
4227
|
-
});
|
|
4228
|
-
return tools;
|
|
4229
|
-
};
|
|
4230
|
-
|
|
4231
4821
|
// src/memory/store.ts
|
|
4232
4822
|
var MemoryStore = class {
|
|
4233
4823
|
data = /* @__PURE__ */ new Map();
|
|
@@ -4390,6 +4980,9 @@ export {
|
|
|
4390
4980
|
MemoryRunStore,
|
|
4391
4981
|
MemorySkillStore,
|
|
4392
4982
|
MemoryStore,
|
|
4983
|
+
PIPELINE_LIMITS,
|
|
4984
|
+
PipelineNodeError,
|
|
4985
|
+
PipelineValidationError,
|
|
4393
4986
|
PlanSchema,
|
|
4394
4987
|
PlanStepSchema,
|
|
4395
4988
|
RUNS_STORE,
|
|
@@ -4425,6 +5018,7 @@ export {
|
|
|
4425
5018
|
createGuardedFetch,
|
|
4426
5019
|
createLearning,
|
|
4427
5020
|
createLogger,
|
|
5021
|
+
createPipeline,
|
|
4428
5022
|
createPlan,
|
|
4429
5023
|
createRunControl,
|
|
4430
5024
|
createSkillTools,
|
|
@@ -4444,6 +5038,7 @@ export {
|
|
|
4444
5038
|
messageTokens as estimateMessagesTokens,
|
|
4445
5039
|
estimateTokens,
|
|
4446
5040
|
executeStep,
|
|
5041
|
+
fileToolBindingOf,
|
|
4447
5042
|
findSecret,
|
|
4448
5043
|
fitCompactionToWindow,
|
|
4449
5044
|
generate,
|
|
@@ -4467,7 +5062,9 @@ export {
|
|
|
4467
5062
|
mediaTypeOf,
|
|
4468
5063
|
mergeProviderOptions,
|
|
4469
5064
|
mimeFromPath,
|
|
5065
|
+
nodeResolver,
|
|
4470
5066
|
normalizePath,
|
|
5067
|
+
normalizePipeline,
|
|
4471
5068
|
normalizeSkillName,
|
|
4472
5069
|
normalizeSteps,
|
|
4473
5070
|
normalizeUsage,
|
|
@@ -4481,6 +5078,7 @@ export {
|
|
|
4481
5078
|
promptHintOf,
|
|
4482
5079
|
renderActiveSkills,
|
|
4483
5080
|
renderCatalog,
|
|
5081
|
+
renderPipelineNodeInput,
|
|
4484
5082
|
renderSearchCatalog,
|
|
4485
5083
|
renderSkillIndex,
|
|
4486
5084
|
replanWanted,
|
|
@@ -4506,6 +5104,7 @@ export {
|
|
|
4506
5104
|
supportsPdf,
|
|
4507
5105
|
supportsStructuredOutput,
|
|
4508
5106
|
synthesizeAnswer,
|
|
5107
|
+
testPipelineCondition,
|
|
4509
5108
|
thinkingFor,
|
|
4510
5109
|
toFilePart,
|
|
4511
5110
|
toImagePart,
|
|
@@ -4514,6 +5113,7 @@ export {
|
|
|
4514
5113
|
toolDefinitionTokens,
|
|
4515
5114
|
toolRunContextOf,
|
|
4516
5115
|
unloadWebLLMModel,
|
|
5116
|
+
validatePipeline,
|
|
4517
5117
|
webLLMContextWindow,
|
|
4518
5118
|
withRollingBreakpoint,
|
|
4519
5119
|
withSystem,
|