crewbee 0.1.23 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +40 -6
  2. package/README.zh-CN.md +15 -5
  3. package/dist/opencode-plugin.mjs +975 -86
  4. package/dist/src/adapters/opencode/delegation/types.d.ts +1 -1
  5. package/dist/src/adapters/opencode/delegation/types.d.ts.map +1 -1
  6. package/dist/src/adapters/opencode/index.d.ts +2 -1
  7. package/dist/src/adapters/opencode/index.d.ts.map +1 -1
  8. package/dist/src/adapters/opencode/index.js +7 -3
  9. package/dist/src/adapters/opencode/index.js.map +1 -1
  10. package/dist/src/adapters/opencode/permission-mapper.d.ts.map +1 -1
  11. package/dist/src/adapters/opencode/permission-mapper.js +11 -0
  12. package/dist/src/adapters/opencode/permission-mapper.js.map +1 -1
  13. package/dist/src/adapters/opencode/plugin-v1.d.ts +9 -0
  14. package/dist/src/adapters/opencode/plugin-v1.d.ts.map +1 -0
  15. package/dist/src/adapters/opencode/plugin-v1.js +84 -0
  16. package/dist/src/adapters/opencode/plugin-v1.js.map +1 -0
  17. package/dist/src/adapters/opencode/plugin.d.ts +18 -3
  18. package/dist/src/adapters/opencode/plugin.d.ts.map +1 -1
  19. package/dist/src/adapters/opencode/plugin.js +19 -75
  20. package/dist/src/adapters/opencode/plugin.js.map +1 -1
  21. package/dist/src/adapters/opencode/prompt-builder.d.ts.map +1 -1
  22. package/dist/src/adapters/opencode/prompt-builder.js +9 -2
  23. package/dist/src/adapters/opencode/prompt-builder.js.map +1 -1
  24. package/dist/src/adapters/opencode/tool-hooks.d.ts +10 -0
  25. package/dist/src/adapters/opencode/tool-hooks.d.ts.map +1 -1
  26. package/dist/src/adapters/opencode/tool-hooks.js +28 -8
  27. package/dist/src/adapters/opencode/tool-hooks.js.map +1 -1
  28. package/dist/src/adapters/opencode/v2/agent-definition.d.ts +39 -0
  29. package/dist/src/adapters/opencode/v2/agent-definition.d.ts.map +1 -0
  30. package/dist/src/adapters/opencode/v2/agent-definition.js +45 -0
  31. package/dist/src/adapters/opencode/v2/agent-definition.js.map +1 -0
  32. package/dist/src/adapters/opencode/v2/logging.d.ts +8 -0
  33. package/dist/src/adapters/opencode/v2/logging.d.ts.map +1 -0
  34. package/dist/src/adapters/opencode/v2/logging.js +45 -0
  35. package/dist/src/adapters/opencode/v2/logging.js.map +1 -0
  36. package/dist/src/adapters/opencode/v2/models.d.ts +9 -0
  37. package/dist/src/adapters/opencode/v2/models.d.ts.map +1 -0
  38. package/dist/src/adapters/opencode/v2/models.js +40 -0
  39. package/dist/src/adapters/opencode/v2/models.js.map +1 -0
  40. package/dist/src/adapters/opencode/v2/permissions.d.ts +10 -0
  41. package/dist/src/adapters/opencode/v2/permissions.d.ts.map +1 -0
  42. package/dist/src/adapters/opencode/v2/permissions.js +49 -0
  43. package/dist/src/adapters/opencode/v2/permissions.js.map +1 -0
  44. package/dist/src/adapters/opencode/v2/plugin.d.ts +20 -0
  45. package/dist/src/adapters/opencode/v2/plugin.d.ts.map +1 -0
  46. package/dist/src/adapters/opencode/v2/plugin.js +321 -0
  47. package/dist/src/adapters/opencode/v2/plugin.js.map +1 -0
  48. package/dist/src/adapters/opencode/v2/session-client.d.ts +82 -0
  49. package/dist/src/adapters/opencode/v2/session-client.d.ts.map +1 -0
  50. package/dist/src/adapters/opencode/v2/session-client.js +153 -0
  51. package/dist/src/adapters/opencode/v2/session-client.js.map +1 -0
  52. package/dist/src/adapters/opencode/v2/tool-registration.d.ts +59 -0
  53. package/dist/src/adapters/opencode/v2/tool-registration.d.ts.map +1 -0
  54. package/dist/src/adapters/opencode/v2/tool-registration.js +198 -0
  55. package/dist/src/adapters/opencode/v2/tool-registration.js.map +1 -0
  56. package/dist/src/agent-teams/canonical-agent-id.d.ts.map +1 -1
  57. package/dist/src/agent-teams/canonical-agent-id.js +22 -9
  58. package/dist/src/agent-teams/canonical-agent-id.js.map +1 -1
  59. package/dist/src/agent-teams/filesystem.d.ts +2 -2
  60. package/dist/src/agent-teams/filesystem.d.ts.map +1 -1
  61. package/dist/src/agent-teams/filesystem.js +13 -8
  62. package/dist/src/agent-teams/filesystem.js.map +1 -1
  63. package/dist/src/agent-teams/library.d.ts.map +1 -1
  64. package/dist/src/agent-teams/library.js +121 -51
  65. package/dist/src/agent-teams/library.js.map +1 -1
  66. package/dist/src/agent-teams/types.d.ts +5 -0
  67. package/dist/src/agent-teams/types.d.ts.map +1 -1
  68. package/dist/src/install/install.d.ts.map +1 -1
  69. package/dist/src/install/install.js +2 -1
  70. package/dist/src/install/install.js.map +1 -1
  71. package/dist/src/install/opencode-config-file.d.ts +3 -1
  72. package/dist/src/install/opencode-config-file.d.ts.map +1 -1
  73. package/dist/src/install/opencode-config-file.js +77 -19
  74. package/dist/src/install/opencode-config-file.js.map +1 -1
  75. package/dist/src/update/intent.d.ts.map +1 -1
  76. package/dist/src/update/intent.js +2 -1
  77. package/dist/src/update/intent.js.map +1 -1
  78. package/dist/src/update/refresh.d.ts +4 -2
  79. package/dist/src/update/refresh.d.ts.map +1 -1
  80. package/dist/src/update/refresh.js +24 -12
  81. package/dist/src/update/refresh.js.map +1 -1
  82. package/package.json +9 -3
@@ -11136,9 +11136,7 @@ function createSkippedAgentIssue(filePath, message) {
11136
11136
  function loadTeamDefinitionFromDirectoryWithIssues(teamDir, workspaceRoot = process.cwd()) {
11137
11137
  const manifest = mapTeamManifest(path3.join(teamDir, TEAM_MANIFEST_FILE));
11138
11138
  const policyPath = path3.join(teamDir, TEAM_POLICY_FILE);
11139
- if (!existsSync3(policyPath)) {
11140
- throw new Error(`${teamDir} is missing ${TEAM_POLICY_FILE}.`);
11141
- }
11139
+ const policy = existsSync3(policyPath) ? mapTeamPolicy(policyPath) : void 0;
11142
11140
  const agentFiles = readdirSync2(teamDir).filter((entry) => entry.endsWith(".agent.md")).sort();
11143
11141
  const issues = [];
11144
11142
  const agents = agentFiles.flatMap((entry) => {
@@ -11151,13 +11149,10 @@ function loadTeamDefinitionFromDirectoryWithIssues(teamDir, workspaceRoot = proc
11151
11149
  return [];
11152
11150
  }
11153
11151
  });
11154
- if (agents.length === 0) {
11155
- throw new Error(`${teamDir} must contain at least one *.agent.md file at the team root.`);
11156
- }
11157
11152
  return {
11158
11153
  team: {
11159
11154
  manifest,
11160
- policy: mapTeamPolicy(policyPath),
11155
+ policy,
11161
11156
  agents,
11162
11157
  documentation: resolveTeamDocumentation(teamDir, workspaceRoot)
11163
11158
  },
@@ -11190,13 +11185,13 @@ function createCanonicalAgentId(teamId, agentId) {
11190
11185
  function createFallbackCanonicalAgentId(teamId, agentId) {
11191
11186
  return `${sanitizeSegment(teamId)}-${resolveAgentSlug(agentId)}`;
11192
11187
  }
11193
- function rewriteBinding(binding2, agentIdMap) {
11188
+ function rewriteBinding(binding2, resolveRef) {
11194
11189
  if (typeof binding2 === "string") {
11195
- return agentIdMap.get(binding2) ?? binding2;
11190
+ return resolveRef(binding2);
11196
11191
  }
11197
11192
  return {
11198
11193
  ...binding2,
11199
- agentRef: agentIdMap.get(binding2.agentRef) ?? binding2.agentRef
11194
+ agentRef: resolveRef(binding2.agentRef)
11200
11195
  };
11201
11196
  }
11202
11197
  function normalizeTeamAgentIds(input) {
@@ -11226,23 +11221,33 @@ function normalizeTeamAgentIds(input) {
11226
11221
  localAssignedIds.add(assigned);
11227
11222
  nextUsedIds.add(assigned);
11228
11223
  }
11224
+ const canonicalAliases = /* @__PURE__ */ new Map();
11225
+ for (const [sourceId, assigned] of agentIdMap) {
11226
+ const canonical = createCanonicalAgentId(input.team.manifest.id, sourceId);
11227
+ canonicalAliases.set(canonical, [...canonicalAliases.get(canonical) ?? [], assigned]);
11228
+ }
11229
+ const resolveRef = (ref) => {
11230
+ if (agentIdMap.has(ref)) return agentIdMap.get(ref);
11231
+ const aliases = canonicalAliases.get(createCanonicalAgentId(input.team.manifest.id, ref));
11232
+ return aliases?.length === 1 ? aliases[0] : ref;
11233
+ };
11229
11234
  const normalizedTeam = {
11230
11235
  ...input.team,
11231
11236
  manifest: {
11232
11237
  ...input.team.manifest,
11233
11238
  leader: {
11234
11239
  ...input.team.manifest.leader,
11235
- agentRef: agentIdMap.get(input.team.manifest.leader.agentRef) ?? input.team.manifest.leader.agentRef
11240
+ agentRef: resolveRef(input.team.manifest.leader.agentRef)
11236
11241
  },
11237
11242
  members: Object.fromEntries(
11238
11243
  Object.entries(input.team.manifest.members).map(([agentId, guidance]) => [
11239
- agentIdMap.get(agentId) ?? agentId,
11244
+ resolveRef(agentId),
11240
11245
  guidance
11241
11246
  ])
11242
11247
  ),
11243
11248
  agentRuntime: input.team.manifest.agentRuntime ? Object.fromEntries(
11244
11249
  Object.entries(input.team.manifest.agentRuntime).map(([agentId, runtime]) => [
11245
- agentIdMap.get(agentId) ?? agentId,
11250
+ resolveRef(agentId),
11246
11251
  runtime
11247
11252
  ])
11248
11253
  ) : void 0
@@ -11251,7 +11256,7 @@ function normalizeTeamAgentIds(input) {
11251
11256
  ...input.team.modelConfigOverride,
11252
11257
  agents: input.team.modelConfigOverride.agents ? Object.fromEntries(
11253
11258
  Object.entries(input.team.modelConfigOverride.agents).map(([agentId, override]) => [
11254
- agentIdMap.get(agentId) ?? agentId,
11259
+ resolveRef(agentId),
11255
11260
  override
11256
11261
  ])
11257
11262
  ) : void 0
@@ -11268,8 +11273,8 @@ function normalizeTeamAgentIds(input) {
11268
11273
  name: canonicalAgentId
11269
11274
  },
11270
11275
  collaboration: {
11271
- defaultConsults: agent.collaboration.defaultConsults.map((binding2) => rewriteBinding(binding2, agentIdMap)),
11272
- defaultHandoffs: agent.collaboration.defaultHandoffs.map((binding2) => rewriteBinding(binding2, agentIdMap))
11276
+ defaultConsults: agent.collaboration.defaultConsults.map((binding2) => rewriteBinding(binding2, resolveRef)),
11277
+ defaultHandoffs: agent.collaboration.defaultHandoffs.map((binding2) => rewriteBinding(binding2, resolveRef))
11273
11278
  },
11274
11279
  entryPoint: agent.entryPoint ? {
11275
11280
  ...agent.entryPoint,
@@ -11484,6 +11489,41 @@ function createSkippedTeamIssue(teamDir, message) {
11484
11489
  suggestion: "Fix this Team directory; CrewBee will continue loading other valid Teams."
11485
11490
  };
11486
11491
  }
11492
+ function mergeTeamDefinitions(higher, lower) {
11493
+ const higherAgentsByCanonicalId = /* @__PURE__ */ new Map();
11494
+ for (const agent of higher.agents) {
11495
+ const key = createCanonicalAgentId(higher.manifest.id, agent.metadata.id);
11496
+ if (higherAgentsByCanonicalId.has(key)) {
11497
+ throw new Error(`Duplicate override for canonical Agent '${key}'.`);
11498
+ }
11499
+ higherAgentsByCanonicalId.set(key, agent);
11500
+ }
11501
+ const mergedAgents = [];
11502
+ const mergedKeys = /* @__PURE__ */ new Set();
11503
+ for (const agent of lower.agents) {
11504
+ const key = createCanonicalAgentId(lower.manifest.id, agent.metadata.id);
11505
+ mergedKeys.add(key);
11506
+ mergedAgents.push(higherAgentsByCanonicalId.get(key) ?? agent);
11507
+ }
11508
+ for (const [key, agent] of higherAgentsByCanonicalId) {
11509
+ if (!mergedKeys.has(key)) {
11510
+ mergedAgents.push(agent);
11511
+ }
11512
+ }
11513
+ return {
11514
+ manifest: higher.manifest,
11515
+ policy: higher.policy ?? lower.policy,
11516
+ agents: mergedAgents,
11517
+ documentation: higher.documentation ?? lower.documentation,
11518
+ modelConfigOverride: higher.modelConfigOverride ?? lower.modelConfigOverride
11519
+ };
11520
+ }
11521
+ function requireTeamPolicy(team) {
11522
+ if (!team.policy) {
11523
+ throw new Error(`Team '${team.manifest.id}' must define team.policy.yaml or inherit an enabled embedded policy.`);
11524
+ }
11525
+ return { ...team, policy: team.policy };
11526
+ }
11487
11527
  function loadDefaultTeamLibrary(input = process.cwd()) {
11488
11528
  const baseDir = typeof input === "string" ? input : input.projectWorktree ?? process.cwd();
11489
11529
  const configured = listConfiguredTeamSources(
@@ -11505,6 +11545,7 @@ function loadDefaultTeamLibrary(input = process.cwd()) {
11505
11545
  team: embeddedTeam.team ? { ...embeddedTeam.team, modelConfigOverride: source.modelConfigOverride } : void 0,
11506
11546
  issues: []
11507
11547
  }),
11548
+ kind: "embedded",
11508
11549
  priority: source.priority,
11509
11550
  order: source.order,
11510
11551
  sourcePrecedence: source.sourcePrecedence,
@@ -11528,6 +11569,7 @@ function loadDefaultTeamLibrary(input = process.cwd()) {
11528
11569
  };
11529
11570
  }
11530
11571
  },
11572
+ kind: "filesystem",
11531
11573
  priority: source.priority,
11532
11574
  order: source.order,
11533
11575
  sourcePrecedence: source.sourcePrecedence,
@@ -11546,58 +11588,70 @@ function loadDefaultTeamLibrary(input = process.cwd()) {
11546
11588
  }
11547
11589
  return left.order - right.order;
11548
11590
  });
11549
- const usedCanonicalIds = /* @__PURE__ */ new Set();
11550
- const usedTeamIds = /* @__PURE__ */ new Map();
11551
- const orderedTeams = [];
11552
- for (const entry of pendingTeams) {
11591
+ const loadedEntries = pendingTeams.flatMap((entry, index) => {
11553
11592
  const loaded = entry.loader();
11554
11593
  configured.issues.push(...loaded.issues);
11555
- if (loaded.team) {
11556
- const existing = usedTeamIds.get(loaded.team.manifest.id);
11557
- if (existing) {
11558
- configured.issues.push({
11594
+ return loaded.team ? [{ ...entry, index, team: loaded.team }] : [];
11595
+ });
11596
+ const embeddedById = /* @__PURE__ */ new Map();
11597
+ for (const entry of loadedEntries) {
11598
+ if (entry.kind === "embedded" && !embeddedById.has(entry.team.manifest.id)) {
11599
+ embeddedById.set(entry.team.manifest.id, entry);
11600
+ }
11601
+ }
11602
+ const usedCanonicalIds = /* @__PURE__ */ new Set();
11603
+ const usedTeamIds = /* @__PURE__ */ new Map();
11604
+ const resolvedTeams = [];
11605
+ const groups = /* @__PURE__ */ new Map();
11606
+ for (const entry of loadedEntries) {
11607
+ const id = entry.team.manifest.id;
11608
+ groups.set(id, [...groups.get(id) ?? [], entry]);
11609
+ }
11610
+ const orderedGroups = [...groups.values()].map((entries) => [
11611
+ ...entries.filter((entry) => entry.kind === "filesystem"),
11612
+ ...entries.filter((entry) => entry.kind === "embedded")
11613
+ ]).sort((left, right) => left[0].index - right[0].index);
11614
+ const candidates = orderedGroups.flat();
11615
+ for (const entry of candidates) {
11616
+ const teamId = entry.team.manifest.id;
11617
+ const existing = usedTeamIds.get(teamId);
11618
+ if (existing) {
11619
+ if (entry.kind !== existing.kind) continue;
11620
+ configured.issues.push({
11621
+ level: "warning",
11622
+ code: "team_id_shadowed_or_duplicate",
11623
+ filePath: entry.configPath,
11624
+ sourceScope: entry.sourceScope === "project" ? "project" : "global",
11625
+ message: entry.sourceScope === "global" && existing.sourceScope === "project" ? `Project Team '${teamId}' shadows global Team '${teamId}'.` : `Skipped Team '${teamId}': duplicate Team id already loaded from ${existing.sourceScope} source.`,
11626
+ suggestion: "Rename one Team id or disable one Team entry unless this override is intentional."
11627
+ });
11628
+ continue;
11629
+ }
11630
+ const base = entry.kind === "filesystem" ? embeddedById.get(teamId) : void 0;
11631
+ const claims = new Set(usedCanonicalIds);
11632
+ try {
11633
+ const raw = base ? mergeTeamDefinitions(entry.team, base.team) : entry.team;
11634
+ const complete = requireTeamPolicy(raw);
11635
+ const normalized = normalizeTeamAgentIds({ team: complete, usedCanonicalIds: claims });
11636
+ const issues = [...normalized.issues, ...normalized.team ? validateTeamDefinition(normalized.team) : []];
11637
+ if (!normalized.team || issues.some((issue2) => issue2.level === "error")) {
11638
+ configured.issues.push(...issues.map((issue2) => ({
11639
+ ...issue2,
11559
11640
  level: "warning",
11560
- filePath: entry.configPath,
11561
- code: "team_id_shadowed_or_duplicate",
11562
- sourceScope: entry.sourceScope === "project" || entry.sourceScope === "global" ? entry.sourceScope : void 0,
11563
- message: entry.sourceScope === "global" && existing.sourceScope === "project" ? `Project Team '${loaded.team.manifest.id}' shadows global Team '${loaded.team.manifest.id}'.` : `Skipped Team '${loaded.team.manifest.id}': duplicate Team id already loaded from ${existing.sourceScope} source.`,
11564
- suggestion: entry.sourceScope === "global" && existing.sourceScope === "project" ? "This is expected when a project intentionally overrides a global Team id." : "Rename one Team id or disable one Team entry."
11565
- });
11641
+ filePath: issue2.filePath ?? entry.configPath,
11642
+ message: `Skipped Team '${teamId}': ${issue2.message}`
11643
+ })));
11566
11644
  continue;
11567
11645
  }
11568
- const usedCanonicalIdsBeforeNormalize = new Set(usedCanonicalIds);
11569
- const normalized = normalizeTeamAgentIds({
11570
- team: loaded.team,
11571
- usedCanonicalIds
11572
- });
11573
- configured.issues.push(...normalized.issues);
11574
- if (normalized.team) {
11575
- const validationIssues = validateTeamDefinition(normalized.team);
11576
- const errors = validationIssues.filter((issue2) => issue2.level === "error");
11577
- if (errors.length > 0) {
11578
- usedCanonicalIds.clear();
11579
- for (const usedId of usedCanonicalIdsBeforeNormalize) {
11580
- usedCanonicalIds.add(usedId);
11581
- }
11582
- configured.issues.push(...errors.map((issue2) => ({
11583
- level: "warning",
11584
- filePath: issue2.filePath,
11585
- code: issue2.code ?? "team_validation_failed",
11586
- path: issue2.path,
11587
- suggestion: issue2.suggestion,
11588
- message: `Skipped Team '${normalized.team?.manifest.id ?? "unknown"}': ${issue2.message}`
11589
- })));
11590
- continue;
11591
- }
11592
- configured.issues.push(...validationIssues.filter((issue2) => issue2.level === "warning"));
11593
- orderedTeams.push(normalized.team);
11594
- usedTeamIds.set(normalized.team.manifest.id, {
11595
- sourceScope: entry.sourceScope,
11596
- configPath: entry.configPath
11597
- });
11598
- }
11646
+ configured.issues.push(...issues);
11647
+ for (const id of claims) usedCanonicalIds.add(id);
11648
+ resolvedTeams.push({ index: entry.index, team: normalized.team });
11649
+ usedTeamIds.set(teamId, entry);
11650
+ } catch (error45) {
11651
+ configured.issues.push(createSkippedTeamIssue(teamId, error45 instanceof Error ? error45.message : String(error45)));
11599
11652
  }
11600
11653
  }
11654
+ const orderedTeams = resolvedTeams.sort((left, right) => left.index - right.index).map((entry) => entry.team);
11601
11655
  return {
11602
11656
  version: "config-driven-v1",
11603
11657
  teams: orderedTeams,
@@ -11750,6 +11804,48 @@ function readOpenCodeConfig(configPath) {
11750
11804
  path: configPath
11751
11805
  };
11752
11806
  }
11807
+ function findCrewBeePluginEntries(config2) {
11808
+ return getRawPluginArray(config2).map((value) => readPluginEntryReference(value)).filter((value) => typeof value === "string" && isCrewBeePluginReference(value));
11809
+ }
11810
+ function getRawPluginArray(config2) {
11811
+ const merged = [];
11812
+ if (Array.isArray(config2.plugins)) {
11813
+ merged.push(...config2.plugins.map(normalizePluginEntry));
11814
+ }
11815
+ if (Array.isArray(config2.plugin)) {
11816
+ merged.push(...config2.plugin.map(normalizePluginEntry));
11817
+ }
11818
+ return merged;
11819
+ }
11820
+ function normalizePluginEntry(entry) {
11821
+ if (Array.isArray(entry) && entry.length >= 1 && typeof entry[0] === "string") {
11822
+ const [name, options] = entry;
11823
+ if (options && typeof options === "object" && !Array.isArray(options)) {
11824
+ return { package: name, options };
11825
+ }
11826
+ return name;
11827
+ }
11828
+ return entry;
11829
+ }
11830
+ function isPluginEntryObject(value) {
11831
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11832
+ }
11833
+ function readPluginEntryReference(value) {
11834
+ if (typeof value === "string") {
11835
+ return value;
11836
+ }
11837
+ if (isPluginEntryObject(value) && typeof value.package === "string") {
11838
+ return value.package;
11839
+ }
11840
+ return void 0;
11841
+ }
11842
+ function isCrewBeePluginReference(value) {
11843
+ if (value === "crewbee" || value.startsWith("crewbee@")) {
11844
+ return true;
11845
+ }
11846
+ const normalized = value.replace(/\\/g, "/").toLowerCase();
11847
+ return normalized.includes("/node_modules/crewbee/") || normalized.endsWith("/entry/crewbee-opencode-entry.mjs");
11848
+ }
11753
11849
 
11754
11850
  // src/runtime/team-library-projection.ts
11755
11851
  function isLeaderAgent(team, agent) {
@@ -12027,6 +12123,13 @@ function detectOpenCodeProjectionCollisions(input) {
12027
12123
  }
12028
12124
 
12029
12125
  // src/adapters/opencode/permission-mapper.ts
12126
+ var ACTION_ONLY_PERMISSIONS = /* @__PURE__ */ new Set([
12127
+ "doom_loop",
12128
+ "question",
12129
+ "todowrite",
12130
+ "webfetch",
12131
+ "websearch"
12132
+ ]);
12030
12133
  var TOOL_MAP = {
12031
12134
  write: "edit",
12032
12135
  patch: "edit",
@@ -12069,6 +12172,10 @@ function createOpenCodePermissionRules(agent, availableTools, allowedTaskTargets
12069
12172
  function createOpenCodePermissionConfig(permissionRules) {
12070
12173
  const permission = {};
12071
12174
  for (const rule of permissionRules) {
12175
+ if (ACTION_ONLY_PERMISSIONS.has(rule.permission)) {
12176
+ permission[rule.permission] = rule.action;
12177
+ continue;
12178
+ }
12072
12179
  const current = permission[rule.permission];
12073
12180
  if (!current) {
12074
12181
  permission[rule.permission] = { [rule.pattern]: rule.action };
@@ -12552,13 +12659,17 @@ function renderPart(title, body) {
12552
12659
  ${body}` : void 0;
12553
12660
  }
12554
12661
  function createOpenCodeAgentPrompt(agent, _requestedTools) {
12662
+ const policy = agent.sourceTeam.policy;
12663
+ if (!policy) {
12664
+ throw new Error(`Team '${agent.sourceTeam.manifest.id}' has no team policy.`);
12665
+ }
12555
12666
  const teamDocument = buildTeamPromptDocument(
12556
12667
  {
12557
12668
  id: agent.sourceTeam.manifest.id,
12558
12669
  name: agent.sourceTeam.manifest.name,
12559
- promptProjection: agent.sourceTeam.policy.promptProjection
12670
+ promptProjection: policy.promptProjection
12560
12671
  },
12561
- agent.sourceTeam.policy
12672
+ policy
12562
12673
  );
12563
12674
  const teamPart = renderNormalizedPromptDocument(teamDocument);
12564
12675
  const normalizedAgent = buildAgentPromptDocumentWithOverrides(agent.sourceAgent, {
@@ -26681,6 +26792,22 @@ function createToolDefinitionHook(_getAgents) {
26681
26792
  return async () => {
26682
26793
  };
26683
26794
  }
26795
+ function normalizeDelegateTaskOutput(output) {
26796
+ const parsed = parseDelegateTaskResult(output);
26797
+ if (!parsed) {
26798
+ return void 0;
26799
+ }
26800
+ const result = withResumeHint(withRetryGuidance(withEmptyWarning(parsed)));
26801
+ const metadata = {};
26802
+ if (result.status !== "failed" && result.session_id) {
26803
+ metadata.sessionId = result.session_id;
26804
+ metadata.taskId = result.task_id ?? result.session_id;
26805
+ if (result.task_ref) {
26806
+ metadata.taskRef = result.task_ref;
26807
+ }
26808
+ }
26809
+ return { output: stringifyDelegateTaskResult(result), metadata };
26810
+ }
26684
26811
  function createToolExecuteBeforeHook(input) {
26685
26812
  return async (event, output) => {
26686
26813
  if (event.tool !== "task" || !input.bindings.has(event.sessionID)) {
@@ -26701,19 +26828,16 @@ function createToolExecuteAfterHook() {
26701
26828
  if (input.tool !== "task") {
26702
26829
  return;
26703
26830
  }
26704
- const parsed = parseDelegateTaskResult(output.output);
26705
- if (!parsed) {
26831
+ const normalized = normalizeDelegateTaskOutput(output.output);
26832
+ if (!normalized) {
26706
26833
  return;
26707
26834
  }
26708
- const result = withResumeHint(withRetryGuidance(withEmptyWarning(parsed)));
26709
- output.output = stringifyDelegateTaskResult(result);
26710
- if (result.status !== "failed" && result.session_id) {
26835
+ output.output = normalized.output;
26836
+ if (Object.keys(normalized.metadata).length > 0) {
26711
26837
  output.title = output.title || "CrewBee task";
26712
26838
  output.metadata = {
26713
26839
  ...output.metadata,
26714
- sessionId: result.session_id,
26715
- taskId: result.task_id ?? result.session_id,
26716
- taskRef: result.task_ref
26840
+ ...normalized.metadata
26717
26841
  };
26718
26842
  }
26719
26843
  };
@@ -26731,7 +26855,7 @@ var CREWBEE_PACKAGE_NAME2 = "crewbee";
26731
26855
  function findConfiguredCrewBeeReleaseIntent() {
26732
26856
  const configPath = resolveOpenCodeConfigPath();
26733
26857
  const config2 = readOpenCodeConfig(configPath).config;
26734
- const plugins = Array.isArray(config2.plugin) ? config2.plugin : [];
26858
+ const plugins = findCrewBeePluginEntries(config2);
26735
26859
  for (const entry of plugins) {
26736
26860
  if (typeof entry !== "string") {
26737
26861
  continue;
@@ -26901,28 +27025,40 @@ function readWorkspacePackageJson(packageJsonPath) {
26901
27025
 
26902
27026
  // src/update/refresh.ts
26903
27027
  var FAILURE_RECHECK_MS = 30 * 60 * 1e3;
26904
- function startBackgroundReleaseRefresh(ctx, deps = createDefaultDependencies()) {
27028
+ function createDefaultReleaseLog(ctx, log) {
27029
+ if (log) {
27030
+ return log;
27031
+ }
27032
+ return async (message, extra, level) => {
27033
+ if (!ctx) {
27034
+ return;
27035
+ }
27036
+ await logCrewBee(ctx, message, extra, level);
27037
+ };
27038
+ }
27039
+ function startBackgroundReleaseRefresh(ctx, deps = createDefaultDependencies(), log) {
26905
27040
  if (!shouldEnableCrewBeeReleaseRefresh()) {
26906
27041
  return;
26907
27042
  }
26908
27043
  queueMicrotask(() => {
26909
- void runBackgroundReleaseRefresh(ctx, deps).catch(() => void 0);
27044
+ void runBackgroundReleaseRefresh(ctx, deps, log).catch(() => void 0);
26910
27045
  });
26911
27046
  }
26912
- async function runBackgroundReleaseRefresh(ctx, deps) {
27047
+ async function runBackgroundReleaseRefresh(ctx, deps, releaseLog) {
27048
+ const log = createDefaultReleaseLog(ctx, releaseLog);
26913
27049
  if (!acquireCrewBeeReleaseLock()) {
26914
- await logCrewBee(ctx, "CrewBee release refresh skipped because another refresh is already running", void 0, "debug");
27050
+ await log("CrewBee release refresh skipped because another refresh is already running", void 0, "debug");
26915
27051
  return { needsRefresh: false, reason: "up-to-date" };
26916
27052
  }
26917
27053
  try {
26918
27054
  const intent = findConfiguredCrewBeeReleaseIntent();
26919
27055
  if (!intent) {
26920
- await logCrewBee(ctx, "CrewBee release refresh skipped because plugin is not configured", void 0, "debug");
27056
+ await log("CrewBee release refresh skipped because plugin is not configured", void 0, "debug");
26921
27057
  return { needsRefresh: false, reason: "plugin-not-configured" };
26922
27058
  }
26923
27059
  if (intent.isPinned) {
26924
27060
  const currentVersion2 = readInstalledWorkspaceVersion(intent.workspaceRoot);
26925
- await logCrewBee(ctx, "CrewBee release refresh skipped for pinned version", {
27061
+ await log("CrewBee release refresh skipped for pinned version", {
26926
27062
  entry: intent.entry,
26927
27063
  pinnedVersion: intent.requestedVersion,
26928
27064
  currentVersion: currentVersion2
@@ -26938,7 +27074,7 @@ async function runBackgroundReleaseRefresh(ctx, deps) {
26938
27074
  ...state,
26939
27075
  lastCheckedAt: now
26940
27076
  });
26941
- await logCrewBee(ctx, "CrewBee release refresh could not resolve latest version", {
27077
+ await log("CrewBee release refresh could not resolve latest version", {
26942
27078
  entry: intent.entry,
26943
27079
  channel: intent.channel,
26944
27080
  currentVersion
@@ -26954,7 +27090,7 @@ async function runBackgroundReleaseRefresh(ctx, deps) {
26954
27090
  lastFailureAt: void 0,
26955
27091
  lastSucceededAt: now
26956
27092
  });
26957
- await logCrewBee(ctx, "CrewBee release refresh found current version already up to date", {
27093
+ await log("CrewBee release refresh found current version already up to date", {
26958
27094
  currentVersion,
26959
27095
  latestVersion,
26960
27096
  workspaceRoot: intent.workspaceRoot
@@ -26962,7 +27098,7 @@ async function runBackgroundReleaseRefresh(ctx, deps) {
26962
27098
  return { currentVersion, latestVersion, needsRefresh: false, reason: "up-to-date" };
26963
27099
  }
26964
27100
  if (shouldSkipFailedTargetByCooldown(state, now, latestVersion)) {
26965
- await logCrewBee(ctx, "CrewBee release refresh skipped by failure cooldown", {
27101
+ await log("CrewBee release refresh skipped by failure cooldown", {
26966
27102
  currentVersion,
26967
27103
  latestVersion,
26968
27104
  lastCheckedAt: state.lastCheckedAt,
@@ -26970,7 +27106,7 @@ async function runBackgroundReleaseRefresh(ctx, deps) {
26970
27106
  }, "debug");
26971
27107
  return { currentVersion, latestVersion, needsRefresh: true, reason: "refresh-required" };
26972
27108
  }
26973
- await logCrewBee(ctx, "CrewBee release refresh found newer version", {
27109
+ await log("CrewBee release refresh found newer version", {
26974
27110
  currentVersion,
26975
27111
  latestVersion,
26976
27112
  workspaceRoot: intent.workspaceRoot,
@@ -26988,7 +27124,7 @@ async function runBackgroundReleaseRefresh(ctx, deps) {
26988
27124
  lastFailureAt: now,
26989
27125
  lastKnownVersion: currentVersion
26990
27126
  });
26991
- await logCrewBee(ctx, "CrewBee release refresh failed to install latest version", {
27127
+ await log("CrewBee release refresh failed to install latest version", {
26992
27128
  currentVersion,
26993
27129
  latestVersion,
26994
27130
  workspaceRoot: intent.workspaceRoot
@@ -27003,7 +27139,7 @@ async function runBackgroundReleaseRefresh(ctx, deps) {
27003
27139
  lastFailureAt: void 0,
27004
27140
  lastSucceededAt: now
27005
27141
  });
27006
- await logCrewBee(ctx, "CrewBee release refresh installed newer version", {
27142
+ await log("CrewBee release refresh installed newer version", {
27007
27143
  currentVersion,
27008
27144
  latestVersion,
27009
27145
  workspaceRoot: intent.workspaceRoot
@@ -27056,7 +27192,7 @@ function createDefaultDependencies() {
27056
27192
  };
27057
27193
  }
27058
27194
 
27059
- // src/adapters/opencode/plugin.ts
27195
+ // src/adapters/opencode/plugin-v1.ts
27060
27196
  var OpenCodeCrewBeePlugin = async (ctx) => {
27061
27197
  const crewbeeConfigUpdate = ensureCrewBeeConfigFile({
27062
27198
  configRoot: resolveOpenCodeConfigRoot(),
@@ -27121,8 +27257,761 @@ var OpenCodeCrewBeePlugin = async (ctx) => {
27121
27257
  "experimental.session.compacting": createCompactionHook(ctx, store)
27122
27258
  };
27123
27259
  };
27124
- var plugin_default = OpenCodeCrewBeePlugin;
27260
+
27261
+ // src/adapters/opencode/v2/permissions.ts
27262
+ var PERMISSION_ACTION_MAP = {
27263
+ bash: "shell",
27264
+ write: "edit",
27265
+ patch: "edit",
27266
+ multiedit: "edit",
27267
+ task: "subagent",
27268
+ delegate_task: "subagent",
27269
+ lsp_diagnostics: void 0,
27270
+ look_at: void 0
27271
+ };
27272
+ var DROPPED_ACTIONS = /* @__PURE__ */ new Set(["lsp_diagnostics", "look_at"]);
27273
+ var DEFAULT_ALLOW_RULE = { action: "*", resource: "*", effect: "allow" };
27274
+ function mapPermissionAction(permission) {
27275
+ if (DROPPED_ACTIONS.has(permission)) {
27276
+ return void 0;
27277
+ }
27278
+ return PERMISSION_ACTION_MAP[permission] ?? permission;
27279
+ }
27280
+ function toV2PermissionRules(rules) {
27281
+ const mapped = [DEFAULT_ALLOW_RULE];
27282
+ for (const rule of rules) {
27283
+ const action = mapPermissionAction(rule.permission);
27284
+ if (!action) {
27285
+ continue;
27286
+ }
27287
+ mapped.push({
27288
+ action,
27289
+ resource: rule.pattern || "*",
27290
+ effect: rule.action
27291
+ });
27292
+ }
27293
+ return mapped;
27294
+ }
27295
+
27296
+ // src/adapters/opencode/v2/agent-definition.ts
27297
+ function createV2AgentDefinition(agent) {
27298
+ const resolved = agent.resolvedModel;
27299
+ return {
27300
+ id: agent.configKey,
27301
+ name: agent.configKey,
27302
+ description: agent.description,
27303
+ mode: agent.mode === "primary" ? "primary" : "subagent",
27304
+ hidden: agent.hidden,
27305
+ system: agent.prompt,
27306
+ model: resolved ? {
27307
+ providerID: resolved.providerID,
27308
+ id: resolved.modelID,
27309
+ ...resolved.variant ? { variant: resolved.variant } : {}
27310
+ } : void 0,
27311
+ permissions: toV2PermissionRules(agent.permission)
27312
+ };
27313
+ }
27314
+ function applyV2AgentDefinition(target, definition) {
27315
+ target.name = definition.name;
27316
+ target.description = definition.description;
27317
+ target.mode = definition.mode;
27318
+ target.hidden = definition.hidden;
27319
+ target.system = definition.system;
27320
+ target.permissions = definition.permissions;
27321
+ if (definition.model) {
27322
+ target.model = definition.model;
27323
+ } else {
27324
+ target.model = void 0;
27325
+ }
27326
+ }
27327
+ var OPEN_CODE_HOST_AGENT_KEYS = ["build", "plan", "general", "explore", "scout"];
27328
+
27329
+ // src/adapters/opencode/v2/logging.ts
27330
+ import { appendFileSync } from "node:fs";
27331
+ var CONSOLE_METHOD = {
27332
+ debug: "debug",
27333
+ info: "info",
27334
+ warn: "warn",
27335
+ error: "error"
27336
+ };
27337
+ function stringifyExtra(extra) {
27338
+ if (!extra || Object.keys(extra).length === 0) {
27339
+ return "";
27340
+ }
27341
+ try {
27342
+ return ` ${JSON.stringify(extra)}`;
27343
+ } catch {
27344
+ return " [unserializable extra]";
27345
+ }
27346
+ }
27347
+ async function logCrewBeeV2(message, extra, level = "info") {
27348
+ if (!shouldEmitCrewBeeLog(level)) {
27349
+ return;
27350
+ }
27351
+ const line = `[crewbee] ${message}${stringifyExtra(extra)}`;
27352
+ console[CONSOLE_METHOD[level] ?? "log"](line);
27353
+ const logFile = process.env.CREWBEE_LOG_FILE?.trim();
27354
+ if (!logFile) {
27355
+ return;
27356
+ }
27357
+ try {
27358
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} level=${level} ${line}
27359
+ `);
27360
+ } catch {
27361
+ }
27362
+ }
27363
+
27364
+ // src/adapters/opencode/v2/models.ts
27365
+ function readModelKey(model) {
27366
+ if (model.enabled === false) {
27367
+ return void 0;
27368
+ }
27369
+ const providerID = typeof model.providerID === "string" ? model.providerID : void 0;
27370
+ const modelID = typeof model.id === "string" ? model.id : typeof model.modelID === "string" ? model.modelID : void 0;
27371
+ if (!providerID || !modelID) {
27372
+ return void 0;
27373
+ }
27374
+ return `${providerID}/${modelID}`;
27375
+ }
27376
+ async function listOpenCodeAvailableModelsV2(ctx) {
27377
+ try {
27378
+ const output = await ctx.model.list();
27379
+ const models = output.data ?? [];
27380
+ const keys = /* @__PURE__ */ new Set();
27381
+ for (const model of models) {
27382
+ const key = readModelKey(model);
27383
+ if (key) {
27384
+ keys.add(key);
27385
+ }
27386
+ }
27387
+ return [...keys].sort();
27388
+ } catch {
27389
+ return void 0;
27390
+ }
27391
+ }
27392
+
27393
+ // src/adapters/opencode/v2/session-client.ts
27394
+ function normalizeRole(message) {
27395
+ if (typeof message.type === "string") {
27396
+ return message.type;
27397
+ }
27398
+ return typeof message.role === "string" ? message.role : "unknown";
27399
+ }
27400
+ function normalizeMessage(message) {
27401
+ const role = normalizeRole(message);
27402
+ const content = Array.isArray(message.content) ? message.content : [];
27403
+ const parts = [];
27404
+ for (const part of content) {
27405
+ if (part?.type === "text" && typeof part.text === "string") {
27406
+ parts.push({ type: "text", text: part.text });
27407
+ }
27408
+ }
27409
+ return {
27410
+ info: {
27411
+ role,
27412
+ id: typeof message.id === "string" ? message.id : "",
27413
+ time: message.time
27414
+ },
27415
+ parts
27416
+ };
27417
+ }
27418
+ function extractPromptText(body) {
27419
+ return body.parts.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n\n").trim();
27420
+ }
27421
+ async function applySessionTarget(ctx, sessionID, body) {
27422
+ if (body.agent) {
27423
+ await ctx.session.switchAgent({ sessionID, agent: body.agent });
27424
+ }
27425
+ if (body.model) {
27426
+ await ctx.session.switchModel({
27427
+ sessionID,
27428
+ model: { providerID: body.model.providerID, id: body.model.modelID }
27429
+ });
27430
+ } else {
27431
+ const fallback = (await ctx.model.default()).data;
27432
+ if (fallback) {
27433
+ await ctx.session.switchModel({ sessionID, model: { providerID: fallback.providerID, id: fallback.id } });
27434
+ }
27435
+ }
27436
+ }
27437
+ function describeLastAssistantError(messages) {
27438
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
27439
+ const message = messages[index];
27440
+ if (!message || normalizeRole(message) !== "assistant" || message.error === void 0 || message.error === null) {
27441
+ continue;
27442
+ }
27443
+ try {
27444
+ return JSON.stringify(message.error);
27445
+ } catch {
27446
+ return String(message.error);
27447
+ }
27448
+ }
27449
+ return void 0;
27450
+ }
27451
+ async function waitForSession(ctx, sessionID, signal) {
27452
+ if (signal?.aborted) {
27453
+ await ctx.session.interrupt({ sessionID, resume: false }).catch(() => void 0);
27454
+ throw new Error("Delegated session aborted before execution.");
27455
+ }
27456
+ const onAbort = () => {
27457
+ void ctx.session.interrupt({ sessionID, resume: false }).catch(() => void 0);
27458
+ };
27459
+ signal?.addEventListener("abort", onAbort, { once: true });
27460
+ try {
27461
+ await ctx.session.wait({ sessionID });
27462
+ } finally {
27463
+ signal?.removeEventListener("abort", onAbort);
27464
+ }
27465
+ if (signal?.aborted) throw new Error("Delegated session aborted.");
27466
+ const info = await ctx.session.get({ sessionID }).catch(() => void 0);
27467
+ if (info?.outcome === "failed") {
27468
+ const messages = await ctx.session.context({ sessionID }).catch(() => []);
27469
+ const detail = describeLastAssistantError(messages) ?? "unknown error";
27470
+ throw new Error(`Delegated session execution failed: ${detail}`);
27471
+ }
27472
+ }
27473
+ async function runPrompt(ctx, input, options) {
27474
+ options.signal?.throwIfAborted();
27475
+ await applySessionTarget(ctx, input.path.id, input.body);
27476
+ const text = extractPromptText(input.body);
27477
+ if (!text) {
27478
+ return { id: input.path.id };
27479
+ }
27480
+ options.signal?.throwIfAborted();
27481
+ await ctx.session.prompt({ sessionID: input.path.id, text });
27482
+ if (options.wait) {
27483
+ await waitForSession(ctx, input.path.id, options.signal);
27484
+ }
27485
+ return { id: input.path.id };
27486
+ }
27487
+ function createV2SessionClient(ctx, options = {}) {
27488
+ return {
27489
+ session: {
27490
+ async abort(input) {
27491
+ await ctx.session.interrupt({ sessionID: input.path.id, resume: false });
27492
+ return {};
27493
+ },
27494
+ async create(input) {
27495
+ return await ctx.session.create({
27496
+ parentID: input.body.parentID,
27497
+ title: input.body.title
27498
+ });
27499
+ },
27500
+ async get(input) {
27501
+ return await ctx.session.get({ sessionID: input.path.id });
27502
+ },
27503
+ async messages(input) {
27504
+ const messages = await ctx.session.context({ sessionID: input.path.id });
27505
+ return messages.map(normalizeMessage);
27506
+ },
27507
+ async prompt(input) {
27508
+ return await runPrompt(ctx, input, { wait: true, signal: options.signal });
27509
+ },
27510
+ async promptAsync(input) {
27511
+ options.signal?.throwIfAborted();
27512
+ return await runPrompt(ctx, input, { wait: true });
27513
+ },
27514
+ async todo() {
27515
+ await logCrewBeeV2(
27516
+ "OpenCode V2 has no session todo API; delegation continuity snapshots are disabled",
27517
+ void 0,
27518
+ "debug"
27519
+ );
27520
+ return [];
27521
+ }
27522
+ }
27523
+ };
27524
+ }
27525
+
27526
+ // src/adapters/opencode/v2/tool-registration.ts
27527
+ var SUBAGENT_TOOL_NAME = "subagent";
27528
+ var TASK_TOOL_ALIAS = "task";
27529
+ var DELEGATE_STATUS_TOOL_NAME = "delegate_status";
27530
+ var DELEGATE_CANCEL_TOOL_NAME = "delegate_cancel";
27531
+ var SUBAGENT_INPUT_SCHEMA = {
27532
+ type: "object",
27533
+ properties: {
27534
+ description: {
27535
+ type: "string",
27536
+ description: "A short (3-5 words) description of the task"
27537
+ },
27538
+ prompt: {
27539
+ type: "string",
27540
+ description: "The task for the CrewBee agent to perform"
27541
+ },
27542
+ agent: {
27543
+ type: "string",
27544
+ description: "CrewBee agent id or alias listed in the current Agent Profile collaboration section"
27545
+ },
27546
+ subagent_type: {
27547
+ type: "string",
27548
+ description: "Alias of `agent`, kept for CrewBee and OpenCode V1 compatibility"
27549
+ },
27550
+ task_id: {
27551
+ type: "string",
27552
+ description: "Existing delegated session to continue"
27553
+ },
27554
+ session_id: {
27555
+ type: "string",
27556
+ description: "Alias of `task_id`"
27557
+ },
27558
+ run_in_background: {
27559
+ type: "boolean",
27560
+ description: "Launch the delegated task in background mode"
27561
+ },
27562
+ background: {
27563
+ type: "boolean",
27564
+ description: "Alias of `run_in_background`"
27565
+ },
27566
+ mode: {
27567
+ type: "string",
27568
+ enum: ["foreground", "background"],
27569
+ description: "Delegation mode; defaults to foreground"
27570
+ }
27571
+ },
27572
+ required: ["prompt"],
27573
+ anyOf: [{ required: ["agent"] }, { required: ["subagent_type"] }],
27574
+ additionalProperties: false
27575
+ };
27576
+ var TASK_REF_INPUT_SCHEMA = {
27577
+ type: "object",
27578
+ properties: {
27579
+ task_ref: {
27580
+ type: "string",
27581
+ description: "CrewBee background task reference"
27582
+ }
27583
+ },
27584
+ required: ["task_ref"],
27585
+ additionalProperties: false
27586
+ };
27587
+ function readString(input, key) {
27588
+ const value = input[key];
27589
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
27590
+ }
27591
+ function normalizeTaskArgs(input) {
27592
+ const subagentType = readString(input, "agent") ?? readString(input, "subagent_type");
27593
+ const taskId = readString(input, "task_id") ?? readString(input, "session_id");
27594
+ const runInBackground = input.run_in_background === true || input.background === true || input.mode === "background";
27595
+ const args = {
27596
+ prompt: typeof input.prompt === "string" ? input.prompt : ""
27597
+ };
27598
+ if (typeof input.description === "string") {
27599
+ args.description = input.description;
27600
+ }
27601
+ if (subagentType) {
27602
+ args.subagent_type = subagentType;
27603
+ }
27604
+ if (taskId) {
27605
+ args.task_id = taskId;
27606
+ }
27607
+ if (runInBackground) {
27608
+ args.run_in_background = true;
27609
+ }
27610
+ if (input.mode === "background" || input.mode === "foreground") {
27611
+ args.mode = input.mode;
27612
+ }
27613
+ return args;
27614
+ }
27615
+ function createToolContext(input) {
27616
+ return {
27617
+ sessionID: input.context.sessionID,
27618
+ messageID: input.context.messageID,
27619
+ agent: input.context.agent,
27620
+ directory: input.directory,
27621
+ worktree: input.directory,
27622
+ abort: input.context.signal,
27623
+ metadata(update) {
27624
+ if (update.metadata) {
27625
+ Object.assign(input.metadata, update.metadata);
27626
+ }
27627
+ }
27628
+ };
27629
+ }
27630
+ function createV2DelegateToolDefinitions(input) {
27631
+ const tools = createDelegateTools({
27632
+ client: input.client,
27633
+ store: input.store,
27634
+ getProjectedAgents: input.getProjectedAgents,
27635
+ getAliasIndex: input.getAliasIndex,
27636
+ bindings: input.bindings
27637
+ });
27638
+ const taskTool = {
27639
+ name: SUBAGENT_TOOL_NAME,
27640
+ description: [
27641
+ "Delegate work to a CrewBee team member. This overrides OpenCode's native subagent tool with CrewBee's",
27642
+ "delegation engine; use `agent` (or `subagent_type`) to select an allowed Team member."
27643
+ ].join(" "),
27644
+ input: SUBAGENT_INPUT_SCHEMA,
27645
+ options: { codemode: false, permission: "subagent" },
27646
+ async execute(rawInput, context) {
27647
+ const scopedTools = input.createClient ? createDelegateTools({
27648
+ ...input,
27649
+ client: input.createClient(context.signal)
27650
+ }) : tools;
27651
+ const metadata = {};
27652
+ try {
27653
+ const args = normalizeTaskArgs(rawInput);
27654
+ const output = await scopedTools.task.execute(args, createToolContext({
27655
+ context,
27656
+ directory: input.directory,
27657
+ metadata
27658
+ }));
27659
+ const normalized = normalizeDelegateTaskOutput(output);
27660
+ return {
27661
+ content: normalized?.output ?? output,
27662
+ metadata: { ...metadata, ...normalized?.metadata ?? {} }
27663
+ };
27664
+ } catch (error45) {
27665
+ const message = error45 instanceof Error ? error45.message : String(error45);
27666
+ await logCrewBeeV2("Delegated task failed", { sessionID: context.sessionID, error: message }, "error");
27667
+ return {
27668
+ content: stringifyDelegateTaskResult(createFailedResult(context.sessionID, "delegate_error", message)),
27669
+ metadata
27670
+ };
27671
+ }
27672
+ }
27673
+ };
27674
+ const taskAliasTool = {
27675
+ ...taskTool,
27676
+ name: TASK_TOOL_ALIAS,
27677
+ description: taskTool.description
27678
+ };
27679
+ const delegateStatusTool = {
27680
+ name: DELEGATE_STATUS_TOOL_NAME,
27681
+ description: "Get the status of a CrewBee background delegation.",
27682
+ input: TASK_REF_INPUT_SCHEMA,
27683
+ options: { codemode: false, permission: DELEGATE_STATUS_TOOL_NAME },
27684
+ async execute(rawInput, context) {
27685
+ const taskRef = readString(rawInput, "task_ref") ?? "";
27686
+ return {
27687
+ content: await tools.delegate_status.execute(
27688
+ { task_ref: taskRef },
27689
+ createToolContext({ context, directory: input.directory, metadata: {} })
27690
+ )
27691
+ };
27692
+ }
27693
+ };
27694
+ const delegateCancelTool = {
27695
+ name: DELEGATE_CANCEL_TOOL_NAME,
27696
+ description: "Cancel a CrewBee background delegation.",
27697
+ input: TASK_REF_INPUT_SCHEMA,
27698
+ options: { codemode: false, permission: DELEGATE_CANCEL_TOOL_NAME },
27699
+ async execute(rawInput, context) {
27700
+ const taskRef = readString(rawInput, "task_ref") ?? "";
27701
+ return {
27702
+ content: await tools.delegate_cancel.execute(
27703
+ { task_ref: taskRef },
27704
+ createToolContext({ context, directory: input.directory, metadata: {} })
27705
+ )
27706
+ };
27707
+ }
27708
+ };
27709
+ return [taskTool, taskAliasTool, delegateStatusTool, delegateCancelTool];
27710
+ }
27711
+ function registerV2DelegateTools(editor, tools) {
27712
+ for (const tool of tools) {
27713
+ editor.add(tool);
27714
+ }
27715
+ }
27716
+
27717
+ // src/adapters/opencode/v2/plugin.ts
27718
+ var CREWBEE_PLUGIN_ID = "crewbee";
27719
+ var BOOTSTRAP_DEFAULTS = { defaultMode: DEFAULT_OPENCODE_EXECUTION_MODE };
27720
+ var HANDLED_EVENT_TYPES = /* @__PURE__ */ new Set([
27721
+ "session.status",
27722
+ "session.idle",
27723
+ "session.execution.failed",
27724
+ "session.compaction.ended",
27725
+ "session.deleted"
27726
+ ]);
27727
+ function resolveEventSessionID(event) {
27728
+ const sessionID = event.data?.sessionID;
27729
+ return typeof sessionID === "string" ? sessionID : void 0;
27730
+ }
27731
+ function createBootstrap(teamLibrary, availableModels, existingConfigKeys) {
27732
+ return createOpenCodeBootstrap({
27733
+ teamLibrary,
27734
+ defaults: BOOTSTRAP_DEFAULTS,
27735
+ availableModels,
27736
+ ...existingConfigKeys ? { existingConfigKeys } : {}
27737
+ });
27738
+ }
27739
+ async function reportTeamIssues(issues) {
27740
+ for (const issue2 of issues) {
27741
+ await logCrewBeeV2(issue2.message, {
27742
+ ...issue2.filePath ? { filePath: issue2.filePath } : {},
27743
+ ...issue2.code ? { code: issue2.code } : {},
27744
+ ...issue2.path ? { path: issue2.path } : {},
27745
+ ...issue2.sourceScope ? { sourceScope: issue2.sourceScope } : {},
27746
+ ...issue2.fixable !== void 0 ? { fixable: issue2.fixable } : {},
27747
+ ...issue2.suggestion ? { suggestion: issue2.suggestion } : {}
27748
+ }, issue2.level === "warning" ? "warn" : "error");
27749
+ }
27750
+ }
27751
+ async function finalizeBackgroundTask2(client, store, sessionID) {
27752
+ const task = store.getTaskBySession(sessionID);
27753
+ if (!task || task.status === "completed" || task.status === "failed" || task.status === "cancelled") {
27754
+ return;
27755
+ }
27756
+ const message = await extractAssistantText(client, task.sessionID, task.anchor).catch((error45) => {
27757
+ store.setTaskStatus(task.taskRef, "failed", {
27758
+ message: "Failed to read delegated session output.",
27759
+ lastError: String(error45)
27760
+ });
27761
+ return void 0;
27762
+ });
27763
+ if (message === void 0) {
27764
+ return;
27765
+ }
27766
+ store.setTaskStatus(task.taskRef, "completed", {
27767
+ message: message || "Delegated session completed with no text output."
27768
+ });
27769
+ }
27770
+ async function setupCrewBeeV2(ctx) {
27771
+ const directory = ctx.location.directory;
27772
+ const crewbeeConfigUpdate = ensureCrewBeeConfigFile({
27773
+ configRoot: resolveOpenCodeConfigRoot(),
27774
+ mode: "startup"
27775
+ });
27776
+ if (crewbeeConfigUpdate.changed) {
27777
+ await logCrewBeeV2("CrewBee auto-repaired Team config", {
27778
+ backupPath: crewbeeConfigUpdate.backupPath,
27779
+ configPath: crewbeeConfigUpdate.configPath,
27780
+ reason: crewbeeConfigUpdate.reason
27781
+ }, "warn");
27782
+ }
27783
+ const teamLibrary = loadDefaultTeamLibrary(directory);
27784
+ const issues = validateTeamLibrary(teamLibrary);
27785
+ const blocking = issues.filter((issue2) => issue2.level === "error" && issue2.blocking !== false);
27786
+ if (blocking.length > 0) {
27787
+ throw new Error(blocking.map((issue2) => issue2.message).join("\n"));
27788
+ }
27789
+ await reportTeamIssues(issues);
27790
+ const availableModels = await listOpenCodeAvailableModelsV2(ctx);
27791
+ let boot = createBootstrap(teamLibrary, availableModels);
27792
+ let aliasIndex = createProjectedAgentAliasIndex(boot.projectedAgents);
27793
+ const managedAgentKeys = /* @__PURE__ */ new Set();
27794
+ const bindings = /* @__PURE__ */ new Map();
27795
+ const store = new DelegateStateStore(directory);
27796
+ const abortController = new AbortController();
27797
+ const client = createV2SessionClient(ctx);
27798
+ await logCrewBeeV2("CrewBee plugin initialized", {
27799
+ directory,
27800
+ projectedAgentCount: boot.projectedAgents.length,
27801
+ visibleAgentCount: boot.projectedAgents.filter((agent) => !agent.hidden).length,
27802
+ defaultAgent: boot.configPatch.defaultAgent,
27803
+ openCodeVersion: ctx.app.version
27804
+ });
27805
+ await ctx.agent.transform((editor) => {
27806
+ const existingConfigKeys = editor.list().map((agent) => String(agent.id)).filter((id) => !managedAgentKeys.has(id));
27807
+ const next = createBootstrap(teamLibrary, availableModels, existingConfigKeys);
27808
+ boot = next;
27809
+ aliasIndex = createProjectedAgentAliasIndex(next.projectedAgents);
27810
+ for (const agent of next.projectedAgents) {
27811
+ const definition = createV2AgentDefinition(agent);
27812
+ const isNew = !managedAgentKeys.has(agent.configKey);
27813
+ editor.update(agent.configKey, (target) => {
27814
+ applyV2AgentDefinition(target, definition);
27815
+ });
27816
+ managedAgentKeys.add(agent.configKey);
27817
+ if (isNew) {
27818
+ void logCrewBeeV2("Projected CrewBee agent", {
27819
+ configKey: agent.configKey,
27820
+ canonicalAgentId: agent.canonicalAgentId,
27821
+ mode: agent.mode,
27822
+ hidden: agent.hidden,
27823
+ model: definition.model ? `${definition.model.providerID}/${definition.model.id}` : void 0
27824
+ }, "debug");
27825
+ }
27826
+ }
27827
+ for (const key of OPEN_CODE_HOST_AGENT_KEYS) {
27828
+ if (!editor.get(key)) {
27829
+ continue;
27830
+ }
27831
+ editor.update(key, (target) => {
27832
+ target.hidden = true;
27833
+ target.mode = "subagent";
27834
+ });
27835
+ }
27836
+ const defaultAgent = next.configPatch.defaultAgent;
27837
+ if (defaultAgent && editor.get(defaultAgent)) {
27838
+ editor.default(defaultAgent);
27839
+ }
27840
+ });
27841
+ await ctx.tool.transform((editor) => {
27842
+ const tools = createV2DelegateToolDefinitions({
27843
+ client,
27844
+ store,
27845
+ getProjectedAgents: () => boot.projectedAgents,
27846
+ getAliasIndex: () => aliasIndex,
27847
+ bindings,
27848
+ directory,
27849
+ createClient: (signal) => createV2SessionClient(ctx, { signal })
27850
+ });
27851
+ registerV2DelegateTools(editor, tools);
27852
+ });
27853
+ const systemTransformHook = createSystemTransformHook(bindings, () => teamLibrary.loadIssues ?? []);
27854
+ await ctx.session.hook("prompt", async (event) => {
27855
+ const session = await ctx.session.get({ sessionID: event.sessionID }).catch(() => void 0);
27856
+ const selectedAgent = typeof session?.agent === "string" ? session.agent : boot.configPatch.defaultAgent;
27857
+ if (!selectedAgent) {
27858
+ return;
27859
+ }
27860
+ const agent = resolveProjectedAgentSelection(boot.projectedAgents, { configKey: selectedAgent });
27861
+ if (!agent) {
27862
+ return;
27863
+ }
27864
+ const binding2 = createSessionRuntimeBinding({
27865
+ projection: boot.projection,
27866
+ sessionID: event.sessionID,
27867
+ teamId: agent.teamId,
27868
+ canonicalAgentId: agent.canonicalAgentId,
27869
+ mode: DEFAULT_OPENCODE_EXECUTION_MODE,
27870
+ source: typeof session?.agent === "string" ? "host-agent-selection" : "plugin-default"
27871
+ });
27872
+ bindings.set(event.sessionID, binding2);
27873
+ const model = session?.model;
27874
+ store.setCheckpoint(
27875
+ event.sessionID,
27876
+ createCheckpoint(
27877
+ agent,
27878
+ model ? { providerID: model.providerID, modelID: model.id } : void 0
27879
+ )
27880
+ );
27881
+ });
27882
+ await ctx.session.hook("context", async (event) => {
27883
+ const agent = boot.projectedAgents.find((candidate) => candidate.configKey === event.agent);
27884
+ const resolved = agent?.resolvedModel;
27885
+ if (resolved?.temperature !== void 0) {
27886
+ event.options.temperature = resolved.temperature;
27887
+ }
27888
+ if (resolved?.topP !== void 0) {
27889
+ event.options.topP = resolved.topP;
27890
+ }
27891
+ const output = { system: [] };
27892
+ await systemTransformHook({ sessionID: event.sessionID, model: event.model }, output);
27893
+ for (const text of output.system) {
27894
+ event.system.push({ type: "text", text });
27895
+ }
27896
+ });
27897
+ await ctx.session.hook("compaction", (event) => {
27898
+ event.system.push({ type: "text", text: buildCompactionContext(store, event.sessionID) });
27899
+ });
27900
+ await ctx.tool.hook("execute.before", (event) => {
27901
+ if (event.tool !== SUBAGENT_TOOL_NAME && event.tool !== TASK_TOOL_ALIAS) {
27902
+ return;
27903
+ }
27904
+ if (!bindings.has(event.sessionID)) {
27905
+ return;
27906
+ }
27907
+ const input = event.input;
27908
+ if (!input || typeof input !== "object") {
27909
+ return;
27910
+ }
27911
+ const args = input;
27912
+ for (const key of ["agent", "subagent_type"]) {
27913
+ const value = args[key];
27914
+ if (typeof value !== "string") {
27915
+ continue;
27916
+ }
27917
+ const resolved = resolveProjectedAgentAlias(aliasIndex, value);
27918
+ if (resolved) {
27919
+ args[key] = resolved.agent.configKey;
27920
+ }
27921
+ }
27922
+ });
27923
+ await ctx.tool.hook("execute.after", (event) => {
27924
+ if (event.tool !== SUBAGENT_TOOL_NAME && event.tool !== TASK_TOOL_ALIAS) {
27925
+ return;
27926
+ }
27927
+ if (event.status !== "completed") {
27928
+ return;
27929
+ }
27930
+ const result = event.result;
27931
+ if (typeof result.content !== "string") {
27932
+ return;
27933
+ }
27934
+ const normalized = normalizeDelegateTaskOutput(result.content);
27935
+ if (!normalized) {
27936
+ return;
27937
+ }
27938
+ result.content = normalized.output;
27939
+ result.metadata = { ...result.metadata ?? {}, ...normalized.metadata };
27940
+ });
27941
+ const subscription = ctx.event.subscribe({ signal: abortController.signal });
27942
+ void (async () => {
27943
+ for await (const raw of subscription) {
27944
+ if (abortController.signal.aborted) {
27945
+ break;
27946
+ }
27947
+ const event = raw;
27948
+ const type = event.type;
27949
+ if (!type || !HANDLED_EVENT_TYPES.has(type)) {
27950
+ continue;
27951
+ }
27952
+ const sessionID = resolveEventSessionID(event);
27953
+ if (!sessionID) {
27954
+ continue;
27955
+ }
27956
+ if (type === "session.status") {
27957
+ const status = event.data?.status;
27958
+ const task = store.getTaskBySession(sessionID);
27959
+ if (task && status?.type === "busy") {
27960
+ store.setTaskStatus(task.taskRef, "running");
27961
+ }
27962
+ if (status?.type === "idle") {
27963
+ await finalizeBackgroundTask2(client, store, sessionID);
27964
+ }
27965
+ continue;
27966
+ }
27967
+ if (type === "session.idle") {
27968
+ await finalizeBackgroundTask2(client, store, sessionID);
27969
+ continue;
27970
+ }
27971
+ if (type === "session.execution.failed") {
27972
+ const task = store.getTaskBySession(sessionID);
27973
+ if (task) {
27974
+ store.setTaskStatus(task.taskRef, "failed", {
27975
+ message: "Delegated session failed.",
27976
+ lastError: JSON.stringify(event.data?.error ?? "session.execution.failed")
27977
+ });
27978
+ }
27979
+ continue;
27980
+ }
27981
+ if (type === "session.compaction.ended") {
27982
+ store.markCompacted(sessionID);
27983
+ continue;
27984
+ }
27985
+ if (type === "session.deleted") {
27986
+ const task = store.getTaskBySession(sessionID);
27987
+ if (task && task.status !== "completed" && task.status !== "failed") {
27988
+ store.setTaskStatus(task.taskRef, "cancelled", { message: "Delegated session deleted." });
27989
+ }
27990
+ store.clearSession(sessionID);
27991
+ bindings.delete(sessionID);
27992
+ }
27993
+ }
27994
+ })().catch((error45) => {
27995
+ void logCrewBeeV2("CrewBee event subscription stopped", { error: String(error45) }, "warn");
27996
+ });
27997
+ startBackgroundReleaseRefresh(void 0, void 0, logCrewBeeV2);
27998
+ return () => {
27999
+ abortController.abort();
28000
+ };
28001
+ }
28002
+ var crewBeePluginV2 = {
28003
+ id: CREWBEE_PLUGIN_ID,
28004
+ setup: setupCrewBeeV2
28005
+ };
28006
+
28007
+ // src/adapters/opencode/plugin.ts
28008
+ var plugin = {
28009
+ ...crewBeePluginV2,
28010
+ server: OpenCodeCrewBeePlugin
28011
+ };
28012
+ var plugin_default = plugin;
27125
28013
  export {
28014
+ CREWBEE_PLUGIN_ID,
27126
28015
  OpenCodeCrewBeePlugin,
27127
28016
  plugin_default as default
27128
28017
  };