@fro.bot/systematic 3.26.4 → 3.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,6 +5,8 @@ import {
5
5
  AgentOverlaySchema,
6
6
  CategoryOverlaySchema,
7
7
  isRecord,
8
+ isPermissionSetting,
9
+ isAgentMode,
8
10
  resolveRouting,
9
11
  loadConfig,
10
12
  loadConfigWithSources,
@@ -15,12 +17,15 @@ import {
15
17
  extractCommandFrontmatter,
16
18
  findSkillsInDir,
17
19
  discoverSkills
18
- } from "./index-1dyb2x0z.js";
20
+ } from "./index-608preny.js";
19
21
 
20
22
  // src/index.ts
23
+ import path8 from "path";
24
+ import { fileURLToPath } from "url";
25
+
26
+ // src/lib/opencode-v1.ts
21
27
  import fs6 from "fs";
22
28
  import path6 from "path";
23
- import { fileURLToPath } from "url";
24
29
 
25
30
  // src/lib/bootstrap.ts
26
31
  import fs from "fs";
@@ -151,12 +156,23 @@ ${content}
151
156
  ${skillUsage}${ruleSection}${profileSection}
152
157
  </SYSTEMATIC_WORKFLOWS>`;
153
158
  }
159
+ function composeBootstrapContent(config, options) {
160
+ const { bundledSkillsDir, profile, usageTemplate } = options;
161
+ return getBootstrapContent(config, {
162
+ bundledSkillsDir,
163
+ usageTemplate,
164
+ worktreePlacementRule: readWorktreePlacementRule(bundledSkillsDir) ?? undefined,
165
+ profileBlock: readHarnessProfile(bundledSkillsDir, profile) ?? undefined
166
+ });
167
+ }
154
168
 
155
169
  // src/lib/config-handler.ts
156
- import fs4 from "fs";
157
170
  import os2 from "os";
158
171
  import path4 from "path";
159
172
 
173
+ // src/lib/asset-plan.ts
174
+ import fs4 from "fs";
175
+
160
176
  // src/lib/agent-overlays.ts
161
177
  import fs2 from "fs";
162
178
  import path2 from "path";
@@ -374,29 +390,7 @@ function loadSkill(skillInfo) {
374
390
  }
375
391
  }
376
392
 
377
- // src/lib/config-handler.ts
378
- function isSystematicAgentConfig(agent) {
379
- const description = agent?.description;
380
- return typeof description === "string" && /\(.* - Systematic\)$/.test(description);
381
- }
382
- function isSystematicCommandConfig(command) {
383
- const description = command?.description;
384
- return typeof description === "string" && description.startsWith("(Systematic) ");
385
- }
386
- function mergeSystematicEntries(existing, emitted, shouldDropExisting) {
387
- const merged = { ...existing ?? {} };
388
- for (const [key, value] of Object.entries(existing ?? {})) {
389
- if (shouldDropExisting(key, value)) {
390
- delete merged[key];
391
- }
392
- }
393
- for (const [key, value] of Object.entries(emitted)) {
394
- if (Object.hasOwn(merged, key))
395
- continue;
396
- merged[key] = value;
397
- }
398
- return merged;
399
- }
393
+ // src/lib/asset-plan.ts
400
394
  function toTitleCase(name) {
401
395
  return name.split("-").map((segment) => segment.length > 0 ? segment.charAt(0).toUpperCase() + segment.slice(1) : segment).join("-");
402
396
  }
@@ -499,7 +493,7 @@ function loadSkillAsCommand(loaded) {
499
493
  config.subtask = loaded.subtask;
500
494
  return config;
501
495
  }
502
- function collectAgents(dir, disabledAgents, nativeAgents, overlays, rawOverlays) {
496
+ function collectAgents(dir, disabledAgents, nativeAgentNames, overlays, rawOverlays) {
503
497
  const agents = {};
504
498
  const agentList = findAgentsInDir(dir);
505
499
  const disabledSet = new Set(disabledAgents);
@@ -507,7 +501,7 @@ function collectAgents(dir, disabledAgents, nativeAgents, overlays, rawOverlays)
507
501
  const id = agentInfo.category ? `${agentInfo.category}/${agentInfo.name}` : agentInfo.name;
508
502
  if (disabledSet.has(agentInfo.name) || disabledSet.has(id))
509
503
  continue;
510
- if (Object.hasOwn(nativeAgents, agentInfo.name))
504
+ if (nativeAgentNames.has(agentInfo.name))
511
505
  continue;
512
506
  const exactOverlay = overlays.agentsByTargetId.get(id);
513
507
  if (exactOverlay?.value.disable === true)
@@ -541,8 +535,11 @@ function applyAgentOverlays(config, agentInfo, overlays, rawOverlays) {
541
535
  });
542
536
  applyAgentOverlayPass(result, categoryOverlay?.value, permissionRules, routing, "category");
543
537
  applyAgentOverlayPass(result, exactOverlay?.value, permissionRules, routing, "agent");
544
- applyPermissionOverlay(result, permissionRules, hasPermissionOverlay);
545
- return result;
538
+ return {
539
+ name: agentInfo.name,
540
+ config: result,
541
+ permission: hasPermissionOverlay ? { kind: "managed", rules: permissionRulesToTriples(permissionRules) } : { kind: "unmanaged" }
542
+ };
546
543
  }
547
544
  function applyAgentOverlayPass(target, overlay, permissionRules, routing, level) {
548
545
  if (routing.source.model?.level === level) {
@@ -568,33 +565,23 @@ function applyRoutingModel(target, model) {
568
565
  target.model = model;
569
566
  }
570
567
  }
571
- function applyPermissionOverlay(target, permissionRules, hasPermissionOverlay) {
572
- if (!hasPermissionOverlay)
573
- return;
574
- const permission = permissionFromRules(permissionRules);
575
- if (permission) {
576
- target.permission = permission;
577
- } else {
578
- delete target.permission;
579
- }
580
- }
581
568
  function overlayControlsPermission(overlay) {
582
569
  return overlay !== undefined && (Object.hasOwn(overlay, "permission") || Object.hasOwn(overlay, "skills"));
583
570
  }
584
- var OVERLAY_ASSIGN_FIELDS = [
585
- "temperature",
586
- "top_p",
587
- "mode",
588
- "color",
589
- "steps",
590
- "hidden"
591
- ];
592
571
  function applyOverlayObjectFields(target, overlay) {
593
- for (const field of OVERLAY_ASSIGN_FIELDS) {
594
- if (Object.hasOwn(overlay, field)) {
595
- target[field] = overlay[field];
596
- }
572
+ if (typeof overlay.temperature === "number") {
573
+ target.temperature = overlay.temperature;
597
574
  }
575
+ if (typeof overlay.top_p === "number")
576
+ target.top_p = overlay.top_p;
577
+ if (isAgentMode(overlay.mode))
578
+ target.mode = overlay.mode;
579
+ if (typeof overlay.color === "string")
580
+ target.color = overlay.color;
581
+ if (typeof overlay.steps === "number")
582
+ target.steps = overlay.steps;
583
+ if (typeof overlay.hidden === "boolean")
584
+ target.hidden = overlay.hidden;
598
585
  }
599
586
  function createPermissionRuleAccumulator() {
600
587
  return new Map;
@@ -615,25 +602,32 @@ function addPermissionRules(accumulator, permission) {
615
602
  }
616
603
  }
617
604
  function addManagedSkillRules(accumulator, skills) {
618
- setPermissionRule(accumulator, "skill", "*", "deny");
605
+ setPermissionRule(accumulator, "skill", "*", "deny", true);
619
606
  for (const skill of skills) {
620
607
  if (typeof skill === "string") {
621
- setPermissionRule(accumulator, "skill", skill, "allow");
608
+ setPermissionRule(accumulator, "skill", skill, "allow", true);
622
609
  }
623
610
  }
624
611
  }
625
- function permissionFromRules(accumulator) {
626
- const permission = {};
627
- for (const [tool, rules] of accumulator) {
628
- permission[tool] = Object.fromEntries(rules);
612
+ function permissionRulesToTriples(accumulator) {
613
+ const triples = [];
614
+ for (const [permission, rules] of accumulator) {
615
+ for (const [pattern, { setting, fromSkillsList }] of rules) {
616
+ triples.push({
617
+ permission,
618
+ pattern,
619
+ setting,
620
+ ...fromSkillsList && { fromSkillsList: true }
621
+ });
622
+ }
629
623
  }
630
- return Object.keys(permission).length > 0 ? permission : undefined;
624
+ return triples;
631
625
  }
632
- function setPermissionRule(accumulator, tool, pattern, setting) {
626
+ function setPermissionRule(accumulator, tool, pattern, setting, fromSkillsList = false) {
633
627
  const rules = accumulator.get(tool) ?? new Map;
634
628
  if (rules.has(pattern))
635
629
  rules.delete(pattern);
636
- rules.set(pattern, setting);
630
+ rules.set(pattern, { setting, fromSkillsList });
637
631
  accumulator.set(tool, rules);
638
632
  }
639
633
  function isPermissionSettingValue(value) {
@@ -704,6 +698,101 @@ function collectEnabledSkillNames(dir, disabledSkills) {
704
698
  const disabledSet = new Set(disabledSkills);
705
699
  return findSkillsInDir(dir).filter((skillInfo) => !disabledSet.has(skillInfo.name)).map((skillInfo) => skillInfo.name);
706
700
  }
701
+ function buildAssetPlan(input) {
702
+ const { config, overlays, bundledSkillsDir, bundledAgentsDir } = input;
703
+ const nativeAgentNames = new Set(input.nativeAgentNames);
704
+ const skillCommands = collectSkillsAsCommands(bundledSkillsDir, config.disabled_skills);
705
+ const enabledSkills = collectEnabledSkillNames(bundledSkillsDir, config.disabled_skills);
706
+ const inventory = buildBundledAgentInventory(bundledAgentsDir, config.disabled_agents);
707
+ const validatedOverlays = validateAgentOverlays({
708
+ inventory,
709
+ overlays,
710
+ nativeAgents: Object.fromEntries(input.nativeAgentNames.map((name) => [name, true])),
711
+ enabledSkills
712
+ });
713
+ const resolvedOverlays = resolveAgentOverlaySet(validatedOverlays);
714
+ const agents = collectAgents(bundledAgentsDir, config.disabled_agents, nativeAgentNames, resolvedOverlays, overlays);
715
+ const bundledCommands = collectCommands(input.bundledCommandsDir, config.disabled_commands);
716
+ const discoveredSkillCommands = config.skills_as_commands !== false ? collectDiscoveredSkillsAsCommands(input.directory, input.homeDir, input.opencodeConfigDir, input.opencodeConfigDirOverride, config.disabled_commands) : {};
717
+ return {
718
+ skillsDir: bundledSkillsDir,
719
+ enabledSkills,
720
+ agents,
721
+ commands: {
722
+ ...bundledCommands,
723
+ ...skillCommands,
724
+ ...discoveredSkillCommands
725
+ }
726
+ };
727
+ }
728
+
729
+ // src/lib/config-handler.ts
730
+ function isSystematicAgentConfig(agent) {
731
+ const description = agent?.description;
732
+ return typeof description === "string" && /\(.* - Systematic\)$/.test(description);
733
+ }
734
+ function isSystematicCommandConfig(command) {
735
+ const description = command?.description;
736
+ return typeof description === "string" && description.startsWith("(Systematic) ");
737
+ }
738
+ function mergeSystematicEntries(existing, emitted, shouldDropExisting) {
739
+ const merged = { ...existing ?? {} };
740
+ for (const [key, value] of Object.entries(existing ?? {})) {
741
+ if (shouldDropExisting(key, value)) {
742
+ delete merged[key];
743
+ }
744
+ }
745
+ for (const [key, value] of Object.entries(emitted)) {
746
+ if (Object.hasOwn(merged, key))
747
+ continue;
748
+ merged[key] = value;
749
+ }
750
+ return merged;
751
+ }
752
+ function foldPermissionRulesToV1Map(rules) {
753
+ const explicitSkillSettings = new Map;
754
+ for (const rule of rules) {
755
+ if (rule.permission === "skill" && !rule.fromSkillsList) {
756
+ explicitSkillSettings.set(rule.pattern, rule.setting);
757
+ }
758
+ }
759
+ const byPermission = new Map;
760
+ const setRule = (permission, pattern, setting) => {
761
+ const patterns = byPermission.get(permission) ?? new Map;
762
+ if (patterns.has(pattern))
763
+ patterns.delete(pattern);
764
+ patterns.set(pattern, setting);
765
+ byPermission.set(permission, patterns);
766
+ };
767
+ for (const { permission, pattern, setting, fromSkillsList } of rules) {
768
+ setRule(permission, pattern, setting);
769
+ if (permission !== "skill" || setting !== "allow" || !fromSkillsList) {
770
+ continue;
771
+ }
772
+ const prefixed = formatSkillCommandName(pattern);
773
+ const explicit = explicitSkillSettings.get(prefixed);
774
+ if (prefixed !== pattern && (explicit ?? "allow") === "allow") {
775
+ setRule(permission, prefixed, setting);
776
+ }
777
+ }
778
+ const folded = {};
779
+ for (const [permission, patterns] of byPermission) {
780
+ folded[permission] = Object.fromEntries(patterns);
781
+ }
782
+ return Object.keys(folded).length > 0 ? folded : undefined;
783
+ }
784
+ function toV1AgentConfig(planned) {
785
+ const result = { ...planned.config };
786
+ if (planned.permission.kind === "unmanaged")
787
+ return result;
788
+ const permission = foldPermissionRulesToV1Map(planned.permission.rules);
789
+ if (permission) {
790
+ result.permission = permission;
791
+ } else {
792
+ delete result.permission;
793
+ }
794
+ return result;
795
+ }
707
796
  function createConfigHandler(deps) {
708
797
  const { directory, bundledSkillsDir, bundledAgentsDir, bundledCommandsDir } = deps;
709
798
  const homeDir = deps.homeDir ?? os2.homedir();
@@ -713,31 +802,78 @@ function createConfigHandler(deps) {
713
802
  const { config: systematicConfig, overlays } = loadConfigWithSources(directory);
714
803
  const existingAgents = { ...config.agent ?? {} };
715
804
  const existingCommands = { ...config.command ?? {} };
716
- const nativeAgents = Object.fromEntries(Object.entries(existingAgents).filter(([, agent]) => !isSystematicAgentConfig(agent)));
717
- const bundledSkills = collectSkillsAsCommands(bundledSkillsDir, systematicConfig.disabled_skills);
718
- const enabledSkillNames = collectEnabledSkillNames(bundledSkillsDir, systematicConfig.disabled_skills);
719
- const inventory = buildBundledAgentInventory(bundledAgentsDir, systematicConfig.disabled_agents);
720
- const validatedOverlays = validateAgentOverlays({
721
- inventory,
805
+ const nativeAgentNames = Object.entries(existingAgents).filter(([, agent]) => !isSystematicAgentConfig(agent)).map(([name]) => name);
806
+ const plan = buildAssetPlan({
807
+ config: systematicConfig,
722
808
  overlays,
723
- nativeAgents,
724
- enabledSkills: enabledSkillNames
809
+ nativeAgentNames,
810
+ directory,
811
+ bundledSkillsDir,
812
+ bundledAgentsDir,
813
+ bundledCommandsDir,
814
+ homeDir,
815
+ opencodeConfigDir,
816
+ opencodeConfigDirOverride
725
817
  });
726
- const resolvedOverlays = resolveAgentOverlaySet(validatedOverlays);
727
- const bundledAgents = collectAgents(bundledAgentsDir, systematicConfig.disabled_agents, nativeAgents, resolvedOverlays, overlays);
728
- const bundledCommands = collectCommands(bundledCommandsDir, systematicConfig.disabled_commands);
729
- const discoveredSkillCommands = systematicConfig.skills_as_commands !== false ? collectDiscoveredSkillsAsCommands(directory, homeDir, opencodeConfigDir, opencodeConfigDirOverride, systematicConfig.disabled_commands) : {};
818
+ const bundledAgents = Object.fromEntries(Object.entries(plan.agents).map(([name, planned]) => [
819
+ name,
820
+ toV1AgentConfig(planned)
821
+ ]));
730
822
  const bundledAgentKeys = new Set(Object.keys(bundledAgents));
731
823
  config.agent = mergeSystematicEntries(existingAgents, bundledAgents, (key, agent) => bundledAgentKeys.has(key) && isSystematicAgentConfig(agent));
732
- const emittedCommands = {
733
- ...bundledCommands,
734
- ...bundledSkills,
735
- ...discoveredSkillCommands
736
- };
737
- config.command = mergeSystematicEntries(existingCommands, emittedCommands, (_key, command) => isSystematicCommandConfig(command));
738
- registerSkillsPaths(config, bundledSkillsDir);
824
+ config.command = mergeSystematicEntries(existingCommands, plan.commands, (_key, command) => isSystematicCommandConfig(command));
825
+ registerSkillsPaths(config, plan.skillsDir);
826
+ denyDisabledSkills(config, systematicConfig.disabled_skills);
739
827
  };
740
828
  }
829
+ var ownedSkillDenies = new WeakMap;
830
+ function readPermissionMap(host) {
831
+ if (isRecord(host.permission))
832
+ return host.permission;
833
+ return typeof host.permission === "string" ? { "*": host.permission } : {};
834
+ }
835
+ function readSkillRuleMap(permission) {
836
+ if (isRecord(permission.skill))
837
+ return permission.skill;
838
+ return typeof permission.skill === "string" ? { "*": permission.skill } : {};
839
+ }
840
+ function skillDenyPatterns(skills) {
841
+ return [...new Set(skills.flatMap((s) => [s, formatSkillCommandName(s)]))];
842
+ }
843
+ function denyDisabledSkills(config, disabledSkills) {
844
+ const host = config;
845
+ const owned = ownedSkillDenies.get(config);
846
+ const current = isRecord(host.permission) ? host.permission : undefined;
847
+ const stillOurs = owned !== undefined && owned.permission === current && owned.skill === current.skill;
848
+ const previous = stillOurs ? owned.patterns : [];
849
+ const wanted = skillDenyPatterns(disabledSkills);
850
+ if (previous.length === 0 && wanted.length === 0) {
851
+ ownedSkillDenies.delete(config);
852
+ return;
853
+ }
854
+ const permission = readPermissionMap(host);
855
+ const skill = readSkillRuleMap(permission);
856
+ for (const pattern of previous) {
857
+ if (skill[pattern] === "deny")
858
+ delete skill[pattern];
859
+ }
860
+ const added = wanted.filter((pattern) => !Object.hasOwn(skill, pattern));
861
+ for (const pattern of added)
862
+ skill[pattern] = "deny";
863
+ if (Object.keys(skill).length > 0)
864
+ permission.skill = skill;
865
+ else
866
+ delete permission.skill;
867
+ if (Object.keys(permission).length > 0)
868
+ host.permission = permission;
869
+ else
870
+ delete host.permission;
871
+ if (added.length > 0) {
872
+ ownedSkillDenies.set(config, { permission, skill, patterns: added });
873
+ } else {
874
+ ownedSkillDenies.delete(config);
875
+ }
876
+ }
741
877
  function registerSkillsPaths(config, skillsDir) {
742
878
  const extended = config;
743
879
  const paths = extended.skills?.paths ?? [];
@@ -942,6 +1078,12 @@ function createSkillOutputStore(options) {
942
1078
  if (now() > entry.expiresAt)
943
1079
  return;
944
1080
  return entry.output;
1081
+ },
1082
+ peek(sessionID, callID) {
1083
+ const entry = entries.get(toKey(sessionID, callID));
1084
+ if (!entry || now() > entry.expiresAt)
1085
+ return;
1086
+ return entry.output;
945
1087
  }
946
1088
  };
947
1089
  }
@@ -1000,6 +1142,7 @@ function restoreCompactedPart(part) {
1000
1142
  const { compacted: _compacted, ...rest } = time;
1001
1143
  state.time = rest;
1002
1144
  }
1145
+ var SKILL_ARGUMENTS_DESCRIPTION = "Raw argument text the user explicitly supplied for this skill, substituted for $ARGUMENTS and $1..$N. Omit to leave those placeholders as written; an explicit empty string substitutes them with nothing. Only pass text the user explicitly supplied; never infer it.";
1003
1146
  function createSkillTool(options) {
1004
1147
  const { bundledSkillsDir, disabledSkills, outputStore } = options;
1005
1148
  const buildDescription = () => buildSkillToolDescription({ bundledSkillsDir, disabledSkills });
@@ -1020,7 +1163,7 @@ function createSkillTool(options) {
1020
1163
  }
1021
1164
  return cachedParameterHint;
1022
1165
  })()),
1023
- arguments: string().optional().describe("Raw argument text the user explicitly supplied for this skill, substituted for $ARGUMENTS and $1..$N. Omit to leave those placeholders as written; an explicit empty string substitutes them with nothing. Only pass text the user explicitly supplied; never infer it.")
1166
+ arguments: string().optional().describe(SKILL_ARGUMENTS_DESCRIPTION)
1024
1167
  },
1025
1168
  async execute(args, context) {
1026
1169
  const requestedName = args.name;
@@ -1049,15 +1192,48 @@ function createSkillTool(options) {
1049
1192
  }
1050
1193
  };
1051
1194
  }
1195
+ function createSkillToolDescriptor(options) {
1196
+ const { bundledSkillsDir, disabledSkills } = options;
1197
+ return {
1198
+ name: SKILL_TOOL_NAME,
1199
+ description: buildSkillToolDescription({
1200
+ bundledSkillsDir,
1201
+ disabledSkills
1202
+ }),
1203
+ input: {
1204
+ type: "object",
1205
+ properties: {
1206
+ name: {
1207
+ type: "string",
1208
+ description: buildSkillToolParameterHint({
1209
+ bundledSkillsDir,
1210
+ disabledSkills
1211
+ })
1212
+ },
1213
+ arguments: {
1214
+ type: "string",
1215
+ description: SKILL_ARGUMENTS_DESCRIPTION
1216
+ }
1217
+ },
1218
+ required: ["name"],
1219
+ additionalProperties: false
1220
+ },
1221
+ load(args) {
1222
+ const matched = resolveSkill({ bundledSkillsDir, disabledSkills }, args.name);
1223
+ const { output, dir } = buildSkillContentOutput(matched, args.arguments);
1224
+ return {
1225
+ skillName: matched.name,
1226
+ prefixedName: matched.prefixedName,
1227
+ title: `Loaded skill: ${matched.prefixedName}`,
1228
+ output,
1229
+ dir
1230
+ };
1231
+ }
1232
+ };
1233
+ }
1052
1234
 
1053
- // src/index.ts
1054
- var __dirname2 = path6.dirname(fileURLToPath(import.meta.url));
1055
- var packageRoot = path6.resolve(__dirname2, "..");
1056
- var bundledSkillsDir = path6.join(packageRoot, "skills");
1057
- var bundledAgentsDir = path6.join(packageRoot, "agents");
1058
- var bundledCommandsDir = path6.join(packageRoot, "commands");
1059
- var packageJsonPath = path6.join(packageRoot, "package.json");
1060
- var getPackageVersion = () => {
1235
+ // src/lib/opencode-v1.ts
1236
+ var getPackageVersion = (packageJsonPath) => {
1061
1237
  try {
1062
1238
  if (!fs6.existsSync(packageJsonPath))
1063
1239
  return "unknown";
@@ -1068,15 +1244,18 @@ var getPackageVersion = () => {
1068
1244
  return "unknown";
1069
1245
  }
1070
1246
  };
1071
- var initializePlugin = async ({ client, directory }) => {
1247
+ var createOpenCodeV1Hooks = async ({ client, directory }, { packageRoot }) => {
1248
+ const bundledSkillsDir = path6.join(packageRoot, "skills");
1249
+ const bundledAgentsDir = path6.join(packageRoot, "agents");
1250
+ const bundledCommandsDir = path6.join(packageRoot, "commands");
1251
+ const packageJsonPath = path6.join(packageRoot, "package.json");
1072
1252
  let hasLoggedInit = false;
1073
1253
  let userOutputLimitSet = false;
1074
1254
  const skillOutputStore = createSkillOutputStore();
1075
1255
  const config = loadConfig(directory);
1076
- const bootstrapContent = getBootstrapContent(config, {
1256
+ const bootstrapContent = composeBootstrapContent(config, {
1077
1257
  bundledSkillsDir,
1078
- worktreePlacementRule: readWorktreePlacementRule(bundledSkillsDir) ?? undefined,
1079
- profileBlock: readHarnessProfile(bundledSkillsDir, "opencode") ?? undefined
1258
+ profile: "opencode"
1080
1259
  });
1081
1260
  const configHandler = createConfigHandler({
1082
1261
  directory,
@@ -1112,7 +1291,7 @@ var initializePlugin = async ({ client, directory }) => {
1112
1291
  "experimental.chat.system.transform": async (_input, output) => {
1113
1292
  if (!hasLoggedInit) {
1114
1293
  hasLoggedInit = true;
1115
- const packageVersion = getPackageVersion();
1294
+ const packageVersion = getPackageVersion(packageJsonPath);
1116
1295
  try {
1117
1296
  await client.app.log({
1118
1297
  body: {
@@ -1151,10 +1330,551 @@ var initializePlugin = async ({ client, directory }) => {
1151
1330
  };
1152
1331
  return hooks;
1153
1332
  };
1154
- var SystematicPlugin = async (input) => {
1155
- return initializePlugin(input);
1333
+
1334
+ // src/lib/opencode-v2.ts
1335
+ import os3 from "os";
1336
+ import path7 from "path";
1337
+
1338
+ // src/lib/opencode-v2-bootstrap.ts
1339
+ var BOOTSTRAP_ENTRY_KEY = "systematic.bootstrap";
1340
+ var BOOTSTRAP_MAX_BYTES = 256 * 1024;
1341
+ var REMEMBERED_SESSIONS = 512;
1342
+ var OPENCODE_V2_USAGE_TEMPLATE = `**Skills naming:**
1343
+ - Systematic bundled skills use the \`systematic:\` prefix (e.g., \`systematic:onboarding\`)
1344
+ - Workflow skills with their own namespace keep it (e.g., \`ce:brainstorm\`)
1345
+ - Skills can also be invoked without prefix if unambiguous
1346
+
1347
+ **Skills usage:**
1348
+ - Use \`systematic_skill\` to load Systematic bundled skills; pass \`arguments\` only when the user supplied them
1349
+ - Use the \`skill\` tool, which takes the skill \`id\`, for non-Systematic skills
1350
+
1351
+ **Skills location:**
1352
+ Bundled skills ship with the Systematic plugin and are discoverable via \`systematic_skill\`.`;
1353
+ function entryValueBytes(content) {
1354
+ return new TextEncoder().encode(JSON.stringify(content)).length;
1355
+ }
1356
+ function sessionIdOf(event) {
1357
+ if (!isRecord(event))
1358
+ return;
1359
+ return typeof event.sessionID === "string" ? event.sessionID : undefined;
1360
+ }
1361
+ var installBootstrap = async ({
1362
+ ctx,
1363
+ snapshot,
1364
+ guard,
1365
+ report
1366
+ }) => {
1367
+ const content = snapshot.bootstrapContent;
1368
+ if (content === null)
1369
+ return;
1370
+ const bytes = entryValueBytes(content);
1371
+ if (bytes > BOOTSTRAP_MAX_BYTES) {
1372
+ report(`the bootstrap is ${bytes} bytes, over the ${BOOTSTRAP_MAX_BYTES} byte limit for an instruction entry; not injecting it`);
1373
+ return;
1374
+ }
1375
+ const done = new Set;
1376
+ const reported = new Set;
1377
+ const put = async (sessionID) => {
1378
+ try {
1379
+ await ctx.session.instructions.entry.put({
1380
+ sessionID,
1381
+ key: BOOTSTRAP_ENTRY_KEY,
1382
+ value: content
1383
+ });
1384
+ } catch (error) {
1385
+ const message = error instanceof Error ? error.message : "unknown error";
1386
+ if (!reported.has(message)) {
1387
+ reported.add(message);
1388
+ report(`bootstrap could not be put for a session: ${message}`);
1389
+ }
1390
+ return;
1391
+ }
1392
+ done.add(sessionID);
1393
+ if (done.size > REMEMBERED_SESSIONS) {
1394
+ const oldest = done.values().next().value;
1395
+ if (oldest !== undefined)
1396
+ done.delete(oldest);
1397
+ }
1398
+ };
1399
+ const onPrompt = guard.async("bootstrap prompt hook", async (event) => {
1400
+ const sessionID = sessionIdOf(event);
1401
+ if (sessionID === undefined || done.has(sessionID))
1402
+ return;
1403
+ await put(sessionID);
1404
+ });
1405
+ await guard.async("bootstrap registration", () => ctx.session.hook("prompt", onPrompt))();
1406
+ };
1407
+
1408
+ // src/lib/opencode-v2-commands.ts
1409
+ function createCommandRuntime(ctx, report) {
1410
+ return { ctx, report, reported: new Set };
1411
+ }
1412
+ function reportOnce(runtime, key, message) {
1413
+ if (runtime.reported.has(key))
1414
+ return;
1415
+ runtime.reported.add(key);
1416
+ runtime.report(message);
1417
+ }
1418
+ function declaredRouting(planned) {
1419
+ if (planned.agent !== undefined)
1420
+ return "agent";
1421
+ if (planned.model !== undefined)
1422
+ return "model";
1423
+ if (planned.subtask !== undefined)
1424
+ return "subtask";
1425
+ return;
1426
+ }
1427
+ function refusalMessage(name, field) {
1428
+ return `Systematic command "${name}" declares ${field}, which OpenCode v2 plugin commands cannot route. Define it as an OpenCode command in Markdown or JSON to choose its agent or model.`;
1429
+ }
1430
+ async function submit(runtime, planned, invocation) {
1431
+ const text = substituteSkillArguments(planned.template, invocation.prompt.text);
1432
+ const { files, agents, skills } = invocation.prompt;
1433
+ await runtime.ctx.session.prompt({
1434
+ sessionID: invocation.sessionID,
1435
+ text,
1436
+ files,
1437
+ agents,
1438
+ skills,
1439
+ delivery: invocation.delivery
1440
+ });
1441
+ }
1442
+ function buildCommand(runtime, name, planned) {
1443
+ return {
1444
+ name,
1445
+ ...planned.description === undefined ? {} : { description: planned.description },
1446
+ async execute(invocation) {
1447
+ const field = declaredRouting(planned);
1448
+ if (field !== undefined) {
1449
+ const message = refusalMessage(name, field);
1450
+ reportOnce(runtime, `refused:${name}`, message);
1451
+ throw new Error(message);
1452
+ }
1453
+ try {
1454
+ await submit(runtime, planned, invocation);
1455
+ } catch (error) {
1456
+ runtime.report(`command "${name}" failed: ${error instanceof Error ? error.message : "unknown error"}`);
1457
+ throw error;
1458
+ }
1459
+ }
1460
+ };
1461
+ }
1462
+ var installCommands = async ({
1463
+ ctx,
1464
+ snapshot,
1465
+ guard,
1466
+ report
1467
+ }) => {
1468
+ const builtIns = await guard.async("command list", async () => new Set((await ctx.command.list()).data.map((entry) => entry.name)))() ?? new Set;
1469
+ const runtime = createCommandRuntime(ctx, report);
1470
+ const transform = guard.sync("command transform", (editor) => {
1471
+ for (const [name, planned] of Object.entries(snapshot.plan.commands)) {
1472
+ if (builtIns.has(name)) {
1473
+ reportOnce(runtime, `built-in:${name}`, `command "${name}" has the name of a built-in command; not registering the bundled one`);
1474
+ continue;
1475
+ }
1476
+ guard.sync(`command "${name}"`, () => {
1477
+ editor.add(buildCommand(runtime, name, planned));
1478
+ })();
1479
+ }
1480
+ });
1481
+ await guard.async("command registration", () => ctx.command.transform(transform))();
1482
+ };
1483
+
1484
+ // src/lib/opencode-v2-permissions.ts
1485
+ var RENAMED_ACTIONS = new Map([
1486
+ ["bash", "shell"],
1487
+ ["task", "subagent"]
1488
+ ]);
1489
+ var DROPPED_ACTIONS = new Set(["doom_loop", "lsp"]);
1490
+ var SKILL_PREFIX2 = "systematic:";
1491
+ function skillResource(pattern) {
1492
+ return pattern.startsWith(SKILL_PREFIX2) ? pattern.slice(SKILL_PREFIX2.length) : pattern;
1493
+ }
1494
+ function translatePermissionRules(rules) {
1495
+ const translated = [];
1496
+ for (const { permission, pattern, setting } of rules) {
1497
+ if (DROPPED_ACTIONS.has(permission))
1498
+ continue;
1499
+ translated.push({
1500
+ action: RENAMED_ACTIONS.get(permission) ?? permission,
1501
+ resource: permission === "skill" ? skillResource(pattern) : pattern,
1502
+ effect: setting
1503
+ });
1504
+ }
1505
+ return translated;
1506
+ }
1507
+ function permissionMapToTriples(permission) {
1508
+ if (!isRecord(permission))
1509
+ return [];
1510
+ const triples = [];
1511
+ for (const [tool, rule] of Object.entries(permission)) {
1512
+ if (isPermissionSetting(rule)) {
1513
+ triples.push({ permission: tool, pattern: "*", setting: rule });
1514
+ continue;
1515
+ }
1516
+ if (!isRecord(rule))
1517
+ continue;
1518
+ for (const [pattern, setting] of Object.entries(rule)) {
1519
+ if (isPermissionSetting(setting)) {
1520
+ triples.push({ permission: tool, pattern, setting });
1521
+ }
1522
+ }
1523
+ }
1524
+ return triples;
1525
+ }
1526
+
1527
+ // src/lib/opencode-v2-skills.ts
1528
+ import fs7 from "fs";
1529
+ var RESTORE_TTL_MS = 24 * 60 * 60 * 1000;
1530
+ var RESTORE_MAX_ENTRIES = 32;
1531
+ function readBundledSkills(bundledSkillsDir, enabledSkills, report) {
1532
+ const enabled = new Set(enabledSkills);
1533
+ const records = [];
1534
+ const infos = findSkillsInDir(bundledSkillsDir).filter((info) => enabled.has(info.name)).sort((a, b) => a.name.localeCompare(b.name));
1535
+ for (const info of infos) {
1536
+ try {
1537
+ const { body } = parseFrontmatter(fs7.readFileSync(info.skillFile, "utf8"));
1538
+ records.push({
1539
+ id: info.name,
1540
+ name: info.name,
1541
+ ...info.description === "" ? {} : { description: info.description },
1542
+ ...info.disableModelInvocation === true ? { autoinvoke: false } : {},
1543
+ path: info.skillFile,
1544
+ content: body.trim()
1545
+ });
1546
+ } catch (error) {
1547
+ report(`skill "${info.name}" could not be read; leaving it out: ${error instanceof Error ? error.message : "unknown error"}`);
1548
+ }
1549
+ }
1550
+ return records;
1551
+ }
1552
+ function addBundledSkill(editor, skill, reported, report) {
1553
+ if (editor.get(skill.id) !== undefined) {
1554
+ if (reported.has(skill.id))
1555
+ return;
1556
+ reported.add(skill.id);
1557
+ report(`skill "${skill.id}" is already defined by another plugin; skipping the bundled skill`);
1558
+ return;
1559
+ }
1560
+ editor.add(skill);
1561
+ }
1562
+ function parseToolInput(input) {
1563
+ if (!isRecord(input) || typeof input.name !== "string") {
1564
+ throw new Error('systematic_skill requires a "name" string');
1565
+ }
1566
+ if (input.arguments !== undefined && typeof input.arguments !== "string") {
1567
+ throw new Error('systematic_skill "arguments" must be a string');
1568
+ }
1569
+ return { name: input.name, arguments: input.arguments };
1570
+ }
1571
+ function restoreSkillResults(store, event) {
1572
+ if (!isRecord(event) || typeof event.sessionID !== "string")
1573
+ return;
1574
+ const { sessionID, messages } = event;
1575
+ if (!Array.isArray(messages))
1576
+ return;
1577
+ for (const message of messages) {
1578
+ if (!isRecord(message) || message.role !== "tool")
1579
+ continue;
1580
+ if (!Array.isArray(message.content))
1581
+ continue;
1582
+ for (const part of message.content)
1583
+ restorePart(store, sessionID, part);
1584
+ }
1585
+ }
1586
+ function restorePart(store, sessionID, part) {
1587
+ if (!isRecord(part) || part.type !== "tool-result")
1588
+ return;
1589
+ if (part.name !== SKILL_TOOL_NAME || typeof part.id !== "string")
1590
+ return;
1591
+ const full = store.peek(sessionID, part.id);
1592
+ if (full === undefined)
1593
+ return;
1594
+ part.result = { type: "content", value: [{ type: "text", text: full }] };
1595
+ }
1596
+ function createToolDefinition(ctx, descriptor, store, guard) {
1597
+ return {
1598
+ name: descriptor.name,
1599
+ description: descriptor.description,
1600
+ input: descriptor.input,
1601
+ options: { codemode: false },
1602
+ async execute(input, context) {
1603
+ const loaded = descriptor.load(parseToolInput(input));
1604
+ await ctx.permission.assert({
1605
+ sessionID: context.sessionID,
1606
+ agent: context.agent,
1607
+ action: "skill",
1608
+ resources: [loaded.skillName],
1609
+ source: {
1610
+ type: "tool",
1611
+ messageID: context.messageID,
1612
+ id: context.id
1613
+ }
1614
+ });
1615
+ const progress = guard.async("skill progress", () => context.progress({
1616
+ title: loaded.title,
1617
+ name: loaded.prefixedName,
1618
+ dir: loaded.dir
1619
+ }));
1620
+ await progress();
1621
+ store.put(context.sessionID, context.id, loaded.output);
1622
+ return {
1623
+ content: loaded.output,
1624
+ metadata: { name: loaded.prefixedName, dir: loaded.dir }
1625
+ };
1626
+ }
1627
+ };
1628
+ }
1629
+ var installSkills = async ({
1630
+ ctx,
1631
+ snapshot,
1632
+ guard,
1633
+ report
1634
+ }) => {
1635
+ const bundledSkills = readBundledSkills(`${snapshot.packageRoot}/skills`, snapshot.plan.enabledSkills, report);
1636
+ const descriptor = createSkillToolDescriptor({
1637
+ bundledSkillsDir: `${snapshot.packageRoot}/skills`,
1638
+ disabledSkills: snapshot.config.disabled_skills
1639
+ });
1640
+ const store = createSkillOutputStore({
1641
+ maxEntries: RESTORE_MAX_ENTRIES,
1642
+ ttlMs: RESTORE_TTL_MS
1643
+ });
1644
+ const reported = new Set;
1645
+ const skillTransform = guard.sync("skill transform", (editor) => {
1646
+ for (const skill of bundledSkills) {
1647
+ const add = guard.sync(`skill "${skill.id}"`, addBundledSkill);
1648
+ add(editor, skill, reported, report);
1649
+ }
1650
+ });
1651
+ const toolTransform = guard.sync("tool transform", (editor) => {
1652
+ if (editor.get(descriptor.name) !== undefined) {
1653
+ if (!reported.has(descriptor.name)) {
1654
+ reported.add(descriptor.name);
1655
+ report(`tool "${descriptor.name}" is already registered by another plugin; not registering the bundled one`);
1656
+ }
1657
+ return;
1658
+ }
1659
+ editor.add(createToolDefinition(ctx, descriptor, store, guard));
1660
+ });
1661
+ const restore = guard.sync("skill output restore", (event) => {
1662
+ restoreSkillResults(store, event);
1663
+ });
1664
+ await guard.async("skill registration", () => ctx.skill.transform(skillTransform))();
1665
+ await guard.async("tool registration", () => ctx.tool.transform(toolTransform))();
1666
+ await guard.async("skill output restore registration", () => ctx.session.hook("context", restore))();
1667
+ };
1668
+
1669
+ // src/lib/opencode-v2.ts
1670
+ var DIAGNOSTIC_PREFIX = "systematic:";
1671
+ function describeFailure(error) {
1672
+ return error instanceof Error ? error.message : "unknown error";
1673
+ }
1674
+ function reportFailure(label, error) {
1675
+ console.error(`${DIAGNOSTIC_PREFIX} ${label} failed: ${describeFailure(error)}`);
1676
+ }
1677
+ function createSafeGuard() {
1678
+ return {
1679
+ sync(label, callback) {
1680
+ return (...args) => {
1681
+ try {
1682
+ return callback(...args);
1683
+ } catch (error) {
1684
+ reportFailure(label, error);
1685
+ return;
1686
+ }
1687
+ };
1688
+ },
1689
+ async(label, callback) {
1690
+ return async (...args) => {
1691
+ try {
1692
+ return await callback(...args);
1693
+ } catch (error) {
1694
+ reportFailure(label, error);
1695
+ return;
1696
+ }
1697
+ };
1698
+ }
1699
+ };
1700
+ }
1701
+ var HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
1702
+ function parseModel(model, variant) {
1703
+ const slash = model.indexOf("/");
1704
+ if (slash <= 0 || slash === model.length - 1)
1705
+ return;
1706
+ const providerID = model.slice(0, slash);
1707
+ const id = model.slice(slash + 1);
1708
+ return variant === undefined ? { providerID, id } : { providerID, id, variant };
1709
+ }
1710
+ function writeAgentModel(agent, planned, reported) {
1711
+ const { model, variant } = planned.config;
1712
+ if (model === undefined)
1713
+ return;
1714
+ const parsed = parseModel(model, typeof variant === "string" ? variant : undefined);
1715
+ if (parsed !== undefined) {
1716
+ agent.model = parsed;
1717
+ return;
1718
+ }
1719
+ const key = `model:${planned.name}`;
1720
+ if (reported.has(key))
1721
+ return;
1722
+ reported.add(key);
1723
+ console.error(`${DIAGNOSTIC_PREFIX} agent "${planned.name}" has model "${model}", which is not provider/model; leaving its model unset`);
1724
+ }
1725
+ function agentPermissionRules(planned) {
1726
+ return translatePermissionRules(planned.permission.kind === "managed" ? planned.permission.rules : permissionMapToTriples(planned.config.permission));
1727
+ }
1728
+ function writeAgentFields(agent, planned, reported) {
1729
+ const { config } = planned;
1730
+ if (config.prompt !== undefined)
1731
+ agent.system = config.prompt;
1732
+ if (config.description !== undefined)
1733
+ agent.description = config.description;
1734
+ agent.mode = config.mode ?? "all";
1735
+ if (typeof config.hidden === "boolean")
1736
+ agent.hidden = config.hidden;
1737
+ if (typeof config.steps === "number")
1738
+ agent.steps = config.steps;
1739
+ if (config.color !== undefined && HEX_COLOR.test(config.color)) {
1740
+ agent.color = config.color;
1741
+ }
1742
+ if (config.temperature !== undefined) {
1743
+ agent.request.body.temperature = config.temperature;
1744
+ }
1745
+ if (config.top_p !== undefined)
1746
+ agent.request.body.top_p = config.top_p;
1747
+ writeAgentModel(agent, planned, reported);
1748
+ agent.permissions.push(...agentPermissionRules(planned));
1749
+ }
1750
+ function applyPlannedAgent(editor, planned, reported = new Set) {
1751
+ if (planned.config.disable === true)
1752
+ return;
1753
+ if (editor.get(planned.name) !== undefined) {
1754
+ const key = `clash:${planned.name}`;
1755
+ if (reported.has(key))
1756
+ return;
1757
+ reported.add(key);
1758
+ console.error(`${DIAGNOSTIC_PREFIX} agent "${planned.name}" is already defined by the host or another plugin; skipping the bundled agent`);
1759
+ return;
1760
+ }
1761
+ editor.update(planned.name, (agent) => {
1762
+ writeAgentFields(agent, planned, reported);
1763
+ });
1764
+ }
1765
+ var installAgents = async ({ ctx, snapshot, guard }) => {
1766
+ const reported = new Set;
1767
+ await ctx.agent.transform(guard.sync("agent transform", (editor) => {
1768
+ for (const planned of Object.values(snapshot.plan.agents)) {
1769
+ const apply = guard.sync(`agent "${planned.name}"`, applyPlannedAgent);
1770
+ apply(editor, planned, reported);
1771
+ }
1772
+ }));
1773
+ };
1774
+ var DEFAULT_INSTALLERS = {
1775
+ agents: installAgents,
1776
+ skills: installSkills,
1777
+ commands: installCommands,
1778
+ bootstrap: installBootstrap
1779
+ };
1780
+ var INSTALLER_ORDER = [
1781
+ "agents",
1782
+ "skills",
1783
+ "commands",
1784
+ "bootstrap"
1785
+ ];
1786
+ function resolveProjectDirectory(ctx) {
1787
+ const directory = ctx.location?.directory;
1788
+ return typeof directory === "string" && directory.length > 0 ? directory : undefined;
1789
+ }
1790
+ function reportDiagnostic(message) {
1791
+ console.error(`${DIAGNOSTIC_PREFIX} ${message}`);
1792
+ }
1793
+ function messageOf(error) {
1794
+ return error instanceof Error ? error.message : "unknown error";
1795
+ }
1796
+ function composeBootstrapOrNull(config, bundledSkillsDir) {
1797
+ try {
1798
+ return composeBootstrapContent(config, {
1799
+ bundledSkillsDir,
1800
+ profile: "opencode-v2",
1801
+ usageTemplate: OPENCODE_V2_USAGE_TEMPLATE
1802
+ });
1803
+ } catch (error) {
1804
+ reportDiagnostic(`bootstrap could not be read: ${messageOf(error)}`);
1805
+ return null;
1806
+ }
1807
+ }
1808
+ function buildSnapshot(ctx, deps) {
1809
+ const { packageRoot } = deps;
1810
+ const homeDir = deps.homeDir ?? os3.homedir();
1811
+ const opencodeConfigDir = deps.opencodeConfigDir ?? path7.join(homeDir, ".config/opencode");
1812
+ const opencodeConfigDirOverride = process.env.OPENCODE_CONFIG_DIR?.trim() ? process.env.OPENCODE_CONFIG_DIR : undefined;
1813
+ const bundledSkillsDir = path7.join(packageRoot, "skills");
1814
+ const projectDirectory = resolveProjectDirectory(ctx);
1815
+ if (projectDirectory === undefined) {
1816
+ reportDiagnostic("the host gave no project directory; loading user-level config only");
1817
+ }
1818
+ const directory = projectDirectory ?? homeDir;
1819
+ const { config, overlays } = loadConfigWithSources(directory, {
1820
+ homeDir,
1821
+ userConfigDir: opencodeConfigDir,
1822
+ includeProject: projectDirectory !== undefined
1823
+ });
1824
+ let plan;
1825
+ try {
1826
+ plan = buildAssetPlan({
1827
+ config,
1828
+ overlays,
1829
+ nativeAgentNames: [],
1830
+ directory,
1831
+ bundledSkillsDir,
1832
+ bundledAgentsDir: path7.join(packageRoot, "agents"),
1833
+ bundledCommandsDir: path7.join(packageRoot, "commands"),
1834
+ homeDir,
1835
+ opencodeConfigDir,
1836
+ opencodeConfigDirOverride
1837
+ });
1838
+ } catch (error) {
1839
+ reportDiagnostic(`asset plan could not be built: ${messageOf(error)}`);
1840
+ return;
1841
+ }
1842
+ const bootstrapContent = composeBootstrapOrNull(config, bundledSkillsDir);
1843
+ return Object.freeze({
1844
+ config,
1845
+ plan,
1846
+ bootstrapContent,
1847
+ directory,
1848
+ packageRoot
1849
+ });
1850
+ }
1851
+ async function setupOpenCodeV2(ctx, deps) {
1852
+ const snapshot = buildSnapshot(ctx, deps);
1853
+ if (snapshot === undefined)
1854
+ return;
1855
+ const guard = createSafeGuard();
1856
+ const report = reportDiagnostic;
1857
+ const installers = { ...DEFAULT_INSTALLERS, ...deps.installers };
1858
+ for (const slot of INSTALLER_ORDER) {
1859
+ const install = guard.async(`${slot} installer`, installers[slot]);
1860
+ await install({ ctx, snapshot, guard, report });
1861
+ }
1862
+ }
1863
+
1864
+ // src/index.ts
1865
+ var __dirname2 = path8.dirname(fileURLToPath(import.meta.url));
1866
+ var packageRoot = path8.resolve(__dirname2, "..");
1867
+ var systematicPlugin = {
1868
+ id: "systematic",
1869
+ async setup(ctx) {
1870
+ if (!ctx.location || !ctx.session)
1871
+ return;
1872
+ await setupOpenCodeV2(ctx, { packageRoot });
1873
+ },
1874
+ server: async (input) => createOpenCodeV1Hooks(input, { packageRoot })
1156
1875
  };
1157
- var src_default = SystematicPlugin;
1876
+ var entry = systematicPlugin;
1877
+ var src_default = entry;
1158
1878
  export {
1159
1879
  src_default as default
1160
1880
  };