@fro.bot/systematic 3.26.3 → 3.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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;
@@ -622,12 +609,14 @@ function addManagedSkillRules(accumulator, skills) {
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] of rules) {
616
+ triples.push({ permission, pattern, setting });
617
+ }
629
618
  }
630
- return Object.keys(permission).length > 0 ? permission : undefined;
619
+ return triples;
631
620
  }
632
621
  function setPermissionRule(accumulator, tool, pattern, setting) {
633
622
  const rules = accumulator.get(tool) ?? new Map;
@@ -704,6 +693,84 @@ function collectEnabledSkillNames(dir, disabledSkills) {
704
693
  const disabledSet = new Set(disabledSkills);
705
694
  return findSkillsInDir(dir).filter((skillInfo) => !disabledSet.has(skillInfo.name)).map((skillInfo) => skillInfo.name);
706
695
  }
696
+ function buildAssetPlan(input) {
697
+ const { config, overlays, bundledSkillsDir, bundledAgentsDir } = input;
698
+ const nativeAgentNames = new Set(input.nativeAgentNames);
699
+ const skillCommands = collectSkillsAsCommands(bundledSkillsDir, config.disabled_skills);
700
+ const enabledSkills = collectEnabledSkillNames(bundledSkillsDir, config.disabled_skills);
701
+ const inventory = buildBundledAgentInventory(bundledAgentsDir, config.disabled_agents);
702
+ const validatedOverlays = validateAgentOverlays({
703
+ inventory,
704
+ overlays,
705
+ nativeAgents: Object.fromEntries(input.nativeAgentNames.map((name) => [name, true])),
706
+ enabledSkills
707
+ });
708
+ const resolvedOverlays = resolveAgentOverlaySet(validatedOverlays);
709
+ const agents = collectAgents(bundledAgentsDir, config.disabled_agents, nativeAgentNames, resolvedOverlays, overlays);
710
+ const bundledCommands = collectCommands(input.bundledCommandsDir, config.disabled_commands);
711
+ const discoveredSkillCommands = config.skills_as_commands !== false ? collectDiscoveredSkillsAsCommands(input.directory, input.homeDir, input.opencodeConfigDir, input.opencodeConfigDirOverride, config.disabled_commands) : {};
712
+ return {
713
+ skillsDir: bundledSkillsDir,
714
+ enabledSkills,
715
+ agents,
716
+ commands: {
717
+ ...bundledCommands,
718
+ ...skillCommands,
719
+ ...discoveredSkillCommands
720
+ }
721
+ };
722
+ }
723
+
724
+ // src/lib/config-handler.ts
725
+ function isSystematicAgentConfig(agent) {
726
+ const description = agent?.description;
727
+ return typeof description === "string" && /\(.* - Systematic\)$/.test(description);
728
+ }
729
+ function isSystematicCommandConfig(command) {
730
+ const description = command?.description;
731
+ return typeof description === "string" && description.startsWith("(Systematic) ");
732
+ }
733
+ function mergeSystematicEntries(existing, emitted, shouldDropExisting) {
734
+ const merged = { ...existing ?? {} };
735
+ for (const [key, value] of Object.entries(existing ?? {})) {
736
+ if (shouldDropExisting(key, value)) {
737
+ delete merged[key];
738
+ }
739
+ }
740
+ for (const [key, value] of Object.entries(emitted)) {
741
+ if (Object.hasOwn(merged, key))
742
+ continue;
743
+ merged[key] = value;
744
+ }
745
+ return merged;
746
+ }
747
+ function foldPermissionRulesToV1Map(rules) {
748
+ const byPermission = new Map;
749
+ for (const { permission, pattern, setting } of rules) {
750
+ const patterns = byPermission.get(permission) ?? new Map;
751
+ if (patterns.has(pattern))
752
+ patterns.delete(pattern);
753
+ patterns.set(pattern, setting);
754
+ byPermission.set(permission, patterns);
755
+ }
756
+ const folded = {};
757
+ for (const [permission, patterns] of byPermission) {
758
+ folded[permission] = Object.fromEntries(patterns);
759
+ }
760
+ return Object.keys(folded).length > 0 ? folded : undefined;
761
+ }
762
+ function toV1AgentConfig(planned) {
763
+ const result = { ...planned.config };
764
+ if (planned.permission.kind === "unmanaged")
765
+ return result;
766
+ const permission = foldPermissionRulesToV1Map(planned.permission.rules);
767
+ if (permission) {
768
+ result.permission = permission;
769
+ } else {
770
+ delete result.permission;
771
+ }
772
+ return result;
773
+ }
707
774
  function createConfigHandler(deps) {
708
775
  const { directory, bundledSkillsDir, bundledAgentsDir, bundledCommandsDir } = deps;
709
776
  const homeDir = deps.homeDir ?? os2.homedir();
@@ -713,29 +780,27 @@ function createConfigHandler(deps) {
713
780
  const { config: systematicConfig, overlays } = loadConfigWithSources(directory);
714
781
  const existingAgents = { ...config.agent ?? {} };
715
782
  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,
783
+ const nativeAgentNames = Object.entries(existingAgents).filter(([, agent]) => !isSystematicAgentConfig(agent)).map(([name]) => name);
784
+ const plan = buildAssetPlan({
785
+ config: systematicConfig,
722
786
  overlays,
723
- nativeAgents,
724
- enabledSkills: enabledSkillNames
787
+ nativeAgentNames,
788
+ directory,
789
+ bundledSkillsDir,
790
+ bundledAgentsDir,
791
+ bundledCommandsDir,
792
+ homeDir,
793
+ opencodeConfigDir,
794
+ opencodeConfigDirOverride
725
795
  });
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) : {};
796
+ const bundledAgents = Object.fromEntries(Object.entries(plan.agents).map(([name, planned]) => [
797
+ name,
798
+ toV1AgentConfig(planned)
799
+ ]));
730
800
  const bundledAgentKeys = new Set(Object.keys(bundledAgents));
731
801
  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);
802
+ config.command = mergeSystematicEntries(existingCommands, plan.commands, (_key, command) => isSystematicCommandConfig(command));
803
+ registerSkillsPaths(config, plan.skillsDir);
739
804
  };
740
805
  }
741
806
  function registerSkillsPaths(config, skillsDir) {
@@ -942,6 +1007,12 @@ function createSkillOutputStore(options) {
942
1007
  if (now() > entry.expiresAt)
943
1008
  return;
944
1009
  return entry.output;
1010
+ },
1011
+ peek(sessionID, callID) {
1012
+ const entry = entries.get(toKey(sessionID, callID));
1013
+ if (!entry || now() > entry.expiresAt)
1014
+ return;
1015
+ return entry.output;
945
1016
  }
946
1017
  };
947
1018
  }
@@ -1000,6 +1071,7 @@ function restoreCompactedPart(part) {
1000
1071
  const { compacted: _compacted, ...rest } = time;
1001
1072
  state.time = rest;
1002
1073
  }
1074
+ 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
1075
  function createSkillTool(options) {
1004
1076
  const { bundledSkillsDir, disabledSkills, outputStore } = options;
1005
1077
  const buildDescription = () => buildSkillToolDescription({ bundledSkillsDir, disabledSkills });
@@ -1020,7 +1092,7 @@ function createSkillTool(options) {
1020
1092
  }
1021
1093
  return cachedParameterHint;
1022
1094
  })()),
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.")
1095
+ arguments: string().optional().describe(SKILL_ARGUMENTS_DESCRIPTION)
1024
1096
  },
1025
1097
  async execute(args, context) {
1026
1098
  const requestedName = args.name;
@@ -1049,15 +1121,48 @@ function createSkillTool(options) {
1049
1121
  }
1050
1122
  };
1051
1123
  }
1124
+ function createSkillToolDescriptor(options) {
1125
+ const { bundledSkillsDir, disabledSkills } = options;
1126
+ return {
1127
+ name: SKILL_TOOL_NAME,
1128
+ description: buildSkillToolDescription({
1129
+ bundledSkillsDir,
1130
+ disabledSkills
1131
+ }),
1132
+ input: {
1133
+ type: "object",
1134
+ properties: {
1135
+ name: {
1136
+ type: "string",
1137
+ description: buildSkillToolParameterHint({
1138
+ bundledSkillsDir,
1139
+ disabledSkills
1140
+ })
1141
+ },
1142
+ arguments: {
1143
+ type: "string",
1144
+ description: SKILL_ARGUMENTS_DESCRIPTION
1145
+ }
1146
+ },
1147
+ required: ["name"],
1148
+ additionalProperties: false
1149
+ },
1150
+ load(args) {
1151
+ const matched = resolveSkill({ bundledSkillsDir, disabledSkills }, args.name);
1152
+ const { output, dir } = buildSkillContentOutput(matched, args.arguments);
1153
+ return {
1154
+ skillName: matched.name,
1155
+ prefixedName: matched.prefixedName,
1156
+ title: `Loaded skill: ${matched.prefixedName}`,
1157
+ output,
1158
+ dir
1159
+ };
1160
+ }
1161
+ };
1162
+ }
1052
1163
 
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 = () => {
1164
+ // src/lib/opencode-v1.ts
1165
+ var getPackageVersion = (packageJsonPath) => {
1061
1166
  try {
1062
1167
  if (!fs6.existsSync(packageJsonPath))
1063
1168
  return "unknown";
@@ -1068,15 +1173,18 @@ var getPackageVersion = () => {
1068
1173
  return "unknown";
1069
1174
  }
1070
1175
  };
1071
- var initializePlugin = async ({ client, directory }) => {
1176
+ var createOpenCodeV1Hooks = async ({ client, directory }, { packageRoot }) => {
1177
+ const bundledSkillsDir = path6.join(packageRoot, "skills");
1178
+ const bundledAgentsDir = path6.join(packageRoot, "agents");
1179
+ const bundledCommandsDir = path6.join(packageRoot, "commands");
1180
+ const packageJsonPath = path6.join(packageRoot, "package.json");
1072
1181
  let hasLoggedInit = false;
1073
1182
  let userOutputLimitSet = false;
1074
1183
  const skillOutputStore = createSkillOutputStore();
1075
1184
  const config = loadConfig(directory);
1076
- const bootstrapContent = getBootstrapContent(config, {
1185
+ const bootstrapContent = composeBootstrapContent(config, {
1077
1186
  bundledSkillsDir,
1078
- worktreePlacementRule: readWorktreePlacementRule(bundledSkillsDir) ?? undefined,
1079
- profileBlock: readHarnessProfile(bundledSkillsDir, "opencode") ?? undefined
1187
+ profile: "opencode"
1080
1188
  });
1081
1189
  const configHandler = createConfigHandler({
1082
1190
  directory,
@@ -1112,7 +1220,7 @@ var initializePlugin = async ({ client, directory }) => {
1112
1220
  "experimental.chat.system.transform": async (_input, output) => {
1113
1221
  if (!hasLoggedInit) {
1114
1222
  hasLoggedInit = true;
1115
- const packageVersion = getPackageVersion();
1223
+ const packageVersion = getPackageVersion(packageJsonPath);
1116
1224
  try {
1117
1225
  await client.app.log({
1118
1226
  body: {
@@ -1151,10 +1259,551 @@ var initializePlugin = async ({ client, directory }) => {
1151
1259
  };
1152
1260
  return hooks;
1153
1261
  };
1154
- var SystematicPlugin = async (input) => {
1155
- return initializePlugin(input);
1262
+
1263
+ // src/lib/opencode-v2.ts
1264
+ import os3 from "os";
1265
+ import path7 from "path";
1266
+
1267
+ // src/lib/opencode-v2-bootstrap.ts
1268
+ var BOOTSTRAP_ENTRY_KEY = "systematic.bootstrap";
1269
+ var BOOTSTRAP_MAX_BYTES = 256 * 1024;
1270
+ var REMEMBERED_SESSIONS = 512;
1271
+ var OPENCODE_V2_USAGE_TEMPLATE = `**Skills naming:**
1272
+ - Systematic bundled skills use the \`systematic:\` prefix (e.g., \`systematic:onboarding\`)
1273
+ - Workflow skills with their own namespace keep it (e.g., \`ce:brainstorm\`)
1274
+ - Skills can also be invoked without prefix if unambiguous
1275
+
1276
+ **Skills usage:**
1277
+ - Use \`systematic_skill\` to load Systematic bundled skills; pass \`arguments\` only when the user supplied them
1278
+ - Use the \`skill\` tool, which takes the skill \`id\`, for non-Systematic skills
1279
+
1280
+ **Skills location:**
1281
+ Bundled skills ship with the Systematic plugin and are discoverable via \`systematic_skill\`.`;
1282
+ function entryValueBytes(content) {
1283
+ return new TextEncoder().encode(JSON.stringify(content)).length;
1284
+ }
1285
+ function sessionIdOf(event) {
1286
+ if (!isRecord(event))
1287
+ return;
1288
+ return typeof event.sessionID === "string" ? event.sessionID : undefined;
1289
+ }
1290
+ var installBootstrap = async ({
1291
+ ctx,
1292
+ snapshot,
1293
+ guard,
1294
+ report
1295
+ }) => {
1296
+ const content = snapshot.bootstrapContent;
1297
+ if (content === null)
1298
+ return;
1299
+ const bytes = entryValueBytes(content);
1300
+ if (bytes > BOOTSTRAP_MAX_BYTES) {
1301
+ report(`the bootstrap is ${bytes} bytes, over the ${BOOTSTRAP_MAX_BYTES} byte limit for an instruction entry; not injecting it`);
1302
+ return;
1303
+ }
1304
+ const done = new Set;
1305
+ const reported = new Set;
1306
+ const put = async (sessionID) => {
1307
+ try {
1308
+ await ctx.session.instructions.entry.put({
1309
+ sessionID,
1310
+ key: BOOTSTRAP_ENTRY_KEY,
1311
+ value: content
1312
+ });
1313
+ } catch (error) {
1314
+ const message = error instanceof Error ? error.message : "unknown error";
1315
+ if (!reported.has(message)) {
1316
+ reported.add(message);
1317
+ report(`bootstrap could not be put for a session: ${message}`);
1318
+ }
1319
+ return;
1320
+ }
1321
+ done.add(sessionID);
1322
+ if (done.size > REMEMBERED_SESSIONS) {
1323
+ const oldest = done.values().next().value;
1324
+ if (oldest !== undefined)
1325
+ done.delete(oldest);
1326
+ }
1327
+ };
1328
+ const onPrompt = guard.async("bootstrap prompt hook", async (event) => {
1329
+ const sessionID = sessionIdOf(event);
1330
+ if (sessionID === undefined || done.has(sessionID))
1331
+ return;
1332
+ await put(sessionID);
1333
+ });
1334
+ await guard.async("bootstrap registration", () => ctx.session.hook("prompt", onPrompt))();
1335
+ };
1336
+
1337
+ // src/lib/opencode-v2-commands.ts
1338
+ function createCommandRuntime(ctx, report) {
1339
+ return { ctx, report, reported: new Set };
1340
+ }
1341
+ function reportOnce(runtime, key, message) {
1342
+ if (runtime.reported.has(key))
1343
+ return;
1344
+ runtime.reported.add(key);
1345
+ runtime.report(message);
1346
+ }
1347
+ function declaredRouting(planned) {
1348
+ if (planned.agent !== undefined)
1349
+ return "agent";
1350
+ if (planned.model !== undefined)
1351
+ return "model";
1352
+ if (planned.subtask !== undefined)
1353
+ return "subtask";
1354
+ return;
1355
+ }
1356
+ function refusalMessage(name, field) {
1357
+ 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.`;
1358
+ }
1359
+ async function submit(runtime, planned, invocation) {
1360
+ const text = substituteSkillArguments(planned.template, invocation.prompt.text);
1361
+ const { files, agents, skills } = invocation.prompt;
1362
+ await runtime.ctx.session.prompt({
1363
+ sessionID: invocation.sessionID,
1364
+ text,
1365
+ files,
1366
+ agents,
1367
+ skills,
1368
+ delivery: invocation.delivery
1369
+ });
1370
+ }
1371
+ function buildCommand(runtime, name, planned) {
1372
+ return {
1373
+ name,
1374
+ ...planned.description === undefined ? {} : { description: planned.description },
1375
+ async execute(invocation) {
1376
+ const field = declaredRouting(planned);
1377
+ if (field !== undefined) {
1378
+ const message = refusalMessage(name, field);
1379
+ reportOnce(runtime, `refused:${name}`, message);
1380
+ throw new Error(message);
1381
+ }
1382
+ try {
1383
+ await submit(runtime, planned, invocation);
1384
+ } catch (error) {
1385
+ runtime.report(`command "${name}" failed: ${error instanceof Error ? error.message : "unknown error"}`);
1386
+ throw error;
1387
+ }
1388
+ }
1389
+ };
1390
+ }
1391
+ var installCommands = async ({
1392
+ ctx,
1393
+ snapshot,
1394
+ guard,
1395
+ report
1396
+ }) => {
1397
+ const builtIns = await guard.async("command list", async () => new Set((await ctx.command.list()).data.map((entry) => entry.name)))() ?? new Set;
1398
+ const runtime = createCommandRuntime(ctx, report);
1399
+ const transform = guard.sync("command transform", (editor) => {
1400
+ for (const [name, planned] of Object.entries(snapshot.plan.commands)) {
1401
+ if (builtIns.has(name)) {
1402
+ reportOnce(runtime, `built-in:${name}`, `command "${name}" has the name of a built-in command; not registering the bundled one`);
1403
+ continue;
1404
+ }
1405
+ guard.sync(`command "${name}"`, () => {
1406
+ editor.add(buildCommand(runtime, name, planned));
1407
+ })();
1408
+ }
1409
+ });
1410
+ await guard.async("command registration", () => ctx.command.transform(transform))();
1411
+ };
1412
+
1413
+ // src/lib/opencode-v2-permissions.ts
1414
+ var RENAMED_ACTIONS = new Map([
1415
+ ["bash", "shell"],
1416
+ ["task", "subagent"]
1417
+ ]);
1418
+ var DROPPED_ACTIONS = new Set(["doom_loop", "lsp"]);
1419
+ var SKILL_PREFIX2 = "systematic:";
1420
+ function skillResource(pattern) {
1421
+ return pattern.startsWith(SKILL_PREFIX2) ? pattern.slice(SKILL_PREFIX2.length) : pattern;
1422
+ }
1423
+ function translatePermissionRules(rules) {
1424
+ const translated = [];
1425
+ for (const { permission, pattern, setting } of rules) {
1426
+ if (DROPPED_ACTIONS.has(permission))
1427
+ continue;
1428
+ translated.push({
1429
+ action: RENAMED_ACTIONS.get(permission) ?? permission,
1430
+ resource: permission === "skill" ? skillResource(pattern) : pattern,
1431
+ effect: setting
1432
+ });
1433
+ }
1434
+ return translated;
1435
+ }
1436
+ function permissionMapToTriples(permission) {
1437
+ if (!isRecord(permission))
1438
+ return [];
1439
+ const triples = [];
1440
+ for (const [tool, rule] of Object.entries(permission)) {
1441
+ if (isPermissionSetting(rule)) {
1442
+ triples.push({ permission: tool, pattern: "*", setting: rule });
1443
+ continue;
1444
+ }
1445
+ if (!isRecord(rule))
1446
+ continue;
1447
+ for (const [pattern, setting] of Object.entries(rule)) {
1448
+ if (isPermissionSetting(setting)) {
1449
+ triples.push({ permission: tool, pattern, setting });
1450
+ }
1451
+ }
1452
+ }
1453
+ return triples;
1454
+ }
1455
+
1456
+ // src/lib/opencode-v2-skills.ts
1457
+ import fs7 from "fs";
1458
+ var RESTORE_TTL_MS = 24 * 60 * 60 * 1000;
1459
+ var RESTORE_MAX_ENTRIES = 32;
1460
+ function readBundledSkills(bundledSkillsDir, enabledSkills, report) {
1461
+ const enabled = new Set(enabledSkills);
1462
+ const records = [];
1463
+ const infos = findSkillsInDir(bundledSkillsDir).filter((info) => enabled.has(info.name)).sort((a, b) => a.name.localeCompare(b.name));
1464
+ for (const info of infos) {
1465
+ try {
1466
+ const { body } = parseFrontmatter(fs7.readFileSync(info.skillFile, "utf8"));
1467
+ records.push({
1468
+ id: info.name,
1469
+ name: info.name,
1470
+ ...info.description === "" ? {} : { description: info.description },
1471
+ ...info.disableModelInvocation === true ? { autoinvoke: false } : {},
1472
+ path: info.skillFile,
1473
+ content: body.trim()
1474
+ });
1475
+ } catch (error) {
1476
+ report(`skill "${info.name}" could not be read; leaving it out: ${error instanceof Error ? error.message : "unknown error"}`);
1477
+ }
1478
+ }
1479
+ return records;
1480
+ }
1481
+ function addBundledSkill(editor, skill, reported, report) {
1482
+ if (editor.get(skill.id) !== undefined) {
1483
+ if (reported.has(skill.id))
1484
+ return;
1485
+ reported.add(skill.id);
1486
+ report(`skill "${skill.id}" is already defined by another plugin; skipping the bundled skill`);
1487
+ return;
1488
+ }
1489
+ editor.add(skill);
1490
+ }
1491
+ function parseToolInput(input) {
1492
+ if (!isRecord(input) || typeof input.name !== "string") {
1493
+ throw new Error('systematic_skill requires a "name" string');
1494
+ }
1495
+ if (input.arguments !== undefined && typeof input.arguments !== "string") {
1496
+ throw new Error('systematic_skill "arguments" must be a string');
1497
+ }
1498
+ return { name: input.name, arguments: input.arguments };
1499
+ }
1500
+ function restoreSkillResults(store, event) {
1501
+ if (!isRecord(event) || typeof event.sessionID !== "string")
1502
+ return;
1503
+ const { sessionID, messages } = event;
1504
+ if (!Array.isArray(messages))
1505
+ return;
1506
+ for (const message of messages) {
1507
+ if (!isRecord(message) || message.role !== "tool")
1508
+ continue;
1509
+ if (!Array.isArray(message.content))
1510
+ continue;
1511
+ for (const part of message.content)
1512
+ restorePart(store, sessionID, part);
1513
+ }
1514
+ }
1515
+ function restorePart(store, sessionID, part) {
1516
+ if (!isRecord(part) || part.type !== "tool-result")
1517
+ return;
1518
+ if (part.name !== SKILL_TOOL_NAME || typeof part.id !== "string")
1519
+ return;
1520
+ const full = store.peek(sessionID, part.id);
1521
+ if (full === undefined)
1522
+ return;
1523
+ part.result = { type: "content", value: [{ type: "text", text: full }] };
1524
+ }
1525
+ function createToolDefinition(ctx, descriptor, store, guard) {
1526
+ return {
1527
+ name: descriptor.name,
1528
+ description: descriptor.description,
1529
+ input: descriptor.input,
1530
+ options: { codemode: false },
1531
+ async execute(input, context) {
1532
+ const loaded = descriptor.load(parseToolInput(input));
1533
+ await ctx.permission.assert({
1534
+ sessionID: context.sessionID,
1535
+ agent: context.agent,
1536
+ action: "skill",
1537
+ resources: [loaded.skillName],
1538
+ source: {
1539
+ type: "tool",
1540
+ messageID: context.messageID,
1541
+ id: context.id
1542
+ }
1543
+ });
1544
+ const progress = guard.async("skill progress", () => context.progress({
1545
+ title: loaded.title,
1546
+ name: loaded.prefixedName,
1547
+ dir: loaded.dir
1548
+ }));
1549
+ await progress();
1550
+ store.put(context.sessionID, context.id, loaded.output);
1551
+ return {
1552
+ content: loaded.output,
1553
+ metadata: { name: loaded.prefixedName, dir: loaded.dir }
1554
+ };
1555
+ }
1556
+ };
1557
+ }
1558
+ var installSkills = async ({
1559
+ ctx,
1560
+ snapshot,
1561
+ guard,
1562
+ report
1563
+ }) => {
1564
+ const bundledSkills = readBundledSkills(`${snapshot.packageRoot}/skills`, snapshot.plan.enabledSkills, report);
1565
+ const descriptor = createSkillToolDescriptor({
1566
+ bundledSkillsDir: `${snapshot.packageRoot}/skills`,
1567
+ disabledSkills: snapshot.config.disabled_skills
1568
+ });
1569
+ const store = createSkillOutputStore({
1570
+ maxEntries: RESTORE_MAX_ENTRIES,
1571
+ ttlMs: RESTORE_TTL_MS
1572
+ });
1573
+ const reported = new Set;
1574
+ const skillTransform = guard.sync("skill transform", (editor) => {
1575
+ for (const skill of bundledSkills) {
1576
+ const add = guard.sync(`skill "${skill.id}"`, addBundledSkill);
1577
+ add(editor, skill, reported, report);
1578
+ }
1579
+ });
1580
+ const toolTransform = guard.sync("tool transform", (editor) => {
1581
+ if (editor.get(descriptor.name) !== undefined) {
1582
+ if (!reported.has(descriptor.name)) {
1583
+ reported.add(descriptor.name);
1584
+ report(`tool "${descriptor.name}" is already registered by another plugin; not registering the bundled one`);
1585
+ }
1586
+ return;
1587
+ }
1588
+ editor.add(createToolDefinition(ctx, descriptor, store, guard));
1589
+ });
1590
+ const restore = guard.sync("skill output restore", (event) => {
1591
+ restoreSkillResults(store, event);
1592
+ });
1593
+ await guard.async("skill registration", () => ctx.skill.transform(skillTransform))();
1594
+ await guard.async("tool registration", () => ctx.tool.transform(toolTransform))();
1595
+ await guard.async("skill output restore registration", () => ctx.session.hook("context", restore))();
1596
+ };
1597
+
1598
+ // src/lib/opencode-v2.ts
1599
+ var DIAGNOSTIC_PREFIX = "systematic:";
1600
+ function describeFailure(error) {
1601
+ return error instanceof Error ? error.message : "unknown error";
1602
+ }
1603
+ function reportFailure(label, error) {
1604
+ console.error(`${DIAGNOSTIC_PREFIX} ${label} failed: ${describeFailure(error)}`);
1605
+ }
1606
+ function createSafeGuard() {
1607
+ return {
1608
+ sync(label, callback) {
1609
+ return (...args) => {
1610
+ try {
1611
+ return callback(...args);
1612
+ } catch (error) {
1613
+ reportFailure(label, error);
1614
+ return;
1615
+ }
1616
+ };
1617
+ },
1618
+ async(label, callback) {
1619
+ return async (...args) => {
1620
+ try {
1621
+ return await callback(...args);
1622
+ } catch (error) {
1623
+ reportFailure(label, error);
1624
+ return;
1625
+ }
1626
+ };
1627
+ }
1628
+ };
1629
+ }
1630
+ var HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
1631
+ function parseModel(model, variant) {
1632
+ const slash = model.indexOf("/");
1633
+ if (slash <= 0 || slash === model.length - 1)
1634
+ return;
1635
+ const providerID = model.slice(0, slash);
1636
+ const id = model.slice(slash + 1);
1637
+ return variant === undefined ? { providerID, id } : { providerID, id, variant };
1638
+ }
1639
+ function writeAgentModel(agent, planned, reported) {
1640
+ const { model, variant } = planned.config;
1641
+ if (model === undefined)
1642
+ return;
1643
+ const parsed = parseModel(model, typeof variant === "string" ? variant : undefined);
1644
+ if (parsed !== undefined) {
1645
+ agent.model = parsed;
1646
+ return;
1647
+ }
1648
+ const key = `model:${planned.name}`;
1649
+ if (reported.has(key))
1650
+ return;
1651
+ reported.add(key);
1652
+ console.error(`${DIAGNOSTIC_PREFIX} agent "${planned.name}" has model "${model}", which is not provider/model; leaving its model unset`);
1653
+ }
1654
+ function agentPermissionRules(planned) {
1655
+ return translatePermissionRules(planned.permission.kind === "managed" ? planned.permission.rules : permissionMapToTriples(planned.config.permission));
1656
+ }
1657
+ function writeAgentFields(agent, planned, reported) {
1658
+ const { config } = planned;
1659
+ if (config.prompt !== undefined)
1660
+ agent.system = config.prompt;
1661
+ if (config.description !== undefined)
1662
+ agent.description = config.description;
1663
+ agent.mode = config.mode ?? "all";
1664
+ if (typeof config.hidden === "boolean")
1665
+ agent.hidden = config.hidden;
1666
+ if (typeof config.steps === "number")
1667
+ agent.steps = config.steps;
1668
+ if (config.color !== undefined && HEX_COLOR.test(config.color)) {
1669
+ agent.color = config.color;
1670
+ }
1671
+ if (config.temperature !== undefined) {
1672
+ agent.request.body.temperature = config.temperature;
1673
+ }
1674
+ if (config.top_p !== undefined)
1675
+ agent.request.body.top_p = config.top_p;
1676
+ writeAgentModel(agent, planned, reported);
1677
+ agent.permissions.push(...agentPermissionRules(planned));
1678
+ }
1679
+ function applyPlannedAgent(editor, planned, reported = new Set) {
1680
+ if (planned.config.disable === true)
1681
+ return;
1682
+ if (editor.get(planned.name) !== undefined) {
1683
+ const key = `clash:${planned.name}`;
1684
+ if (reported.has(key))
1685
+ return;
1686
+ reported.add(key);
1687
+ console.error(`${DIAGNOSTIC_PREFIX} agent "${planned.name}" is already defined by the host or another plugin; skipping the bundled agent`);
1688
+ return;
1689
+ }
1690
+ editor.update(planned.name, (agent) => {
1691
+ writeAgentFields(agent, planned, reported);
1692
+ });
1693
+ }
1694
+ var installAgents = async ({ ctx, snapshot, guard }) => {
1695
+ const reported = new Set;
1696
+ await ctx.agent.transform(guard.sync("agent transform", (editor) => {
1697
+ for (const planned of Object.values(snapshot.plan.agents)) {
1698
+ const apply = guard.sync(`agent "${planned.name}"`, applyPlannedAgent);
1699
+ apply(editor, planned, reported);
1700
+ }
1701
+ }));
1702
+ };
1703
+ var DEFAULT_INSTALLERS = {
1704
+ agents: installAgents,
1705
+ skills: installSkills,
1706
+ commands: installCommands,
1707
+ bootstrap: installBootstrap
1708
+ };
1709
+ var INSTALLER_ORDER = [
1710
+ "agents",
1711
+ "skills",
1712
+ "commands",
1713
+ "bootstrap"
1714
+ ];
1715
+ function resolveProjectDirectory(ctx) {
1716
+ const directory = ctx.location?.directory;
1717
+ return typeof directory === "string" && directory.length > 0 ? directory : undefined;
1718
+ }
1719
+ function reportDiagnostic(message) {
1720
+ console.error(`${DIAGNOSTIC_PREFIX} ${message}`);
1721
+ }
1722
+ function messageOf(error) {
1723
+ return error instanceof Error ? error.message : "unknown error";
1724
+ }
1725
+ function composeBootstrapOrNull(config, bundledSkillsDir) {
1726
+ try {
1727
+ return composeBootstrapContent(config, {
1728
+ bundledSkillsDir,
1729
+ profile: "opencode-v2",
1730
+ usageTemplate: OPENCODE_V2_USAGE_TEMPLATE
1731
+ });
1732
+ } catch (error) {
1733
+ reportDiagnostic(`bootstrap could not be read: ${messageOf(error)}`);
1734
+ return null;
1735
+ }
1736
+ }
1737
+ function buildSnapshot(ctx, deps) {
1738
+ const { packageRoot } = deps;
1739
+ const homeDir = deps.homeDir ?? os3.homedir();
1740
+ const opencodeConfigDir = deps.opencodeConfigDir ?? path7.join(homeDir, ".config/opencode");
1741
+ const opencodeConfigDirOverride = process.env.OPENCODE_CONFIG_DIR?.trim() ? process.env.OPENCODE_CONFIG_DIR : undefined;
1742
+ const bundledSkillsDir = path7.join(packageRoot, "skills");
1743
+ const projectDirectory = resolveProjectDirectory(ctx);
1744
+ if (projectDirectory === undefined) {
1745
+ reportDiagnostic("the host gave no project directory; loading user-level config only");
1746
+ }
1747
+ const directory = projectDirectory ?? homeDir;
1748
+ const { config, overlays } = loadConfigWithSources(directory, {
1749
+ homeDir,
1750
+ userConfigDir: opencodeConfigDir,
1751
+ includeProject: projectDirectory !== undefined
1752
+ });
1753
+ let plan;
1754
+ try {
1755
+ plan = buildAssetPlan({
1756
+ config,
1757
+ overlays,
1758
+ nativeAgentNames: [],
1759
+ directory,
1760
+ bundledSkillsDir,
1761
+ bundledAgentsDir: path7.join(packageRoot, "agents"),
1762
+ bundledCommandsDir: path7.join(packageRoot, "commands"),
1763
+ homeDir,
1764
+ opencodeConfigDir,
1765
+ opencodeConfigDirOverride
1766
+ });
1767
+ } catch (error) {
1768
+ reportDiagnostic(`asset plan could not be built: ${messageOf(error)}`);
1769
+ return;
1770
+ }
1771
+ const bootstrapContent = composeBootstrapOrNull(config, bundledSkillsDir);
1772
+ return Object.freeze({
1773
+ config,
1774
+ plan,
1775
+ bootstrapContent,
1776
+ directory,
1777
+ packageRoot
1778
+ });
1779
+ }
1780
+ async function setupOpenCodeV2(ctx, deps) {
1781
+ const snapshot = buildSnapshot(ctx, deps);
1782
+ if (snapshot === undefined)
1783
+ return;
1784
+ const guard = createSafeGuard();
1785
+ const report = reportDiagnostic;
1786
+ const installers = { ...DEFAULT_INSTALLERS, ...deps.installers };
1787
+ for (const slot of INSTALLER_ORDER) {
1788
+ const install = guard.async(`${slot} installer`, installers[slot]);
1789
+ await install({ ctx, snapshot, guard, report });
1790
+ }
1791
+ }
1792
+
1793
+ // src/index.ts
1794
+ var __dirname2 = path8.dirname(fileURLToPath(import.meta.url));
1795
+ var packageRoot = path8.resolve(__dirname2, "..");
1796
+ var systematicPlugin = {
1797
+ id: "systematic",
1798
+ async setup(ctx) {
1799
+ if (!ctx.location || !ctx.session)
1800
+ return;
1801
+ await setupOpenCodeV2(ctx, { packageRoot });
1802
+ },
1803
+ server: async (input) => createOpenCodeV1Hooks(input, { packageRoot })
1156
1804
  };
1157
- var src_default = SystematicPlugin;
1805
+ var entry = systematicPlugin;
1806
+ var src_default = entry;
1158
1807
  export {
1159
1808
  src_default as default
1160
1809
  };