@dudko.dev/agent-web 0.0.41 → 0.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -586,7 +586,7 @@ var init_webllm = __esm({
586
586
  });
587
587
 
588
588
  // src/mcp/skills.ts
589
- var MCP_SKILLS_EXTENSION, MCP_SKILL_MAX_RESOURCES, MCP_SKILL_MAX_TOTAL_BYTES, MCP_SKILLS_MAX_PER_SERVER, MCP_SKILLS_MAX_TOTAL, MCP_SKILL_DESCRIPTION_MAX_CHARS, MCP_SKILL_BODY_MAX_CHARS, MCP_SKILL_FILE_MAX_CHARS, MCP_SKILL_FILES_SHOWN_MAX, MCP_SKILL_SERVER_LABEL_MAX_CHARS, INVISIBLE, cleanMcpSkillText, oneLine, MCP_SKILL_NAME_PATTERN, DIGEST, SKILL_URI, isRecord, mcpSkillPath, mcpSkillFilePath, mcpSkillEntryRefusal, mcpSkillRecordOf, labelOf, segmentOf, assignMcpSkillNames, isMcpSkillName, selectMcpSkills, clipped, shownUri, mcpSkillTag, mcpSkillDescription, mcpSkillPreamble, mcpSkillBodyPreview, mcpSkillBodyText, mcpSkillFileText, resolveMcpSkillFile, MCP_SKILL_URI_MAX_CHARS, mcpSkillUriRefusal, resolveMcpSkillServer, mcpSkillRoomRefusal, assignAddedMcpSkillName, mcpSkillEnclosingUri, mcpSkillLoadByUriNote, MCP_SKILL_CONSENTS, MCP_SKILL_CONSENT_DEFAULT, consentList, mcpSkillConsentOf, resolveMcpSkillConsent, createMcpSkillGrants, createMcpSkillRunConsent, mcpSkillGrantKey, decideMcpSkillConsent, recordMcpSkillConsent, mcpSkillConsentView, mcpSkillDeniedMessage, MCP_SKILLS_MARK, collectMcpSkillSources;
589
+ var MCP_SKILLS_EXTENSION, MCP_SKILL_MAX_RESOURCES, MCP_SKILL_MAX_TOTAL_BYTES, MCP_SKILLS_MAX_PER_SERVER, MCP_SKILLS_MAX_TOTAL, MCP_SKILL_DESCRIPTION_MAX_CHARS, MCP_SKILL_BODY_MAX_CHARS, MCP_SKILL_FILE_MAX_CHARS, MCP_SKILL_FILES_SHOWN_MAX, MCP_SKILL_SERVER_LABEL_MAX_CHARS, INVISIBLE, cleanMcpSkillText, oneLine, MCP_SKILL_NAME_PATTERN, DIGEST, SKILL_URI, isRecord, mcpSkillPath, mcpSkillFilePath, mcpSkillEntryRefusal, mcpSkillRecordOf, labelOf, segmentOf, assignMcpSkillNames, isMcpSkillName, selectMcpSkills, clipped, shownUri, mcpSkillTag, mcpSkillDescription, mcpSkillPreamble, mcpSkillBodyPreview, mcpSkillBodyText, mcpSkillFileText, resolveMcpSkillFile, MCP_SKILL_DIRECTORY_ENTRIES_MAX, skillDirectoryRef, isPlainPath, skillDirectoryChildren, skillDirectoryOf, resolveMcpSkillPath, mcpSkillDirectoryNote, skillDirectoryListing, MCP_SKILL_URI_MAX_CHARS, mcpSkillUriRefusal, resolveMcpSkillServer, mcpSkillRoomRefusal, assignAddedMcpSkillName, mcpSkillEnclosingUri, mcpSkillLoadByUriNote, MCP_SKILL_CONSENTS, MCP_SKILL_CONSENT_DEFAULT, consentList, mcpSkillConsentOf, resolveMcpSkillConsent, createMcpSkillGrants, createMcpSkillRunConsent, mcpSkillGrantKey, decideMcpSkillConsent, recordMcpSkillConsent, mcpSkillConsentView, mcpSkillDeniedMessage, MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES, MCP_SKILL_SNAPSHOT_MAX_DEPTH, MCP_SKILL_SNAPSHOTS_MAX_BYTES, createMcpSkillSnapshotMemory, MCP_SKILLS_MARK, collectMcpSkillSources;
590
590
  var init_skills = __esm({
591
591
  "src/mcp/skills.ts"() {
592
592
  "use strict";
@@ -629,7 +629,7 @@ var init_skills = __esm({
629
629
  }
630
630
  return path;
631
631
  };
632
- mcpSkillEntryRefusal = (entry) => {
632
+ mcpSkillEntryRefusal = (entry, options = {}) => {
633
633
  if (!isRecord(entry) || typeof entry.uri !== "string") return "not a skill entry (no uri)";
634
634
  const path = mcpSkillPath(entry.uri);
635
635
  if (!path) return `${entry.uri} is not the SKILL.md of a named skill directory`;
@@ -646,6 +646,7 @@ var init_skills = __esm({
646
646
  if (!oneLine(frontmatter.description)) return "the frontmatter has no description";
647
647
  const resources = entry.resources;
648
648
  if (resources === "dynamic") {
649
+ if (options.dynamic === true) return void 0;
649
650
  return 'its content is generated ("resources": "dynamic"): there are no digests to verify it against';
650
651
  }
651
652
  if (!Array.isArray(resources)) return 'the entry does not list its files ("resources")';
@@ -691,7 +692,8 @@ var init_skills = __esm({
691
692
  name: entry.frontmatter.name,
692
693
  description: oneLine(entry.frontmatter.description),
693
694
  path: mcpSkillPath(entry.uri) ?? [entry.frontmatter.name],
694
- files
695
+ files,
696
+ ...entry.resources === "dynamic" ? { dynamic: true } : {}
695
697
  };
696
698
  };
697
699
  labelOf = (server) => (server.replace(/[^a-zA-Z0-9_-]/g, "_") || "_").slice(0, MCP_SKILL_SERVER_LABEL_MAX_CHARS);
@@ -729,9 +731,9 @@ var init_skills = __esm({
729
731
  clipped = (text, max, what) => text.length > max ? `${text.slice(0, max)}
730
732
  \u2026 [${what} cut at ${max} characters; the rest is not shown]` : text;
731
733
  shownUri = (uri) => oneLine(uri).replace(/[[\]]/g, "").slice(0, 200);
732
- mcpSkillTag = (server) => `[from the MCP server "${labelOf(server)}" - third-party]`;
733
- mcpSkillDescription = (description, server) => {
734
- const tag = ` ${mcpSkillTag(server)}`;
734
+ mcpSkillTag = (server, dynamic = false) => `[from the MCP server "${labelOf(server)}" - third-party${dynamic ? ", no checksums" : ""}]`;
735
+ mcpSkillDescription = (description, server, dynamic = false) => {
736
+ const tag = ` ${mcpSkillTag(server, dynamic)}`;
735
737
  const room = Math.max(0, MCP_SKILL_DESCRIPTION_MAX_CHARS - tag.length);
736
738
  const text = oneLine(description);
737
739
  return `${text.length > room ? `${text.slice(0, Math.max(0, room - 1))}\u2026` : text}${tag}`;
@@ -765,6 +767,78 @@ var init_skills = __esm({
765
767
  }
766
768
  return { path };
767
769
  };
770
+ MCP_SKILL_DIRECTORY_ENTRIES_MAX = MCP_SKILL_MAX_RESOURCES + 128;
771
+ skillDirectoryRef = (requested) => {
772
+ if (typeof requested !== "string") return { refused: "no directory path given" };
773
+ const raw = requested.trim();
774
+ if (raw === "" || raw === "." || raw === "./" || raw === "/") return { dir: "" };
775
+ const refused = { refused: `"${oneLine(requested)}" is not a directory inside the skill` };
776
+ if (/^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith("/") || /[?#\\]/.test(raw)) {
777
+ return refused;
778
+ }
779
+ const dir = raw.replace(/^\.\/+/, "").replace(/\/+$/, "");
780
+ if (!dir) return { dir: "" };
781
+ if (dir.split("/").some((s) => !s || s === "." || s === "..")) return refused;
782
+ return { dir };
783
+ };
784
+ isPlainPath = (path) => path.split("/").every((s) => s !== "" && s !== "." && s !== "..");
785
+ skillDirectoryChildren = (paths, dir) => {
786
+ const prefix = dir ? `${dir}/` : "";
787
+ const files = /* @__PURE__ */ new Set();
788
+ const directories = /* @__PURE__ */ new Set();
789
+ for (const path of paths) {
790
+ if (typeof path !== "string" || !isPlainPath(path) || !path.startsWith(prefix)) continue;
791
+ const rest = path.slice(prefix.length);
792
+ const cut = rest.indexOf("/");
793
+ if (cut < 0) files.add(path);
794
+ else directories.add(`${prefix}${rest.slice(0, cut)}`);
795
+ }
796
+ if (dir && !files.size && !directories.size) return void 0;
797
+ return { files: [...files].sort(), directories: [...directories].sort() };
798
+ };
799
+ skillDirectoryOf = (paths, requested) => {
800
+ const ref = skillDirectoryRef(requested);
801
+ if ("refused" in ref) return void 0;
802
+ const children = skillDirectoryChildren(paths, ref.dir);
803
+ return children ? { dir: ref.dir, ...children } : void 0;
804
+ };
805
+ resolveMcpSkillPath = (files, requested) => {
806
+ const file = resolveMcpSkillFile(files, requested);
807
+ if ("path" in file) return file;
808
+ return skillDirectoryOf(files, requested) ?? file;
809
+ };
810
+ mcpSkillDirectoryNote = (extra, notServed, truncated2 = false) => {
811
+ const parts = [];
812
+ if (extra > 0) {
813
+ parts.push(
814
+ `The server now lists ${truncated2 ? "at least " : ""}${extra} more item(s) here than the approved entry of this skill: the skill changed on the server. They are not shown and cannot be read under the current approval.`
815
+ );
816
+ }
817
+ if (notServed > 0) {
818
+ parts.push(
819
+ `${notServed} item(s) listed here (notServed) are no longer listed by the server: a read of them will fail - the skill changed on the server.`
820
+ );
821
+ }
822
+ if (!parts.length) return void 0;
823
+ return `${parts.join(" ")} The skill is read again, and asked about again, when the server's skills are refreshed.`;
824
+ };
825
+ skillDirectoryListing = (name, dir, children, drift) => {
826
+ const directories = children.directories.slice(0, MCP_SKILL_FILES_SHOWN_MAX);
827
+ const files = children.files.slice(0, MCP_SKILL_FILES_SHOWN_MAX - directories.length);
828
+ const more = children.files.length + children.directories.length - files.length - directories.length;
829
+ const shown = /* @__PURE__ */ new Set([...directories, ...files]);
830
+ const notServed = drift ? drift.notServed.filter((p) => shown.has(p)) : [];
831
+ const note = drift ? mcpSkillDirectoryNote(drift.extra, notServed.length, drift.truncated) : void 0;
832
+ return {
833
+ name,
834
+ directory: dir || ".",
835
+ files,
836
+ directories,
837
+ ...more > 0 ? { more } : {},
838
+ ...notServed.length ? { notServed } : {},
839
+ ...note ? { note } : {}
840
+ };
841
+ };
768
842
  MCP_SKILL_URI_MAX_CHARS = 512;
769
843
  mcpSkillUriRefusal = (uri) => {
770
844
  if (typeof uri !== "string" || !uri) return "no skill URI given";
@@ -890,6 +964,7 @@ var init_skills = __esm({
890
964
  body: mcpSkillBodyPreview(o.body),
891
965
  ...o.byUri ? { byUri: true } : {},
892
966
  ...o.nestedIn ? { nestedIn: oneLine(o.nestedIn).slice(0, 200) } : {},
967
+ ...o.snapshot ? { dynamic: true, ...o.snapshot.listed ? {} : { noFileListing: true } } : {},
893
968
  consent: o.consent
894
969
  };
895
970
  };
@@ -899,6 +974,10 @@ var init_skills = __esm({
899
974
  const head = why === "denied" ? `The user did not allow ${what} to be loaded${said}` : why === "denied-earlier" ? `The user already refused ${what} in this task` : why === "no-one-to-ask" ? `${what[0].toUpperCase()}${what.slice(1)} is loaded only with a person's consent, and no one can be asked (no approval handler is configured)` : `No one answered whether ${what} may be loaded${said}`;
900
975
  return `${head}: nothing of it is in your context. Do not load it again in this task; continue without it, or say what it would have been needed for.`;
901
976
  };
977
+ MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES = 64;
978
+ MCP_SKILL_SNAPSHOT_MAX_DEPTH = 8;
979
+ MCP_SKILL_SNAPSHOTS_MAX_BYTES = 64 * 1024 * 1024;
980
+ createMcpSkillSnapshotMemory = () => ({ used: 0 });
902
981
  MCP_SKILLS_MARK = /* @__PURE__ */ Symbol.for("@dudko.dev/agent:mcp-skills");
903
982
  collectMcpSkillSources = (tools) => {
904
983
  const out = [];
@@ -3033,9 +3112,13 @@ __export(src_exports, {
3033
3112
  MCP_SKILL_CONSENTS: () => MCP_SKILL_CONSENTS,
3034
3113
  MCP_SKILL_CONSENT_DEFAULT: () => MCP_SKILL_CONSENT_DEFAULT,
3035
3114
  MCP_SKILL_DESCRIPTION_MAX_CHARS: () => MCP_SKILL_DESCRIPTION_MAX_CHARS,
3115
+ MCP_SKILL_DIRECTORY_ENTRIES_MAX: () => MCP_SKILL_DIRECTORY_ENTRIES_MAX,
3036
3116
  MCP_SKILL_FILE_MAX_CHARS: () => MCP_SKILL_FILE_MAX_CHARS,
3037
3117
  MCP_SKILL_MAX_RESOURCES: () => MCP_SKILL_MAX_RESOURCES,
3038
3118
  MCP_SKILL_MAX_TOTAL_BYTES: () => MCP_SKILL_MAX_TOTAL_BYTES,
3119
+ MCP_SKILL_SNAPSHOTS_MAX_BYTES: () => MCP_SKILL_SNAPSHOTS_MAX_BYTES,
3120
+ MCP_SKILL_SNAPSHOT_MAX_DEPTH: () => MCP_SKILL_SNAPSHOT_MAX_DEPTH,
3121
+ MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES: () => MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES,
3039
3122
  MCP_SKILL_URI_MAX_CHARS: () => MCP_SKILL_URI_MAX_CHARS,
3040
3123
  MEDIA_AUDIO_TYPES: () => MEDIA_AUDIO_TYPES,
3041
3124
  MEDIA_DEFAULT_MAX_CALLS: () => MEDIA_DEFAULT_MAX_CALLS,
@@ -3057,6 +3140,7 @@ __export(src_exports, {
3057
3140
  MemorySkillStore: () => MemorySkillStore,
3058
3141
  MemoryStore: () => MemoryStore,
3059
3142
  PIPELINE_LIMITS: () => PIPELINE_LIMITS,
3143
+ PIPELINE_ROUTER_SYSTEM: () => PIPELINE_ROUTER_SYSTEM,
3060
3144
  PipelineNodeError: () => PipelineNodeError,
3061
3145
  PipelineValidationError: () => PipelineValidationError,
3062
3146
  PlanSchema: () => PlanSchema,
@@ -3175,6 +3259,7 @@ __export(src_exports, {
3175
3259
  looksLikeJson: () => looksLikeJson,
3176
3260
  markCodeExecution: () => markCodeExecution,
3177
3261
  markReadOnly: () => markReadOnly,
3262
+ matchPipelineRoute: () => matchPipelineRoute,
3178
3263
  matchRule: () => matchRule,
3179
3264
  mcpAppOrigin: () => mcpAppOrigin,
3180
3265
  mcpSkillEntryRefusal: () => mcpSkillEntryRefusal,
@@ -3199,12 +3284,15 @@ __export(src_exports, {
3199
3284
  parseReplannerResponse: () => parseReplannerResponse,
3200
3285
  parseSearchResponse: () => parseSearchResponse,
3201
3286
  parseSkillMarkdown: () => parseSkillMarkdown,
3287
+ pickPipelineRoute: () => pickPipelineRoute,
3202
3288
  pickTier: () => pickTier,
3203
3289
  preloadWebLLMModel: () => preloadWebLLMModel,
3290
+ preparePipeline: () => preparePipeline,
3204
3291
  promptHintOf: () => promptHintOf,
3205
3292
  renderActiveSkills: () => renderActiveSkills,
3206
3293
  renderCatalog: () => renderCatalog,
3207
3294
  renderPipelineNodeInput: () => renderPipelineNodeInput,
3295
+ renderPipelineRoutePrompt: () => renderPipelineRoutePrompt,
3208
3296
  renderSearchCatalog: () => renderSearchCatalog,
3209
3297
  renderSkillIndex: () => renderSkillIndex,
3210
3298
  replanWanted: () => replanWanted,
@@ -3221,6 +3309,7 @@ __export(src_exports, {
3221
3309
  resolveResume: () => resolveResume,
3222
3310
  resolveStage: () => resolveStage,
3223
3311
  resolveThinking: () => resolveThinking,
3312
+ runPipelineGraph: () => runPipelineGraph,
3224
3313
  runToolLoop: () => runToolLoop,
3225
3314
  sanitizeSearchResults: () => sanitizeSearchResults,
3226
3315
  schemaHintOf: () => schemaHintOf,
@@ -3748,17 +3837,24 @@ var McpSkillDeniedError = class extends Error {
3748
3837
  return this.message;
3749
3838
  }
3750
3839
  };
3751
- var mcpSkillOf = (source, record2, name, byUri) => {
3840
+ var mcpSkillOf = (source, record2, name, byUri, memory) => {
3752
3841
  const skill = {
3753
3842
  name,
3754
- description: mcpSkillDescription(record2.description, source.server),
3843
+ description: mcpSkillDescription(record2.description, source.server, record2.dynamic === true),
3755
3844
  content: "",
3756
3845
  mcp: { server: source.server, uri: record2.uri }
3757
3846
  };
3758
- mcpSkillStates.set(skill, { source, record: record2, ...byUri ? { byUri: true } : {} });
3847
+ mcpSkillStates.set(skill, { source, record: record2, memory, ...byUri ? { byUri: true } : {} });
3759
3848
  return skill;
3760
3849
  };
3761
- var createMcpSkills = (sources, names, warn) => {
3850
+ var memoryOf = (skills) => {
3851
+ for (const skill of skills) {
3852
+ const memory = mcpSkillStates.get(skill)?.memory;
3853
+ if (memory) return memory;
3854
+ }
3855
+ return void 0;
3856
+ };
3857
+ var createMcpSkills = (sources, names, warn, memory = createMcpSkillSnapshotMemory()) => {
3762
3858
  const own = new Set(names);
3763
3859
  const taken = new Set(own);
3764
3860
  const { kept, notices } = selectMcpSkills(
@@ -3789,12 +3885,12 @@ var createMcpSkills = (sources, names, warn) => {
3789
3885
  `[mcp] ${source.server}: its skill "${record2.name}" has the name of one of this agent's own skills; the agent's keeps the name, the server's is "${name}"`
3790
3886
  );
3791
3887
  }
3792
- out.push(mcpSkillOf(source, record2, name, added.has(record2)));
3888
+ out.push(mcpSkillOf(source, record2, name, added.has(record2), memory));
3793
3889
  }
3794
3890
  }
3795
3891
  return out;
3796
3892
  };
3797
- var addMcpSkillByUri = async (skills, sources, requested, signal) => {
3893
+ var addMcpSkillByUri = async (skills, sources, requested, signal, memory) => {
3798
3894
  const refused = mcpSkillUriRefusal(requested.uri);
3799
3895
  if (refused) throw new Error(`load_skill: ${refused}`);
3800
3896
  const able = sources.filter((s) => typeof s.get === "function");
@@ -3819,13 +3915,22 @@ var addMcpSkillByUri = async (skills, sources, requested, signal) => {
3819
3915
  const meanwhile = held();
3820
3916
  if (meanwhile) return meanwhile;
3821
3917
  const name = assignAddedMcpSkillName(source.server, record2, new Set(skills.map((s) => s.name)));
3822
- const skill = mcpSkillOf(source, record2, name, true);
3918
+ const skill = mcpSkillOf(
3919
+ source,
3920
+ record2,
3921
+ name,
3922
+ true,
3923
+ memoryOf(skills) ?? memory ?? createMcpSkillSnapshotMemory()
3924
+ );
3823
3925
  skills.push(skill);
3824
3926
  return skill;
3825
3927
  };
3826
3928
  var fetchMcpSkill = async (state, signal) => {
3827
3929
  if (state.fetched) return state.fetched;
3828
- state.fetching ??= state.source.load(state.record.uri, signal ? { signal } : void 0);
3930
+ state.fetching ??= state.source.load(state.record.uri, {
3931
+ ...signal ? { signal } : {},
3932
+ memory: state.memory
3933
+ });
3829
3934
  try {
3830
3935
  state.fetched = await state.fetching;
3831
3936
  return state.fetched;
@@ -3886,7 +3991,8 @@ var acquireMcpSkill = async (skill, skills, scope, opts = {}) => {
3886
3991
  body: fetched.body,
3887
3992
  consent,
3888
3993
  ...state.byUri ? { byUri: true } : {},
3889
- ...enclosing ? { nestedIn: enclosing } : {}
3994
+ ...enclosing ? { nestedIn: enclosing } : {},
3995
+ ...fetched.snapshot ? { snapshot: fetched.snapshot } : {}
3890
3996
  });
3891
3997
  const answer = await scope.ask(opts.input ?? { name: skill.name }, view, opts.signal);
3892
3998
  if (answer.by === "person") {
@@ -3931,8 +4037,16 @@ var readMcpSkillFile = async (skill, skills, requested, scope, signal) => {
3931
4037
  }
3932
4038
  const state = mcpSkillStates.get(skill);
3933
4039
  const loaded = state.loaded;
3934
- const target = resolveMcpSkillFile(loaded.files, requested);
4040
+ const target = resolveMcpSkillPath(loaded.files, requested);
3935
4041
  if ("refused" in target) throw new Error(`skill "${skill.name}": ${target.refused}`);
4042
+ if ("dir" in target) {
4043
+ const drift = await state.source.readDirectory?.(
4044
+ loaded,
4045
+ target.dir,
4046
+ signal ? { signal } : void 0
4047
+ );
4048
+ return skillDirectoryListing(skill.name, target.dir, target, drift);
4049
+ }
3936
4050
  const text = await state.source.readFile(loaded, target.path, signal ? { signal } : void 0);
3937
4051
  return mcpSkillFileText(state.source.server, state.record.uri, target.path, text);
3938
4052
  };
@@ -3999,7 +4113,8 @@ var createSkillTools = (skills, onLoad, mcp) => {
3999
4113
  skills,
4000
4114
  servers,
4001
4115
  { server, uri },
4002
- signalOf(options)
4116
+ signalOf(options),
4117
+ mcp?.memory
4003
4118
  );
4004
4119
  return load(skill2, { server, uri }, signalOf(options));
4005
4120
  }
@@ -4025,12 +4140,15 @@ var createSkillTools = (skills, onLoad, mcp) => {
4025
4140
  }
4026
4141
  });
4027
4142
  const readFile = (0, import_ai4.tool)({
4028
- description: "Read one of a skill's bundled files (paths are listed by load_skill).",
4143
+ description: `Read one of a skill's bundled files (paths are listed by load_skill); a directory path ("templates/", "." for the root) returns its listing.`,
4029
4144
  inputSchema: (0, import_ai4.jsonSchema)({
4030
4145
  type: "object",
4031
4146
  properties: {
4032
4147
  name: { type: "string", description: "The skill name" },
4033
- path: { type: "string", description: "The file path, relative to the skill" }
4148
+ path: {
4149
+ type: "string",
4150
+ description: "The file path, relative to the skill, or a directory to list"
4151
+ }
4034
4152
  },
4035
4153
  required: ["name", "path"],
4036
4154
  additionalProperties: false
@@ -4043,8 +4161,12 @@ var createSkillTools = (skills, onLoad, mcp) => {
4043
4161
  }
4044
4162
  const file = skill.files?.find((f) => f.path === path);
4045
4163
  if (!file) {
4046
- const listed = (skill.files ?? []).map((f) => f.path).join(", ") || "none";
4047
- throw new Error(`skill "${name}" has no file "${path}"; files: ${listed}`);
4164
+ const paths = (skill.files ?? []).map((f) => f.path);
4165
+ const directory = skillDirectoryOf(paths, path);
4166
+ if (directory) return skillDirectoryListing(skill.name, directory.dir, directory);
4167
+ throw new Error(
4168
+ `skill "${name}" has no file "${path}"; files: ${paths.join(", ") || "none"}`
4169
+ );
4048
4170
  }
4049
4171
  return file.content;
4050
4172
  }
@@ -7272,6 +7394,7 @@ var SPAWN_INPUT_SCHEMA = {
7272
7394
  description: "Optional: the names of YOUR tools the helper may use. Only tools you have can be named. Omit it for the default set; pass [] for a helper that only reasons."
7273
7395
  }
7274
7396
  },
7397
+ // A mutable array: JSON Schema 7's `required` is `string[]`, and `as const` would make it readonly.
7275
7398
  required: ["task"],
7276
7399
  additionalProperties: false
7277
7400
  };
@@ -7691,8 +7814,49 @@ var resolveResume = async (persistence, resumeFromRunId) => {
7691
7814
  `Run "${resumeFromRunId}" has no steps left to run (status="${snapshot.status}"); nothing to resume`
7692
7815
  );
7693
7816
  }
7817
+ if (snapshot.attempt !== void 0 && !(Number.isSafeInteger(snapshot.attempt) && snapshot.attempt >= 1)) {
7818
+ throw new Error(
7819
+ `Run "${resumeFromRunId}" has an invalid attempt (${JSON.stringify(snapshot.attempt)}); it must be a positive integer`
7820
+ );
7821
+ }
7694
7822
  return snapshot;
7695
7823
  };
7824
+ var resolveRunId = async (persistence, runId, resumeFromRunId) => {
7825
+ if (runId === void 0) return void 0;
7826
+ if (resumeFromRunId !== void 0) {
7827
+ throw new Error(
7828
+ "runId names a fresh run and cannot be combined with resumeFromRunId: a resume keeps the id of the run it resumes"
7829
+ );
7830
+ }
7831
+ assertSafeRunId(runId, "runId");
7832
+ const snapshot = await persistence?.loadRun?.(runId);
7833
+ if (snapshot) {
7834
+ throw new Error(
7835
+ `Run "${runId}" already exists (status "${snapshot.status}"); resume it with resumeFromRunId instead of starting it again`
7836
+ );
7837
+ }
7838
+ return runId;
7839
+ };
7840
+ var resumeAttemptOf = (snapshot) => (snapshot.attempt ?? 1) + 1;
7841
+ var recordResume = async (persistence, resumed, attempt, warn) => {
7842
+ const hook = persistence?.onRunResume ? "onRunResume" : persistence?.onStepComplete ? "onStepComplete" : void 0;
7843
+ if (!persistence || !hook) {
7844
+ warn(
7845
+ `persistence has neither onRunResume nor onStepComplete: attempt ${attempt} of run ${resumed.runId} is not on record until the run ends`
7846
+ );
7847
+ return;
7848
+ }
7849
+ const { error: _error, completedAt: _completedAt, text: _text, ...rest } = resumed;
7850
+ void [_error, _completedAt, _text];
7851
+ try {
7852
+ await persistence[hook]?.call(persistence, { ...rest, status: "executing", attempt });
7853
+ } catch (err) {
7854
+ throw new Error(
7855
+ `persistence.${hook} threw while recording attempt ${attempt} of run ${resumed.runId}; the resume was refused: ${err instanceof Error ? err.message : String(err)}`,
7856
+ { cause: err }
7857
+ );
7858
+ }
7859
+ };
7696
7860
 
7697
7861
  // src/agent/planner.ts
7698
7862
  init_context_window();
@@ -8783,12 +8947,14 @@ var createAgent = async (config) => {
8783
8947
  const spawnBuiltIn = Boolean(dynamicSubagents) && config.tools?.[SPAWN_SUBAGENT_TOOL] === void 0 && baseTools[SPAWN_SUBAGENT_TOOL] !== void 0;
8784
8948
  const mcpInstructions = config.mcpInstructions === false ? "" : renderMcpInstructions(collectMcpInstructions(baseTools));
8785
8949
  const mcpSkillSources = collectMcpSkillSources(baseTools);
8950
+ const mcpSkillMemory = createMcpSkillSnapshotMemory();
8786
8951
  if (!seed) {
8787
8952
  skills.push(
8788
8953
  ...createMcpSkills(
8789
8954
  mcpSkillSources,
8790
8955
  skills.map((s) => s.name),
8791
- (m) => log.warn(m)
8956
+ (m) => log.warn(m),
8957
+ mcpSkillMemory
8792
8958
  )
8793
8959
  );
8794
8960
  }
@@ -8865,16 +9031,20 @@ ${renderActiveSkills(active)}`
8865
9031
  spentBySession.set(sessionId, addUsage(spentBySession.get(sessionId) ?? emptyUsage(), u));
8866
9032
  };
8867
9033
  const runCore = async (goal, opts, track, port) => {
9034
+ const ownRunId = await resolveRunId(config.persistence, opts.runId, opts.resumeFromRunId);
8868
9035
  const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
9036
+ const attempt = resumed ? resumeAttemptOf(resumed) : 1;
9037
+ let seq4 = 0;
8869
9038
  const emit = (event) => {
8870
9039
  try {
8871
- opts.onEvent?.(event);
9040
+ opts.onEvent?.({ ...event, seq: ++seq4, attempt });
8872
9041
  } catch {
8873
9042
  }
8874
9043
  };
9044
+ if (resumed) await recordResume(config.persistence, resumed, attempt, (m) => log.warn(m));
8875
9045
  let text = (resumed?.goal ?? goal).trim();
8876
9046
  const sessionId = resumed?.sessionId ?? opts.sessionId ?? cfg.sessionId;
8877
- const runId = resumed?.runId ?? newRunId();
9047
+ const runId = resumed?.runId ?? ownRunId ?? newRunId();
8878
9048
  const startedAt = resumed?.startedAt ?? Date.now();
8879
9049
  let usage = resumed ? { ...resumed.usage } : emptyUsage();
8880
9050
  const result = {
@@ -8992,7 +9162,7 @@ ${renderActiveSkills(active)}`
8992
9162
  createSkillTools(
8993
9163
  skills,
8994
9164
  (s) => activateSkill(s.name, "tool"),
8995
- mcpSkillSources.length ? { sources: mcpSkillSources, scope: skillScope } : void 0
9165
+ mcpSkillSources.length ? { sources: mcpSkillSources, scope: skillScope, memory: mcpSkillMemory } : void 0
8996
9166
  )
8997
9167
  );
8998
9168
  }
@@ -9259,6 +9429,7 @@ ${renderActiveSkills(active)}`
9259
9429
  ...userUpdates.length ? { userUpdates: userUpdates.map((u) => ({ ...u })) } : {},
9260
9430
  ...escalationCount ? { escalations: escalationCount } : {},
9261
9431
  ...spawnRun && !seed && spawnRun.root.spawned ? { subagentsSpawned: spawnRun.root.spawned } : {},
9432
+ attempt,
9262
9433
  ...extra
9263
9434
  });
9264
9435
  const persist = async (hook, snapshot) => {
@@ -10596,7 +10767,100 @@ var preparePipeline = (definition) => {
10596
10767
  reaches: (from, to) => descendants(from).has(to)
10597
10768
  };
10598
10769
  };
10599
- var abortError2 = () => new DOMException("Aborted", "AbortError");
10770
+ var passReach = (plan) => {
10771
+ const entry = plan.definition.entry;
10772
+ const order = [entry];
10773
+ const preds = /* @__PURE__ */ new Map([[entry, []]]);
10774
+ for (let i = 0; i < order.length; i++) {
10775
+ for (const { edge } of plan.outgoing.get(order[i]) ?? []) {
10776
+ if (!preds.has(edge.to)) {
10777
+ preds.set(edge.to, []);
10778
+ order.push(edge.to);
10779
+ }
10780
+ ;
10781
+ preds.get(edge.to).push(order[i]);
10782
+ }
10783
+ }
10784
+ const dom = /* @__PURE__ */ new Map();
10785
+ for (const nodeId of order) dom.set(nodeId, new Set(nodeId === entry ? [entry] : order));
10786
+ for (let changed = true; changed; ) {
10787
+ changed = false;
10788
+ for (const nodeId of order) {
10789
+ if (nodeId === entry) continue;
10790
+ const [first, ...rest] = preds.get(nodeId).map((p) => dom.get(p));
10791
+ const next = /* @__PURE__ */ new Set([nodeId]);
10792
+ for (const d of first) if (rest.every((set) => set.has(d))) next.add(d);
10793
+ if (next.size < dom.get(nodeId).size) {
10794
+ dom.set(nodeId, next);
10795
+ changed = true;
10796
+ }
10797
+ }
10798
+ }
10799
+ const closure = /* @__PURE__ */ new Map();
10800
+ return (from, to) => {
10801
+ let seen = closure.get(from);
10802
+ if (!seen) {
10803
+ const found = /* @__PURE__ */ new Set();
10804
+ const queue = [from];
10805
+ while (queue.length) {
10806
+ const at = queue.pop();
10807
+ for (const { edge } of plan.outgoing.get(at) ?? []) {
10808
+ if (dom.get(at)?.has(edge.to) || found.has(edge.to)) continue;
10809
+ found.add(edge.to);
10810
+ queue.push(edge.to);
10811
+ }
10812
+ }
10813
+ closure.set(from, seen = found);
10814
+ }
10815
+ return seen.has(to);
10816
+ };
10817
+ };
10818
+ var abortError2 = () => {
10819
+ if (typeof DOMException === "function") return new DOMException("Aborted", "AbortError");
10820
+ const error = new Error("Aborted");
10821
+ error.name = "AbortError";
10822
+ return error;
10823
+ };
10824
+ var createStopper = () => {
10825
+ if (typeof AbortController === "function") {
10826
+ const controller = new AbortController();
10827
+ return { signal: controller.signal, abort: () => controller.abort() };
10828
+ }
10829
+ const listeners = [];
10830
+ const signal = {
10831
+ aborted: false,
10832
+ reason: void 0,
10833
+ onabort: null,
10834
+ addEventListener(type, listener) {
10835
+ if (type === "abort" && listener && !listeners.includes(listener)) listeners.push(listener);
10836
+ },
10837
+ removeEventListener(type, listener) {
10838
+ const index = listener ? listeners.indexOf(listener) : -1;
10839
+ if (type === "abort" && index >= 0) listeners.splice(index, 1);
10840
+ },
10841
+ throwIfAborted() {
10842
+ if (signal.aborted) throw signal.reason;
10843
+ }
10844
+ };
10845
+ const abort = () => {
10846
+ if (signal.aborted) return;
10847
+ signal.aborted = true;
10848
+ signal.reason = abortError2();
10849
+ const event = { type: "abort", target: signal };
10850
+ const call = (fn, thisArg) => {
10851
+ try {
10852
+ fn.call(thisArg, event);
10853
+ } catch {
10854
+ }
10855
+ };
10856
+ for (const listener of listeners.splice(0)) {
10857
+ if (typeof listener === "function") call(listener, signal);
10858
+ else call(listener.handleEvent, listener);
10859
+ }
10860
+ if (typeof signal.onabort === "function") call(signal.onabort, signal);
10861
+ };
10862
+ return { signal, abort };
10863
+ };
10600
10864
  var addUsage2 = (into, usage) => {
10601
10865
  if (!usage) return;
10602
10866
  const sum = into;
@@ -10604,9 +10868,10 @@ var addUsage2 = (into, usage) => {
10604
10868
  if (typeof value === "number" && Number.isFinite(value)) sum[key] = (sum[key] ?? 0) + value;
10605
10869
  }
10606
10870
  };
10607
- var runPipelineGraph = async (plan, runNode, options, onAbort) => {
10871
+ var runPipelineGraph = async (plan, runNode, options) => {
10608
10872
  const { definition } = plan;
10609
- const controller = new AbortController();
10873
+ const onAbort = options.onAbort ?? "reject";
10874
+ const stopper = createStopper();
10610
10875
  let halted;
10611
10876
  let halt = () => {
10612
10877
  };
@@ -10641,7 +10906,7 @@ ${t.text}`).join("\n\n");
10641
10906
  const onOuterAbort = () => {
10642
10907
  if (halted) return;
10643
10908
  halted = "aborted";
10644
- controller.abort();
10909
+ stopper.abort();
10645
10910
  halt(abortError2());
10646
10911
  };
10647
10912
  const visit = async (nodeId, activations) => {
@@ -10657,7 +10922,7 @@ ${t.text}`).join("\n\n");
10657
10922
  node,
10658
10923
  { request: options.input, from: activations.map((a) => ({ ...a.source })), visit: number },
10659
10924
  {
10660
- signal: controller.signal,
10925
+ signal: stopper.signal,
10661
10926
  pipeline: definition,
10662
10927
  emit: (event) => {
10663
10928
  if (!halted) emit({ ...event, nodeId, visit: number });
@@ -10674,7 +10939,7 @@ ${t.text}`).join("\n\n");
10674
10939
  visit: number,
10675
10940
  error: err instanceof Error ? err.message : String(err)
10676
10941
  });
10677
- controller.abort();
10942
+ stopper.abort();
10678
10943
  halt(failure);
10679
10944
  return;
10680
10945
  }
@@ -10730,7 +10995,8 @@ ${t.text}`).join("\n\n");
10730
10995
  if (record2.live === 0) terminals.push(record2);
10731
10996
  }
10732
10997
  };
10733
- const deferred = (nodeId, all) => (plan.nodes.get(nodeId)?.join ?? "all") === "all" && all.some((other) => other !== nodeId && plan.reaches(other, nodeId));
10998
+ const deferred = (nodeId, all, reaches = plan.reaches) => (plan.nodes.get(nodeId)?.join ?? "all") === "all" && all.some((other) => other !== nodeId && reaches(other, nodeId));
10999
+ let inPass;
10734
11000
  emit({ type: "pipeline.started", ...definition.name ? { pipeline: definition.name } : {} });
10735
11001
  options.signal?.addEventListener("abort", onOuterAbort, { once: true });
10736
11002
  try {
@@ -10738,6 +11004,10 @@ ${t.text}`).join("\n\n");
10738
11004
  while (pending.size > 0 && !halted) {
10739
11005
  const waiting = [...pending.keys()];
10740
11006
  let ready = waiting.filter((nodeId) => !deferred(nodeId, waiting));
11007
+ if (ready.length === 0) {
11008
+ const reaches = inPass ??= passReach(plan);
11009
+ ready = waiting.filter((nodeId) => !deferred(nodeId, waiting, reaches));
11010
+ }
10741
11011
  if (ready.length === 0) ready = waiting;
10742
11012
  const starting = [];
10743
11013
  for (const nodeId of ready) {
@@ -10825,6 +11095,21 @@ var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, e
10825
11095
  ...outcome.accepted && outcome.choice !== void 0 ? { route: outcome.choice } : {}
10826
11096
  };
10827
11097
  };
11098
+ var pickPipelineRoute = async (node, text, options) => {
11099
+ if (!node.routes?.length) return { usage: normalizeUsage() };
11100
+ const entry = { agent: options.agent, config: options.config };
11101
+ const signal = options.signal ?? new AbortController().signal;
11102
+ const emit = (event) => {
11103
+ try {
11104
+ options.onEvent?.(event);
11105
+ } catch {
11106
+ }
11107
+ };
11108
+ const quick = await pickRouteWithDecisionModel(entry, node, text, signal, emit);
11109
+ if (quick?.route) return quick;
11110
+ const slow = await pickRoute(entry, node, text, signal);
11111
+ return quick ? { ...slow, usage: addUsage(quick.usage, slow.usage) } : slow;
11112
+ };
10828
11113
  var createPipeline = (definition, options) => {
10829
11114
  const plan = preparePipeline(definition);
10830
11115
  const { resolveNode } = options;
@@ -10859,11 +11144,11 @@ var createPipeline = (definition, options) => {
10859
11144
  if (result.stopped || ctx.signal.aborted) throw aborted();
10860
11145
  if (failure !== void 0) throw new Error(failure);
10861
11146
  if (!node.routes?.length) return { text: result.final, usage: result.usage };
10862
- const quick = await pickRouteWithDecisionModel(entry, node, result.final, ctx.signal, ctx.emit);
10863
- const picked = quick?.route ? quick : await pickRoute(entry, node, result.final, ctx.signal).then((slow) => ({
10864
- ...slow,
10865
- usage: quick ? addUsage(quick.usage, slow.usage) : slow.usage
10866
- }));
11147
+ const picked = await pickPipelineRoute(node, result.final, {
11148
+ ...entry,
11149
+ signal: ctx.signal,
11150
+ onEvent: ctx.emit
11151
+ });
10867
11152
  return {
10868
11153
  text: result.final,
10869
11154
  usage: addUsage(result.usage, picked.usage),
@@ -10872,12 +11157,12 @@ var createPipeline = (definition, options) => {
10872
11157
  };
10873
11158
  return {
10874
11159
  definition: plan.definition,
10875
- run: (run) => runPipelineGraph(
10876
- plan,
10877
- options.runNode ?? runWithAgent,
10878
- { input: run.input, signal: run.signal, onEvent: run.onEvent },
10879
- "resolve"
10880
- ),
11160
+ run: (run) => runPipelineGraph(plan, options.runNode ?? runWithAgent, {
11161
+ input: run.input,
11162
+ signal: run.signal,
11163
+ onEvent: run.onEvent,
11164
+ onAbort: "resolve"
11165
+ }),
10881
11166
  close: async () => {
10882
11167
  agents.clear();
10883
11168
  }
@@ -11617,6 +11902,10 @@ var MemoryRunStore = class {
11617
11902
  onStepComplete(snapshot) {
11618
11903
  this.runs.set(snapshot.runId, snapshot);
11619
11904
  }
11905
+ /** A resume started: its attempt is on record before any of its events. */
11906
+ onRunResume(snapshot) {
11907
+ this.runs.set(snapshot.runId, snapshot);
11908
+ }
11620
11909
  onRunComplete(snapshot) {
11621
11910
  if (snapshot.status === "complete" && !this.keepCompleted) this.runs.delete(snapshot.runId);
11622
11911
  else this.runs.set(snapshot.runId, snapshot);
@@ -11667,6 +11956,10 @@ var IndexedDBRunStore = class {
11667
11956
  onStepComplete(snapshot) {
11668
11957
  return this.put(snapshot);
11669
11958
  }
11959
+ /** A resume started: its attempt is on record before any of its events. */
11960
+ onRunResume(snapshot) {
11961
+ return this.put(snapshot);
11962
+ }
11670
11963
  async onRunComplete(snapshot) {
11671
11964
  if (snapshot.status === "complete" && !this.keepCompleted) {
11672
11965
  await this.delete(snapshot.runId);
@@ -11762,9 +12055,13 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
11762
12055
  MCP_SKILL_CONSENTS,
11763
12056
  MCP_SKILL_CONSENT_DEFAULT,
11764
12057
  MCP_SKILL_DESCRIPTION_MAX_CHARS,
12058
+ MCP_SKILL_DIRECTORY_ENTRIES_MAX,
11765
12059
  MCP_SKILL_FILE_MAX_CHARS,
11766
12060
  MCP_SKILL_MAX_RESOURCES,
11767
12061
  MCP_SKILL_MAX_TOTAL_BYTES,
12062
+ MCP_SKILL_SNAPSHOTS_MAX_BYTES,
12063
+ MCP_SKILL_SNAPSHOT_MAX_DEPTH,
12064
+ MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES,
11768
12065
  MCP_SKILL_URI_MAX_CHARS,
11769
12066
  MEDIA_AUDIO_TYPES,
11770
12067
  MEDIA_DEFAULT_MAX_CALLS,
@@ -11786,6 +12083,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
11786
12083
  MemorySkillStore,
11787
12084
  MemoryStore,
11788
12085
  PIPELINE_LIMITS,
12086
+ PIPELINE_ROUTER_SYSTEM,
11789
12087
  PipelineNodeError,
11790
12088
  PipelineValidationError,
11791
12089
  PlanSchema,
@@ -11904,6 +12202,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
11904
12202
  looksLikeJson,
11905
12203
  markCodeExecution,
11906
12204
  markReadOnly,
12205
+ matchPipelineRoute,
11907
12206
  matchRule,
11908
12207
  mcpAppOrigin,
11909
12208
  mcpSkillEntryRefusal,
@@ -11928,12 +12227,15 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
11928
12227
  parseReplannerResponse,
11929
12228
  parseSearchResponse,
11930
12229
  parseSkillMarkdown,
12230
+ pickPipelineRoute,
11931
12231
  pickTier,
11932
12232
  preloadWebLLMModel,
12233
+ preparePipeline,
11933
12234
  promptHintOf,
11934
12235
  renderActiveSkills,
11935
12236
  renderCatalog,
11936
12237
  renderPipelineNodeInput,
12238
+ renderPipelineRoutePrompt,
11937
12239
  renderSearchCatalog,
11938
12240
  renderSkillIndex,
11939
12241
  replanWanted,
@@ -11950,6 +12252,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
11950
12252
  resolveResume,
11951
12253
  resolveStage,
11952
12254
  resolveThinking,
12255
+ runPipelineGraph,
11953
12256
  runToolLoop,
11954
12257
  sanitizeSearchResults,
11955
12258
  schemaHintOf,