pantheon-opencode 2.1.4 → 2.1.6

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 (49) hide show
  1. package/AGENTS.global.md +6 -6
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/README.md +60 -233
  5. package/README.pt-BR.md +64 -220
  6. package/package.json +1 -1
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +1 -1
  9. package/scripts/install/opencode.mjs +12 -0
  10. package/scripts/test-slice.mjs +34 -2
  11. package/skills-lock.json +1 -1
  12. package/src/agents/aphrodite.md +3 -1
  13. package/src/agents/apollo.md +1 -0
  14. package/src/agents/athena.md +1 -0
  15. package/src/agents/demeter.md +2 -0
  16. package/src/agents/gaia.md +1 -0
  17. package/src/agents/hephaestus.md +1 -0
  18. package/src/agents/hermes.md +2 -1
  19. package/src/agents/iris.md +1 -0
  20. package/src/agents/mnemosyne.md +1 -0
  21. package/src/agents/nyx.md +1 -0
  22. package/src/agents/prometheus.md +1 -0
  23. package/src/agents/talos.md +1 -0
  24. package/src/agents/themis.md +1 -0
  25. package/src/agents/zeus.md +8 -2
  26. package/src/instructions/backend-standards.instructions.md +5 -0
  27. package/src/instructions/test-economy.instructions.md +6 -6
  28. package/src/mcp/pantheon_vision.py +4 -1
  29. package/src/pantheon/auto-permissions.ts +4 -3
  30. package/src/pantheon/deepwork/deepwork-tool.ts +23 -75
  31. package/src/pantheon/deepwork/plan-schema.ts +4 -2
  32. package/src/pantheon/deepwork/plan-tracker.ts +380 -90
  33. package/src/pantheon/jev-decision-tool.ts +1 -7
  34. package/src/pantheon/local-decision-tool.ts +1 -1
  35. package/src/pantheon/native-vision.ts +1 -1
  36. package/src/pantheon/skill-search-tool.ts +241 -47
  37. package/src/pantheon/tool-context.ts +23 -0
  38. package/src/pantheon/tools.ts +46 -41
  39. package/src/plugin/index.js +521 -222
  40. package/src/plugin.ts +1 -0
  41. package/src/plugins/tui/dist/tui.d.ts +7 -6
  42. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  43. package/src/plugins/tui/dist/tui.js +198 -269
  44. package/src/plugins/tui/dist/tui.js.map +1 -1
  45. package/src/plugins/tui/package-lock.json +2 -2
  46. package/src/plugins/tui/package.json +1 -1
  47. package/src/plugins/tui/src/index.tsx +7 -45
  48. package/src/plugins/tui/src/tui-prefs.ts +3 -9
  49. package/src/skills/test-slicing/SKILL.md +14 -8
@@ -51,7 +51,8 @@ var SAFE_DEV_BINARIES = /* @__PURE__ */ new Set([
51
51
  "cargo",
52
52
  "go",
53
53
  "sh",
54
- "bash"
54
+ "bash",
55
+ "opencode-quota"
55
56
  ]);
56
57
  function isExcludedReadPath(rawPath) {
57
58
  const trimmed = rawPath.trim();
@@ -144,7 +145,7 @@ function evaluateAutoPermission(event, options = {}) {
144
145
  return { decision: "allow", reason: "pantheon-native-tool" };
145
146
  }
146
147
  if (READ_ONLY_AGENTS.has(agent)) {
147
- if (["edit", "write", "hashline_edit", "bash", "shell"].includes(action)) {
148
+ if (["edit", "write", "hashline_edit", "bash", "shell", "execute"].includes(action)) {
148
149
  event.effect = "deny";
149
150
  event.message = `Pantheon auto-permissions denied: read-only agent '${agent}' cannot execute mutating action '${action}'`;
150
151
  return { decision: "deny", reason: "read-only-role-violation" };
@@ -163,7 +164,7 @@ function evaluateAutoPermission(event, options = {}) {
163
164
  event.effect = "allow";
164
165
  return { decision: "allow", reason: "safe-read-action" };
165
166
  }
166
- if (action === "bash" || action === "shell") {
167
+ if (action === "bash" || action === "shell" || action === "execute") {
167
168
  const rawCmd = Array.isArray(event.resources) && typeof event.resources[0] === "string" ? event.resources[0] : "";
168
169
  if (rawCmd) {
169
170
  if (isDangerousCommand(rawCmd)) {
@@ -7531,14 +7532,8 @@ var JEV_INPUT_SCHEMA = {
7531
7532
  type: "object",
7532
7533
  additionalProperties: false,
7533
7534
  required: ["schemaVersion"],
7534
- anyOf: [
7535
- { required: ["state"] },
7536
- { required: ["delegateId", "resultSummaryKind", "resultMetrics", "criteria"] },
7537
- { required: ["candidates"] },
7538
- { required: ["claims"] }
7539
- ],
7540
7535
  properties: {
7541
- schemaVersion: { type: "integer", const: 1 },
7536
+ schemaVersion: { type: "integer", enum: [1] },
7542
7537
  state: { type: "string", minLength: 1, maxLength: 12e3 },
7543
7538
  mode: { type: "string", enum: ["skills", "delegation", "review", "rank", "verify", "order"] },
7544
7539
  questions: { type: "array", minItems: 1, maxItems: 4, items: questionSchema },
@@ -9267,7 +9262,7 @@ function discoverActiveSessionId(directory) {
9267
9262
  function createV2VisionTool(runtime) {
9268
9263
  return {
9269
9264
  name: "vision_describe",
9270
- description: "Analyze an image with an OpenCode Zen multimodal model confirmed by the current V2 model catalog. Prefers the OpenCode Go MiMo 2.6 Flash model and falls back to another live image-capable Zen model. Free-tier models are excluded (the direct gateway rejects them). Accepts a local path, file URL, public HTTP(S) URL, or base64 image data URI.",
9265
+ description: "Analyze an image with an OpenCode Zen multimodal model confirmed by the current model catalog. Prefers the OpenCode Go MiMo 2.6 Flash model and falls back to another live image-capable Zen model. Free-tier models are excluded (the direct gateway rejects them). Accepts a local path, file URL, public HTTP(S) URL, or base64 image data URI.",
9271
9266
  input: {
9272
9267
  type: "object",
9273
9268
  additionalProperties: false,
@@ -12035,6 +12030,21 @@ ${renderMarkdown(query, days, pricing)}`;
12035
12030
  // src/pantheon/deepwork/deepwork-tool.ts
12036
12031
  import { z as z3 } from "zod";
12037
12032
 
12033
+ // src/pantheon/tool-context.ts
12034
+ function resolveToolCwd(context, fallbackDir) {
12035
+ const ctx = context ?? {};
12036
+ if (typeof ctx.directory === "string" && ctx.directory.trim().length > 0) {
12037
+ return ctx.directory;
12038
+ }
12039
+ if (typeof ctx.worktree === "string" && ctx.worktree.trim().length > 0) {
12040
+ return ctx.worktree;
12041
+ }
12042
+ if (typeof fallbackDir === "string" && fallbackDir.trim().length > 0) {
12043
+ return fallbackDir;
12044
+ }
12045
+ return process.cwd();
12046
+ }
12047
+
12038
12048
  // src/pantheon/deepwork/plan-projection.ts
12039
12049
  import { join as join15 } from "node:path";
12040
12050
  function generateChatProjection(plan, cwd = process.cwd()) {
@@ -12263,9 +12273,11 @@ var DecisionStatusSchema = z2.enum(["pending", "resolved"]);
12263
12273
  var PlanDecisionSchema = z2.object({
12264
12274
  id: z2.string().min(1),
12265
12275
  question: z2.string().min(1),
12266
- options: z2.array(z2.string()).min(2),
12276
+ options: z2.array(z2.string()).default([]),
12267
12277
  chosen: z2.string().optional(),
12268
- status: DecisionStatusSchema.default("pending")
12278
+ choice: z2.string().optional(),
12279
+ status: DecisionStatusSchema.default("pending"),
12280
+ resolved_at: z2.string().optional()
12269
12281
  });
12270
12282
  var PlanRiskSchema = z2.object({
12271
12283
  id: z2.string().min(1),
@@ -12280,7 +12292,7 @@ var PlanMetadataSchema = z2.object({
12280
12292
  var DeepworkPlanSchema = z2.object({
12281
12293
  plan_id: z2.string().min(1),
12282
12294
  title: z2.string().min(1),
12283
- intent: z2.string().min(1),
12295
+ intent: z2.string().default("Plano de deepwork estruturado."),
12284
12296
  done_when: z2.array(z2.string()).default([]),
12285
12297
  decisions_needed: z2.array(PlanDecisionSchema).default([]),
12286
12298
  risks: z2.array(PlanRiskSchema).default([]),
@@ -12325,14 +12337,193 @@ function computeTaskReadiness(plan) {
12325
12337
  });
12326
12338
  return { ...plan, tasks: updatedTasks };
12327
12339
  }
12340
+ function inferAcceptanceKind(check) {
12341
+ const lower = check.toLowerCase();
12342
+ if (lower.includes("test") || lower.includes("pytest") || lower.includes("assert")) return "test";
12343
+ if (lower.includes("file") || lower.includes("exist") || lower.includes("criado") || lower.includes("path"))
12344
+ return "file";
12345
+ if (lower.startsWith("npm ") || lower.startsWith("bash ") || lower.startsWith("alembic ") || lower.startsWith("git ") || lower.includes(" && ") || lower.includes(" || "))
12346
+ return "command";
12347
+ return "manual";
12348
+ }
12349
+ function normalizePlanData(data, fallbackSlug = "plan") {
12350
+ const obj = data && typeof data === "object" ? data : {};
12351
+ const slug = String(obj.plan_id ?? obj.slug ?? fallbackSlug).trim() || fallbackSlug;
12352
+ const title = String(obj.title ?? slug).trim() || slug;
12353
+ const intent = String(obj.intent ?? "").trim() || "Plano de deepwork estruturado.";
12354
+ const done_when = Array.isArray(obj.done_when) ? obj.done_when.map((s) => String(s).trim()).filter(Boolean) : [];
12355
+ const rawDecisions = Array.isArray(obj.decisions_needed) ? obj.decisions_needed : Array.isArray(obj.decisions) ? obj.decisions : [];
12356
+ const decisions_needed = rawDecisions.map((d, idx) => {
12357
+ const dec = d && typeof d === "object" ? d : {};
12358
+ const id = String(dec.id ?? `D${String(idx + 1).padStart(2, "0")}`).trim();
12359
+ const question = String(dec.question ?? dec.title ?? "Decis\xE3o necess\xE1ria").trim();
12360
+ const rawOptions = Array.isArray(dec.options) ? dec.options : typeof dec.options === "string" ? [dec.options] : [];
12361
+ const options = rawOptions.map((opt) => String(opt).trim()).filter(Boolean);
12362
+ const chosenVal = dec.chosen ?? dec.choice;
12363
+ const chosen = typeof chosenVal === "string" ? chosenVal : void 0;
12364
+ const statusVal = String(dec.status ?? "").trim().toLowerCase();
12365
+ const status = statusVal === "resolved" || chosen !== void 0 ? "resolved" : "pending";
12366
+ return {
12367
+ id,
12368
+ question,
12369
+ options,
12370
+ chosen,
12371
+ choice: chosen,
12372
+ status,
12373
+ resolved_at: typeof dec.resolved_at === "string" ? dec.resolved_at : void 0
12374
+ };
12375
+ });
12376
+ const rawRisks = Array.isArray(obj.risks) ? obj.risks : [];
12377
+ const risks = rawRisks.map((r, idx) => {
12378
+ const risk = r && typeof r === "object" ? r : {};
12379
+ return {
12380
+ id: String(risk.id ?? `R${String(idx + 1).padStart(2, "0")}`).trim(),
12381
+ description: String(risk.description ?? risk.risk ?? "").trim() || "Risco n\xE3o especificado",
12382
+ mitigation: typeof risk.mitigation === "string" ? risk.mitigation : void 0
12383
+ };
12384
+ });
12385
+ const out_of_scope = Array.isArray(obj.out_of_scope) ? obj.out_of_scope.map((s) => String(s).trim()).filter(Boolean) : [];
12386
+ const rawTasks = Array.isArray(obj.tasks) ? obj.tasks : [];
12387
+ const tasks = rawTasks.map((t, idx) => {
12388
+ const task = t && typeof t === "object" ? t : {};
12389
+ const id = String(task.id ?? `T${String(idx + 1).padStart(2, "0")}`).trim();
12390
+ const taskTitle = String(task.title ?? task.name ?? `Task ${idx + 1}`).trim();
12391
+ const description = typeof task.description === "string" ? task.description : void 0;
12392
+ const rawAgent = task.agent ?? task.owner ?? task.assignee;
12393
+ const agent = typeof rawAgent === "string" && rawAgent.trim().length > 0 ? rawAgent.replace(/^@/, "").trim() : "zeus";
12394
+ const rawPhase = task.phase;
12395
+ let phase = 1;
12396
+ if (typeof rawPhase === "number" && Number.isFinite(rawPhase)) {
12397
+ phase = rawPhase;
12398
+ } else if (typeof rawPhase === "string") {
12399
+ const match = rawPhase.match(/\d+/);
12400
+ if (match) phase = Number.parseInt(match[0], 10);
12401
+ }
12402
+ const rawState = String(task.state ?? task.status ?? "pending").trim().toLowerCase();
12403
+ const validStates = [
12404
+ "pending",
12405
+ "ready",
12406
+ "in_progress",
12407
+ "done",
12408
+ "failed",
12409
+ "blocked"
12410
+ ];
12411
+ const state = validStates.includes(rawState) ? rawState : "pending";
12412
+ const depends_on = Array.isArray(task.depends_on) ? task.depends_on.map((dep) => String(dep).trim()).filter(Boolean) : [];
12413
+ const parallel_safe = Boolean(task.parallel_safe ?? task.parallel);
12414
+ const rawAcceptance = Array.isArray(task.acceptance) ? task.acceptance : Array.isArray(task.acceptance_criteria) ? task.acceptance_criteria : Array.isArray(task.criteria) ? task.criteria : [];
12415
+ const acceptance = rawAcceptance.map((a) => {
12416
+ if (typeof a === "string") {
12417
+ const checkText2 = a.trim();
12418
+ return {
12419
+ kind: inferAcceptanceKind(checkText2),
12420
+ check: checkText2,
12421
+ fails_now: true,
12422
+ verified: false
12423
+ };
12424
+ }
12425
+ const acc = a && typeof a === "object" ? a : {};
12426
+ const checkText = String(
12427
+ acc.check ?? acc.description ?? acc.title ?? acc.name ?? "verify"
12428
+ ).trim();
12429
+ const rawKind = String(acc.kind ?? "").trim().toLowerCase();
12430
+ const validKinds = ["test", "command", "file", "manual"];
12431
+ const kind = validKinds.includes(rawKind) ? rawKind : inferAcceptanceKind(checkText);
12432
+ return {
12433
+ kind,
12434
+ check: checkText || "verify",
12435
+ fails_now: typeof acc.fails_now === "boolean" ? acc.fails_now : true,
12436
+ verified: Boolean(acc.verified),
12437
+ proof: typeof acc.proof === "string" ? acc.proof : void 0
12438
+ };
12439
+ });
12440
+ const rawResult = task.result && typeof task.result === "object" ? task.result : void 0;
12441
+ const result = rawResult ? {
12442
+ summary: typeof rawResult.summary === "string" ? rawResult.summary : void 0,
12443
+ verified_at: typeof rawResult.verified_at === "string" ? rawResult.verified_at : void 0,
12444
+ artifacts: Array.isArray(rawResult.artifacts) ? rawResult.artifacts.map((art) => String(art)) : void 0
12445
+ } : void 0;
12446
+ return {
12447
+ id,
12448
+ title: taskTitle,
12449
+ description,
12450
+ agent,
12451
+ phase,
12452
+ state,
12453
+ depends_on,
12454
+ parallel_safe,
12455
+ acceptance,
12456
+ result
12457
+ };
12458
+ });
12459
+ const rawMeta = obj.metadata && typeof obj.metadata === "object" ? obj.metadata : {};
12460
+ const now = (/* @__PURE__ */ new Date()).toISOString();
12461
+ const metadata = {
12462
+ created_at: typeof rawMeta.created_at === "string" ? rawMeta.created_at : now,
12463
+ updated_at: typeof rawMeta.updated_at === "string" ? rawMeta.updated_at : now,
12464
+ version: typeof rawMeta.version === "number" ? rawMeta.version : 1
12465
+ };
12466
+ return computeTaskReadiness({
12467
+ plan_id: slug,
12468
+ title,
12469
+ intent,
12470
+ done_when,
12471
+ decisions_needed,
12472
+ risks,
12473
+ out_of_scope,
12474
+ tasks,
12475
+ metadata
12476
+ });
12477
+ }
12328
12478
  async function readPlan(cwd = process.cwd(), slug) {
12329
12479
  const path5 = deepworkPlanJsonPath(cwd, slug);
12480
+ let raw;
12481
+ try {
12482
+ raw = await readFile6(path5, "utf8");
12483
+ } catch (err) {
12484
+ if (err.code === "ENOENT") {
12485
+ return null;
12486
+ }
12487
+ throw err;
12488
+ }
12489
+ let parsed;
12330
12490
  try {
12331
- const raw = await readFile6(path5, "utf8");
12332
- const parsed = JSON.parse(raw);
12333
- return DeepworkPlanSchema.parse(parsed);
12491
+ parsed = JSON.parse(raw);
12492
+ } catch (err) {
12493
+ throw new Error(`Plano '${slug}' em ${path5} cont\xE9m JSON inv\xE1lido: ${err.message}`);
12494
+ }
12495
+ const result = DeepworkPlanSchema.safeParse(parsed);
12496
+ if (result.success) {
12497
+ return result.data;
12498
+ }
12499
+ try {
12500
+ const normalized = normalizePlanData(parsed, slug);
12501
+ const repairedResult = DeepworkPlanSchema.safeParse(normalized);
12502
+ if (repairedResult.success) {
12503
+ return repairedResult.data;
12504
+ }
12334
12505
  } catch {
12335
- return null;
12506
+ }
12507
+ const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
12508
+ throw new Error(`Plano '${slug}' em ${path5} falhou na valida\xE7\xE3o de schema: ${issues}`);
12509
+ }
12510
+ var planLocks = /* @__PURE__ */ new Map();
12511
+ async function withPlanLock(cwd, slug, fn) {
12512
+ const key = `${cwd}::${slug}`;
12513
+ const prev = planLocks.get(key) ?? Promise.resolve();
12514
+ let resolveCurrent;
12515
+ const current = new Promise((resolve8) => {
12516
+ resolveCurrent = resolve8;
12517
+ });
12518
+ planLocks.set(key, current);
12519
+ try {
12520
+ await prev;
12521
+ return await fn();
12522
+ } finally {
12523
+ resolveCurrent?.();
12524
+ if (planLocks.get(key) === current) {
12525
+ planLocks.delete(key);
12526
+ }
12336
12527
  }
12337
12528
  }
12338
12529
  async function writePlan(cwd = process.cwd(), plan) {
@@ -12346,14 +12537,17 @@ async function writePlan(cwd = process.cwd(), plan) {
12346
12537
  version: (plan.metadata.version || 1) + 1
12347
12538
  }
12348
12539
  });
12540
+ const randomSuffix = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;
12349
12541
  const jsonPath = deepworkPlanJsonPath(cwd, plan.plan_id);
12350
- const jsonTmp = `${jsonPath}.tmp`;
12542
+ const jsonTmp = `${jsonPath}.tmp.${randomSuffix}`;
12351
12543
  await writeFile3(jsonTmp, `${JSON.stringify(normalized, null, 2)}
12352
12544
  `, "utf8");
12353
12545
  await rename5(jsonTmp, jsonPath);
12354
12546
  const mdPath = deepworkPlanMdPath(cwd, plan.plan_id);
12547
+ const mdTmp = `${mdPath}.tmp.${randomSuffix}`;
12355
12548
  const mdContent = generateMarkdownDocument(normalized);
12356
- await writeFile3(mdPath, mdContent, "utf8");
12549
+ await writeFile3(mdTmp, mdContent, "utf8");
12550
+ await rename5(mdTmp, mdPath);
12357
12551
  }
12358
12552
  async function appendJournal(cwd = process.cwd(), slug, event) {
12359
12553
  const dir = deepworkPlanDir(cwd, slug);
@@ -12364,93 +12558,101 @@ async function appendJournal(cwd = process.cwd(), slug, event) {
12364
12558
  await appendFile3(journalPath, line, "utf8");
12365
12559
  }
12366
12560
  async function updateTaskState(cwd = process.cwd(), slug, taskId, state, result) {
12367
- const plan = await readPlan(cwd, slug);
12368
- if (!plan) {
12369
- throw new Error(`Deepwork plan "${slug}" not found`);
12370
- }
12371
- const taskIndex = plan.tasks.findIndex((t) => t.id === taskId);
12372
- const existingTask = plan.tasks[taskIndex];
12373
- if (taskIndex === -1 || !existingTask) {
12374
- throw new Error(`Task "${taskId}" not found in plan "${slug}"`);
12375
- }
12376
- const updatedResult = result ? { ...existingTask.result ?? {}, ...result } : existingTask.result;
12377
- const updatedTask = {
12378
- ...existingTask,
12379
- state,
12380
- ...updatedResult !== void 0 ? { result: updatedResult } : {}
12381
- };
12382
- const updatedTasks = [...plan.tasks];
12383
- updatedTasks[taskIndex] = updatedTask;
12384
- const nextPlan = { ...plan, tasks: updatedTasks };
12385
- await writePlan(cwd, nextPlan);
12386
- await appendJournal(cwd, slug, {
12387
- type: "task_state_changed",
12388
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12389
- payload: { taskId, state, result }
12561
+ return withPlanLock(cwd, slug, async () => {
12562
+ const plan = await readPlan(cwd, slug);
12563
+ if (!plan) {
12564
+ throw new Error(`Deepwork plan "${slug}" not found`);
12565
+ }
12566
+ const taskIndex = plan.tasks.findIndex((t) => t.id === taskId);
12567
+ const existingTask = plan.tasks[taskIndex];
12568
+ if (taskIndex === -1 || !existingTask) {
12569
+ throw new Error(`Task "${taskId}" not found in plan "${slug}"`);
12570
+ }
12571
+ const updatedResult = result ? { ...existingTask.result ?? {}, ...result } : existingTask.result;
12572
+ const updatedTask = {
12573
+ ...existingTask,
12574
+ state,
12575
+ ...updatedResult !== void 0 ? { result: updatedResult } : {}
12576
+ };
12577
+ const updatedTasks = [...plan.tasks];
12578
+ updatedTasks[taskIndex] = updatedTask;
12579
+ const nextPlan = { ...plan, tasks: updatedTasks };
12580
+ await writePlan(cwd, nextPlan);
12581
+ await appendJournal(cwd, slug, {
12582
+ type: "task_state_changed",
12583
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12584
+ payload: { taskId, state, result }
12585
+ });
12586
+ return await readPlan(cwd, slug) ?? nextPlan;
12390
12587
  });
12391
- return await readPlan(cwd, slug) ?? nextPlan;
12392
12588
  }
12393
12589
  async function verifyTaskAcceptance(cwd = process.cwd(), slug, taskId, checkIndex, verified, proof) {
12394
- const plan = await readPlan(cwd, slug);
12395
- if (!plan) {
12396
- throw new Error(`Deepwork plan "${slug}" not found`);
12397
- }
12398
- const taskIndex = plan.tasks.findIndex((t) => t.id === taskId);
12399
- const task = plan.tasks[taskIndex];
12400
- if (taskIndex === -1 || !task) {
12401
- throw new Error(`Task "${taskId}" not found in plan "${slug}"`);
12402
- }
12403
- const currentAcc = task.acceptance[checkIndex];
12404
- if (!currentAcc) {
12405
- throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`);
12406
- }
12407
- const updatedAcceptance = [...task.acceptance];
12408
- const resolvedProof = proof ?? currentAcc.proof;
12409
- updatedAcceptance[checkIndex] = {
12410
- ...currentAcc,
12411
- verified,
12412
- ...resolvedProof !== void 0 ? { proof: resolvedProof } : {}
12413
- };
12414
- const allVerified = updatedAcceptance.every((acc) => acc.verified);
12415
- const updatedTasks = [...plan.tasks];
12416
- updatedTasks[taskIndex] = {
12417
- ...task,
12418
- acceptance: updatedAcceptance,
12419
- state: allVerified ? "done" : task.state
12420
- };
12421
- const nextPlan = { ...plan, tasks: updatedTasks };
12422
- await writePlan(cwd, nextPlan);
12423
- await appendJournal(cwd, slug, {
12424
- type: "acceptance_verified",
12425
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12426
- payload: { taskId, checkIndex, verified, proof, allVerified }
12590
+ return withPlanLock(cwd, slug, async () => {
12591
+ const plan = await readPlan(cwd, slug);
12592
+ if (!plan) {
12593
+ throw new Error(`Deepwork plan "${slug}" not found`);
12594
+ }
12595
+ const taskIndex = plan.tasks.findIndex((t) => t.id === taskId);
12596
+ const task = plan.tasks[taskIndex];
12597
+ if (taskIndex === -1 || !task) {
12598
+ throw new Error(`Task "${taskId}" not found in plan "${slug}"`);
12599
+ }
12600
+ const currentAcc = task.acceptance[checkIndex];
12601
+ if (!currentAcc) {
12602
+ throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`);
12603
+ }
12604
+ const updatedAcceptance = [...task.acceptance];
12605
+ const resolvedProof = proof ?? currentAcc.proof;
12606
+ updatedAcceptance[checkIndex] = {
12607
+ ...currentAcc,
12608
+ verified,
12609
+ ...resolvedProof !== void 0 ? { proof: resolvedProof } : {}
12610
+ };
12611
+ const allVerified = updatedAcceptance.every((acc) => acc.verified);
12612
+ const updatedTasks = [...plan.tasks];
12613
+ updatedTasks[taskIndex] = {
12614
+ ...task,
12615
+ acceptance: updatedAcceptance,
12616
+ state: allVerified ? "done" : task.state
12617
+ };
12618
+ const nextPlan = { ...plan, tasks: updatedTasks };
12619
+ await writePlan(cwd, nextPlan);
12620
+ await appendJournal(cwd, slug, {
12621
+ type: "acceptance_verified",
12622
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12623
+ payload: { taskId, checkIndex, verified, proof, allVerified }
12624
+ });
12625
+ return await readPlan(cwd, slug) ?? nextPlan;
12427
12626
  });
12428
- return await readPlan(cwd, slug) ?? nextPlan;
12429
12627
  }
12430
12628
  async function resolvePlanDecision(cwd = process.cwd(), slug, decisionId, chosen) {
12431
- const plan = await readPlan(cwd, slug);
12432
- if (!plan) {
12433
- throw new Error(`Deepwork plan "${slug}" not found`);
12434
- }
12435
- const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId);
12436
- const existingDec = plan.decisions_needed[decIndex];
12437
- if (decIndex === -1 || !existingDec) {
12438
- throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`);
12439
- }
12440
- const updatedDecisions = [...plan.decisions_needed];
12441
- updatedDecisions[decIndex] = {
12442
- ...existingDec,
12443
- chosen,
12444
- status: "resolved"
12445
- };
12446
- const nextPlan = { ...plan, decisions_needed: updatedDecisions };
12447
- await writePlan(cwd, nextPlan);
12448
- await appendJournal(cwd, slug, {
12449
- type: "decision_resolved",
12450
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12451
- payload: { decisionId, chosen }
12629
+ return withPlanLock(cwd, slug, async () => {
12630
+ const plan = await readPlan(cwd, slug);
12631
+ if (!plan) {
12632
+ throw new Error(`Deepwork plan "${slug}" not found`);
12633
+ }
12634
+ const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId);
12635
+ const existingDec = plan.decisions_needed[decIndex];
12636
+ if (decIndex === -1 || !existingDec) {
12637
+ throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`);
12638
+ }
12639
+ const updatedDecisions = [...plan.decisions_needed];
12640
+ updatedDecisions[decIndex] = {
12641
+ ...existingDec,
12642
+ chosen,
12643
+ choice: chosen,
12644
+ status: "resolved",
12645
+ resolved_at: (/* @__PURE__ */ new Date()).toISOString()
12646
+ };
12647
+ const nextPlan = { ...plan, decisions_needed: updatedDecisions };
12648
+ await writePlan(cwd, nextPlan);
12649
+ await appendJournal(cwd, slug, {
12650
+ type: "decision_resolved",
12651
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12652
+ payload: { decisionId, chosen }
12653
+ });
12654
+ return await readPlan(cwd, slug) ?? nextPlan;
12452
12655
  });
12453
- return await readPlan(cwd, slug) ?? nextPlan;
12454
12656
  }
12455
12657
  async function listPlans(cwd = process.cwd()) {
12456
12658
  const root = deepworkRootDir(cwd);
@@ -12583,7 +12785,7 @@ function createDeepworkTool(cwd = process.cwd()) {
12583
12785
  output: {},
12584
12786
  async execute(input, context) {
12585
12787
  const parsed = DeepworkToolInputSchema.parse(input);
12586
- const effectiveCwd = typeof context?.directory === "string" ? context.directory : cwd;
12788
+ const effectiveCwd = resolveToolCwd(context, cwd);
12587
12789
  if (parsed.action === "list") {
12588
12790
  const plans = await listPlans(effectiveCwd);
12589
12791
  if (plans.length === 0) {
@@ -12612,67 +12814,36 @@ function createDeepworkTool(cwd = process.cwd()) {
12612
12814
  throw new Error(`O par\xE2metro 'slug' \xE9 obrigat\xF3rio para a a\xE7\xE3o '${parsed.action}'.`);
12613
12815
  }
12614
12816
  if (parsed.action === "init") {
12615
- const title = parsed.title?.trim() || slug;
12616
- const intent = parsed.intent?.trim() || "Plano de deepwork estruturado.";
12617
- const rawTasks = parsed.tasks ?? [];
12618
- const rawDecisions = parsed.decisions ?? [];
12619
- const doneWhen = parsed.done_when ?? [];
12620
- const tasks = rawTasks.map((t, idx) => ({
12621
- id: typeof t.id === "string" ? t.id : `T${String(idx + 1).padStart(2, "0")}`,
12622
- title: typeof t.title === "string" ? t.title : `Task ${idx + 1}`,
12623
- description: typeof t.description === "string" ? t.description : void 0,
12624
- agent: typeof t.agent === "string" ? t.agent : "zeus",
12625
- phase: typeof t.phase === "number" ? t.phase : 1,
12626
- state: typeof t.state === "string" ? t.state : "pending",
12627
- depends_on: Array.isArray(t.depends_on) ? t.depends_on : [],
12628
- parallel_safe: Boolean(t.parallel_safe),
12629
- acceptance: Array.isArray(t.acceptance) ? t.acceptance.map((a) => ({
12630
- kind: a.kind || "command",
12631
- check: a.check || "verify",
12632
- fails_now: a.fails_now ?? true,
12633
- verified: a.verified ?? false,
12634
- proof: a.proof
12635
- })) : []
12636
- }));
12637
- const decisions = rawDecisions.map((d, idx) => ({
12638
- id: typeof d.id === "string" ? d.id : `D${String(idx + 1).padStart(2, "0")}`,
12639
- question: typeof d.question === "string" ? d.question : "Decis\xE3o necess\xE1ria",
12640
- options: Array.isArray(d.options) ? d.options : ["Sim", "N\xE3o"],
12641
- chosen: typeof d.chosen === "string" ? d.chosen : void 0,
12642
- status: d.chosen ? "resolved" : "pending"
12643
- }));
12644
- const initialPlan = computeTaskReadiness({
12645
- plan_id: slug,
12646
- title,
12647
- intent,
12648
- done_when: doneWhen,
12649
- decisions_needed: decisions,
12650
- risks: [],
12651
- out_of_scope: [],
12652
- tasks,
12653
- metadata: {
12654
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
12655
- updated_at: (/* @__PURE__ */ new Date()).toISOString(),
12656
- version: 1
12657
- }
12658
- });
12659
- await writePlan(effectiveCwd, initialPlan);
12660
- await appendJournal(effectiveCwd, slug, {
12661
- type: "plan_created",
12662
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12663
- payload: { slug, title, tasks_count: tasks.length }
12817
+ const initialPlan = normalizePlanData(
12818
+ {
12819
+ plan_id: slug,
12820
+ title: parsed.title,
12821
+ intent: parsed.intent,
12822
+ done_when: parsed.done_when,
12823
+ decisions_needed: parsed.decisions,
12824
+ tasks: parsed.tasks
12825
+ },
12826
+ slug
12827
+ );
12828
+ await withPlanLock(effectiveCwd, slug, async () => {
12829
+ await writePlan(effectiveCwd, initialPlan);
12830
+ await appendJournal(effectiveCwd, slug, {
12831
+ type: "plan_created",
12832
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12833
+ payload: { slug, title: initialPlan.title, tasks_count: initialPlan.tasks.length }
12834
+ });
12664
12835
  });
12665
12836
  const projection = generateChatProjection(initialPlan, effectiveCwd);
12666
12837
  const approvalQ = buildApprovalQuestion(initialPlan);
12667
12838
  const todoPayload = {
12668
- todos: tasks.map((t) => ({
12839
+ todos: initialPlan.tasks.map((t) => ({
12669
12840
  content: `[${t.id}] ${t.title}`,
12670
12841
  status: t.state === "done" ? "completed" : t.state === "in_progress" ? "in_progress" : "pending"
12671
12842
  }))
12672
12843
  };
12673
12844
  return {
12674
12845
  output: [
12675
- `\u2705 Plano de Deepwork '${title}' inicializado com sucesso em \`.pantheon/deepwork/${slug}/\`!`,
12846
+ `\u2705 Plano de Deepwork '${initialPlan.title}' inicializado com sucesso em \`.pantheon/deepwork/${slug}/\`!`,
12676
12847
  `- \u{1F517} **Deeplink PLAN.md:** [Abrir PLAN.md](file://${deepworkPlanMdPath(effectiveCwd, slug)})`,
12677
12848
  `- \u{1F517} **Deeplink plan.json:** [Abrir plan.json](file://${deepworkPlanJsonPath(effectiveCwd, slug)})`,
12678
12849
  "",
@@ -13012,7 +13183,7 @@ var v2InputSchema = {
13012
13183
  "complexity"
13013
13184
  ],
13014
13185
  properties: {
13015
- schemaVersion: { type: "integer", const: 1 },
13186
+ schemaVersion: { type: "integer", enum: [1] },
13016
13187
  candidateAgents: { type: "array", maxItems: 14, items: { type: "string", minLength: 1 } },
13017
13188
  domain: { type: ["string", "null"] },
13018
13189
  candidateSkillIds: { type: "array", maxItems: 64, items: { type: "string", minLength: 1 } },
@@ -13799,6 +13970,11 @@ function createModelCommand(options = {}) {
13799
13970
  };
13800
13971
  }
13801
13972
 
13973
+ // src/pantheon/skill-search-tool.ts
13974
+ import { existsSync as existsSync8, readdirSync as readdirSync2, readFileSync as readFileSync7 } from "node:fs";
13975
+ import { homedir as homedir8 } from "node:os";
13976
+ import { join as join18 } from "node:path";
13977
+
13802
13978
  // scripts/skill-search.mjs
13803
13979
  import { spawnSync } from "node:child_process";
13804
13980
  import { pathToFileURL } from "node:url";
@@ -14018,6 +14194,75 @@ var invokedDirectly = process.argv[1] !== void 0 && import.meta.url === pathToFi
14018
14194
  if (invokedDirectly) main();
14019
14195
 
14020
14196
  // src/pantheon/skill-search-tool.ts
14197
+ function extractSkillMetadata(content, fallbackName) {
14198
+ let name = fallbackName;
14199
+ let description = "";
14200
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14201
+ const yaml = fmMatch?.[1];
14202
+ if (yaml) {
14203
+ const nameMatch = yaml.match(/^name:\s*["']?([^"'\r\n]+)["']?/m);
14204
+ if (nameMatch?.[1]) name = nameMatch[1].trim();
14205
+ const descMatch = yaml.match(/^description:\s*["']?([^"'\r\n]+)["']?/m);
14206
+ if (descMatch?.[1]) description = descMatch[1].trim();
14207
+ }
14208
+ if (!description) {
14209
+ const withoutFm = content.replace(/^---\r?\n[\s\S]*?\r?\n---/, "").trim();
14210
+ const lines = withoutFm.split("\n");
14211
+ for (const l of lines) {
14212
+ const trimmed = l.trim();
14213
+ if (trimmed && !trimmed.startsWith("#")) {
14214
+ description = trimmed.slice(0, 160);
14215
+ break;
14216
+ }
14217
+ }
14218
+ }
14219
+ return { name, description };
14220
+ }
14221
+ function scanInstalledSkills(cwd = process.cwd()) {
14222
+ const map = /* @__PURE__ */ new Map();
14223
+ for (const entry of PANTHEON_SKILL_CATALOG) {
14224
+ map.set(entry.id.toLowerCase(), {
14225
+ id: entry.id,
14226
+ description: entry.description,
14227
+ path: `src/skills/${entry.id}/SKILL.md`,
14228
+ scope: "internal"
14229
+ });
14230
+ }
14231
+ const scanDir = (baseDir, scope) => {
14232
+ try {
14233
+ if (!existsSync8(baseDir)) return;
14234
+ const entries = readdirSync2(baseDir, { withFileTypes: true });
14235
+ for (const entry of entries) {
14236
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
14237
+ const skillName = entry.name;
14238
+ if (skillName.startsWith(".")) continue;
14239
+ const skillMd = join18(baseDir, skillName, "SKILL.md");
14240
+ if (existsSync8(skillMd)) {
14241
+ try {
14242
+ const raw = readFileSync7(skillMd, "utf8");
14243
+ const { name, description } = extractSkillMetadata(raw, skillName);
14244
+ const id = (name || skillName).trim();
14245
+ map.set(id.toLowerCase(), {
14246
+ id,
14247
+ description: description || skillName,
14248
+ path: skillMd,
14249
+ scope
14250
+ });
14251
+ } catch {
14252
+ }
14253
+ }
14254
+ }
14255
+ } catch {
14256
+ }
14257
+ };
14258
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join18(homedir8(), ".config");
14259
+ scanDir(join18(xdgConfig, "opencode", "skills"), "global");
14260
+ scanDir(join18(homedir8(), ".agents", "skills"), "global");
14261
+ scanDir(join18(cwd, ".opencode", "skills"), "project");
14262
+ scanDir(join18(cwd, ".agents", "skills"), "project");
14263
+ scanDir(join18(cwd, "skills"), "project");
14264
+ return map;
14265
+ }
14021
14266
  var TOOL_DESCRIPTION3 = "Advisory discovery tool for skills. Queries installed Pantheon skills and external registries (Anthropic catalog, skills.sh, GitHub). Returns matched skill IDs, descriptions, install counts, and provenance tiers. Zeus uses this to recommend project-scoped skills (.agents/skills/) before proactively prompting the user via the question tool.";
14022
14267
  var SKILL_SEARCH_INPUT_SCHEMA = {
14023
14268
  type: "object",
@@ -14047,7 +14292,38 @@ var SKILL_SEARCH_INPUT_SCHEMA = {
14047
14292
  }
14048
14293
  }
14049
14294
  };
14050
- function executeSkillSearch(input) {
14295
+ function scoreSkillMatch(id, description, queryTokens) {
14296
+ const idLower = id.toLowerCase();
14297
+ const descLower = description.toLowerCase();
14298
+ const idTokens = idLower.split(/[^a-z0-9]+/).filter(Boolean);
14299
+ const descWords = descLower.split(/[^a-z0-9]+/).filter(Boolean);
14300
+ let score = 0;
14301
+ let matchedTokens = 0;
14302
+ for (const t of queryTokens) {
14303
+ let tokenScore = 0;
14304
+ if (idLower === t) {
14305
+ tokenScore += 20;
14306
+ } else if (idTokens.includes(t)) {
14307
+ tokenScore += 12;
14308
+ } else if (idTokens.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w)))) {
14309
+ tokenScore += 6;
14310
+ }
14311
+ if (descWords.includes(t)) {
14312
+ tokenScore += 5;
14313
+ } else if (descWords.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w)))) {
14314
+ tokenScore += 2;
14315
+ }
14316
+ if (tokenScore > 0) {
14317
+ score += tokenScore;
14318
+ matchedTokens += 1;
14319
+ }
14320
+ }
14321
+ if (matchedTokens > 1) {
14322
+ score += matchedTokens * 5;
14323
+ }
14324
+ return { score, matchedTokens };
14325
+ }
14326
+ function executeSkillSearch(input, options = {}) {
14051
14327
  const query = typeof input.query === "string" ? input.query.trim() : "";
14052
14328
  if (query.length === 0) {
14053
14329
  return { ok: false, query: "", count: 0, results: [], failures: ["query must be non-empty"] };
@@ -14061,35 +14337,34 @@ function executeSkillSearch(input) {
14061
14337
  "skills-sh"
14062
14338
  ]
14063
14339
  );
14064
- const results = [];
14065
14340
  const failures = [];
14066
- if (sources.has("installed")) {
14067
- const tokens = query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2);
14068
- if (tokens.length > 0) {
14069
- for (const entry of PANTHEON_SKILL_CATALOG) {
14070
- const idLower = entry.id.toLowerCase();
14071
- const descLower = entry.description.toLowerCase();
14072
- const matchScore = tokens.reduce((score, t) => {
14073
- const stem = t.length > 4 ? t.slice(0, 4) : t;
14074
- return score + (idLower.includes(t) || descLower.includes(t) || idLower.includes(stem) || descLower.includes(stem) ? 1 : 0);
14075
- }, 0);
14076
- if (matchScore > 0) {
14077
- results.push({
14078
- skill: entry.id,
14079
- description: entry.description,
14080
- source: "installed",
14081
- installed: true,
14082
- installs: null,
14083
- installCommand: null
14084
- });
14085
- }
14341
+ const cwd = options.cwd ?? process.cwd();
14342
+ const installedMap = scanInstalledSkills(cwd);
14343
+ const tokens = query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1);
14344
+ const scoredResults = [];
14345
+ if (sources.has("installed") && tokens.length > 0) {
14346
+ const minThreshold = tokens.length > 1 ? 5 : 2;
14347
+ for (const entry of installedMap.values()) {
14348
+ const { score } = scoreSkillMatch(entry.id, entry.description, tokens);
14349
+ if (score >= minThreshold) {
14350
+ scoredResults.push({
14351
+ skill: entry.id,
14352
+ description: entry.description,
14353
+ source: "installed",
14354
+ installed: true,
14355
+ installs: null,
14356
+ installCommand: null,
14357
+ path: entry.path,
14358
+ scope: entry.scope,
14359
+ score
14360
+ });
14086
14361
  }
14087
14362
  }
14088
14363
  }
14089
14364
  const externalSources = ["anthropic", "skills-sh", "github"].filter((s) => sources.has(s));
14090
- if (externalSources.length > 0 && results.length < limit) {
14365
+ if (externalSources.length > 0 && scoredResults.length < limit) {
14091
14366
  try {
14092
- const extLimit = limit - results.length;
14367
+ const extLimit = limit - scoredResults.length;
14093
14368
  const extRes = searchSkillSources(query, {
14094
14369
  limit: extLimit,
14095
14370
  sources: externalSources
@@ -14098,15 +14373,31 @@ function executeSkillSearch(input) {
14098
14373
  failures.push(...extRes.failures);
14099
14374
  }
14100
14375
  if (Array.isArray(extRes.entries)) {
14376
+ const minThreshold = tokens.length > 1 ? 5 : 2;
14101
14377
  for (const entry of extRes.entries) {
14102
- results.push({
14378
+ const bareName = (entry.skill.includes("@") ? entry.skill.split("@")[1] : entry.skill).toLowerCase();
14379
+ const isInstalled = installedMap.has(entry.skill.toLowerCase()) || installedMap.has(bareName);
14380
+ const installedRecord = installedMap.get(entry.skill.toLowerCase()) || installedMap.get(bareName);
14381
+ const { score } = scoreSkillMatch(entry.skill, entry.skill, tokens);
14382
+ if (score < minThreshold && !isInstalled) {
14383
+ continue;
14384
+ }
14385
+ if (scoredResults.some(
14386
+ (r) => r.skill.toLowerCase() === entry.skill.toLowerCase() || bareName && r.skill.toLowerCase() === bareName
14387
+ )) {
14388
+ continue;
14389
+ }
14390
+ scoredResults.push({
14103
14391
  skill: entry.skill,
14104
14392
  description: entry.skill,
14105
14393
  source: entry.source,
14106
- installed: false,
14394
+ installed: isInstalled,
14107
14395
  installs: entry.installs ?? null,
14108
- url: entry.url,
14109
- installCommand: `npx skills add ${entry.skill} -a opencode -y`
14396
+ ...entry.url ? { url: entry.url } : {},
14397
+ installCommand: isInstalled ? null : `npx skills add ${entry.skill} -a opencode -y`,
14398
+ path: isInstalled && installedRecord ? installedRecord.path : null,
14399
+ ...isInstalled && installedRecord ? { scope: installedRecord.scope } : {},
14400
+ score: score || 1
14110
14401
  });
14111
14402
  }
14112
14403
  }
@@ -14116,7 +14407,8 @@ function executeSkillSearch(input) {
14116
14407
  );
14117
14408
  }
14118
14409
  }
14119
- const bounded = results.slice(0, limit);
14410
+ scoredResults.sort((a, b) => b.score - a.score);
14411
+ const bounded = scoredResults.slice(0, limit).map(({ score: _, ...item }) => item);
14120
14412
  return {
14121
14413
  ok: true,
14122
14414
  query,
@@ -14125,15 +14417,18 @@ function executeSkillSearch(input) {
14125
14417
  failures
14126
14418
  };
14127
14419
  }
14128
- function createV2SkillSearchDefinition() {
14420
+ function createV2SkillSearchDefinition(defaultDir) {
14129
14421
  return {
14130
14422
  name: "pantheon_skill_search",
14131
14423
  description: TOOL_DESCRIPTION3,
14132
14424
  input: SKILL_SEARCH_INPUT_SCHEMA,
14133
14425
  output: {},
14134
- execute: async (input) => ({
14135
- output: JSON.stringify(executeSkillSearch(input), null, 2)
14136
- })
14426
+ execute: async (input, context) => {
14427
+ const cwd = resolveToolCwd(context, defaultDir);
14428
+ return {
14429
+ output: JSON.stringify(executeSkillSearch(input, { cwd }), null, 2)
14430
+ };
14431
+ }
14137
14432
  };
14138
14433
  }
14139
14434
 
@@ -14351,18 +14646,18 @@ var MODEL_INPUT = {
14351
14646
  scope: {
14352
14647
  type: "string",
14353
14648
  enum: ["project"],
14354
- description: "Project scope only; global overrides are not supported in V2."
14649
+ description: "Project scope only; global overrides are not supported."
14355
14650
  }
14356
14651
  }
14357
14652
  };
14358
14653
  var modelCommand = createModelCommand({ v2Mode: true });
14359
14654
  async function executeModel(input, context) {
14360
14655
  if (input.scope !== void 0 && input.scope !== "project") {
14361
- return { output: "Error: V2 pantheon_model is project-only; global scope is not supported." };
14656
+ return { output: "Error: pantheon_model is project-only; global scope is not supported." };
14362
14657
  }
14363
14658
  if (Object.hasOwn(input, "confirm") || Object.hasOwn(input, "authorize_global")) {
14364
14659
  return {
14365
- output: "Error: V2 pantheon_model does not accept authorization flags; global authorization is not supported by this tool."
14660
+ output: "Error: pantheon_model does not accept authorization flags; global authorization is not supported by this tool."
14366
14661
  };
14367
14662
  }
14368
14663
  const output = await modelCommand.pantheon_model.execute(
@@ -14446,34 +14741,37 @@ var SHELL_INPUT = {
14446
14741
  }
14447
14742
  }
14448
14743
  };
14449
- var shellTool = {
14450
- name: "shell",
14451
- description: "Execute a shell command in the workspace directory. Alias for bash execution.",
14452
- input: SHELL_INPUT,
14453
- output: {},
14454
- execute: async (input, context) => {
14455
- const command = String(input.command ?? "");
14456
- if (!command.trim()) {
14457
- return { output: "", ok: false, error: "Command cannot be empty" };
14458
- }
14459
- const toolCtx = toolContext(context);
14460
- const cwd = toolCtx.directory || process.cwd();
14461
- try {
14462
- const { stdout, stderr } = await execAsync(command, {
14463
- cwd,
14464
- maxBuffer: 10 * 1024 * 1024,
14465
- shell: "/bin/bash"
14466
- });
14467
- const output = [stdout, stderr].filter(Boolean).join("\n");
14468
- return { output, ok: true };
14469
- } catch (err) {
14470
- const execError = err;
14471
- const output = [execError.stdout, execError.stderr, execError.message].filter(Boolean).join("\n");
14472
- return { output, ok: false, error: output };
14744
+ function createShellTool(fallbackDir) {
14745
+ return {
14746
+ name: "shell",
14747
+ description: "Execute a shell command in the workspace directory. Alias for bash execution.",
14748
+ input: SHELL_INPUT,
14749
+ output: {},
14750
+ execute: async (input, context) => {
14751
+ const raw = input ?? {};
14752
+ const command = String(raw.command ?? raw.cmd ?? "");
14753
+ if (!command.trim()) {
14754
+ return { output: "", ok: false, error: "Command cannot be empty" };
14755
+ }
14756
+ const cwd = resolveToolCwd(context, fallbackDir);
14757
+ try {
14758
+ const { stdout, stderr } = await execAsync(command, {
14759
+ cwd,
14760
+ maxBuffer: 10 * 1024 * 1024,
14761
+ shell: "/bin/bash"
14762
+ });
14763
+ const output = [stdout, stderr].filter(Boolean).join("\n");
14764
+ return { output, ok: true };
14765
+ } catch (err) {
14766
+ const execError = err;
14767
+ const output = [execError.stdout, execError.stderr, execError.message].filter(Boolean).join("\n");
14768
+ return { output, ok: false, error: output };
14769
+ }
14473
14770
  }
14474
- }
14475
- };
14476
- function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) {
14771
+ };
14772
+ }
14773
+ var shellTool = createShellTool();
14774
+ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime, hostLocationDirectory) {
14477
14775
  const definitions = [
14478
14776
  {
14479
14777
  name: "hashline_edit",
@@ -14484,14 +14782,14 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) {
14484
14782
  },
14485
14783
  {
14486
14784
  name: "pantheon_cost",
14487
- description: "Report token usage and USD cost by agent and phase, by model, and by session, over the last N days from opencode.db (read-only). Costs come from the models.dev catalog cached on disk: a call reads that cache and never waits on the network unless refreshPricing is set, a stale cache is refreshed in the background and the report says so, and an unpriced model reads \u2014 and is excluded from the totals, which then say partial. Pass session=<root session id> to aggregate that session plus its descendant sessions. Phase may be unknown on V2; costs are catalog list prices, not an invoice.",
14785
+ description: "Report token usage and USD cost by agent and phase, by model, and by session, over the last N days from opencode.db (read-only). Costs come from the models.dev catalog cached on disk: a call reads that cache and never waits on the network unless refreshPricing is set, a stale cache is refreshed in the background and the report says so, and an unpriced model reads \u2014 and is excluded from the totals, which then say partial. Pass session=<root session id> to aggregate that session plus its descendant sessions. Phase may be unknown; costs are catalog list prices, not an invoice.",
14488
14786
  input: COST_INPUT,
14489
14787
  output: {},
14490
14788
  execute: executeCost
14491
14789
  },
14492
14790
  {
14493
14791
  name: "pantheon_model",
14494
- description: 'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. V2 ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model selection. Global overrides are not read or written in V2; future global support requires separate explicit authorization. Pass action="status" to read project-scoped overrides. Never writes .env or top-level model/small_model.',
14792
+ description: 'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. Ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model selection. Global overrides are not read or written; future global support requires separate explicit authorization. Pass action="status" to read project-scoped overrides. Never writes .env or top-level model/small_model.',
14495
14793
  input: MODEL_INPUT,
14496
14794
  output: {},
14497
14795
  execute: executeModel
@@ -14504,9 +14802,9 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) {
14504
14802
  );
14505
14803
  definitions.push(todowriteTool);
14506
14804
  definitions.push(todoreadTool);
14507
- definitions.push(shellTool);
14508
- definitions.push(createV2SkillSearchDefinition());
14509
- definitions.push(createDeepworkTool());
14805
+ definitions.push(createShellTool(hostLocationDirectory));
14806
+ definitions.push(createV2SkillSearchDefinition(hostLocationDirectory));
14807
+ definitions.push(createDeepworkTool(hostLocationDirectory));
14510
14808
  if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime));
14511
14809
  if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime));
14512
14810
  return definitions;
@@ -14834,7 +15132,8 @@ async function registerV2Tools(context, boundedRead, jevRuntime) {
14834
15132
  p3Sink.emit({ ...record2, mode: "shadow" });
14835
15133
  }
14836
15134
  },
14837
- runtime
15135
+ runtime,
15136
+ host.location?.directory
14838
15137
  );
14839
15138
  if (boundedRead !== void 0) toolDefs.push(boundedRead);
14840
15139
  const p11Sink = createTelemetrySink();