pantheon-opencode 2.1.5 → 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.
@@ -7532,14 +7532,8 @@ var JEV_INPUT_SCHEMA = {
7532
7532
  type: "object",
7533
7533
  additionalProperties: false,
7534
7534
  required: ["schemaVersion"],
7535
- anyOf: [
7536
- { required: ["state"] },
7537
- { required: ["delegateId", "resultSummaryKind", "resultMetrics", "criteria"] },
7538
- { required: ["candidates"] },
7539
- { required: ["claims"] }
7540
- ],
7541
7535
  properties: {
7542
- schemaVersion: { type: "integer", const: 1 },
7536
+ schemaVersion: { type: "integer", enum: [1] },
7543
7537
  state: { type: "string", minLength: 1, maxLength: 12e3 },
7544
7538
  mode: { type: "string", enum: ["skills", "delegation", "review", "rank", "verify", "order"] },
7545
7539
  questions: { type: "array", minItems: 1, maxItems: 4, items: questionSchema },
@@ -9268,7 +9262,7 @@ function discoverActiveSessionId(directory) {
9268
9262
  function createV2VisionTool(runtime) {
9269
9263
  return {
9270
9264
  name: "vision_describe",
9271
- 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.",
9272
9266
  input: {
9273
9267
  type: "object",
9274
9268
  additionalProperties: false,
@@ -12036,6 +12030,21 @@ ${renderMarkdown(query, days, pricing)}`;
12036
12030
  // src/pantheon/deepwork/deepwork-tool.ts
12037
12031
  import { z as z3 } from "zod";
12038
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
+
12039
12048
  // src/pantheon/deepwork/plan-projection.ts
12040
12049
  import { join as join15 } from "node:path";
12041
12050
  function generateChatProjection(plan, cwd = process.cwd()) {
@@ -12264,9 +12273,11 @@ var DecisionStatusSchema = z2.enum(["pending", "resolved"]);
12264
12273
  var PlanDecisionSchema = z2.object({
12265
12274
  id: z2.string().min(1),
12266
12275
  question: z2.string().min(1),
12267
- options: z2.array(z2.string()).min(2),
12276
+ options: z2.array(z2.string()).default([]),
12268
12277
  chosen: z2.string().optional(),
12269
- status: DecisionStatusSchema.default("pending")
12278
+ choice: z2.string().optional(),
12279
+ status: DecisionStatusSchema.default("pending"),
12280
+ resolved_at: z2.string().optional()
12270
12281
  });
12271
12282
  var PlanRiskSchema = z2.object({
12272
12283
  id: z2.string().min(1),
@@ -12281,7 +12292,7 @@ var PlanMetadataSchema = z2.object({
12281
12292
  var DeepworkPlanSchema = z2.object({
12282
12293
  plan_id: z2.string().min(1),
12283
12294
  title: z2.string().min(1),
12284
- intent: z2.string().min(1),
12295
+ intent: z2.string().default("Plano de deepwork estruturado."),
12285
12296
  done_when: z2.array(z2.string()).default([]),
12286
12297
  decisions_needed: z2.array(PlanDecisionSchema).default([]),
12287
12298
  risks: z2.array(PlanRiskSchema).default([]),
@@ -12326,14 +12337,193 @@ function computeTaskReadiness(plan) {
12326
12337
  });
12327
12338
  return { ...plan, tasks: updatedTasks };
12328
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
+ }
12329
12478
  async function readPlan(cwd = process.cwd(), slug) {
12330
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;
12331
12490
  try {
12332
- const raw = await readFile6(path5, "utf8");
12333
- const parsed = JSON.parse(raw);
12334
- 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
+ }
12335
12505
  } catch {
12336
- 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
+ }
12337
12527
  }
12338
12528
  }
12339
12529
  async function writePlan(cwd = process.cwd(), plan) {
@@ -12347,14 +12537,17 @@ async function writePlan(cwd = process.cwd(), plan) {
12347
12537
  version: (plan.metadata.version || 1) + 1
12348
12538
  }
12349
12539
  });
12540
+ const randomSuffix = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;
12350
12541
  const jsonPath = deepworkPlanJsonPath(cwd, plan.plan_id);
12351
- const jsonTmp = `${jsonPath}.tmp`;
12542
+ const jsonTmp = `${jsonPath}.tmp.${randomSuffix}`;
12352
12543
  await writeFile3(jsonTmp, `${JSON.stringify(normalized, null, 2)}
12353
12544
  `, "utf8");
12354
12545
  await rename5(jsonTmp, jsonPath);
12355
12546
  const mdPath = deepworkPlanMdPath(cwd, plan.plan_id);
12547
+ const mdTmp = `${mdPath}.tmp.${randomSuffix}`;
12356
12548
  const mdContent = generateMarkdownDocument(normalized);
12357
- await writeFile3(mdPath, mdContent, "utf8");
12549
+ await writeFile3(mdTmp, mdContent, "utf8");
12550
+ await rename5(mdTmp, mdPath);
12358
12551
  }
12359
12552
  async function appendJournal(cwd = process.cwd(), slug, event) {
12360
12553
  const dir = deepworkPlanDir(cwd, slug);
@@ -12365,93 +12558,101 @@ async function appendJournal(cwd = process.cwd(), slug, event) {
12365
12558
  await appendFile3(journalPath, line, "utf8");
12366
12559
  }
12367
12560
  async function updateTaskState(cwd = process.cwd(), slug, taskId, state, result) {
12368
- const plan = await readPlan(cwd, slug);
12369
- if (!plan) {
12370
- throw new Error(`Deepwork plan "${slug}" not found`);
12371
- }
12372
- const taskIndex = plan.tasks.findIndex((t) => t.id === taskId);
12373
- const existingTask = plan.tasks[taskIndex];
12374
- if (taskIndex === -1 || !existingTask) {
12375
- throw new Error(`Task "${taskId}" not found in plan "${slug}"`);
12376
- }
12377
- const updatedResult = result ? { ...existingTask.result ?? {}, ...result } : existingTask.result;
12378
- const updatedTask = {
12379
- ...existingTask,
12380
- state,
12381
- ...updatedResult !== void 0 ? { result: updatedResult } : {}
12382
- };
12383
- const updatedTasks = [...plan.tasks];
12384
- updatedTasks[taskIndex] = updatedTask;
12385
- const nextPlan = { ...plan, tasks: updatedTasks };
12386
- await writePlan(cwd, nextPlan);
12387
- await appendJournal(cwd, slug, {
12388
- type: "task_state_changed",
12389
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12390
- 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;
12391
12587
  });
12392
- return await readPlan(cwd, slug) ?? nextPlan;
12393
12588
  }
12394
12589
  async function verifyTaskAcceptance(cwd = process.cwd(), slug, taskId, checkIndex, verified, proof) {
12395
- const plan = await readPlan(cwd, slug);
12396
- if (!plan) {
12397
- throw new Error(`Deepwork plan "${slug}" not found`);
12398
- }
12399
- const taskIndex = plan.tasks.findIndex((t) => t.id === taskId);
12400
- const task = plan.tasks[taskIndex];
12401
- if (taskIndex === -1 || !task) {
12402
- throw new Error(`Task "${taskId}" not found in plan "${slug}"`);
12403
- }
12404
- const currentAcc = task.acceptance[checkIndex];
12405
- if (!currentAcc) {
12406
- throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`);
12407
- }
12408
- const updatedAcceptance = [...task.acceptance];
12409
- const resolvedProof = proof ?? currentAcc.proof;
12410
- updatedAcceptance[checkIndex] = {
12411
- ...currentAcc,
12412
- verified,
12413
- ...resolvedProof !== void 0 ? { proof: resolvedProof } : {}
12414
- };
12415
- const allVerified = updatedAcceptance.every((acc) => acc.verified);
12416
- const updatedTasks = [...plan.tasks];
12417
- updatedTasks[taskIndex] = {
12418
- ...task,
12419
- acceptance: updatedAcceptance,
12420
- state: allVerified ? "done" : task.state
12421
- };
12422
- const nextPlan = { ...plan, tasks: updatedTasks };
12423
- await writePlan(cwd, nextPlan);
12424
- await appendJournal(cwd, slug, {
12425
- type: "acceptance_verified",
12426
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12427
- 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;
12428
12626
  });
12429
- return await readPlan(cwd, slug) ?? nextPlan;
12430
12627
  }
12431
12628
  async function resolvePlanDecision(cwd = process.cwd(), slug, decisionId, chosen) {
12432
- const plan = await readPlan(cwd, slug);
12433
- if (!plan) {
12434
- throw new Error(`Deepwork plan "${slug}" not found`);
12435
- }
12436
- const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId);
12437
- const existingDec = plan.decisions_needed[decIndex];
12438
- if (decIndex === -1 || !existingDec) {
12439
- throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`);
12440
- }
12441
- const updatedDecisions = [...plan.decisions_needed];
12442
- updatedDecisions[decIndex] = {
12443
- ...existingDec,
12444
- chosen,
12445
- status: "resolved"
12446
- };
12447
- const nextPlan = { ...plan, decisions_needed: updatedDecisions };
12448
- await writePlan(cwd, nextPlan);
12449
- await appendJournal(cwd, slug, {
12450
- type: "decision_resolved",
12451
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12452
- 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;
12453
12655
  });
12454
- return await readPlan(cwd, slug) ?? nextPlan;
12455
12656
  }
12456
12657
  async function listPlans(cwd = process.cwd()) {
12457
12658
  const root = deepworkRootDir(cwd);
@@ -12584,7 +12785,7 @@ function createDeepworkTool(cwd = process.cwd()) {
12584
12785
  output: {},
12585
12786
  async execute(input, context) {
12586
12787
  const parsed = DeepworkToolInputSchema.parse(input);
12587
- const effectiveCwd = typeof context?.directory === "string" ? context.directory : cwd;
12788
+ const effectiveCwd = resolveToolCwd(context, cwd);
12588
12789
  if (parsed.action === "list") {
12589
12790
  const plans = await listPlans(effectiveCwd);
12590
12791
  if (plans.length === 0) {
@@ -12613,67 +12814,36 @@ function createDeepworkTool(cwd = process.cwd()) {
12613
12814
  throw new Error(`O par\xE2metro 'slug' \xE9 obrigat\xF3rio para a a\xE7\xE3o '${parsed.action}'.`);
12614
12815
  }
12615
12816
  if (parsed.action === "init") {
12616
- const title = parsed.title?.trim() || slug;
12617
- const intent = parsed.intent?.trim() || "Plano de deepwork estruturado.";
12618
- const rawTasks = parsed.tasks ?? [];
12619
- const rawDecisions = parsed.decisions ?? [];
12620
- const doneWhen = parsed.done_when ?? [];
12621
- const tasks = rawTasks.map((t, idx) => ({
12622
- id: typeof t.id === "string" ? t.id : `T${String(idx + 1).padStart(2, "0")}`,
12623
- title: typeof t.title === "string" ? t.title : `Task ${idx + 1}`,
12624
- description: typeof t.description === "string" ? t.description : void 0,
12625
- agent: typeof t.agent === "string" ? t.agent : "zeus",
12626
- phase: typeof t.phase === "number" ? t.phase : 1,
12627
- state: typeof t.state === "string" ? t.state : "pending",
12628
- depends_on: Array.isArray(t.depends_on) ? t.depends_on : [],
12629
- parallel_safe: Boolean(t.parallel_safe),
12630
- acceptance: Array.isArray(t.acceptance) ? t.acceptance.map((a) => ({
12631
- kind: a.kind || "command",
12632
- check: a.check || "verify",
12633
- fails_now: a.fails_now ?? true,
12634
- verified: a.verified ?? false,
12635
- proof: a.proof
12636
- })) : []
12637
- }));
12638
- const decisions = rawDecisions.map((d, idx) => ({
12639
- id: typeof d.id === "string" ? d.id : `D${String(idx + 1).padStart(2, "0")}`,
12640
- question: typeof d.question === "string" ? d.question : "Decis\xE3o necess\xE1ria",
12641
- options: Array.isArray(d.options) ? d.options : ["Sim", "N\xE3o"],
12642
- chosen: typeof d.chosen === "string" ? d.chosen : void 0,
12643
- status: d.chosen ? "resolved" : "pending"
12644
- }));
12645
- const initialPlan = computeTaskReadiness({
12646
- plan_id: slug,
12647
- title,
12648
- intent,
12649
- done_when: doneWhen,
12650
- decisions_needed: decisions,
12651
- risks: [],
12652
- out_of_scope: [],
12653
- tasks,
12654
- metadata: {
12655
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
12656
- updated_at: (/* @__PURE__ */ new Date()).toISOString(),
12657
- version: 1
12658
- }
12659
- });
12660
- await writePlan(effectiveCwd, initialPlan);
12661
- await appendJournal(effectiveCwd, slug, {
12662
- type: "plan_created",
12663
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12664
- 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
+ });
12665
12835
  });
12666
12836
  const projection = generateChatProjection(initialPlan, effectiveCwd);
12667
12837
  const approvalQ = buildApprovalQuestion(initialPlan);
12668
12838
  const todoPayload = {
12669
- todos: tasks.map((t) => ({
12839
+ todos: initialPlan.tasks.map((t) => ({
12670
12840
  content: `[${t.id}] ${t.title}`,
12671
12841
  status: t.state === "done" ? "completed" : t.state === "in_progress" ? "in_progress" : "pending"
12672
12842
  }))
12673
12843
  };
12674
12844
  return {
12675
12845
  output: [
12676
- `\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}/\`!`,
12677
12847
  `- \u{1F517} **Deeplink PLAN.md:** [Abrir PLAN.md](file://${deepworkPlanMdPath(effectiveCwd, slug)})`,
12678
12848
  `- \u{1F517} **Deeplink plan.json:** [Abrir plan.json](file://${deepworkPlanJsonPath(effectiveCwd, slug)})`,
12679
12849
  "",
@@ -13013,7 +13183,7 @@ var v2InputSchema = {
13013
13183
  "complexity"
13014
13184
  ],
13015
13185
  properties: {
13016
- schemaVersion: { type: "integer", const: 1 },
13186
+ schemaVersion: { type: "integer", enum: [1] },
13017
13187
  candidateAgents: { type: "array", maxItems: 14, items: { type: "string", minLength: 1 } },
13018
13188
  domain: { type: ["string", "null"] },
13019
13189
  candidateSkillIds: { type: "array", maxItems: 64, items: { type: "string", minLength: 1 } },
@@ -14122,6 +14292,37 @@ var SKILL_SEARCH_INPUT_SCHEMA = {
14122
14292
  }
14123
14293
  }
14124
14294
  };
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
+ }
14125
14326
  function executeSkillSearch(input, options = {}) {
14126
14327
  const query = typeof input.query === "string" ? input.query.trim() : "";
14127
14328
  if (query.length === 0) {
@@ -14136,39 +14337,34 @@ function executeSkillSearch(input, options = {}) {
14136
14337
  "skills-sh"
14137
14338
  ]
14138
14339
  );
14139
- const results = [];
14140
14340
  const failures = [];
14141
14341
  const cwd = options.cwd ?? process.cwd();
14142
14342
  const installedMap = scanInstalledSkills(cwd);
14143
- if (sources.has("installed")) {
14144
- const tokens = query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2);
14145
- if (tokens.length > 0) {
14146
- for (const entry of installedMap.values()) {
14147
- const idLower = entry.id.toLowerCase();
14148
- const descLower = entry.description.toLowerCase();
14149
- const matchScore = tokens.reduce((score, t) => {
14150
- const stem = t.length > 4 ? t.slice(0, 4) : t;
14151
- return score + (idLower.includes(t) || descLower.includes(t) || idLower.includes(stem) || descLower.includes(stem) ? 1 : 0);
14152
- }, 0);
14153
- if (matchScore > 0) {
14154
- results.push({
14155
- skill: entry.id,
14156
- description: entry.description,
14157
- source: "installed",
14158
- installed: true,
14159
- installs: null,
14160
- installCommand: null,
14161
- path: entry.path,
14162
- scope: entry.scope
14163
- });
14164
- }
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
+ });
14165
14361
  }
14166
14362
  }
14167
14363
  }
14168
14364
  const externalSources = ["anthropic", "skills-sh", "github"].filter((s) => sources.has(s));
14169
- if (externalSources.length > 0 && results.length < limit) {
14365
+ if (externalSources.length > 0 && scoredResults.length < limit) {
14170
14366
  try {
14171
- const extLimit = limit - results.length;
14367
+ const extLimit = limit - scoredResults.length;
14172
14368
  const extRes = searchSkillSources(query, {
14173
14369
  limit: extLimit,
14174
14370
  sources: externalSources
@@ -14177,11 +14373,21 @@ function executeSkillSearch(input, options = {}) {
14177
14373
  failures.push(...extRes.failures);
14178
14374
  }
14179
14375
  if (Array.isArray(extRes.entries)) {
14376
+ const minThreshold = tokens.length > 1 ? 5 : 2;
14180
14377
  for (const entry of extRes.entries) {
14181
14378
  const bareName = (entry.skill.includes("@") ? entry.skill.split("@")[1] : entry.skill).toLowerCase();
14182
14379
  const isInstalled = installedMap.has(entry.skill.toLowerCase()) || installedMap.has(bareName);
14183
14380
  const installedRecord = installedMap.get(entry.skill.toLowerCase()) || installedMap.get(bareName);
14184
- const pushItem = {
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({
14185
14391
  skill: entry.skill,
14186
14392
  description: entry.skill,
14187
14393
  source: entry.source,
@@ -14190,9 +14396,9 @@ function executeSkillSearch(input, options = {}) {
14190
14396
  ...entry.url ? { url: entry.url } : {},
14191
14397
  installCommand: isInstalled ? null : `npx skills add ${entry.skill} -a opencode -y`,
14192
14398
  path: isInstalled && installedRecord ? installedRecord.path : null,
14193
- ...isInstalled && installedRecord ? { scope: installedRecord.scope } : {}
14194
- };
14195
- results.push(pushItem);
14399
+ ...isInstalled && installedRecord ? { scope: installedRecord.scope } : {},
14400
+ score: score || 1
14401
+ });
14196
14402
  }
14197
14403
  }
14198
14404
  } catch (err) {
@@ -14201,7 +14407,8 @@ function executeSkillSearch(input, options = {}) {
14201
14407
  );
14202
14408
  }
14203
14409
  }
14204
- 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);
14205
14412
  return {
14206
14413
  ok: true,
14207
14414
  query,
@@ -14210,14 +14417,14 @@ function executeSkillSearch(input, options = {}) {
14210
14417
  failures
14211
14418
  };
14212
14419
  }
14213
- function createV2SkillSearchDefinition() {
14420
+ function createV2SkillSearchDefinition(defaultDir) {
14214
14421
  return {
14215
14422
  name: "pantheon_skill_search",
14216
14423
  description: TOOL_DESCRIPTION3,
14217
14424
  input: SKILL_SEARCH_INPUT_SCHEMA,
14218
14425
  output: {},
14219
14426
  execute: async (input, context) => {
14220
- const cwd = context?.directory || process.cwd();
14427
+ const cwd = resolveToolCwd(context, defaultDir);
14221
14428
  return {
14222
14429
  output: JSON.stringify(executeSkillSearch(input, { cwd }), null, 2)
14223
14430
  };
@@ -14439,18 +14646,18 @@ var MODEL_INPUT = {
14439
14646
  scope: {
14440
14647
  type: "string",
14441
14648
  enum: ["project"],
14442
- description: "Project scope only; global overrides are not supported in V2."
14649
+ description: "Project scope only; global overrides are not supported."
14443
14650
  }
14444
14651
  }
14445
14652
  };
14446
14653
  var modelCommand = createModelCommand({ v2Mode: true });
14447
14654
  async function executeModel(input, context) {
14448
14655
  if (input.scope !== void 0 && input.scope !== "project") {
14449
- 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." };
14450
14657
  }
14451
14658
  if (Object.hasOwn(input, "confirm") || Object.hasOwn(input, "authorize_global")) {
14452
14659
  return {
14453
- 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."
14454
14661
  };
14455
14662
  }
14456
14663
  const output = await modelCommand.pantheon_model.execute(
@@ -14534,35 +14741,37 @@ var SHELL_INPUT = {
14534
14741
  }
14535
14742
  }
14536
14743
  };
14537
- var shellTool = {
14538
- name: "shell",
14539
- description: "Execute a shell command in the workspace directory. Alias for bash execution.",
14540
- input: SHELL_INPUT,
14541
- output: {},
14542
- execute: async (input, context) => {
14543
- const raw = input ?? {};
14544
- const command = String(raw.command ?? raw.cmd ?? "");
14545
- if (!command.trim()) {
14546
- return { output: "", ok: false, error: "Command cannot be empty" };
14547
- }
14548
- const toolCtx = toolContext(context);
14549
- const cwd = toolCtx.directory || process.cwd();
14550
- try {
14551
- const { stdout, stderr } = await execAsync(command, {
14552
- cwd,
14553
- maxBuffer: 10 * 1024 * 1024,
14554
- shell: "/bin/bash"
14555
- });
14556
- const output = [stdout, stderr].filter(Boolean).join("\n");
14557
- return { output, ok: true };
14558
- } catch (err) {
14559
- const execError = err;
14560
- const output = [execError.stdout, execError.stderr, execError.message].filter(Boolean).join("\n");
14561
- 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
+ }
14562
14770
  }
14563
- }
14564
- };
14565
- function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) {
14771
+ };
14772
+ }
14773
+ var shellTool = createShellTool();
14774
+ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime, hostLocationDirectory) {
14566
14775
  const definitions = [
14567
14776
  {
14568
14777
  name: "hashline_edit",
@@ -14573,14 +14782,14 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) {
14573
14782
  },
14574
14783
  {
14575
14784
  name: "pantheon_cost",
14576
- 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.",
14577
14786
  input: COST_INPUT,
14578
14787
  output: {},
14579
14788
  execute: executeCost
14580
14789
  },
14581
14790
  {
14582
14791
  name: "pantheon_model",
14583
- 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.',
14584
14793
  input: MODEL_INPUT,
14585
14794
  output: {},
14586
14795
  execute: executeModel
@@ -14593,9 +14802,9 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) {
14593
14802
  );
14594
14803
  definitions.push(todowriteTool);
14595
14804
  definitions.push(todoreadTool);
14596
- definitions.push(shellTool);
14597
- definitions.push(createV2SkillSearchDefinition());
14598
- definitions.push(createDeepworkTool());
14805
+ definitions.push(createShellTool(hostLocationDirectory));
14806
+ definitions.push(createV2SkillSearchDefinition(hostLocationDirectory));
14807
+ definitions.push(createDeepworkTool(hostLocationDirectory));
14599
14808
  if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime));
14600
14809
  if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime));
14601
14810
  return definitions;
@@ -14923,7 +15132,8 @@ async function registerV2Tools(context, boundedRead, jevRuntime) {
14923
15132
  p3Sink.emit({ ...record2, mode: "shadow" });
14924
15133
  }
14925
15134
  },
14926
- runtime
15135
+ runtime,
15136
+ host.location?.directory
14927
15137
  );
14928
15138
  if (boundedRead !== void 0) toolDefs.push(boundedRead);
14929
15139
  const p11Sink = createTelemetrySink();