pantheon-opencode 2.1.6 → 2.2.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.global.md +2 -2
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +64 -0
- package/README.md +13 -9
- package/README.pt-BR.md +13 -9
- package/bin/pantheon-init.mjs +1 -1
- package/commands/pantheon-audit.md +4 -5
- package/commands/pantheon-model.md +1 -2
- package/package.json +8 -2
- package/plugin.json +1 -1
- package/prompts/dynamic/agora-generated.txt +2 -2
- package/prompts/dynamic/orchestrate-generated.txt +4 -4
- package/prompts/sketch.prompt.md +1 -1
- package/pyproject.toml +1 -1
- package/scripts/build-agents-md.mjs +73 -12
- package/scripts/build-plugin.mjs +3 -1
- package/scripts/hooks/format-multi-language.sh +30 -29
- package/scripts/install-mcp.mjs +55 -27
- package/scripts/prune.mjs +124 -2
- package/scripts/setup.mjs +1 -1
- package/scripts/themis_heuristic_scan.py +3 -5
- package/skills-lock.json +1 -1
- package/src/agents/aphrodite.md +1 -1
- package/src/agents/athena.md +6 -14
- package/src/agents/demeter.md +1 -1
- package/src/agents/hermes.md +3 -2
- package/src/agents/iris.md +4 -6
- package/src/agents/prometheus.md +3 -7
- package/src/agents/roster.json +567 -0
- package/src/agents/zeus.md +3 -0
- package/src/instructions/agent-return-format.instructions.md +1 -1
- package/src/instructions/zeus-anti-stall.instructions.md +11 -35
- package/src/instructions/zeus-council-synthesis.instructions.md +17 -49
- package/src/instructions/zeus-timeout-retry.instructions.md +12 -80
- package/src/mcp/mcp_codemap_module.py +6 -5
- package/src/mcp/pantheon-mcp-server.mjs +875 -0
- package/src/pantheon/agent-forge-tool.ts +316 -0
- package/src/pantheon/auto-permissions.ts +31 -1
- package/src/pantheon/codemap-tools.ts +525 -0
- package/src/pantheon/deepwork/plan-tracker.ts +63 -2
- package/src/pantheon/execute-after.ts +21 -0
- package/src/pantheon/hook-engine.ts +2 -1
- package/src/pantheon/native-memory-tools.ts +686 -0
- package/src/pantheon/presets.mjs +15 -0
- package/src/pantheon/step-ledger.ts +259 -0
- package/src/pantheon/swe-eval-harness.ts +211 -0
- package/src/pantheon/tools.ts +62 -7
- package/src/plugin/index.js +2091 -136
- package/src/plugin/index.ts +1 -14
- package/src/plugin.ts +167 -10
- package/src/plugins/tui/dist/tui.d.ts +66 -0
- package/src/plugins/tui/dist/tui.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui.js +1259 -367
- package/src/plugins/tui/dist/tui.js.map +1 -1
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
- package/src/plugins/tui/src/index.tsx +632 -71
- package/src/plugins/tui/src/pantheon-settings.tsx +78 -14
- package/src/plugins/tui/src/quota-state.ts +190 -0
- package/src/plugins/tui/src/tui-prefs.ts +169 -12
- package/src/routing.yml +3 -0
- package/src/skills/auto-continue/references/auto-continue-details.md +2 -31
- /package/scripts/{setup-v2-config.mjs → setup-config.mjs} +0 -0
package/src/plugin/index.js
CHANGED
|
@@ -6,7 +6,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
6
6
|
});
|
|
7
7
|
|
|
8
8
|
// src/plugin.ts
|
|
9
|
-
import { appendFileSync as appendFileSync2, mkdirSync as
|
|
9
|
+
import { appendFileSync as appendFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync10, readFileSync as readFileSync13 } from "node:fs";
|
|
10
10
|
import { realpath as realpathAsync } from "node:fs/promises";
|
|
11
11
|
import path4 from "node:path";
|
|
12
12
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
@@ -14,6 +14,22 @@ import { define } from "@opencode-ai/plugin/v2/promise";
|
|
|
14
14
|
|
|
15
15
|
// src/pantheon/auto-permissions.ts
|
|
16
16
|
var READ_ONLY_AGENTS = /* @__PURE__ */ new Set(["zeus", "athena", "apollo", "gaia"]);
|
|
17
|
+
var NON_EDIT_AGENTS = /* @__PURE__ */ new Set([
|
|
18
|
+
"zeus",
|
|
19
|
+
"athena",
|
|
20
|
+
"apollo",
|
|
21
|
+
"gaia",
|
|
22
|
+
"themis",
|
|
23
|
+
"nyx",
|
|
24
|
+
"iris"
|
|
25
|
+
]);
|
|
26
|
+
var NON_SHELL_AGENTS = /* @__PURE__ */ new Set([
|
|
27
|
+
"zeus",
|
|
28
|
+
"athena",
|
|
29
|
+
"apollo",
|
|
30
|
+
"gaia",
|
|
31
|
+
"mnemosyne"
|
|
32
|
+
]);
|
|
17
33
|
var SAFE_DEV_BINARIES = /* @__PURE__ */ new Set([
|
|
18
34
|
"git",
|
|
19
35
|
"npm",
|
|
@@ -151,6 +167,16 @@ function evaluateAutoPermission(event, options = {}) {
|
|
|
151
167
|
return { decision: "deny", reason: "read-only-role-violation" };
|
|
152
168
|
}
|
|
153
169
|
}
|
|
170
|
+
if (NON_EDIT_AGENTS.has(agent) && ["edit", "write", "hashline_edit"].includes(action)) {
|
|
171
|
+
event.effect = "deny";
|
|
172
|
+
event.message = `Pantheon auto-permissions denied: agent '${agent}' cannot execute file mutation '${action}'`;
|
|
173
|
+
return { decision: "deny", reason: "read-only-role-violation" };
|
|
174
|
+
}
|
|
175
|
+
if (NON_SHELL_AGENTS.has(agent) && ["bash", "shell"].includes(action)) {
|
|
176
|
+
event.effect = "deny";
|
|
177
|
+
event.message = `Pantheon auto-permissions denied: agent '${agent}' cannot execute shell command '${action}'`;
|
|
178
|
+
return { decision: "deny", reason: "read-only-role-violation" };
|
|
179
|
+
}
|
|
154
180
|
if (["read", "glob", "grep", "webfetch", "question"].includes(action)) {
|
|
155
181
|
const firstResource = Array.isArray(event.resources) && typeof event.resources[0] === "string" ? event.resources[0] : "";
|
|
156
182
|
if (firstResource.startsWith("http://") || firstResource.startsWith("https://")) {
|
|
@@ -467,8 +493,8 @@ function parseArgs(input) {
|
|
|
467
493
|
return { path: filePath, offset, limit };
|
|
468
494
|
}
|
|
469
495
|
function isWithin(root, target) {
|
|
470
|
-
const
|
|
471
|
-
return
|
|
496
|
+
const relative3 = path.relative(root, target);
|
|
497
|
+
return relative3 === "" || !relative3.startsWith(`..${path.sep}`) && relative3 !== ".." && !path.isAbsolute(relative3);
|
|
472
498
|
}
|
|
473
499
|
function sensitivePath(relativePath) {
|
|
474
500
|
const components = relativePath.split("/").map((component) => component.toLowerCase());
|
|
@@ -4055,6 +4081,9 @@ function createEnforcementGuard(input) {
|
|
|
4055
4081
|
};
|
|
4056
4082
|
}
|
|
4057
4083
|
|
|
4084
|
+
// src/pantheon/execute-after.ts
|
|
4085
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
4086
|
+
|
|
4058
4087
|
// src/pantheon/context-sandbox.ts
|
|
4059
4088
|
var DEFAULT_LIMITS = {
|
|
4060
4089
|
read: { maxLines: 200, keepHead: 50, keepTail: 10 },
|
|
@@ -4365,6 +4394,20 @@ function createV2ExecuteAfter(options = {}) {
|
|
|
4365
4394
|
await taskResultGuard(input, output);
|
|
4366
4395
|
await sandbox(input, output);
|
|
4367
4396
|
await readEnhancer(input, output);
|
|
4397
|
+
const lowerTool = tool2.trim().toLowerCase();
|
|
4398
|
+
if (lowerTool === "edit" || lowerTool === "write" || lowerTool === "hashline_edit") {
|
|
4399
|
+
const rawArgs = payload.input ?? {};
|
|
4400
|
+
const editedPath = rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file;
|
|
4401
|
+
if (typeof editedPath === "string" && editedPath.endsWith(".json") && existsSync2(editedPath)) {
|
|
4402
|
+
try {
|
|
4403
|
+
JSON.parse(readFileSync3(editedPath, "utf8"));
|
|
4404
|
+
} catch (jsonErr) {
|
|
4405
|
+
const msg = jsonErr instanceof Error ? jsonErr.message : String(jsonErr);
|
|
4406
|
+
output.output = `${output.output}
|
|
4407
|
+
[Pantheon Diagnostic] JSON syntax error in ${editedPath}: ${msg}`;
|
|
4408
|
+
}
|
|
4409
|
+
}
|
|
4410
|
+
}
|
|
4368
4411
|
if (output.output !== original.text) {
|
|
4369
4412
|
writeText(result, original.field, output.output, original.text, tool2);
|
|
4370
4413
|
}
|
|
@@ -4495,8 +4538,8 @@ function isMissing(error) {
|
|
|
4495
4538
|
return MISSING_CODES.has(errorCode(error));
|
|
4496
4539
|
}
|
|
4497
4540
|
function isWithin2(root, target) {
|
|
4498
|
-
const
|
|
4499
|
-
return
|
|
4541
|
+
const relative3 = path2.relative(root, target);
|
|
4542
|
+
return relative3 === "" || !relative3.startsWith(`..${path2.sep}`) && relative3 !== ".." && !path2.isAbsolute(relative3);
|
|
4500
4543
|
}
|
|
4501
4544
|
function resolveExistingPrefix(absolute) {
|
|
4502
4545
|
let cursor = path2.resolve(absolute);
|
|
@@ -4522,8 +4565,8 @@ function resolveExistingPrefix(absolute) {
|
|
|
4522
4565
|
return void 0;
|
|
4523
4566
|
}
|
|
4524
4567
|
function toGuardForm(resolvedAbsolute, rootReal) {
|
|
4525
|
-
const
|
|
4526
|
-
return
|
|
4568
|
+
const relative3 = isWithin2(rootReal, resolvedAbsolute) ? path2.relative(rootReal, resolvedAbsolute) : resolvedAbsolute;
|
|
4569
|
+
return relative3.split(path2.sep).join("/");
|
|
4527
4570
|
}
|
|
4528
4571
|
function canonicalProjectRoot(projectRoot) {
|
|
4529
4572
|
try {
|
|
@@ -4749,7 +4792,8 @@ function formatterApplies(tool2, input) {
|
|
|
4749
4792
|
const normalized = tool2.trim().toLowerCase();
|
|
4750
4793
|
if (normalized === "edit" || normalized === "write" || normalized === "hashline_edit") {
|
|
4751
4794
|
if (input !== null && typeof input === "object") {
|
|
4752
|
-
|
|
4795
|
+
const rec = input;
|
|
4796
|
+
return formattablePath(rec.file_path ?? rec.filePath ?? rec.file ?? rec.path);
|
|
4753
4797
|
}
|
|
4754
4798
|
return false;
|
|
4755
4799
|
}
|
|
@@ -5969,12 +6013,12 @@ function recordSkip(sink, skipReason) {
|
|
|
5969
6013
|
);
|
|
5970
6014
|
}
|
|
5971
6015
|
function abortDeadline(signal) {
|
|
5972
|
-
return new Promise((
|
|
6016
|
+
return new Promise((resolve12) => {
|
|
5973
6017
|
if (signal.aborted) {
|
|
5974
|
-
|
|
6018
|
+
resolve12("timeout");
|
|
5975
6019
|
return;
|
|
5976
6020
|
}
|
|
5977
|
-
signal.addEventListener("abort", () =>
|
|
6021
|
+
signal.addEventListener("abort", () => resolve12("timeout"), { once: true });
|
|
5978
6022
|
});
|
|
5979
6023
|
}
|
|
5980
6024
|
function createJ1RiskGateObserver(options) {
|
|
@@ -6061,7 +6105,7 @@ import { randomUUID } from "node:crypto";
|
|
|
6061
6105
|
import {
|
|
6062
6106
|
chmodSync as chmodSync2,
|
|
6063
6107
|
closeSync as closeSync2,
|
|
6064
|
-
existsSync as
|
|
6108
|
+
existsSync as existsSync3,
|
|
6065
6109
|
lstatSync as lstatSync4,
|
|
6066
6110
|
mkdirSync as mkdirSync3,
|
|
6067
6111
|
openSync as openSync2
|
|
@@ -6994,7 +7038,7 @@ function isPermittedGroupWritable2(env = process.env) {
|
|
|
6994
7038
|
if (env.PANTHEON_ALLOW_GROUP_WRITABLE === "1" || env.PANTHEON_ALLOW_GROUP_WRITABLE === "true") {
|
|
6995
7039
|
return true;
|
|
6996
7040
|
}
|
|
6997
|
-
if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container ||
|
|
7041
|
+
if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container || existsSync3("/.dockerenv")) {
|
|
6998
7042
|
return true;
|
|
6999
7043
|
}
|
|
7000
7044
|
return false;
|
|
@@ -7593,7 +7637,7 @@ function createV2JevDecisionDefinition(runtime) {
|
|
|
7593
7637
|
import { createHash as createHash4 } from "node:crypto";
|
|
7594
7638
|
|
|
7595
7639
|
// src/pantheon/model-overrides.ts
|
|
7596
|
-
import { closeSync as closeSync3, constants as constants2, fstatSync, openSync as openSync3, readFileSync as
|
|
7640
|
+
import { closeSync as closeSync3, constants as constants2, fstatSync, openSync as openSync3, readFileSync as readFileSync5 } from "node:fs";
|
|
7597
7641
|
import { join as join8 } from "node:path";
|
|
7598
7642
|
|
|
7599
7643
|
// src/pantheon/model-agents.ts
|
|
@@ -7615,7 +7659,7 @@ var KNOWN_AGENTS = [
|
|
|
7615
7659
|
];
|
|
7616
7660
|
|
|
7617
7661
|
// src/pantheon/presets.mjs
|
|
7618
|
-
import { readFileSync as
|
|
7662
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
7619
7663
|
import { join as join7 } from "node:path";
|
|
7620
7664
|
import { fileURLToPath } from "node:url";
|
|
7621
7665
|
import { load as load2 } from "js-yaml";
|
|
@@ -7668,7 +7712,22 @@ var CAPABILITY_TABLE = [
|
|
|
7668
7712
|
{ prefix: "big-pickle", maxEffort: "medium", stripEffort: false, vision: false },
|
|
7669
7713
|
{ prefix: "nemotron-3-super-free", maxEffort: "high", stripEffort: false, vision: false },
|
|
7670
7714
|
{ prefix: "nemotron-3-ultra-free", maxEffort: "high", stripEffort: false, vision: false },
|
|
7671
|
-
{ prefix: "north-mini-code-free", maxEffort: "high", stripEffort: false, vision: false }
|
|
7715
|
+
{ prefix: "north-mini-code-free", maxEffort: "high", stripEffort: false, vision: false },
|
|
7716
|
+
// Multi-provider catalog extensions (Gemini, GPT-4o/4.1/5, Llama, Mistral, Grok, Ollama, OpenRouter)
|
|
7717
|
+
{ prefix: "gemini-2.0", maxEffort: "high", stripEffort: false, vision: true },
|
|
7718
|
+
{ prefix: "gemini-2.5", maxEffort: "high", stripEffort: false, vision: true },
|
|
7719
|
+
{ prefix: "gemini-3-", maxEffort: "high", stripEffort: false, vision: true },
|
|
7720
|
+
{ prefix: "gemini-3.0", maxEffort: "high", stripEffort: false, vision: true },
|
|
7721
|
+
{ prefix: "gemini-3.1", maxEffort: "high", stripEffort: false, vision: true },
|
|
7722
|
+
{ prefix: "gpt-4o", maxEffort: null, stripEffort: true, vision: true },
|
|
7723
|
+
{ prefix: "gpt-4.1", maxEffort: null, stripEffort: true, vision: true },
|
|
7724
|
+
{ prefix: "gpt-5", maxEffort: "high", stripEffort: false, vision: true },
|
|
7725
|
+
{ prefix: "llama", maxEffort: null, stripEffort: true, vision: false },
|
|
7726
|
+
{ prefix: "mistral", maxEffort: null, stripEffort: true, vision: false },
|
|
7727
|
+
{ prefix: "codestral", maxEffort: null, stripEffort: true, vision: false },
|
|
7728
|
+
{ prefix: "grok", maxEffort: "high", stripEffort: false, vision: true },
|
|
7729
|
+
{ prefix: "ollama/", maxEffort: null, stripEffort: true, vision: false },
|
|
7730
|
+
{ prefix: "openrouter/", maxEffort: "high", stripEffort: false, vision: true }
|
|
7672
7731
|
];
|
|
7673
7732
|
function capabilityEntry(model) {
|
|
7674
7733
|
const matches = CAPABILITY_TABLE.filter((entry) => {
|
|
@@ -7709,7 +7768,7 @@ function loadPresetDefs(routingPath) {
|
|
|
7709
7768
|
const path5 = routingPath ?? fileURLToPath(new URL("../routing.yml", import.meta.url));
|
|
7710
7769
|
let raw;
|
|
7711
7770
|
try {
|
|
7712
|
-
raw =
|
|
7771
|
+
raw = readFileSync4(path5, "utf8");
|
|
7713
7772
|
} catch (err) {
|
|
7714
7773
|
throw new Error(`presets: failed to load routing.yml: ${path5} \u2014 ${err.message}`);
|
|
7715
7774
|
}
|
|
@@ -7744,7 +7803,7 @@ function resolveActivePreset({
|
|
|
7744
7803
|
if (!candidate) continue;
|
|
7745
7804
|
let exists;
|
|
7746
7805
|
try {
|
|
7747
|
-
exists =
|
|
7806
|
+
exists = readFileSync4(candidate);
|
|
7748
7807
|
} catch {
|
|
7749
7808
|
continue;
|
|
7750
7809
|
}
|
|
@@ -7835,7 +7894,7 @@ var NonRegularPresetFileError = class extends Error {
|
|
|
7835
7894
|
super("Preset file is not a regular file");
|
|
7836
7895
|
}
|
|
7837
7896
|
};
|
|
7838
|
-
function readV2PresetFile(candidate, fileSystem = { openSync: openSync3, fstatSync, readFileSync:
|
|
7897
|
+
function readV2PresetFile(candidate, fileSystem = { openSync: openSync3, fstatSync, readFileSync: readFileSync5, closeSync: closeSync3 }) {
|
|
7839
7898
|
const noFollowFlag = constants2.O_NOFOLLOW;
|
|
7840
7899
|
const nonBlockFlag = constants2.O_NONBLOCK;
|
|
7841
7900
|
if (noFollowFlag === void 0 || noFollowFlag === 0 || nonBlockFlag === void 0 || nonBlockFlag === 0) {
|
|
@@ -8172,12 +8231,12 @@ function recordSkip2(sink, skipReason) {
|
|
|
8172
8231
|
);
|
|
8173
8232
|
}
|
|
8174
8233
|
function abortDeadline2(signal) {
|
|
8175
|
-
return new Promise((
|
|
8234
|
+
return new Promise((resolve12) => {
|
|
8176
8235
|
if (signal.aborted) {
|
|
8177
|
-
|
|
8236
|
+
resolve12("timeout");
|
|
8178
8237
|
return;
|
|
8179
8238
|
}
|
|
8180
|
-
signal.addEventListener("abort", () =>
|
|
8239
|
+
signal.addEventListener("abort", () => resolve12("timeout"), { once: true });
|
|
8181
8240
|
});
|
|
8182
8241
|
}
|
|
8183
8242
|
function createJ3EscalationObserver(options) {
|
|
@@ -8261,7 +8320,7 @@ function createJ3EscalationObserver(options) {
|
|
|
8261
8320
|
|
|
8262
8321
|
// src/pantheon/native-vision.ts
|
|
8263
8322
|
import { lookup as dnsLookup } from "node:dns/promises";
|
|
8264
|
-
import { existsSync as
|
|
8323
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
8265
8324
|
import { readFile as readFile4 } from "node:fs/promises";
|
|
8266
8325
|
import { request as httpRequest } from "node:http";
|
|
8267
8326
|
import { request as httpsRequest } from "node:https";
|
|
@@ -8283,10 +8342,10 @@ function safeSessionPath(id) {
|
|
|
8283
8342
|
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
8284
8343
|
import {
|
|
8285
8344
|
chmodSync as chmodSync3,
|
|
8286
|
-
existsSync as
|
|
8345
|
+
existsSync as existsSync4,
|
|
8287
8346
|
mkdirSync as mkdirSync4,
|
|
8288
8347
|
readdirSync,
|
|
8289
|
-
readFileSync as
|
|
8348
|
+
readFileSync as readFileSync6,
|
|
8290
8349
|
renameSync as renameSync2,
|
|
8291
8350
|
statSync as statSync2,
|
|
8292
8351
|
unlinkSync as unlinkSync2,
|
|
@@ -8535,18 +8594,18 @@ function extractCredentialCellToken(value) {
|
|
|
8535
8594
|
}
|
|
8536
8595
|
async function readV2CredentialToken(providerIDs, stateDir, env) {
|
|
8537
8596
|
const dbPath = v2CredentialDbPath(stateDir, env);
|
|
8538
|
-
if (!
|
|
8597
|
+
if (!existsSync4(dbPath)) return null;
|
|
8539
8598
|
let sqlite;
|
|
8540
8599
|
try {
|
|
8541
8600
|
sqlite = await import("node:sqlite");
|
|
8542
8601
|
} catch {
|
|
8543
8602
|
return null;
|
|
8544
8603
|
}
|
|
8545
|
-
const
|
|
8546
|
-
if (typeof
|
|
8604
|
+
const DatabaseSync4 = sqlite.DatabaseSync;
|
|
8605
|
+
if (typeof DatabaseSync4 !== "function") return null;
|
|
8547
8606
|
let db;
|
|
8548
8607
|
try {
|
|
8549
|
-
db = new
|
|
8608
|
+
db = new DatabaseSync4(`file:${dbPath}?mode=ro`, { readOnly: true });
|
|
8550
8609
|
const statement = db.prepare(
|
|
8551
8610
|
"SELECT value FROM credential WHERE integration_id = ? AND active = 1 LIMIT 1"
|
|
8552
8611
|
);
|
|
@@ -8698,7 +8757,7 @@ function writeFileAtomicSync(filePath, data) {
|
|
|
8698
8757
|
}
|
|
8699
8758
|
function fileHasContent(filePath, data) {
|
|
8700
8759
|
try {
|
|
8701
|
-
return
|
|
8760
|
+
return readFileSync6(filePath).equals(data);
|
|
8702
8761
|
} catch {
|
|
8703
8762
|
return false;
|
|
8704
8763
|
}
|
|
@@ -9240,7 +9299,7 @@ function discoverActiveSessionId(directory) {
|
|
|
9240
9299
|
try {
|
|
9241
9300
|
const dataHome = process.env.XDG_DATA_HOME || join10(homedir4(), ".local", "share");
|
|
9242
9301
|
const dbPath = process.env.OPENCODE_DB || join10(dataHome, "opencode", "opencode.db");
|
|
9243
|
-
if (!
|
|
9302
|
+
if (!existsSync5(dbPath)) return void 0;
|
|
9244
9303
|
const sqlite = __require("node:sqlite");
|
|
9245
9304
|
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
|
|
9246
9305
|
try {
|
|
@@ -9355,6 +9414,42 @@ function createV2VisionTool(runtime) {
|
|
|
9355
9414
|
};
|
|
9356
9415
|
}
|
|
9357
9416
|
|
|
9417
|
+
// src/pantheon/prompt-cache-order.ts
|
|
9418
|
+
var DEFAULT_CACHE_MIN_TOKENS = 1024;
|
|
9419
|
+
function buildPrefixCachedPrompt(layers, minCacheTokens = DEFAULT_CACHE_MIN_TOKENS) {
|
|
9420
|
+
const invariantParts = [];
|
|
9421
|
+
invariantParts.push(layers.identity.trim());
|
|
9422
|
+
if (layers.tools && layers.tools.length > 0) {
|
|
9423
|
+
invariantParts.push(`## Tool Specifications
|
|
9424
|
+
${layers.tools.map((t) => t.trim()).join("\n\n")}`);
|
|
9425
|
+
}
|
|
9426
|
+
if (layers.conventions && layers.conventions.length > 0) {
|
|
9427
|
+
invariantParts.push(
|
|
9428
|
+
`## Project Standards & Gates
|
|
9429
|
+
${layers.conventions.map((c) => c.trim()).join("\n\n")}`
|
|
9430
|
+
);
|
|
9431
|
+
}
|
|
9432
|
+
const prefix = invariantParts.join("\n\n");
|
|
9433
|
+
const prefixBoundaryIndex = prefix.length;
|
|
9434
|
+
const volatileParts = [];
|
|
9435
|
+
if (layers.history && layers.history.length > 0) {
|
|
9436
|
+
volatileParts.push(
|
|
9437
|
+
`## Conversation History
|
|
9438
|
+
${layers.history.map((h) => h.trim()).join("\n\n")}`
|
|
9439
|
+
);
|
|
9440
|
+
}
|
|
9441
|
+
volatileParts.push(layers.currentTurn.trim());
|
|
9442
|
+
const fullPrompt = [prefix, volatileParts.join("\n\n")].join("\n\n");
|
|
9443
|
+
const estimatedTokens = Math.ceil(fullPrompt.length / 4);
|
|
9444
|
+
const estimatedPrefixTokens = Math.ceil(prefix.length / 4);
|
|
9445
|
+
return {
|
|
9446
|
+
prompt: fullPrompt,
|
|
9447
|
+
prefixBoundaryIndex,
|
|
9448
|
+
estimatedTokens,
|
|
9449
|
+
cacheEligible: estimatedPrefixTokens >= minCacheTokens
|
|
9450
|
+
};
|
|
9451
|
+
}
|
|
9452
|
+
|
|
9358
9453
|
// src/pantheon/background-job-board.ts
|
|
9359
9454
|
import { mkdir as mkdir4, rename as rename3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
9360
9455
|
import { dirname as dirname5, join as join11 } from "node:path";
|
|
@@ -9412,7 +9507,7 @@ var PantheonBus = class {
|
|
|
9412
9507
|
* Wait asynchronously for a specific event matching a predicate, with an optional timeout.
|
|
9413
9508
|
*/
|
|
9414
9509
|
waitFor(event, predicate, timeoutMs = 3e4) {
|
|
9415
|
-
return new Promise((
|
|
9510
|
+
return new Promise((resolve12, reject) => {
|
|
9416
9511
|
let timer = null;
|
|
9417
9512
|
let unsubscribe = null;
|
|
9418
9513
|
if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {
|
|
@@ -9426,7 +9521,7 @@ var PantheonBus = class {
|
|
|
9426
9521
|
if (predicate(payload)) {
|
|
9427
9522
|
if (timer) clearTimeout(timer);
|
|
9428
9523
|
unsubscribe?.();
|
|
9429
|
-
|
|
9524
|
+
resolve12(payload);
|
|
9430
9525
|
}
|
|
9431
9526
|
} catch (err) {
|
|
9432
9527
|
if (timer) clearTimeout(timer);
|
|
@@ -9813,9 +9908,9 @@ var BackgroundJobBoard = class {
|
|
|
9813
9908
|
if (existing && (TERMINAL_STATES.has(existing.state) || existing.state === "reconciled")) {
|
|
9814
9909
|
return Promise.resolve(existing);
|
|
9815
9910
|
}
|
|
9816
|
-
return new Promise((
|
|
9911
|
+
return new Promise((resolve12, reject) => {
|
|
9817
9912
|
const waiter = {
|
|
9818
|
-
resolve:
|
|
9913
|
+
resolve: resolve12,
|
|
9819
9914
|
reject,
|
|
9820
9915
|
timer: setTimeout(() => {
|
|
9821
9916
|
this.removeTerminalWaiter(taskID, waiter);
|
|
@@ -10285,7 +10380,7 @@ function runHook(script, payload, opts = {}) {
|
|
|
10285
10380
|
timedOut: false
|
|
10286
10381
|
});
|
|
10287
10382
|
}
|
|
10288
|
-
return new Promise((
|
|
10383
|
+
return new Promise((resolve12) => {
|
|
10289
10384
|
const stdoutBuf = { value: "" };
|
|
10290
10385
|
const stderrBuf = { value: "" };
|
|
10291
10386
|
let settled = false;
|
|
@@ -10295,7 +10390,7 @@ function runHook(script, payload, opts = {}) {
|
|
|
10295
10390
|
if (!settled) {
|
|
10296
10391
|
settled = true;
|
|
10297
10392
|
if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
|
|
10298
|
-
|
|
10393
|
+
resolve12(result);
|
|
10299
10394
|
}
|
|
10300
10395
|
};
|
|
10301
10396
|
const spawnOpts = {
|
|
@@ -10792,21 +10887,712 @@ var TodoEnforcer = class {
|
|
|
10792
10887
|
import { exec } from "node:child_process";
|
|
10793
10888
|
import { promisify } from "node:util";
|
|
10794
10889
|
|
|
10890
|
+
// src/pantheon/agent-forge-tool.ts
|
|
10891
|
+
import {
|
|
10892
|
+
existsSync as existsSync6,
|
|
10893
|
+
mkdirSync as mkdirSync5,
|
|
10894
|
+
readdirSync as readdirSync2,
|
|
10895
|
+
readFileSync as readFileSync7,
|
|
10896
|
+
realpathSync as realpathSync2,
|
|
10897
|
+
rmSync,
|
|
10898
|
+
writeFileSync as writeFileSync4
|
|
10899
|
+
} from "node:fs";
|
|
10900
|
+
import { join as join12, resolve as resolve6, sep as sep4 } from "node:path";
|
|
10901
|
+
|
|
10902
|
+
// src/pantheon/tool-context.ts
|
|
10903
|
+
function resolveToolCwd(context, fallbackDir) {
|
|
10904
|
+
const ctx = context ?? {};
|
|
10905
|
+
if (typeof ctx.directory === "string" && ctx.directory.trim().length > 0) {
|
|
10906
|
+
return ctx.directory;
|
|
10907
|
+
}
|
|
10908
|
+
if (typeof ctx.worktree === "string" && ctx.worktree.trim().length > 0) {
|
|
10909
|
+
return ctx.worktree;
|
|
10910
|
+
}
|
|
10911
|
+
if (typeof fallbackDir === "string" && fallbackDir.trim().length > 0) {
|
|
10912
|
+
return fallbackDir;
|
|
10913
|
+
}
|
|
10914
|
+
return process.cwd();
|
|
10915
|
+
}
|
|
10916
|
+
|
|
10917
|
+
// src/pantheon/agent-forge-tool.ts
|
|
10918
|
+
var SAFE_AGENT_NAME_RE = /^[a-z][a-z0-9-]{1,48}$/;
|
|
10919
|
+
function isValidAgentSlug(value) {
|
|
10920
|
+
return typeof value === "string" && SAFE_AGENT_NAME_RE.test(value) && !value.includes("..") && !value.includes("/") && !value.includes("\\");
|
|
10921
|
+
}
|
|
10922
|
+
function resolveAgentsDir(workspaceDir) {
|
|
10923
|
+
const dir = join12(workspaceDir, ".opencode", "agents");
|
|
10924
|
+
mkdirSync5(dir, { recursive: true });
|
|
10925
|
+
return realpathSync2(dir);
|
|
10926
|
+
}
|
|
10927
|
+
function resolveConfinedAgentFile(agentsDir, name) {
|
|
10928
|
+
const filePath = resolve6(agentsDir, `${name}.md`);
|
|
10929
|
+
const prefix = agentsDir.endsWith(sep4) ? agentsDir : `${agentsDir}${sep4}`;
|
|
10930
|
+
if (!filePath.startsWith(prefix)) {
|
|
10931
|
+
throw new Error("Path traversal denied: agent file escapes .opencode/agents");
|
|
10932
|
+
}
|
|
10933
|
+
return filePath;
|
|
10934
|
+
}
|
|
10935
|
+
function buildAgentMarkdown(params) {
|
|
10936
|
+
const { name, description, archetype, stack, readOnly, testCommand, conventions } = params;
|
|
10937
|
+
const stackLine = stack.length > 0 ? stack.join(", ") : "Polyglot project stack";
|
|
10938
|
+
const permEdit = readOnly ? "deny" : "allow";
|
|
10939
|
+
const permShell = readOnly ? "deny" : "allow";
|
|
10940
|
+
const roleKind = readOnly ? "READ-ONLY ANALYSIS & AUDIT SPECIALIST" : "DOMAIN IMPLEMENTATION SPECIALIST";
|
|
10941
|
+
const conventionBullets = conventions.length > 0 ? conventions.map((c) => `- ${c}`).join("\n") : [
|
|
10942
|
+
`- Adapt idiomatic patterns to the active stack (${stackLine}).`,
|
|
10943
|
+
"- Follow strict TDD (RED -> GREEN -> REFACTOR) for behavioral changes.",
|
|
10944
|
+
"- Never introduce mock servers on real service ports; fail fast on missing dependencies."
|
|
10945
|
+
].join("\n");
|
|
10946
|
+
return [
|
|
10947
|
+
"---",
|
|
10948
|
+
`name: ${name}`,
|
|
10949
|
+
`description: ${JSON.stringify(description)}`,
|
|
10950
|
+
"mode: subagent",
|
|
10951
|
+
`temperature: ${readOnly ? "0.1" : "0.2"}`,
|
|
10952
|
+
"permission:",
|
|
10953
|
+
" read: allow",
|
|
10954
|
+
" grep: allow",
|
|
10955
|
+
" glob: allow",
|
|
10956
|
+
` edit: ${permEdit}`,
|
|
10957
|
+
` hashline_edit: ${permEdit}`,
|
|
10958
|
+
` bash: ${permShell}`,
|
|
10959
|
+
` shell: ${permShell}`,
|
|
10960
|
+
` execute: ${permShell}`,
|
|
10961
|
+
" todowrite: allow",
|
|
10962
|
+
" todoread: allow",
|
|
10963
|
+
" task:",
|
|
10964
|
+
' "*": deny',
|
|
10965
|
+
"---",
|
|
10966
|
+
"",
|
|
10967
|
+
`# @${name} \u2014 ${description}`,
|
|
10968
|
+
"",
|
|
10969
|
+
`- **Archetype:** \`${archetype}\` (${roleKind})`,
|
|
10970
|
+
`- **Target Stack & Domain:** ${stackLine}`,
|
|
10971
|
+
`- **Default Verification Slice:** \`${testCommand}\``,
|
|
10972
|
+
"",
|
|
10973
|
+
"## Role & Execution Boundaries",
|
|
10974
|
+
"",
|
|
10975
|
+
readOnly ? "You are a **READ-ONLY** domain specialist. Inspect files, analyze patterns, and return structured findings with file:line references. Never modify files or run mutating commands." : "You are a **bounded domain implementer**. Inspect relevant files directly, apply surgical edits using `hashline_edit` or `edit`, and verify every change using the narrowest test slice (<10s).",
|
|
10976
|
+
"",
|
|
10977
|
+
"## Domain Conventions & Quality Gates",
|
|
10978
|
+
"",
|
|
10979
|
+
conventionBullets,
|
|
10980
|
+
"",
|
|
10981
|
+
"## Strict Test Slicing & Return Contract",
|
|
10982
|
+
"",
|
|
10983
|
+
`- Run only the targeted slice (\`${testCommand}\`); never run unconstrained full-repository suites during iterative loops.`,
|
|
10984
|
+
"- Return a concise `## subtask_summary` with `files_changed`, `summary`, `tests` (`[PASS|WARN|FAIL] <cmd>`), `status`, and `blockers`.",
|
|
10985
|
+
""
|
|
10986
|
+
].join("\n");
|
|
10987
|
+
}
|
|
10988
|
+
function jsonResult(payload) {
|
|
10989
|
+
return { output: JSON.stringify(payload) };
|
|
10990
|
+
}
|
|
10991
|
+
function createAgentForgeTool(fallbackDir) {
|
|
10992
|
+
return {
|
|
10993
|
+
name: "pantheon_agent_forge",
|
|
10994
|
+
description: "Create, list, inspect, or remove custom project-scoped domain specialist agents in .opencode/agents/<name>.md.",
|
|
10995
|
+
input: {
|
|
10996
|
+
type: "object",
|
|
10997
|
+
additionalProperties: false,
|
|
10998
|
+
required: ["action"],
|
|
10999
|
+
properties: {
|
|
11000
|
+
action: {
|
|
11001
|
+
type: "string",
|
|
11002
|
+
enum: ["create", "list", "inspect", "remove"],
|
|
11003
|
+
description: "Forge operation to execute"
|
|
11004
|
+
},
|
|
11005
|
+
name: {
|
|
11006
|
+
type: "string",
|
|
11007
|
+
description: "Lowercase kebab-case agent identifier (e.g. rust-embedded, prisma-dba)"
|
|
11008
|
+
},
|
|
11009
|
+
description: {
|
|
11010
|
+
type: "string",
|
|
11011
|
+
description: "One-line role summary used for routing and @mention discovery"
|
|
11012
|
+
},
|
|
11013
|
+
archetype: {
|
|
11014
|
+
type: "string",
|
|
11015
|
+
enum: ["backend", "frontend", "data", "security", "ml-pipeline", "geospatial", "custom"],
|
|
11016
|
+
description: "Base specialist template"
|
|
11017
|
+
},
|
|
11018
|
+
stack: {
|
|
11019
|
+
type: "array",
|
|
11020
|
+
items: { type: "string" },
|
|
11021
|
+
description: "Technologies, frameworks, or domain libraries this specialist owns"
|
|
11022
|
+
},
|
|
11023
|
+
readOnly: {
|
|
11024
|
+
type: "boolean",
|
|
11025
|
+
description: "When true, denies file edits and shell execution (investigation/audit only)"
|
|
11026
|
+
},
|
|
11027
|
+
testCommand: {
|
|
11028
|
+
type: "string",
|
|
11029
|
+
description: "Default targeted verification slice command (<10s)"
|
|
11030
|
+
},
|
|
11031
|
+
conventions: {
|
|
11032
|
+
type: "array",
|
|
11033
|
+
items: { type: "string" },
|
|
11034
|
+
description: "Domain-specific rules and invariants enforced by this agent"
|
|
11035
|
+
},
|
|
11036
|
+
allowOverrideCanonical: {
|
|
11037
|
+
type: "boolean",
|
|
11038
|
+
description: "Allow creating a project override for a built-in Pantheon agent name"
|
|
11039
|
+
}
|
|
11040
|
+
}
|
|
11041
|
+
},
|
|
11042
|
+
output: {},
|
|
11043
|
+
execute: async (input, context) => {
|
|
11044
|
+
try {
|
|
11045
|
+
const action = typeof input.action === "string" ? input.action : "list";
|
|
11046
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
11047
|
+
const agentsDir = resolveAgentsDir(cwd);
|
|
11048
|
+
if (action === "list") {
|
|
11049
|
+
const files = readdirSync2(agentsDir).filter((f) => f.endsWith(".md") && f.toLowerCase() !== "readme.md").sort();
|
|
11050
|
+
const agents = files.map((file) => {
|
|
11051
|
+
const id = file.replace(/\.md$/, "");
|
|
11052
|
+
const raw = readFileSync7(join12(agentsDir, file), "utf8");
|
|
11053
|
+
const descMatch = raw.match(/^description:\s*(.+)$/m);
|
|
11054
|
+
return {
|
|
11055
|
+
name: id,
|
|
11056
|
+
path: `.opencode/agents/${file}`,
|
|
11057
|
+
description: descMatch?.[1]?.replace(/^["']|["']$/g, "") ?? ""
|
|
11058
|
+
};
|
|
11059
|
+
});
|
|
11060
|
+
return jsonResult({ ok: true, count: agents.length, agents });
|
|
11061
|
+
}
|
|
11062
|
+
const name = typeof input.name === "string" ? input.name.trim().toLowerCase() : "";
|
|
11063
|
+
if (!isValidAgentSlug(name)) {
|
|
11064
|
+
return jsonResult({
|
|
11065
|
+
ok: false,
|
|
11066
|
+
error: "name must be a lowercase kebab-case identifier (2..49 chars, [a-z0-9-])"
|
|
11067
|
+
});
|
|
11068
|
+
}
|
|
11069
|
+
const filePath = resolveConfinedAgentFile(agentsDir, name);
|
|
11070
|
+
if (action === "inspect") {
|
|
11071
|
+
if (!existsSync6(filePath)) {
|
|
11072
|
+
return jsonResult({ ok: false, error: "agent_not_found", name });
|
|
11073
|
+
}
|
|
11074
|
+
return jsonResult({
|
|
11075
|
+
ok: true,
|
|
11076
|
+
name,
|
|
11077
|
+
path: `.opencode/agents/${name}.md`,
|
|
11078
|
+
content: readFileSync7(filePath, "utf8")
|
|
11079
|
+
});
|
|
11080
|
+
}
|
|
11081
|
+
if (action === "remove") {
|
|
11082
|
+
if (!existsSync6(filePath)) {
|
|
11083
|
+
return jsonResult({ ok: false, error: "agent_not_found", name });
|
|
11084
|
+
}
|
|
11085
|
+
rmSync(filePath, { force: true });
|
|
11086
|
+
return jsonResult({ ok: true, removed: true, name });
|
|
11087
|
+
}
|
|
11088
|
+
if (action === "create") {
|
|
11089
|
+
if (PANTHEON_AGENTS.has(name) && input.allowOverrideCanonical !== true) {
|
|
11090
|
+
return jsonResult({
|
|
11091
|
+
ok: false,
|
|
11092
|
+
error: `"${name}" is a canonical Pantheon agent. Pass allowOverrideCanonical: true only if you intentionally want a project-local override.`
|
|
11093
|
+
});
|
|
11094
|
+
}
|
|
11095
|
+
const description = typeof input.description === "string" && input.description.trim() ? input.description.trim() : `Custom ${name} specialist`;
|
|
11096
|
+
const archetype = typeof input.archetype === "string" && [
|
|
11097
|
+
"backend",
|
|
11098
|
+
"frontend",
|
|
11099
|
+
"data",
|
|
11100
|
+
"security",
|
|
11101
|
+
"ml-pipeline",
|
|
11102
|
+
"geospatial",
|
|
11103
|
+
"custom"
|
|
11104
|
+
].includes(input.archetype) ? input.archetype : "custom";
|
|
11105
|
+
const readOnly = typeof input.readOnly === "boolean" ? input.readOnly : archetype === "security" || archetype === "geospatial";
|
|
11106
|
+
const stack = Array.isArray(input.stack) ? input.stack.map(String) : [];
|
|
11107
|
+
const testCommand = typeof input.testCommand === "string" && input.testCommand.trim() ? input.testCommand.trim() : "npm run test:slice";
|
|
11108
|
+
const conventions = Array.isArray(input.conventions) ? input.conventions.map(String) : [];
|
|
11109
|
+
const markdown = buildAgentMarkdown({
|
|
11110
|
+
name,
|
|
11111
|
+
description,
|
|
11112
|
+
archetype,
|
|
11113
|
+
stack,
|
|
11114
|
+
readOnly,
|
|
11115
|
+
testCommand,
|
|
11116
|
+
conventions
|
|
11117
|
+
});
|
|
11118
|
+
writeFileSync4(filePath, markdown, "utf8");
|
|
11119
|
+
return jsonResult({
|
|
11120
|
+
ok: true,
|
|
11121
|
+
created: true,
|
|
11122
|
+
name,
|
|
11123
|
+
path: `.opencode/agents/${name}.md`,
|
|
11124
|
+
readOnly,
|
|
11125
|
+
archetype
|
|
11126
|
+
});
|
|
11127
|
+
}
|
|
11128
|
+
return jsonResult({ ok: false, error: `Unsupported action: ${action}` });
|
|
11129
|
+
} catch (err) {
|
|
11130
|
+
return jsonResult({
|
|
11131
|
+
ok: false,
|
|
11132
|
+
error: err instanceof Error ? err.message : String(err)
|
|
11133
|
+
});
|
|
11134
|
+
}
|
|
11135
|
+
}
|
|
11136
|
+
};
|
|
11137
|
+
}
|
|
11138
|
+
|
|
11139
|
+
// src/pantheon/codemap-tools.ts
|
|
11140
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
11141
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync3, statSync as statSync3 } from "node:fs";
|
|
11142
|
+
import { extname, join as join13, relative as relative2, resolve as resolve7, sep as sep5 } from "node:path";
|
|
11143
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
11144
|
+
var IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
11145
|
+
".git",
|
|
11146
|
+
"node_modules",
|
|
11147
|
+
"dist",
|
|
11148
|
+
"build",
|
|
11149
|
+
".venv",
|
|
11150
|
+
"__pycache__",
|
|
11151
|
+
".pytest_cache",
|
|
11152
|
+
".pantheon",
|
|
11153
|
+
".opencode",
|
|
11154
|
+
"coverage"
|
|
11155
|
+
]);
|
|
11156
|
+
var SUPPORTED_EXT_LANG = {
|
|
11157
|
+
".ts": "typescript",
|
|
11158
|
+
".tsx": "typescript",
|
|
11159
|
+
".js": "javascript",
|
|
11160
|
+
".jsx": "javascript",
|
|
11161
|
+
".mjs": "javascript",
|
|
11162
|
+
".py": "python",
|
|
11163
|
+
".go": "go",
|
|
11164
|
+
".rs": "rust"
|
|
11165
|
+
};
|
|
11166
|
+
var codemapDbCache = /* @__PURE__ */ new Map();
|
|
11167
|
+
function getCodemapDb(workspaceDir) {
|
|
11168
|
+
const memoryDir = join13(workspaceDir, ".pantheon", "memory");
|
|
11169
|
+
mkdirSync6(memoryDir, { recursive: true });
|
|
11170
|
+
const canonicalBase = realpathSync3(memoryDir);
|
|
11171
|
+
const dbPath = resolve7(canonicalBase, "memory.db");
|
|
11172
|
+
const prefix = canonicalBase.endsWith(sep5) ? canonicalBase : `${canonicalBase}${sep5}`;
|
|
11173
|
+
if (!dbPath.startsWith(prefix)) {
|
|
11174
|
+
throw new Error("Path traversal denied for codemap database");
|
|
11175
|
+
}
|
|
11176
|
+
const cached = codemapDbCache.get(dbPath);
|
|
11177
|
+
if (cached) return cached;
|
|
11178
|
+
const db = new DatabaseSync2(dbPath);
|
|
11179
|
+
db.exec(`
|
|
11180
|
+
CREATE TABLE IF NOT EXISTS code_files (
|
|
11181
|
+
path TEXT PRIMARY KEY,
|
|
11182
|
+
hash TEXT NOT NULL,
|
|
11183
|
+
language TEXT NOT NULL,
|
|
11184
|
+
indexed_at TEXT NOT NULL
|
|
11185
|
+
);
|
|
11186
|
+
CREATE TABLE IF NOT EXISTS code_entities (
|
|
11187
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
11188
|
+
name TEXT NOT NULL,
|
|
11189
|
+
kind TEXT NOT NULL,
|
|
11190
|
+
file TEXT NOT NULL,
|
|
11191
|
+
line INTEGER NOT NULL,
|
|
11192
|
+
signature TEXT NOT NULL
|
|
11193
|
+
);
|
|
11194
|
+
CREATE INDEX IF NOT EXISTS idx_code_entities_name ON code_entities(name);
|
|
11195
|
+
CREATE INDEX IF NOT EXISTS idx_code_entities_file ON code_entities(file);
|
|
11196
|
+
CREATE TABLE IF NOT EXISTS code_relations (
|
|
11197
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
11198
|
+
source TEXT NOT NULL,
|
|
11199
|
+
target TEXT NOT NULL,
|
|
11200
|
+
kind TEXT NOT NULL,
|
|
11201
|
+
file TEXT NOT NULL,
|
|
11202
|
+
line INTEGER NOT NULL
|
|
11203
|
+
);
|
|
11204
|
+
CREATE INDEX IF NOT EXISTS idx_code_relations_source ON code_relations(source);
|
|
11205
|
+
CREATE INDEX IF NOT EXISTS idx_code_relations_target ON code_relations(target);
|
|
11206
|
+
`);
|
|
11207
|
+
codemapDbCache.set(dbPath, db);
|
|
11208
|
+
return db;
|
|
11209
|
+
}
|
|
11210
|
+
function extractSymbolsAndRelations(relPath, content, language) {
|
|
11211
|
+
const entities = [];
|
|
11212
|
+
const relations = [];
|
|
11213
|
+
const lines = content.split(/\r?\n/);
|
|
11214
|
+
for (let i = 0; i < lines.length; i++) {
|
|
11215
|
+
const rawLine = lines[i] ?? "";
|
|
11216
|
+
const trimmed = rawLine.trim();
|
|
11217
|
+
const lineNo = i + 1;
|
|
11218
|
+
if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*")) {
|
|
11219
|
+
continue;
|
|
11220
|
+
}
|
|
11221
|
+
if (language === "typescript" || language === "javascript") {
|
|
11222
|
+
const fnMatch = trimmed.match(
|
|
11223
|
+
/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/
|
|
11224
|
+
);
|
|
11225
|
+
if (fnMatch?.[1]) {
|
|
11226
|
+
entities.push({
|
|
11227
|
+
name: fnMatch[1],
|
|
11228
|
+
kind: "function",
|
|
11229
|
+
file: relPath,
|
|
11230
|
+
line: lineNo,
|
|
11231
|
+
signature: trimmed.slice(0, 120)
|
|
11232
|
+
});
|
|
11233
|
+
continue;
|
|
11234
|
+
}
|
|
11235
|
+
const classMatch = trimmed.match(
|
|
11236
|
+
/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)(?:\s+extends\s+([A-Za-z_$][\w$]*))?/
|
|
11237
|
+
);
|
|
11238
|
+
if (classMatch?.[1]) {
|
|
11239
|
+
entities.push({
|
|
11240
|
+
name: classMatch[1],
|
|
11241
|
+
kind: "class",
|
|
11242
|
+
file: relPath,
|
|
11243
|
+
line: lineNo,
|
|
11244
|
+
signature: trimmed.slice(0, 120)
|
|
11245
|
+
});
|
|
11246
|
+
if (classMatch[2]) {
|
|
11247
|
+
relations.push({
|
|
11248
|
+
source: classMatch[1],
|
|
11249
|
+
target: classMatch[2],
|
|
11250
|
+
kind: "extends",
|
|
11251
|
+
file: relPath,
|
|
11252
|
+
line: lineNo
|
|
11253
|
+
});
|
|
11254
|
+
}
|
|
11255
|
+
continue;
|
|
11256
|
+
}
|
|
11257
|
+
const ifaceMatch = trimmed.match(/^(?:export\s+)?(interface|type)\s+([A-Za-z_$][\w$]*)/);
|
|
11258
|
+
if (ifaceMatch?.[1] && ifaceMatch[2]) {
|
|
11259
|
+
entities.push({
|
|
11260
|
+
name: ifaceMatch[2],
|
|
11261
|
+
kind: ifaceMatch[1] === "interface" ? "interface" : "type",
|
|
11262
|
+
file: relPath,
|
|
11263
|
+
line: lineNo,
|
|
11264
|
+
signature: trimmed.slice(0, 120)
|
|
11265
|
+
});
|
|
11266
|
+
continue;
|
|
11267
|
+
}
|
|
11268
|
+
const constMatch = trimmed.match(/^export\s+(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=/);
|
|
11269
|
+
if (constMatch?.[1]) {
|
|
11270
|
+
entities.push({
|
|
11271
|
+
name: constMatch[1],
|
|
11272
|
+
kind: "variable",
|
|
11273
|
+
file: relPath,
|
|
11274
|
+
line: lineNo,
|
|
11275
|
+
signature: trimmed.slice(0, 120)
|
|
11276
|
+
});
|
|
11277
|
+
continue;
|
|
11278
|
+
}
|
|
11279
|
+
const importMatch = trimmed.match(/from\s+['"]([^'"]+)['"]/);
|
|
11280
|
+
if (importMatch?.[1] && trimmed.startsWith("import ")) {
|
|
11281
|
+
relations.push({
|
|
11282
|
+
source: relPath,
|
|
11283
|
+
target: importMatch[1],
|
|
11284
|
+
kind: "imports",
|
|
11285
|
+
file: relPath,
|
|
11286
|
+
line: lineNo
|
|
11287
|
+
});
|
|
11288
|
+
}
|
|
11289
|
+
} else if (language === "python") {
|
|
11290
|
+
const defMatch = trimmed.match(/^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/);
|
|
11291
|
+
if (defMatch?.[1]) {
|
|
11292
|
+
entities.push({
|
|
11293
|
+
name: defMatch[1],
|
|
11294
|
+
kind: "function",
|
|
11295
|
+
file: relPath,
|
|
11296
|
+
line: lineNo,
|
|
11297
|
+
signature: trimmed.slice(0, 120)
|
|
11298
|
+
});
|
|
11299
|
+
continue;
|
|
11300
|
+
}
|
|
11301
|
+
const pyClassMatch = trimmed.match(/^class\s+([A-Za-z_]\w*)(?:\(([^)]+)\))?:/);
|
|
11302
|
+
if (pyClassMatch?.[1]) {
|
|
11303
|
+
entities.push({
|
|
11304
|
+
name: pyClassMatch[1],
|
|
11305
|
+
kind: "class",
|
|
11306
|
+
file: relPath,
|
|
11307
|
+
line: lineNo,
|
|
11308
|
+
signature: trimmed.slice(0, 120)
|
|
11309
|
+
});
|
|
11310
|
+
if (pyClassMatch[2]) {
|
|
11311
|
+
relations.push({
|
|
11312
|
+
source: pyClassMatch[1],
|
|
11313
|
+
target: pyClassMatch[2].split(",")[0]?.trim() ?? pyClassMatch[2],
|
|
11314
|
+
kind: "extends",
|
|
11315
|
+
file: relPath,
|
|
11316
|
+
line: lineNo
|
|
11317
|
+
});
|
|
11318
|
+
}
|
|
11319
|
+
continue;
|
|
11320
|
+
}
|
|
11321
|
+
const pyImportMatch = trimmed.match(/^(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))/);
|
|
11322
|
+
const targetMod = pyImportMatch?.[1] ?? pyImportMatch?.[2];
|
|
11323
|
+
if (targetMod) {
|
|
11324
|
+
relations.push({
|
|
11325
|
+
source: relPath,
|
|
11326
|
+
target: targetMod,
|
|
11327
|
+
kind: "imports",
|
|
11328
|
+
file: relPath,
|
|
11329
|
+
line: lineNo
|
|
11330
|
+
});
|
|
11331
|
+
}
|
|
11332
|
+
} else if (language === "go") {
|
|
11333
|
+
const goFnMatch = trimmed.match(/^func\s+(?:\([^)]+\)\s+)?([A-Za-z_]\w*)\s*\(/);
|
|
11334
|
+
if (goFnMatch?.[1]) {
|
|
11335
|
+
entities.push({
|
|
11336
|
+
name: goFnMatch[1],
|
|
11337
|
+
kind: "function",
|
|
11338
|
+
file: relPath,
|
|
11339
|
+
line: lineNo,
|
|
11340
|
+
signature: trimmed.slice(0, 120)
|
|
11341
|
+
});
|
|
11342
|
+
}
|
|
11343
|
+
} else if (language === "rust") {
|
|
11344
|
+
const rsFnMatch = trimmed.match(/^(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/);
|
|
11345
|
+
if (rsFnMatch?.[1]) {
|
|
11346
|
+
entities.push({
|
|
11347
|
+
name: rsFnMatch[1],
|
|
11348
|
+
kind: "function",
|
|
11349
|
+
file: relPath,
|
|
11350
|
+
line: lineNo,
|
|
11351
|
+
signature: trimmed.slice(0, 120)
|
|
11352
|
+
});
|
|
11353
|
+
}
|
|
11354
|
+
}
|
|
11355
|
+
}
|
|
11356
|
+
return { entities, relations };
|
|
11357
|
+
}
|
|
11358
|
+
function collectSourceFiles(currentDir, maxFiles = 500) {
|
|
11359
|
+
const results = [];
|
|
11360
|
+
function walk(dir) {
|
|
11361
|
+
if (results.length >= maxFiles) return;
|
|
11362
|
+
let entries;
|
|
11363
|
+
try {
|
|
11364
|
+
entries = readdirSync3(dir, { withFileTypes: true });
|
|
11365
|
+
} catch {
|
|
11366
|
+
return;
|
|
11367
|
+
}
|
|
11368
|
+
for (const entry of entries) {
|
|
11369
|
+
if (results.length >= maxFiles) return;
|
|
11370
|
+
const name = String(entry.name);
|
|
11371
|
+
if (entry.isDirectory()) {
|
|
11372
|
+
if (!IGNORED_DIRS.has(name) && !name.startsWith(".")) {
|
|
11373
|
+
walk(join13(dir, name));
|
|
11374
|
+
}
|
|
11375
|
+
} else if (entry.isFile()) {
|
|
11376
|
+
const ext = extname(name).toLowerCase();
|
|
11377
|
+
if (ext in SUPPORTED_EXT_LANG) {
|
|
11378
|
+
results.push(join13(dir, name));
|
|
11379
|
+
}
|
|
11380
|
+
}
|
|
11381
|
+
}
|
|
11382
|
+
}
|
|
11383
|
+
walk(currentDir);
|
|
11384
|
+
return results;
|
|
11385
|
+
}
|
|
11386
|
+
function jsonResult2(payload) {
|
|
11387
|
+
return { output: JSON.stringify(payload) };
|
|
11388
|
+
}
|
|
11389
|
+
function createCodemapTools(fallbackDir) {
|
|
11390
|
+
return [
|
|
11391
|
+
{
|
|
11392
|
+
name: "code_index",
|
|
11393
|
+
description: "Index codebase symbols (functions, classes, interfaces, types) and import/inheritance edges into SQLite.",
|
|
11394
|
+
input: {
|
|
11395
|
+
type: "object",
|
|
11396
|
+
additionalProperties: false,
|
|
11397
|
+
properties: {
|
|
11398
|
+
path: {
|
|
11399
|
+
type: "string",
|
|
11400
|
+
description: "Optional relative subdirectory or file path within the workspace to index"
|
|
11401
|
+
},
|
|
11402
|
+
force: {
|
|
11403
|
+
type: "boolean",
|
|
11404
|
+
description: "Re-index files even when SHA-256 hash is unchanged"
|
|
11405
|
+
}
|
|
11406
|
+
}
|
|
11407
|
+
},
|
|
11408
|
+
output: {},
|
|
11409
|
+
execute: async (input, context) => {
|
|
11410
|
+
try {
|
|
11411
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
11412
|
+
const canonicalRoot = realpathSync3(cwd);
|
|
11413
|
+
const subPath = typeof input.path === "string" && input.path.trim() ? input.path.trim() : ".";
|
|
11414
|
+
const targetPath = resolve7(canonicalRoot, subPath);
|
|
11415
|
+
const rootPrefix = canonicalRoot.endsWith(sep5) ? canonicalRoot : `${canonicalRoot}${sep5}`;
|
|
11416
|
+
if (targetPath !== canonicalRoot && !targetPath.startsWith(rootPrefix)) {
|
|
11417
|
+
return jsonResult2({ ok: false, error: "path escapes workspace root" });
|
|
11418
|
+
}
|
|
11419
|
+
if (!existsSync7(targetPath)) {
|
|
11420
|
+
return jsonResult2({ ok: false, error: `path not found: ${subPath}` });
|
|
11421
|
+
}
|
|
11422
|
+
const force = input.force === true;
|
|
11423
|
+
const db = getCodemapDb(canonicalRoot);
|
|
11424
|
+
const st = statSync3(targetPath);
|
|
11425
|
+
const files = st.isFile() ? [targetPath] : collectSourceFiles(targetPath);
|
|
11426
|
+
let indexed = 0;
|
|
11427
|
+
let skipped = 0;
|
|
11428
|
+
let entitiesCount = 0;
|
|
11429
|
+
let relationsCount = 0;
|
|
11430
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
11431
|
+
for (const filePath of files) {
|
|
11432
|
+
const ext = extname(filePath).toLowerCase();
|
|
11433
|
+
const lang = SUPPORTED_EXT_LANG[ext];
|
|
11434
|
+
if (!lang) continue;
|
|
11435
|
+
const relFile = relative2(canonicalRoot, filePath).replace(/\\/g, "/");
|
|
11436
|
+
const content = readFileSync8(filePath, "utf8");
|
|
11437
|
+
const hash = createHash6("sha256").update(content).digest("hex");
|
|
11438
|
+
const existing = db.prepare("SELECT hash FROM code_files WHERE path = ?").get(relFile);
|
|
11439
|
+
if (!force && existing?.hash === hash) {
|
|
11440
|
+
skipped += 1;
|
|
11441
|
+
continue;
|
|
11442
|
+
}
|
|
11443
|
+
const { entities, relations } = extractSymbolsAndRelations(relFile, content, lang);
|
|
11444
|
+
db.prepare("DELETE FROM code_entities WHERE file = ?").run(relFile);
|
|
11445
|
+
db.prepare("DELETE FROM code_relations WHERE file = ?").run(relFile);
|
|
11446
|
+
const insertEnt = db.prepare(
|
|
11447
|
+
"INSERT INTO code_entities (name, kind, file, line, signature) VALUES (?, ?, ?, ?, ?)"
|
|
11448
|
+
);
|
|
11449
|
+
for (const ent of entities) {
|
|
11450
|
+
insertEnt.run(ent.name, ent.kind, ent.file, ent.line, ent.signature);
|
|
11451
|
+
entitiesCount += 1;
|
|
11452
|
+
}
|
|
11453
|
+
const insertRel = db.prepare(
|
|
11454
|
+
"INSERT INTO code_relations (source, target, kind, file, line) VALUES (?, ?, ?, ?, ?)"
|
|
11455
|
+
);
|
|
11456
|
+
for (const rel of relations) {
|
|
11457
|
+
insertRel.run(rel.source, rel.target, rel.kind, rel.file, rel.line);
|
|
11458
|
+
relationsCount += 1;
|
|
11459
|
+
}
|
|
11460
|
+
db.prepare(
|
|
11461
|
+
"INSERT OR REPLACE INTO code_files (path, hash, language, indexed_at) VALUES (?, ?, ?, ?)"
|
|
11462
|
+
).run(relFile, hash, lang, nowIso);
|
|
11463
|
+
indexed += 1;
|
|
11464
|
+
}
|
|
11465
|
+
return jsonResult2({
|
|
11466
|
+
ok: true,
|
|
11467
|
+
indexed,
|
|
11468
|
+
skipped,
|
|
11469
|
+
entities: entitiesCount,
|
|
11470
|
+
relations: relationsCount
|
|
11471
|
+
});
|
|
11472
|
+
} catch (err) {
|
|
11473
|
+
return jsonResult2({
|
|
11474
|
+
ok: false,
|
|
11475
|
+
error: err instanceof Error ? err.message : String(err)
|
|
11476
|
+
});
|
|
11477
|
+
}
|
|
11478
|
+
}
|
|
11479
|
+
},
|
|
11480
|
+
{
|
|
11481
|
+
name: "code_query",
|
|
11482
|
+
description: "Query indexed symbols (functions, classes, interfaces, types) by name prefix or substring.",
|
|
11483
|
+
input: {
|
|
11484
|
+
type: "object",
|
|
11485
|
+
additionalProperties: false,
|
|
11486
|
+
required: ["query"],
|
|
11487
|
+
properties: {
|
|
11488
|
+
query: { type: "string", description: "Symbol name or substring to search for" },
|
|
11489
|
+
kind: {
|
|
11490
|
+
type: "string",
|
|
11491
|
+
description: "Optional filter: function, class, interface, type, variable"
|
|
11492
|
+
},
|
|
11493
|
+
limit: { type: "number", description: "Max results (default 25)" }
|
|
11494
|
+
}
|
|
11495
|
+
},
|
|
11496
|
+
output: {},
|
|
11497
|
+
execute: async (input, context) => {
|
|
11498
|
+
try {
|
|
11499
|
+
const q = typeof input.query === "string" ? input.query.trim() : "";
|
|
11500
|
+
if (!q) return jsonResult2({ ok: false, error: "query is required", results: [] });
|
|
11501
|
+
const limit = typeof input.limit === "number" && Number.isFinite(input.limit) && input.limit > 0 ? Math.min(Math.floor(input.limit), 100) : 25;
|
|
11502
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
11503
|
+
const db = getCodemapDb(cwd);
|
|
11504
|
+
const escaped = q.replace(/[\\%_]/g, "\\$&");
|
|
11505
|
+
let sql = `
|
|
11506
|
+
SELECT name, kind, file, line, signature
|
|
11507
|
+
FROM code_entities
|
|
11508
|
+
WHERE name LIKE ? ESCAPE '\\'
|
|
11509
|
+
`;
|
|
11510
|
+
const params = [`%${escaped}%`];
|
|
11511
|
+
if (typeof input.kind === "string" && input.kind.trim()) {
|
|
11512
|
+
sql += " AND kind = ?";
|
|
11513
|
+
params.push(input.kind.trim());
|
|
11514
|
+
}
|
|
11515
|
+
sql += " ORDER BY CASE WHEN name = ? THEN 0 WHEN name LIKE ? THEN 1 ELSE 2 END, file, line LIMIT ?";
|
|
11516
|
+
params.push(q, `${escaped}%`, limit);
|
|
11517
|
+
const rows = db.prepare(sql).all(...params);
|
|
11518
|
+
return jsonResult2({ ok: true, count: rows.length, results: rows });
|
|
11519
|
+
} catch (err) {
|
|
11520
|
+
return jsonResult2({
|
|
11521
|
+
ok: false,
|
|
11522
|
+
error: err instanceof Error ? err.message : String(err)
|
|
11523
|
+
});
|
|
11524
|
+
}
|
|
11525
|
+
}
|
|
11526
|
+
},
|
|
11527
|
+
{
|
|
11528
|
+
name: "code_neighbors",
|
|
11529
|
+
description: "Find structural neighbors (imports, callers, subclasses) for a symbol or file path.",
|
|
11530
|
+
input: {
|
|
11531
|
+
type: "object",
|
|
11532
|
+
additionalProperties: false,
|
|
11533
|
+
required: ["target"],
|
|
11534
|
+
properties: {
|
|
11535
|
+
target: { type: "string", description: "Symbol name or relative file path" },
|
|
11536
|
+
direction: {
|
|
11537
|
+
type: "string",
|
|
11538
|
+
enum: ["both", "outgoing", "incoming"],
|
|
11539
|
+
description: "Edge direction to traverse (default both)"
|
|
11540
|
+
}
|
|
11541
|
+
}
|
|
11542
|
+
},
|
|
11543
|
+
output: {},
|
|
11544
|
+
execute: async (input, context) => {
|
|
11545
|
+
try {
|
|
11546
|
+
const target = typeof input.target === "string" ? input.target.trim() : "";
|
|
11547
|
+
if (!target) return jsonResult2({ ok: false, error: "target is required", neighbors: [] });
|
|
11548
|
+
const direction = typeof input.direction === "string" ? input.direction : "both";
|
|
11549
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
11550
|
+
const db = getCodemapDb(cwd);
|
|
11551
|
+
const escaped = target.replace(/[\\%_]/g, "\\$&");
|
|
11552
|
+
const outgoing = direction === "incoming" ? [] : db.prepare(
|
|
11553
|
+
`SELECT source, target, kind, file, line
|
|
11554
|
+
FROM code_relations
|
|
11555
|
+
WHERE source = ? OR source LIKE ? ESCAPE '\\'
|
|
11556
|
+
LIMIT 50`
|
|
11557
|
+
).all(target, `%${escaped}%`);
|
|
11558
|
+
const incoming = direction === "outgoing" ? [] : db.prepare(
|
|
11559
|
+
`SELECT source, target, kind, file, line
|
|
11560
|
+
FROM code_relations
|
|
11561
|
+
WHERE target = ? OR target LIKE ? ESCAPE '\\'
|
|
11562
|
+
LIMIT 50`
|
|
11563
|
+
).all(target, `%${escaped}%`);
|
|
11564
|
+
return jsonResult2({
|
|
11565
|
+
ok: true,
|
|
11566
|
+
target,
|
|
11567
|
+
outgoing,
|
|
11568
|
+
incoming
|
|
11569
|
+
});
|
|
11570
|
+
} catch (err) {
|
|
11571
|
+
return jsonResult2({
|
|
11572
|
+
ok: false,
|
|
11573
|
+
error: err instanceof Error ? err.message : String(err)
|
|
11574
|
+
});
|
|
11575
|
+
}
|
|
11576
|
+
}
|
|
11577
|
+
}
|
|
11578
|
+
];
|
|
11579
|
+
}
|
|
11580
|
+
|
|
10795
11581
|
// src/pantheon/cost-command.ts
|
|
10796
11582
|
import { execFile } from "node:child_process";
|
|
10797
|
-
import { accessSync, constants as constants3, existsSync as
|
|
10798
|
-
import { delimiter, dirname as dirname8, join as
|
|
11583
|
+
import { accessSync, constants as constants3, existsSync as existsSync9, statSync as statSync4 } from "node:fs";
|
|
11584
|
+
import { delimiter, dirname as dirname8, join as join16 } from "node:path";
|
|
10799
11585
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
10800
11586
|
import { z } from "zod";
|
|
10801
11587
|
|
|
10802
11588
|
// src/plugins/tui/src/cost-data.ts
|
|
10803
11589
|
import { homedir as homedir6 } from "node:os";
|
|
10804
|
-
import { join as
|
|
11590
|
+
import { join as join15 } from "node:path";
|
|
10805
11591
|
|
|
10806
11592
|
// src/plugins/tui/src/model-pricing.ts
|
|
10807
|
-
import { existsSync as
|
|
11593
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "node:fs";
|
|
10808
11594
|
import { homedir as homedir5 } from "node:os";
|
|
10809
|
-
import { dirname as dirname7, join as
|
|
11595
|
+
import { dirname as dirname7, join as join14 } from "node:path";
|
|
10810
11596
|
var MODELS_DEV_URL = "https://models.dev/api.json";
|
|
10811
11597
|
var PRICING_CACHE_VERSION = 1;
|
|
10812
11598
|
var PRICING_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -10815,11 +11601,11 @@ function resolvePricingCacheDir(env = process.env) {
|
|
|
10815
11601
|
const explicit = env.PANTHEON_HOME?.trim();
|
|
10816
11602
|
if (explicit !== void 0 && explicit !== "") return explicit;
|
|
10817
11603
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
10818
|
-
const base = xdg !== void 0 && xdg !== "" ? xdg :
|
|
10819
|
-
return
|
|
11604
|
+
const base = xdg !== void 0 && xdg !== "" ? xdg : join14(homedir5(), ".config");
|
|
11605
|
+
return join14(base, "opencode");
|
|
10820
11606
|
}
|
|
10821
11607
|
function resolvePricingCachePath(env = process.env) {
|
|
10822
|
-
return
|
|
11608
|
+
return join14(resolvePricingCacheDir(env), "cache", "models-dev.json");
|
|
10823
11609
|
}
|
|
10824
11610
|
function isRecord19(value) {
|
|
10825
11611
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -10950,8 +11736,8 @@ function parseCachedCatalog(raw) {
|
|
|
10950
11736
|
}
|
|
10951
11737
|
function readPricingCache(cachePath) {
|
|
10952
11738
|
try {
|
|
10953
|
-
if (!
|
|
10954
|
-
return parseCachedCatalog(JSON.parse(
|
|
11739
|
+
if (!existsSync8(cachePath)) return void 0;
|
|
11740
|
+
return parseCachedCatalog(JSON.parse(readFileSync9(cachePath, "utf8")));
|
|
10955
11741
|
} catch {
|
|
10956
11742
|
return void 0;
|
|
10957
11743
|
}
|
|
@@ -10959,8 +11745,8 @@ function readPricingCache(cachePath) {
|
|
|
10959
11745
|
function writePricingCache(cachePath, catalog) {
|
|
10960
11746
|
const temp = `${cachePath}.tmp-${process.pid}`;
|
|
10961
11747
|
try {
|
|
10962
|
-
|
|
10963
|
-
|
|
11748
|
+
mkdirSync7(dirname7(cachePath), { recursive: true });
|
|
11749
|
+
writeFileSync5(temp, `${JSON.stringify(catalog)}
|
|
10964
11750
|
`, "utf8");
|
|
10965
11751
|
renameSync3(temp, cachePath);
|
|
10966
11752
|
return true;
|
|
@@ -11109,8 +11895,8 @@ var VERSION_SOURCES = {
|
|
|
11109
11895
|
};
|
|
11110
11896
|
function defaultDbPath() {
|
|
11111
11897
|
const xdg = process.env.XDG_DATA_HOME;
|
|
11112
|
-
const dataHome = xdg !== void 0 && xdg !== "" ? xdg :
|
|
11113
|
-
return
|
|
11898
|
+
const dataHome = xdg !== void 0 && xdg !== "" ? xdg : join15(homedir6(), ".local", "share");
|
|
11899
|
+
return join15(dataHome, "opencode", "opencode.db");
|
|
11114
11900
|
}
|
|
11115
11901
|
function requestedVersion() {
|
|
11116
11902
|
const configured = process.env.PANTHEON_OPENCODE_VERSION;
|
|
@@ -11181,7 +11967,7 @@ var costArgs = {
|
|
|
11181
11967
|
};
|
|
11182
11968
|
function findExistingDb(override) {
|
|
11183
11969
|
const candidate = override === void 0 ? resolveCostDbPath() : resolveCostDbPath({ dbPath: override });
|
|
11184
|
-
return
|
|
11970
|
+
return existsSync9(candidate) ? candidate : void 0;
|
|
11185
11971
|
}
|
|
11186
11972
|
var COST_AGGREGATE_SQL = {
|
|
11187
11973
|
message: (sessionId) => `
|
|
@@ -11798,13 +12584,13 @@ var NODE_SQLITE_MIN_VERSION = "22.5";
|
|
|
11798
12584
|
function defaultIsExecutable(path5) {
|
|
11799
12585
|
try {
|
|
11800
12586
|
accessSync(path5, constants3.X_OK);
|
|
11801
|
-
return
|
|
12587
|
+
return statSync4(path5).isFile();
|
|
11802
12588
|
} catch {
|
|
11803
12589
|
return false;
|
|
11804
12590
|
}
|
|
11805
12591
|
}
|
|
11806
12592
|
function defaultExecFile(file, args) {
|
|
11807
|
-
return new Promise((
|
|
12593
|
+
return new Promise((resolve12, reject) => {
|
|
11808
12594
|
execFile(file, [...args], { encoding: "utf8" }, (error, stdout, stderr) => {
|
|
11809
12595
|
if (error) {
|
|
11810
12596
|
const failure = error;
|
|
@@ -11813,7 +12599,7 @@ function defaultExecFile(file, args) {
|
|
|
11813
12599
|
reject(failure);
|
|
11814
12600
|
return;
|
|
11815
12601
|
}
|
|
11816
|
-
|
|
12602
|
+
resolve12({ stdout, stderr });
|
|
11817
12603
|
});
|
|
11818
12604
|
});
|
|
11819
12605
|
}
|
|
@@ -11825,7 +12611,7 @@ function resolveNodeFromPath(env, isExecutable = defaultIsExecutable) {
|
|
|
11825
12611
|
for (const dir of pathValue.split(delimiter)) {
|
|
11826
12612
|
if (dir === "") continue;
|
|
11827
12613
|
for (const ext of extensions) {
|
|
11828
|
-
const candidate =
|
|
12614
|
+
const candidate = join16(dir, `node${ext}`);
|
|
11829
12615
|
if (isExecutable(candidate)) return candidate;
|
|
11830
12616
|
}
|
|
11831
12617
|
}
|
|
@@ -11889,8 +12675,8 @@ async function queryWithCliFallback(dbPath, days, deps) {
|
|
|
11889
12675
|
const env = deps?.env ?? process.env;
|
|
11890
12676
|
const execFileAsync = deps?.execFile ?? defaultExecFile;
|
|
11891
12677
|
const isExecutable = deps?.isExecutable ?? defaultIsExecutable;
|
|
11892
|
-
const costScript =
|
|
11893
|
-
if (!
|
|
12678
|
+
const costScript = join16(__dirname, "..", "..", "scripts", "cost.mjs");
|
|
12679
|
+
if (!existsSync9(costScript)) {
|
|
11894
12680
|
throw new Error(`CLI fallback script not found: ${costScript}`);
|
|
11895
12681
|
}
|
|
11896
12682
|
const node = resolveNodeExecutable(env, isExecutable);
|
|
@@ -12030,23 +12816,8 @@ ${renderMarkdown(query, days, pricing)}`;
|
|
|
12030
12816
|
// src/pantheon/deepwork/deepwork-tool.ts
|
|
12031
12817
|
import { z as z3 } from "zod";
|
|
12032
12818
|
|
|
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
|
-
|
|
12048
12819
|
// src/pantheon/deepwork/plan-projection.ts
|
|
12049
|
-
import { join as
|
|
12820
|
+
import { join as join17 } from "node:path";
|
|
12050
12821
|
function generateChatProjection(plan, cwd = process.cwd()) {
|
|
12051
12822
|
const pendingDecisions = plan.decisions_needed.filter((d) => d.status === "pending");
|
|
12052
12823
|
const totalTasks = plan.tasks.length;
|
|
@@ -12056,8 +12827,8 @@ function generateChatProjection(plan, cwd = process.cwd()) {
|
|
|
12056
12827
|
const readyTasks = plan.tasks.filter((t) => t.state === "ready");
|
|
12057
12828
|
const nextTask = inProgressTasks[0] || readyTasks[0] || plan.tasks.find((t) => t.state === "pending");
|
|
12058
12829
|
const percent = totalTasks > 0 ? Math.round(doneTasks / totalTasks * 100) : 0;
|
|
12059
|
-
const absPlanMd =
|
|
12060
|
-
const absPlanJson =
|
|
12830
|
+
const absPlanMd = join17(cwd, ".pantheon", "deepwork", plan.plan_id, "PLAN.md");
|
|
12831
|
+
const absPlanJson = join17(cwd, ".pantheon", "deepwork", plan.plan_id, "plan.json");
|
|
12061
12832
|
const lines = [];
|
|
12062
12833
|
lines.push(`### Deepwork: ${plan.title} (\`${plan.plan_id}\`)`);
|
|
12063
12834
|
lines.push(
|
|
@@ -12231,15 +13002,155 @@ function buildApprovalQuestion(plan) {
|
|
|
12231
13002
|
}
|
|
12232
13003
|
|
|
12233
13004
|
// src/pantheon/deepwork/plan-tracker.ts
|
|
12234
|
-
import { existsSync as
|
|
13005
|
+
import { existsSync as existsSync10 } from "node:fs";
|
|
12235
13006
|
import { appendFile as appendFile3, mkdir as mkdir6, readdir, readFile as readFile6, rename as rename5, writeFile as writeFile3 } from "node:fs/promises";
|
|
12236
|
-
import { join as
|
|
13007
|
+
import { join as join18 } from "node:path";
|
|
12237
13008
|
|
|
12238
|
-
// src/pantheon/
|
|
12239
|
-
import {
|
|
12240
|
-
|
|
12241
|
-
|
|
12242
|
-
|
|
13009
|
+
// src/pantheon/execution-receipt.ts
|
|
13010
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
13011
|
+
function hashContent2(content) {
|
|
13012
|
+
return createHash7("sha256").update(content).digest("hex");
|
|
13013
|
+
}
|
|
13014
|
+
function computeReceiptSignature(taskID, agent, timestamp, files) {
|
|
13015
|
+
const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path));
|
|
13016
|
+
const payload = [
|
|
13017
|
+
taskID,
|
|
13018
|
+
agent,
|
|
13019
|
+
String(timestamp),
|
|
13020
|
+
sortedFiles.map((f) => `${f.path}:${f.hash}`).join(";")
|
|
13021
|
+
].join("|");
|
|
13022
|
+
return createHash7("sha256").update(payload).digest("hex");
|
|
13023
|
+
}
|
|
13024
|
+
function createExecutionReceipt(input) {
|
|
13025
|
+
const timestamp = Date.now();
|
|
13026
|
+
const files = input.files.map((f) => {
|
|
13027
|
+
const buf = typeof f.content === "string" ? Buffer.from(f.content, "utf8") : f.content;
|
|
13028
|
+
return {
|
|
13029
|
+
path: f.path,
|
|
13030
|
+
hash: hashContent2(buf),
|
|
13031
|
+
sizeBytes: buf.length
|
|
13032
|
+
};
|
|
13033
|
+
});
|
|
13034
|
+
const signature = computeReceiptSignature(input.taskID, input.agent, timestamp, files);
|
|
13035
|
+
const receiptId = `rcpt_${signature.slice(0, 16)}`;
|
|
13036
|
+
let status = "UNVERIFIED";
|
|
13037
|
+
if (input.testSlice) {
|
|
13038
|
+
status = input.testSlice.exitCode === 0 ? "VERIFIED" : "FAILED";
|
|
13039
|
+
}
|
|
13040
|
+
const receipt = {
|
|
13041
|
+
receiptId,
|
|
13042
|
+
taskID: input.taskID,
|
|
13043
|
+
agent: input.agent,
|
|
13044
|
+
status,
|
|
13045
|
+
files,
|
|
13046
|
+
testSlice: input.testSlice,
|
|
13047
|
+
timestamp,
|
|
13048
|
+
signature
|
|
13049
|
+
};
|
|
13050
|
+
getSharedBus().emit("agent:execution:receipt", receipt);
|
|
13051
|
+
return receipt;
|
|
13052
|
+
}
|
|
13053
|
+
|
|
13054
|
+
// src/pantheon/themis-reflex.ts
|
|
13055
|
+
var ThemisReflexController = class {
|
|
13056
|
+
states = /* @__PURE__ */ new Map();
|
|
13057
|
+
maxRetries;
|
|
13058
|
+
constructor(options = {}) {
|
|
13059
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
13060
|
+
}
|
|
13061
|
+
/**
|
|
13062
|
+
* Evaluate a task execution result against Themis verification findings.
|
|
13063
|
+
* If discrepancies are found and attempts remain, returns an actionable retry directive.
|
|
13064
|
+
*/
|
|
13065
|
+
evaluate(taskID, agent, discrepancies) {
|
|
13066
|
+
if (discrepancies.length === 0) {
|
|
13067
|
+
const existing = this.states.get(taskID);
|
|
13068
|
+
if (existing) {
|
|
13069
|
+
getSharedBus().emit("themis:reflex:resolved", {
|
|
13070
|
+
taskID,
|
|
13071
|
+
agent,
|
|
13072
|
+
file: existing.discrepancies[0]?.file ?? "",
|
|
13073
|
+
error: "",
|
|
13074
|
+
attempt: existing.attempt,
|
|
13075
|
+
maxAttempts: this.maxRetries,
|
|
13076
|
+
timestamp: Date.now(),
|
|
13077
|
+
resolved: true
|
|
13078
|
+
});
|
|
13079
|
+
this.states.delete(taskID);
|
|
13080
|
+
}
|
|
13081
|
+
return { action: "pass", verdict: "PASS" };
|
|
13082
|
+
}
|
|
13083
|
+
let state = this.states.get(taskID);
|
|
13084
|
+
if (!state) {
|
|
13085
|
+
state = {
|
|
13086
|
+
taskID,
|
|
13087
|
+
agent,
|
|
13088
|
+
attempt: 0,
|
|
13089
|
+
maxAttempts: this.maxRetries,
|
|
13090
|
+
discrepancies: [...discrepancies],
|
|
13091
|
+
timestamp: Date.now()
|
|
13092
|
+
};
|
|
13093
|
+
this.states.set(taskID, state);
|
|
13094
|
+
}
|
|
13095
|
+
state.attempt += 1;
|
|
13096
|
+
state.discrepancies = [...discrepancies];
|
|
13097
|
+
state.timestamp = Date.now();
|
|
13098
|
+
const firstDisc = discrepancies[0];
|
|
13099
|
+
getSharedBus().emit("themis:reflex:discrepancy", {
|
|
13100
|
+
taskID,
|
|
13101
|
+
agent,
|
|
13102
|
+
file: firstDisc?.file ?? "unknown",
|
|
13103
|
+
error: firstDisc?.error ?? "unspecified",
|
|
13104
|
+
attempt: state.attempt,
|
|
13105
|
+
maxAttempts: this.maxRetries,
|
|
13106
|
+
timestamp: state.timestamp
|
|
13107
|
+
});
|
|
13108
|
+
if (state.attempt <= this.maxRetries) {
|
|
13109
|
+
const prompt = this.formatReflexPrompt(state.attempt, this.maxRetries, discrepancies);
|
|
13110
|
+
return {
|
|
13111
|
+
action: "retry",
|
|
13112
|
+
prompt,
|
|
13113
|
+
attempt: state.attempt,
|
|
13114
|
+
maxAttempts: this.maxRetries
|
|
13115
|
+
};
|
|
13116
|
+
}
|
|
13117
|
+
this.states.delete(taskID);
|
|
13118
|
+
return {
|
|
13119
|
+
action: "escalate",
|
|
13120
|
+
verdict: "FAIL",
|
|
13121
|
+
reason: `themis.reflex.exhausted:${state.attempt - 1}_retries_failed`,
|
|
13122
|
+
attempts: state.attempt
|
|
13123
|
+
};
|
|
13124
|
+
}
|
|
13125
|
+
/**
|
|
13126
|
+
* Format an inline, high-density reflex prompt directing the implementer to self-heal.
|
|
13127
|
+
*/
|
|
13128
|
+
formatReflexPrompt(attempt, maxAttempts, discrepancies) {
|
|
13129
|
+
const lines = [
|
|
13130
|
+
`[THEMIS INLINE REFLEX \u2014 Attempt ${attempt}/${maxAttempts}]`,
|
|
13131
|
+
"Themis automated audit detected discrepancies in your edits. Fix them directly before returning:"
|
|
13132
|
+
];
|
|
13133
|
+
for (const d of discrepancies) {
|
|
13134
|
+
lines.push(`- File: ${d.file}`);
|
|
13135
|
+
lines.push(` Error: ${d.error}`);
|
|
13136
|
+
if (d.expected) lines.push(` Expected: ${d.expected}`);
|
|
13137
|
+
if (d.actual) lines.push(` Actual: ${d.actual}`);
|
|
13138
|
+
if (d.suggestedFix) lines.push(` Fix hint: ${d.suggestedFix}`);
|
|
13139
|
+
}
|
|
13140
|
+
lines.push("Do NOT escalate to Zeus yet. Apply the targeted fix and re-verify your slice.");
|
|
13141
|
+
return lines.join("\n");
|
|
13142
|
+
}
|
|
13143
|
+
/** Reset state for a taskID */
|
|
13144
|
+
reset(taskID) {
|
|
13145
|
+
this.states.delete(taskID);
|
|
13146
|
+
}
|
|
13147
|
+
};
|
|
13148
|
+
|
|
13149
|
+
// src/pantheon/deepwork/plan-schema.ts
|
|
13150
|
+
import { z as z2 } from "zod";
|
|
13151
|
+
var PlanAcceptanceKindSchema = z2.enum(["test", "command", "file", "manual"]);
|
|
13152
|
+
var PlanAcceptanceCriterionSchema = z2.object({
|
|
13153
|
+
kind: PlanAcceptanceKindSchema,
|
|
12243
13154
|
check: z2.string().min(1),
|
|
12244
13155
|
fails_now: z2.boolean().default(true),
|
|
12245
13156
|
verified: z2.boolean().default(false),
|
|
@@ -12303,19 +13214,25 @@ var DeepworkPlanSchema = z2.object({
|
|
|
12303
13214
|
|
|
12304
13215
|
// src/pantheon/deepwork/plan-tracker.ts
|
|
12305
13216
|
function deepworkRootDir(cwd = process.cwd()) {
|
|
12306
|
-
return
|
|
13217
|
+
return join18(cwd, ".pantheon", "deepwork");
|
|
12307
13218
|
}
|
|
12308
13219
|
function deepworkPlanDir(cwd = process.cwd(), slug) {
|
|
12309
|
-
|
|
13220
|
+
const safeSlug = String(slug ?? "").trim();
|
|
13221
|
+
if (!safeSlug || safeSlug === "." || safeSlug === ".." || safeSlug.includes("..") || safeSlug.includes("/") || safeSlug.includes("\\")) {
|
|
13222
|
+
throw new Error(
|
|
13223
|
+
`Invalid deepwork plan slug "${slug}": path traversal or separator characters are not allowed`
|
|
13224
|
+
);
|
|
13225
|
+
}
|
|
13226
|
+
return join18(deepworkRootDir(cwd), safeSlug);
|
|
12310
13227
|
}
|
|
12311
13228
|
function deepworkPlanJsonPath(cwd = process.cwd(), slug) {
|
|
12312
|
-
return
|
|
13229
|
+
return join18(deepworkPlanDir(cwd, slug), "plan.json");
|
|
12313
13230
|
}
|
|
12314
13231
|
function deepworkPlanMdPath(cwd = process.cwd(), slug) {
|
|
12315
|
-
return
|
|
13232
|
+
return join18(deepworkPlanDir(cwd, slug), "PLAN.md");
|
|
12316
13233
|
}
|
|
12317
13234
|
function deepworkJournalPath(cwd = process.cwd(), slug) {
|
|
12318
|
-
return
|
|
13235
|
+
return join18(deepworkPlanDir(cwd, slug), "journal.ndjson");
|
|
12319
13236
|
}
|
|
12320
13237
|
function computeTaskReadiness(plan) {
|
|
12321
13238
|
const doneIds = new Set(plan.tasks.filter((t) => t.state === "done").map((t) => t.id));
|
|
@@ -12512,8 +13429,8 @@ async function withPlanLock(cwd, slug, fn) {
|
|
|
12512
13429
|
const key = `${cwd}::${slug}`;
|
|
12513
13430
|
const prev = planLocks.get(key) ?? Promise.resolve();
|
|
12514
13431
|
let resolveCurrent;
|
|
12515
|
-
const current = new Promise((
|
|
12516
|
-
resolveCurrent =
|
|
13432
|
+
const current = new Promise((resolve12) => {
|
|
13433
|
+
resolveCurrent = resolve12;
|
|
12517
13434
|
});
|
|
12518
13435
|
planLocks.set(key, current);
|
|
12519
13436
|
try {
|
|
@@ -12586,6 +13503,7 @@ async function updateTaskState(cwd = process.cwd(), slug, taskId, state, result)
|
|
|
12586
13503
|
return await readPlan(cwd, slug) ?? nextPlan;
|
|
12587
13504
|
});
|
|
12588
13505
|
}
|
|
13506
|
+
var deepworkReflexController = new ThemisReflexController({ maxRetries: 2 });
|
|
12589
13507
|
async function verifyTaskAcceptance(cwd = process.cwd(), slug, taskId, checkIndex, verified, proof) {
|
|
12590
13508
|
return withPlanLock(cwd, slug, async () => {
|
|
12591
13509
|
const plan = await readPlan(cwd, slug);
|
|
@@ -12617,10 +13535,49 @@ async function verifyTaskAcceptance(cwd = process.cwd(), slug, taskId, checkInde
|
|
|
12617
13535
|
};
|
|
12618
13536
|
const nextPlan = { ...plan, tasks: updatedTasks };
|
|
12619
13537
|
await writePlan(cwd, nextPlan);
|
|
13538
|
+
const taskKey = `${slug}:${taskId}`;
|
|
13539
|
+
const agentId = task.agent ?? "specialist";
|
|
13540
|
+
let receiptId;
|
|
13541
|
+
let reflexAction;
|
|
13542
|
+
try {
|
|
13543
|
+
if (verified) {
|
|
13544
|
+
deepworkReflexController.evaluate(taskKey, agentId, []);
|
|
13545
|
+
const receipt = createExecutionReceipt({
|
|
13546
|
+
taskID: taskKey,
|
|
13547
|
+
agent: agentId,
|
|
13548
|
+
files: [
|
|
13549
|
+
{ path: `${slug}/${taskId}#${checkIndex}`, content: resolvedProof ?? "verified" }
|
|
13550
|
+
],
|
|
13551
|
+
testSlice: {
|
|
13552
|
+
command: currentAcc.check,
|
|
13553
|
+
exitCode: 0,
|
|
13554
|
+
durationMs: 0
|
|
13555
|
+
}
|
|
13556
|
+
});
|
|
13557
|
+
receiptId = receipt.receiptId;
|
|
13558
|
+
} else {
|
|
13559
|
+
const decision2 = deepworkReflexController.evaluate(taskKey, agentId, [
|
|
13560
|
+
{
|
|
13561
|
+
file: `${slug}/${taskId}`,
|
|
13562
|
+
error: resolvedProof ?? `Acceptance check #${checkIndex} failed: ${currentAcc.check}`
|
|
13563
|
+
}
|
|
13564
|
+
]);
|
|
13565
|
+
reflexAction = decision2.action;
|
|
13566
|
+
}
|
|
13567
|
+
} catch {
|
|
13568
|
+
}
|
|
12620
13569
|
await appendJournal(cwd, slug, {
|
|
12621
13570
|
type: "acceptance_verified",
|
|
12622
13571
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
12623
|
-
payload: {
|
|
13572
|
+
payload: {
|
|
13573
|
+
taskId,
|
|
13574
|
+
checkIndex,
|
|
13575
|
+
verified,
|
|
13576
|
+
proof,
|
|
13577
|
+
allVerified,
|
|
13578
|
+
...receiptId ? { receiptId } : {},
|
|
13579
|
+
...reflexAction ? { reflexAction } : {}
|
|
13580
|
+
}
|
|
12624
13581
|
});
|
|
12625
13582
|
return await readPlan(cwd, slug) ?? nextPlan;
|
|
12626
13583
|
});
|
|
@@ -12656,7 +13613,7 @@ async function resolvePlanDecision(cwd = process.cwd(), slug, decisionId, chosen
|
|
|
12656
13613
|
}
|
|
12657
13614
|
async function listPlans(cwd = process.cwd()) {
|
|
12658
13615
|
const root = deepworkRootDir(cwd);
|
|
12659
|
-
if (!
|
|
13616
|
+
if (!existsSync10(root)) return [];
|
|
12660
13617
|
const entries = await readdir(root, { withFileTypes: true });
|
|
12661
13618
|
const result = [];
|
|
12662
13619
|
for (const entry of entries) {
|
|
@@ -12956,7 +13913,7 @@ ${JSON.stringify(todoPayload, null, 2)}
|
|
|
12956
13913
|
|
|
12957
13914
|
// src/pantheon/hashline/tool.ts
|
|
12958
13915
|
import { readFile as readFile7, rename as rename6, rm, writeFile as writeFile4 } from "node:fs/promises";
|
|
12959
|
-
import { isAbsolute as isAbsolute4, resolve as
|
|
13916
|
+
import { isAbsolute as isAbsolute4, resolve as resolve8, sep as sep6 } from "node:path";
|
|
12960
13917
|
import { z as z4 } from "zod";
|
|
12961
13918
|
var hashlineEditOpArgs = {
|
|
12962
13919
|
op: z4.enum(["replace", "append", "prepend", "delete"]),
|
|
@@ -12970,10 +13927,10 @@ var hashlineEditArgs = {
|
|
|
12970
13927
|
edits: z4.array(z4.object(hashlineEditOpArgs)).min(1)
|
|
12971
13928
|
};
|
|
12972
13929
|
function resolveFile(file, ctx) {
|
|
12973
|
-
if (isAbsolute4(file)) return { ok: true, file:
|
|
12974
|
-
const base =
|
|
12975
|
-
const resolved =
|
|
12976
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
13930
|
+
if (isAbsolute4(file)) return { ok: true, file: resolve8(file) };
|
|
13931
|
+
const base = resolve8(ctx.worktree ?? ctx.directory ?? process.cwd());
|
|
13932
|
+
const resolved = resolve8(base, file);
|
|
13933
|
+
if (resolved !== base && !resolved.startsWith(base + sep6)) {
|
|
12977
13934
|
return {
|
|
12978
13935
|
ok: false,
|
|
12979
13936
|
error: `hashline_edit: file "${file}" escapes the worktree (resolved to "${resolved}") \u2014 path containment denied`
|
|
@@ -13223,7 +14180,7 @@ import { randomBytes } from "node:crypto";
|
|
|
13223
14180
|
import { constants as constants4 } from "node:fs";
|
|
13224
14181
|
import { lstat as lstat2, mkdir as mkdir7, open as open3, rename as rename7, unlink as unlink4 } from "node:fs/promises";
|
|
13225
14182
|
import { homedir as homedir7 } from "node:os";
|
|
13226
|
-
import { basename as basename2, dirname as dirname9, join as
|
|
14183
|
+
import { basename as basename2, dirname as dirname9, join as join19, resolve as resolve9 } from "node:path";
|
|
13227
14184
|
import { z as z5 } from "zod";
|
|
13228
14185
|
var MODEL_REF_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:+-]*$/;
|
|
13229
14186
|
var SAFE_PRESET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
@@ -13312,7 +14269,7 @@ async function createTemporaryFile(path5) {
|
|
|
13312
14269
|
const prefix = `.${basename2(path5)}.tmp-`;
|
|
13313
14270
|
const flags = constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | NO_FOLLOW;
|
|
13314
14271
|
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
13315
|
-
const temporaryPath =
|
|
14272
|
+
const temporaryPath = join19(directory, `${prefix}${randomBytes(16).toString("hex")}`);
|
|
13316
14273
|
try {
|
|
13317
14274
|
return { path: temporaryPath, file: await open3(temporaryPath, flags, DEFAULT_FILE_MODE) };
|
|
13318
14275
|
} catch (error) {
|
|
@@ -13379,30 +14336,30 @@ function envValue(options) {
|
|
|
13379
14336
|
return options.env ?? process.env;
|
|
13380
14337
|
}
|
|
13381
14338
|
function projectConfigPath(options) {
|
|
13382
|
-
return options.projectConfigPath ??
|
|
14339
|
+
return options.projectConfigPath ?? join19(options.cwd ?? process.cwd(), "opencode.json");
|
|
13383
14340
|
}
|
|
13384
14341
|
function defaultGlobalConfigPath(options) {
|
|
13385
14342
|
const env = envValue(options);
|
|
13386
14343
|
const home = env.HOME?.trim() || homedir7();
|
|
13387
|
-
const xdg = env.XDG_CONFIG_HOME?.trim() ||
|
|
13388
|
-
return
|
|
14344
|
+
const xdg = env.XDG_CONFIG_HOME?.trim() || join19(home, ".config");
|
|
14345
|
+
return join19(xdg, "opencode", "opencode.json");
|
|
13389
14346
|
}
|
|
13390
14347
|
function globalConfigCandidates(options) {
|
|
13391
14348
|
if (options.globalConfigPath !== void 0) return [options.globalConfigPath];
|
|
13392
14349
|
const canonical = defaultGlobalConfigPath(options);
|
|
13393
14350
|
const home = envValue(options).HOME?.trim() || homedir7();
|
|
13394
|
-
const legacy =
|
|
14351
|
+
const legacy = join19(home, ".opencode", "opencode.json");
|
|
13395
14352
|
return [.../* @__PURE__ */ new Set([canonical, legacy])];
|
|
13396
14353
|
}
|
|
13397
14354
|
function activePresetCandidatesList(options) {
|
|
13398
14355
|
if (options.activePresetCandidates !== void 0) {
|
|
13399
|
-
return options.activePresetCandidates.map((p) =>
|
|
14356
|
+
return options.activePresetCandidates.map((p) => resolve9(p));
|
|
13400
14357
|
}
|
|
13401
|
-
const projectPreset =
|
|
14358
|
+
const projectPreset = join19(dirname9(projectConfigPath(options)), ".pantheon", "active-preset.json");
|
|
13402
14359
|
const globalPresets = globalConfigCandidates(options).map(
|
|
13403
|
-
(p) =>
|
|
14360
|
+
(p) => join19(dirname9(p), ".pantheon", "active-preset.json")
|
|
13404
14361
|
);
|
|
13405
|
-
return [...new Set([projectPreset, ...globalPresets].map((p) =>
|
|
14362
|
+
return [...new Set([projectPreset, ...globalPresets].map((p) => resolve9(p)))];
|
|
13406
14363
|
}
|
|
13407
14364
|
function presetPathForScope(options, scope) {
|
|
13408
14365
|
const candidates = activePresetCandidatesList(options);
|
|
@@ -13414,7 +14371,7 @@ function presetPathForScope(options, scope) {
|
|
|
13414
14371
|
const second = candidates[1];
|
|
13415
14372
|
if (second) return second;
|
|
13416
14373
|
const globalCandidates = globalConfigCandidates(options).map(
|
|
13417
|
-
(p) =>
|
|
14374
|
+
(p) => resolve9(join19(dirname9(p), ".pantheon", "active-preset.json"))
|
|
13418
14375
|
);
|
|
13419
14376
|
const fallback = globalCandidates[0] ?? candidates[0];
|
|
13420
14377
|
if (!fallback) throw new ModelCommandError("global preset path is unavailable");
|
|
@@ -13970,10 +14927,638 @@ function createModelCommand(options = {}) {
|
|
|
13970
14927
|
};
|
|
13971
14928
|
}
|
|
13972
14929
|
|
|
14930
|
+
// src/pantheon/native-memory-tools.ts
|
|
14931
|
+
import {
|
|
14932
|
+
existsSync as existsSync11,
|
|
14933
|
+
mkdirSync as mkdirSync8,
|
|
14934
|
+
readdirSync as readdirSync4,
|
|
14935
|
+
readFileSync as readFileSync10,
|
|
14936
|
+
realpathSync as realpathSync4,
|
|
14937
|
+
writeFileSync as writeFileSync6
|
|
14938
|
+
} from "node:fs";
|
|
14939
|
+
import { join as join20, resolve as resolve10, sep as sep7 } from "node:path";
|
|
14940
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
14941
|
+
var SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/;
|
|
14942
|
+
var MAX_MEMORY_VALUE_BYTES = 65536;
|
|
14943
|
+
function isSafeSegment(value) {
|
|
14944
|
+
return typeof value === "string" && SAFE_SEGMENT_RE.test(value) && value !== "." && value !== ".." && !value.includes("..") && !value.includes("/") && !value.includes("\\");
|
|
14945
|
+
}
|
|
14946
|
+
function resolveConfinedPath(baseDir, ...segments) {
|
|
14947
|
+
mkdirSync8(baseDir, { recursive: true });
|
|
14948
|
+
const canonicalBase = realpathSync4(baseDir);
|
|
14949
|
+
const candidate = resolve10(canonicalBase, ...segments);
|
|
14950
|
+
const prefix = canonicalBase.endsWith(sep7) ? canonicalBase : `${canonicalBase}${sep7}`;
|
|
14951
|
+
if (candidate !== canonicalBase && !candidate.startsWith(prefix)) {
|
|
14952
|
+
throw new Error("Path traversal denied: target escapes confined directory");
|
|
14953
|
+
}
|
|
14954
|
+
return candidate;
|
|
14955
|
+
}
|
|
14956
|
+
var dbCache = /* @__PURE__ */ new Map();
|
|
14957
|
+
function getMemoryDb(workspaceDir) {
|
|
14958
|
+
const memoryDir = join20(workspaceDir, ".pantheon", "memory");
|
|
14959
|
+
mkdirSync8(memoryDir, { recursive: true });
|
|
14960
|
+
const dbPath = resolveConfinedPath(memoryDir, "memory.db");
|
|
14961
|
+
const cached = dbCache.get(dbPath);
|
|
14962
|
+
if (cached) return cached;
|
|
14963
|
+
const db = new DatabaseSync3(dbPath);
|
|
14964
|
+
db.exec(`
|
|
14965
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
14966
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
14967
|
+
namespace TEXT NOT NULL,
|
|
14968
|
+
key TEXT NOT NULL,
|
|
14969
|
+
value TEXT NOT NULL,
|
|
14970
|
+
metadata TEXT,
|
|
14971
|
+
created_at TEXT NOT NULL,
|
|
14972
|
+
expires_at TEXT,
|
|
14973
|
+
UNIQUE(namespace, key)
|
|
14974
|
+
);
|
|
14975
|
+
CREATE INDEX IF NOT EXISTS idx_memories_ns_key ON memories(namespace, key);
|
|
14976
|
+
`);
|
|
14977
|
+
try {
|
|
14978
|
+
db.exec(`
|
|
14979
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
14980
|
+
namespace,
|
|
14981
|
+
key,
|
|
14982
|
+
value,
|
|
14983
|
+
content='memories',
|
|
14984
|
+
content_rowid='id',
|
|
14985
|
+
tokenize='porter unicode61'
|
|
14986
|
+
);
|
|
14987
|
+
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
|
|
14988
|
+
INSERT INTO memories_fts(rowid, namespace, key, value)
|
|
14989
|
+
VALUES (new.id, new.namespace, new.key, new.value);
|
|
14990
|
+
END;
|
|
14991
|
+
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
|
|
14992
|
+
INSERT INTO memories_fts(memories_fts, rowid, namespace, key, value)
|
|
14993
|
+
VALUES ('delete', old.id, old.namespace, old.key, old.value);
|
|
14994
|
+
END;
|
|
14995
|
+
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
|
|
14996
|
+
INSERT INTO memories_fts(memories_fts, rowid, namespace, key, value)
|
|
14997
|
+
VALUES ('delete', old.id, old.namespace, old.key, old.value);
|
|
14998
|
+
INSERT INTO memories_fts(rowid, namespace, key, value)
|
|
14999
|
+
VALUES (new.id, new.namespace, new.key, new.value);
|
|
15000
|
+
END;
|
|
15001
|
+
`);
|
|
15002
|
+
} catch {
|
|
15003
|
+
}
|
|
15004
|
+
dbCache.set(dbPath, db);
|
|
15005
|
+
return db;
|
|
15006
|
+
}
|
|
15007
|
+
function jsonResult3(payload) {
|
|
15008
|
+
return { output: JSON.stringify(payload) };
|
|
15009
|
+
}
|
|
15010
|
+
var NOT_EXPIRED_SQL = "(expires_at IS NULL OR expires_at > ?)";
|
|
15011
|
+
function createNativeMemoryAndPersistenceTools(fallbackDir) {
|
|
15012
|
+
return [
|
|
15013
|
+
{
|
|
15014
|
+
name: "memory_store",
|
|
15015
|
+
description: "Store a durable memory entry in .pantheon/memory/memory.db with FTS5 indexing and optional TTL.",
|
|
15016
|
+
input: {
|
|
15017
|
+
type: "object",
|
|
15018
|
+
additionalProperties: false,
|
|
15019
|
+
required: ["namespace", "key", "value"],
|
|
15020
|
+
properties: {
|
|
15021
|
+
namespace: { type: "string", description: "Project or domain namespace" },
|
|
15022
|
+
key: { type: "string", description: "Unique key within the namespace" },
|
|
15023
|
+
value: { type: "string", description: "Durable fact, ADR, or convention text (<=64KiB)" },
|
|
15024
|
+
metadata: { type: "string", description: "Optional JSON metadata string" },
|
|
15025
|
+
expires_at: { type: "string", description: "Optional ISO-8601 expiration timestamp" }
|
|
15026
|
+
}
|
|
15027
|
+
},
|
|
15028
|
+
output: {},
|
|
15029
|
+
execute: async (input, context) => {
|
|
15030
|
+
try {
|
|
15031
|
+
const ns = input.namespace;
|
|
15032
|
+
const key = input.key;
|
|
15033
|
+
const value = input.value;
|
|
15034
|
+
if (typeof ns !== "string" || !ns.trim() || typeof key !== "string" || !key.trim()) {
|
|
15035
|
+
return jsonResult3({
|
|
15036
|
+
ok: false,
|
|
15037
|
+
error: "namespace and key are required non-empty strings"
|
|
15038
|
+
});
|
|
15039
|
+
}
|
|
15040
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
15041
|
+
return jsonResult3({
|
|
15042
|
+
ok: false,
|
|
15043
|
+
error: "value is required and must be a non-empty string"
|
|
15044
|
+
});
|
|
15045
|
+
}
|
|
15046
|
+
if (Buffer.byteLength(value, "utf8") > MAX_MEMORY_VALUE_BYTES) {
|
|
15047
|
+
return jsonResult3({ ok: false, error: "value exceeds maximum size of 64 KiB" });
|
|
15048
|
+
}
|
|
15049
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15050
|
+
const db = getMemoryDb(cwd);
|
|
15051
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15052
|
+
db.prepare(
|
|
15053
|
+
`INSERT INTO memories (namespace, key, value, metadata, created_at, expires_at)
|
|
15054
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
15055
|
+
ON CONFLICT(namespace, key) DO UPDATE SET
|
|
15056
|
+
value = excluded.value,
|
|
15057
|
+
metadata = excluded.metadata,
|
|
15058
|
+
created_at = excluded.created_at,
|
|
15059
|
+
expires_at = excluded.expires_at`
|
|
15060
|
+
).run(
|
|
15061
|
+
ns.trim(),
|
|
15062
|
+
key.trim(),
|
|
15063
|
+
value,
|
|
15064
|
+
typeof input.metadata === "string" ? input.metadata : null,
|
|
15065
|
+
nowIso,
|
|
15066
|
+
typeof input.expires_at === "string" ? input.expires_at : null
|
|
15067
|
+
);
|
|
15068
|
+
return jsonResult3({ ok: true, status: "stored", namespace: ns.trim(), key: key.trim() });
|
|
15069
|
+
} catch (err) {
|
|
15070
|
+
return jsonResult3({
|
|
15071
|
+
ok: false,
|
|
15072
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15073
|
+
});
|
|
15074
|
+
}
|
|
15075
|
+
}
|
|
15076
|
+
},
|
|
15077
|
+
{
|
|
15078
|
+
name: "memory_recall",
|
|
15079
|
+
description: "Recall a specific memory entry by exact namespace and key.",
|
|
15080
|
+
input: {
|
|
15081
|
+
type: "object",
|
|
15082
|
+
additionalProperties: false,
|
|
15083
|
+
required: ["namespace", "key"],
|
|
15084
|
+
properties: {
|
|
15085
|
+
namespace: { type: "string", description: "Memory namespace" },
|
|
15086
|
+
key: { type: "string", description: "Memory key" }
|
|
15087
|
+
}
|
|
15088
|
+
},
|
|
15089
|
+
output: {},
|
|
15090
|
+
execute: async (input, context) => {
|
|
15091
|
+
try {
|
|
15092
|
+
const ns = input.namespace;
|
|
15093
|
+
const key = input.key;
|
|
15094
|
+
if (typeof ns !== "string" || !ns.trim() || typeof key !== "string" || !key.trim()) {
|
|
15095
|
+
return jsonResult3({ ok: false, error: "namespace and key are required" });
|
|
15096
|
+
}
|
|
15097
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15098
|
+
const db = getMemoryDb(cwd);
|
|
15099
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15100
|
+
const row = db.prepare(
|
|
15101
|
+
`SELECT namespace, key, value, metadata, created_at, expires_at
|
|
15102
|
+
FROM memories
|
|
15103
|
+
WHERE namespace = ? AND key = ? AND ${NOT_EXPIRED_SQL}`
|
|
15104
|
+
).get(ns.trim(), key.trim(), nowIso);
|
|
15105
|
+
return jsonResult3(row ?? { ok: false, error: "not_found" });
|
|
15106
|
+
} catch (err) {
|
|
15107
|
+
return jsonResult3({
|
|
15108
|
+
ok: false,
|
|
15109
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15110
|
+
});
|
|
15111
|
+
}
|
|
15112
|
+
}
|
|
15113
|
+
},
|
|
15114
|
+
{
|
|
15115
|
+
name: "memory_search",
|
|
15116
|
+
description: "Search durable memories using SQLite FTS5 BM25 ranking with lexical fallback.",
|
|
15117
|
+
input: {
|
|
15118
|
+
type: "object",
|
|
15119
|
+
additionalProperties: false,
|
|
15120
|
+
required: ["query"],
|
|
15121
|
+
properties: {
|
|
15122
|
+
query: { type: "string", description: "Search query terms" },
|
|
15123
|
+
namespace: { type: "string", description: "Optional namespace filter" },
|
|
15124
|
+
top_k: { type: "number", description: "Maximum results to return (default 10)" }
|
|
15125
|
+
}
|
|
15126
|
+
},
|
|
15127
|
+
output: {},
|
|
15128
|
+
execute: async (input, context) => {
|
|
15129
|
+
try {
|
|
15130
|
+
const rawQuery = typeof input.query === "string" ? input.query.trim() : "";
|
|
15131
|
+
if (!rawQuery) {
|
|
15132
|
+
return jsonResult3({ ok: false, error: "query is required", count: 0, results: [] });
|
|
15133
|
+
}
|
|
15134
|
+
const limit = typeof input.top_k === "number" && Number.isFinite(input.top_k) && input.top_k > 0 ? Math.min(Math.floor(input.top_k), 100) : 10;
|
|
15135
|
+
const ns = typeof input.namespace === "string" && input.namespace.trim() ? input.namespace.trim() : void 0;
|
|
15136
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15137
|
+
const db = getMemoryDb(cwd);
|
|
15138
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15139
|
+
const tokens = rawQuery.replace(/[^\p{L}\p{N}_-]+/gu, " ").trim().split(/\s+/).filter((t) => t.length >= 2);
|
|
15140
|
+
if (tokens.length > 0) {
|
|
15141
|
+
try {
|
|
15142
|
+
const ftsExpr = tokens.map((t) => `"${t.replace(/"/g, '""')}"*`).join(" OR ");
|
|
15143
|
+
let ftsSql = `
|
|
15144
|
+
SELECT m.namespace, m.key, m.value, m.metadata, m.created_at, bm25(memories_fts) AS score
|
|
15145
|
+
FROM memories_fts
|
|
15146
|
+
JOIN memories m ON m.id = memories_fts.rowid
|
|
15147
|
+
WHERE memories_fts MATCH ? AND (m.expires_at IS NULL OR m.expires_at > ?)
|
|
15148
|
+
`;
|
|
15149
|
+
const ftsParams = [ftsExpr, nowIso];
|
|
15150
|
+
if (ns) {
|
|
15151
|
+
ftsSql += " AND m.namespace = ?";
|
|
15152
|
+
ftsParams.push(ns);
|
|
15153
|
+
}
|
|
15154
|
+
ftsSql += " ORDER BY score LIMIT ?";
|
|
15155
|
+
ftsParams.push(limit);
|
|
15156
|
+
const rows2 = db.prepare(ftsSql).all(...ftsParams);
|
|
15157
|
+
if (rows2.length > 0) {
|
|
15158
|
+
return jsonResult3({ ok: true, count: rows2.length, results: rows2 });
|
|
15159
|
+
}
|
|
15160
|
+
} catch {
|
|
15161
|
+
}
|
|
15162
|
+
}
|
|
15163
|
+
const escaped = rawQuery.replace(/[\\%_]/g, "\\$&");
|
|
15164
|
+
let sql = `
|
|
15165
|
+
SELECT namespace, key, value, metadata, created_at
|
|
15166
|
+
FROM memories
|
|
15167
|
+
WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\')
|
|
15168
|
+
AND ${NOT_EXPIRED_SQL}
|
|
15169
|
+
`;
|
|
15170
|
+
const params = [`%${escaped}%`, `%${escaped}%`, nowIso];
|
|
15171
|
+
if (ns) {
|
|
15172
|
+
sql += " AND namespace = ?";
|
|
15173
|
+
params.push(ns);
|
|
15174
|
+
}
|
|
15175
|
+
sql += " ORDER BY id DESC LIMIT ?";
|
|
15176
|
+
params.push(limit);
|
|
15177
|
+
const rows = db.prepare(sql).all(...params);
|
|
15178
|
+
return jsonResult3({ ok: true, count: rows.length, results: rows });
|
|
15179
|
+
} catch (err) {
|
|
15180
|
+
return jsonResult3({
|
|
15181
|
+
ok: false,
|
|
15182
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15183
|
+
});
|
|
15184
|
+
}
|
|
15185
|
+
}
|
|
15186
|
+
},
|
|
15187
|
+
{
|
|
15188
|
+
name: "memory_forget",
|
|
15189
|
+
description: "Delete a durable memory entry by namespace and key.",
|
|
15190
|
+
input: {
|
|
15191
|
+
type: "object",
|
|
15192
|
+
additionalProperties: false,
|
|
15193
|
+
required: ["namespace", "key"],
|
|
15194
|
+
properties: {
|
|
15195
|
+
namespace: { type: "string", description: "Memory namespace" },
|
|
15196
|
+
key: { type: "string", description: "Memory key to delete" }
|
|
15197
|
+
}
|
|
15198
|
+
},
|
|
15199
|
+
output: {},
|
|
15200
|
+
execute: async (input, context) => {
|
|
15201
|
+
try {
|
|
15202
|
+
const ns = input.namespace;
|
|
15203
|
+
const key = input.key;
|
|
15204
|
+
if (typeof ns !== "string" || !ns.trim() || typeof key !== "string" || !key.trim()) {
|
|
15205
|
+
return jsonResult3({ ok: false, error: "namespace and key are required" });
|
|
15206
|
+
}
|
|
15207
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15208
|
+
const db = getMemoryDb(cwd);
|
|
15209
|
+
const info = db.prepare("DELETE FROM memories WHERE namespace = ? AND key = ?").run(ns.trim(), key.trim());
|
|
15210
|
+
return jsonResult3({
|
|
15211
|
+
ok: true,
|
|
15212
|
+
deleted: info.changes > 0,
|
|
15213
|
+
namespace: ns.trim(),
|
|
15214
|
+
key: key.trim()
|
|
15215
|
+
});
|
|
15216
|
+
} catch (err) {
|
|
15217
|
+
return jsonResult3({
|
|
15218
|
+
ok: false,
|
|
15219
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15220
|
+
});
|
|
15221
|
+
}
|
|
15222
|
+
}
|
|
15223
|
+
},
|
|
15224
|
+
{
|
|
15225
|
+
name: "memory_list",
|
|
15226
|
+
description: "List active memory keys in a namespace.",
|
|
15227
|
+
input: {
|
|
15228
|
+
type: "object",
|
|
15229
|
+
additionalProperties: false,
|
|
15230
|
+
properties: {
|
|
15231
|
+
namespace: { type: "string", description: "Optional namespace filter" },
|
|
15232
|
+
limit: { type: "number", description: "Maximum entries to list (default 50)" }
|
|
15233
|
+
}
|
|
15234
|
+
},
|
|
15235
|
+
output: {},
|
|
15236
|
+
execute: async (input, context) => {
|
|
15237
|
+
try {
|
|
15238
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15239
|
+
const db = getMemoryDb(cwd);
|
|
15240
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15241
|
+
const limit = typeof input.limit === "number" && Number.isFinite(input.limit) && input.limit > 0 ? Math.min(Math.floor(input.limit), 200) : 50;
|
|
15242
|
+
let sql = `SELECT namespace, key, created_at FROM memories WHERE ${NOT_EXPIRED_SQL}`;
|
|
15243
|
+
const params = [nowIso];
|
|
15244
|
+
if (typeof input.namespace === "string" && input.namespace.trim()) {
|
|
15245
|
+
sql += " AND namespace = ?";
|
|
15246
|
+
params.push(input.namespace.trim());
|
|
15247
|
+
}
|
|
15248
|
+
sql += " ORDER BY id DESC LIMIT ?";
|
|
15249
|
+
params.push(limit);
|
|
15250
|
+
const rows = db.prepare(sql).all(...params);
|
|
15251
|
+
return jsonResult3({ ok: true, count: rows.length, entries: rows });
|
|
15252
|
+
} catch (err) {
|
|
15253
|
+
return jsonResult3({
|
|
15254
|
+
ok: false,
|
|
15255
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15256
|
+
});
|
|
15257
|
+
}
|
|
15258
|
+
}
|
|
15259
|
+
},
|
|
15260
|
+
{
|
|
15261
|
+
name: "memory_stats",
|
|
15262
|
+
description: "Get counts of active durable memory entries by namespace.",
|
|
15263
|
+
input: {
|
|
15264
|
+
type: "object",
|
|
15265
|
+
additionalProperties: false,
|
|
15266
|
+
properties: {
|
|
15267
|
+
namespace: { type: "string", description: "Optional namespace filter" }
|
|
15268
|
+
}
|
|
15269
|
+
},
|
|
15270
|
+
output: {},
|
|
15271
|
+
execute: async (_input, context) => {
|
|
15272
|
+
try {
|
|
15273
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15274
|
+
const db = getMemoryDb(cwd);
|
|
15275
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15276
|
+
const total = db.prepare(`SELECT count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL}`).get(nowIso);
|
|
15277
|
+
const byNamespace = db.prepare(
|
|
15278
|
+
`SELECT namespace, count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL} GROUP BY namespace`
|
|
15279
|
+
).all(nowIso);
|
|
15280
|
+
return jsonResult3({ ok: true, total: total?.count ?? 0, byNamespace });
|
|
15281
|
+
} catch (err) {
|
|
15282
|
+
return jsonResult3({
|
|
15283
|
+
ok: false,
|
|
15284
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15285
|
+
});
|
|
15286
|
+
}
|
|
15287
|
+
}
|
|
15288
|
+
},
|
|
15289
|
+
{
|
|
15290
|
+
name: "context_save",
|
|
15291
|
+
description: "Save a milestone session checkpoint under .pantheon/persistence.",
|
|
15292
|
+
input: {
|
|
15293
|
+
type: "object",
|
|
15294
|
+
additionalProperties: false,
|
|
15295
|
+
required: ["session_id", "content"],
|
|
15296
|
+
properties: {
|
|
15297
|
+
session_id: { type: "string", description: "Session identifier" },
|
|
15298
|
+
content: { type: "string", description: "Serialized JSON state object" },
|
|
15299
|
+
namespace: { type: "string", description: "Optional checkpoint namespace" }
|
|
15300
|
+
}
|
|
15301
|
+
},
|
|
15302
|
+
output: {},
|
|
15303
|
+
execute: async (input, context) => {
|
|
15304
|
+
try {
|
|
15305
|
+
const sessionId = input.session_id;
|
|
15306
|
+
const ns = input.namespace ?? "checkpoints";
|
|
15307
|
+
if (!isSafeSegment(sessionId) || !isSafeSegment(ns)) {
|
|
15308
|
+
return jsonResult3({
|
|
15309
|
+
ok: false,
|
|
15310
|
+
error: "session_id and namespace must be safe identifiers without path traversal"
|
|
15311
|
+
});
|
|
15312
|
+
}
|
|
15313
|
+
if (typeof input.content !== "string" || !input.content.trim()) {
|
|
15314
|
+
return jsonResult3({ ok: false, error: "content must be a non-empty string" });
|
|
15315
|
+
}
|
|
15316
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15317
|
+
const baseDir = join20(cwd, ".pantheon", "persistence");
|
|
15318
|
+
const dir = resolveConfinedPath(baseDir, ns);
|
|
15319
|
+
mkdirSync8(dir, { recursive: true });
|
|
15320
|
+
const filePath = resolveConfinedPath(dir, `${sessionId}.json`);
|
|
15321
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15322
|
+
writeFileSync6(
|
|
15323
|
+
filePath,
|
|
15324
|
+
JSON.stringify(
|
|
15325
|
+
{
|
|
15326
|
+
session_id: sessionId,
|
|
15327
|
+
namespace: ns,
|
|
15328
|
+
content: input.content,
|
|
15329
|
+
updated_at: nowIso
|
|
15330
|
+
},
|
|
15331
|
+
null,
|
|
15332
|
+
2
|
|
15333
|
+
),
|
|
15334
|
+
"utf8"
|
|
15335
|
+
);
|
|
15336
|
+
return jsonResult3({
|
|
15337
|
+
ok: true,
|
|
15338
|
+
status: "saved",
|
|
15339
|
+
session_id: sessionId,
|
|
15340
|
+
updated_at: nowIso
|
|
15341
|
+
});
|
|
15342
|
+
} catch (err) {
|
|
15343
|
+
return jsonResult3({
|
|
15344
|
+
ok: false,
|
|
15345
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15346
|
+
});
|
|
15347
|
+
}
|
|
15348
|
+
}
|
|
15349
|
+
},
|
|
15350
|
+
{
|
|
15351
|
+
name: "context_get",
|
|
15352
|
+
description: "Retrieve a saved session checkpoint by session_id.",
|
|
15353
|
+
input: {
|
|
15354
|
+
type: "object",
|
|
15355
|
+
additionalProperties: false,
|
|
15356
|
+
required: ["session_id"],
|
|
15357
|
+
properties: {
|
|
15358
|
+
session_id: { type: "string", description: "Session identifier" },
|
|
15359
|
+
namespace: { type: "string", description: "Optional checkpoint namespace" }
|
|
15360
|
+
}
|
|
15361
|
+
},
|
|
15362
|
+
output: {},
|
|
15363
|
+
execute: async (input, context) => {
|
|
15364
|
+
try {
|
|
15365
|
+
const sessionId = input.session_id;
|
|
15366
|
+
const ns = input.namespace ?? "checkpoints";
|
|
15367
|
+
if (!isSafeSegment(sessionId) || !isSafeSegment(ns)) {
|
|
15368
|
+
return jsonResult3({
|
|
15369
|
+
ok: false,
|
|
15370
|
+
error: "session_id and namespace must be safe identifiers without path traversal"
|
|
15371
|
+
});
|
|
15372
|
+
}
|
|
15373
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15374
|
+
const baseDir = join20(cwd, ".pantheon", "persistence");
|
|
15375
|
+
const dir = resolveConfinedPath(baseDir, ns);
|
|
15376
|
+
const filePath = resolveConfinedPath(dir, `${sessionId}.json`);
|
|
15377
|
+
if (!existsSync11(filePath)) {
|
|
15378
|
+
return jsonResult3({ ok: false, error: "not_found", session_id: sessionId });
|
|
15379
|
+
}
|
|
15380
|
+
return jsonResult3(JSON.parse(readFileSync10(filePath, "utf8")));
|
|
15381
|
+
} catch (err) {
|
|
15382
|
+
return jsonResult3({
|
|
15383
|
+
ok: false,
|
|
15384
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15385
|
+
});
|
|
15386
|
+
}
|
|
15387
|
+
}
|
|
15388
|
+
},
|
|
15389
|
+
{
|
|
15390
|
+
name: "goal_create",
|
|
15391
|
+
description: "Create a persistent session goal in .pantheon/goals (read by compaction hooks).",
|
|
15392
|
+
input: {
|
|
15393
|
+
type: "object",
|
|
15394
|
+
additionalProperties: false,
|
|
15395
|
+
required: ["title"],
|
|
15396
|
+
properties: {
|
|
15397
|
+
id: { type: "string", description: "Optional goal identifier" },
|
|
15398
|
+
title: { type: "string", description: "Concise goal statement" },
|
|
15399
|
+
criteria: {
|
|
15400
|
+
type: "array",
|
|
15401
|
+
items: { type: "string" },
|
|
15402
|
+
description: "Completion criteria checklist"
|
|
15403
|
+
}
|
|
15404
|
+
}
|
|
15405
|
+
},
|
|
15406
|
+
output: {},
|
|
15407
|
+
execute: async (input, context) => {
|
|
15408
|
+
try {
|
|
15409
|
+
const title = typeof input.title === "string" ? input.title.trim() : "";
|
|
15410
|
+
if (!title) return jsonResult3({ ok: false, error: "title is required" });
|
|
15411
|
+
const rawId = typeof input.id === "string" && input.id.trim() ? input.id.trim() : `goal-${Date.now()}`;
|
|
15412
|
+
if (!isSafeSegment(rawId)) {
|
|
15413
|
+
return jsonResult3({ ok: false, error: "id must be a safe identifier" });
|
|
15414
|
+
}
|
|
15415
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15416
|
+
const goalsDir = join20(cwd, ".pantheon", "goals");
|
|
15417
|
+
const filePath = resolveConfinedPath(goalsDir, `${rawId}.json`);
|
|
15418
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
15419
|
+
const goal = {
|
|
15420
|
+
id: rawId,
|
|
15421
|
+
title,
|
|
15422
|
+
criteria: Array.isArray(input.criteria) ? input.criteria.map(String) : [],
|
|
15423
|
+
status: "active",
|
|
15424
|
+
created_at: nowIso,
|
|
15425
|
+
updated_at: nowIso
|
|
15426
|
+
};
|
|
15427
|
+
writeFileSync6(filePath, JSON.stringify(goal, null, 2), "utf8");
|
|
15428
|
+
return jsonResult3({ ok: true, goal });
|
|
15429
|
+
} catch (err) {
|
|
15430
|
+
return jsonResult3({
|
|
15431
|
+
ok: false,
|
|
15432
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15433
|
+
});
|
|
15434
|
+
}
|
|
15435
|
+
}
|
|
15436
|
+
},
|
|
15437
|
+
{
|
|
15438
|
+
name: "goal_get",
|
|
15439
|
+
description: "Retrieve an active session goal by id or latest.",
|
|
15440
|
+
input: {
|
|
15441
|
+
type: "object",
|
|
15442
|
+
additionalProperties: false,
|
|
15443
|
+
properties: {
|
|
15444
|
+
id: { type: "string", description: "Optional goal id (defaults to latest)" }
|
|
15445
|
+
}
|
|
15446
|
+
},
|
|
15447
|
+
output: {},
|
|
15448
|
+
execute: async (input, context) => {
|
|
15449
|
+
try {
|
|
15450
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15451
|
+
const goalsDir = join20(cwd, ".pantheon", "goals");
|
|
15452
|
+
mkdirSync8(goalsDir, { recursive: true });
|
|
15453
|
+
if (typeof input.id === "string" && input.id.trim()) {
|
|
15454
|
+
const id = input.id.trim();
|
|
15455
|
+
if (!isSafeSegment(id)) {
|
|
15456
|
+
return jsonResult3({ ok: false, error: "id must be a safe identifier" });
|
|
15457
|
+
}
|
|
15458
|
+
const filePath = resolveConfinedPath(goalsDir, `${id}.json`);
|
|
15459
|
+
if (!existsSync11(filePath)) return jsonResult3({ ok: false, error: "not_found", id });
|
|
15460
|
+
return jsonResult3(JSON.parse(readFileSync10(filePath, "utf8")));
|
|
15461
|
+
}
|
|
15462
|
+
const files = readdirSync4(goalsDir).filter((f) => f.endsWith(".json")).sort();
|
|
15463
|
+
const latest = files.at(-1);
|
|
15464
|
+
if (!latest) return jsonResult3({ ok: false, error: "no_active_goals" });
|
|
15465
|
+
return jsonResult3(JSON.parse(readFileSync10(resolveConfinedPath(goalsDir, latest), "utf8")));
|
|
15466
|
+
} catch (err) {
|
|
15467
|
+
return jsonResult3({
|
|
15468
|
+
ok: false,
|
|
15469
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15470
|
+
});
|
|
15471
|
+
}
|
|
15472
|
+
}
|
|
15473
|
+
},
|
|
15474
|
+
{
|
|
15475
|
+
name: "goal_update",
|
|
15476
|
+
description: "Update progress or status on an active session goal.",
|
|
15477
|
+
input: {
|
|
15478
|
+
type: "object",
|
|
15479
|
+
additionalProperties: false,
|
|
15480
|
+
required: ["id"],
|
|
15481
|
+
properties: {
|
|
15482
|
+
id: { type: "string", description: "Goal identifier" },
|
|
15483
|
+
status: { type: "string", description: "Updated status (active, paused, completed)" },
|
|
15484
|
+
notes: { type: "string", description: "Progress notes" }
|
|
15485
|
+
}
|
|
15486
|
+
},
|
|
15487
|
+
output: {},
|
|
15488
|
+
execute: async (input, context) => {
|
|
15489
|
+
try {
|
|
15490
|
+
const id = typeof input.id === "string" ? input.id.trim() : "";
|
|
15491
|
+
if (!isSafeSegment(id)) {
|
|
15492
|
+
return jsonResult3({ ok: false, error: "valid goal id is required" });
|
|
15493
|
+
}
|
|
15494
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15495
|
+
const goalsDir = join20(cwd, ".pantheon", "goals");
|
|
15496
|
+
const filePath = resolveConfinedPath(goalsDir, `${id}.json`);
|
|
15497
|
+
if (!existsSync11(filePath)) return jsonResult3({ ok: false, error: "not_found", id });
|
|
15498
|
+
const existing = JSON.parse(readFileSync10(filePath, "utf8"));
|
|
15499
|
+
const updated = {
|
|
15500
|
+
...existing,
|
|
15501
|
+
status: typeof input.status === "string" ? input.status : existing.status,
|
|
15502
|
+
...typeof input.notes === "string" ? { notes: input.notes } : {},
|
|
15503
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
15504
|
+
};
|
|
15505
|
+
writeFileSync6(filePath, JSON.stringify(updated, null, 2), "utf8");
|
|
15506
|
+
return jsonResult3({ ok: true, goal: updated });
|
|
15507
|
+
} catch (err) {
|
|
15508
|
+
return jsonResult3({
|
|
15509
|
+
ok: false,
|
|
15510
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15511
|
+
});
|
|
15512
|
+
}
|
|
15513
|
+
}
|
|
15514
|
+
},
|
|
15515
|
+
{
|
|
15516
|
+
name: "goal_done",
|
|
15517
|
+
description: "Mark a session goal as completed.",
|
|
15518
|
+
input: {
|
|
15519
|
+
type: "object",
|
|
15520
|
+
additionalProperties: false,
|
|
15521
|
+
required: ["id"],
|
|
15522
|
+
properties: {
|
|
15523
|
+
id: { type: "string", description: "Goal identifier" },
|
|
15524
|
+
summary: { type: "string", description: "Completion summary" }
|
|
15525
|
+
}
|
|
15526
|
+
},
|
|
15527
|
+
output: {},
|
|
15528
|
+
execute: async (input, context) => {
|
|
15529
|
+
try {
|
|
15530
|
+
const id = typeof input.id === "string" ? input.id.trim() : "";
|
|
15531
|
+
if (!isSafeSegment(id)) {
|
|
15532
|
+
return jsonResult3({ ok: false, error: "valid goal id is required" });
|
|
15533
|
+
}
|
|
15534
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
15535
|
+
const goalsDir = join20(cwd, ".pantheon", "goals");
|
|
15536
|
+
const filePath = resolveConfinedPath(goalsDir, `${id}.json`);
|
|
15537
|
+
if (!existsSync11(filePath)) return jsonResult3({ ok: false, error: "not_found", id });
|
|
15538
|
+
const existing = JSON.parse(readFileSync10(filePath, "utf8"));
|
|
15539
|
+
const updated = {
|
|
15540
|
+
...existing,
|
|
15541
|
+
status: "completed",
|
|
15542
|
+
...typeof input.summary === "string" ? { summary: input.summary } : {},
|
|
15543
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
15544
|
+
};
|
|
15545
|
+
writeFileSync6(filePath, JSON.stringify(updated, null, 2), "utf8");
|
|
15546
|
+
return jsonResult3({ ok: true, goal: updated });
|
|
15547
|
+
} catch (err) {
|
|
15548
|
+
return jsonResult3({
|
|
15549
|
+
ok: false,
|
|
15550
|
+
error: err instanceof Error ? err.message : String(err)
|
|
15551
|
+
});
|
|
15552
|
+
}
|
|
15553
|
+
}
|
|
15554
|
+
}
|
|
15555
|
+
];
|
|
15556
|
+
}
|
|
15557
|
+
|
|
13973
15558
|
// src/pantheon/skill-search-tool.ts
|
|
13974
|
-
import { existsSync as
|
|
15559
|
+
import { existsSync as existsSync12, readdirSync as readdirSync5, readFileSync as readFileSync11 } from "node:fs";
|
|
13975
15560
|
import { homedir as homedir8 } from "node:os";
|
|
13976
|
-
import { join as
|
|
15561
|
+
import { join as join21 } from "node:path";
|
|
13977
15562
|
|
|
13978
15563
|
// scripts/skill-search.mjs
|
|
13979
15564
|
import { spawnSync } from "node:child_process";
|
|
@@ -14230,16 +15815,16 @@ function scanInstalledSkills(cwd = process.cwd()) {
|
|
|
14230
15815
|
}
|
|
14231
15816
|
const scanDir = (baseDir, scope) => {
|
|
14232
15817
|
try {
|
|
14233
|
-
if (!
|
|
14234
|
-
const entries =
|
|
15818
|
+
if (!existsSync12(baseDir)) return;
|
|
15819
|
+
const entries = readdirSync5(baseDir, { withFileTypes: true });
|
|
14235
15820
|
for (const entry of entries) {
|
|
14236
15821
|
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
|
|
14237
15822
|
const skillName = entry.name;
|
|
14238
15823
|
if (skillName.startsWith(".")) continue;
|
|
14239
|
-
const skillMd =
|
|
14240
|
-
if (
|
|
15824
|
+
const skillMd = join21(baseDir, skillName, "SKILL.md");
|
|
15825
|
+
if (existsSync12(skillMd)) {
|
|
14241
15826
|
try {
|
|
14242
|
-
const raw =
|
|
15827
|
+
const raw = readFileSync11(skillMd, "utf8");
|
|
14243
15828
|
const { name, description } = extractSkillMetadata(raw, skillName);
|
|
14244
15829
|
const id = (name || skillName).trim();
|
|
14245
15830
|
map.set(id.toLowerCase(), {
|
|
@@ -14255,12 +15840,12 @@ function scanInstalledSkills(cwd = process.cwd()) {
|
|
|
14255
15840
|
} catch {
|
|
14256
15841
|
}
|
|
14257
15842
|
};
|
|
14258
|
-
const xdgConfig = process.env.XDG_CONFIG_HOME ||
|
|
14259
|
-
scanDir(
|
|
14260
|
-
scanDir(
|
|
14261
|
-
scanDir(
|
|
14262
|
-
scanDir(
|
|
14263
|
-
scanDir(
|
|
15843
|
+
const xdgConfig = process.env.XDG_CONFIG_HOME || join21(homedir8(), ".config");
|
|
15844
|
+
scanDir(join21(xdgConfig, "opencode", "skills"), "global");
|
|
15845
|
+
scanDir(join21(homedir8(), ".agents", "skills"), "global");
|
|
15846
|
+
scanDir(join21(cwd, ".opencode", "skills"), "project");
|
|
15847
|
+
scanDir(join21(cwd, ".agents", "skills"), "project");
|
|
15848
|
+
scanDir(join21(cwd, "skills"), "project");
|
|
14264
15849
|
return map;
|
|
14265
15850
|
}
|
|
14266
15851
|
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.";
|
|
@@ -14432,6 +16017,196 @@ function createV2SkillSearchDefinition(defaultDir) {
|
|
|
14432
16017
|
};
|
|
14433
16018
|
}
|
|
14434
16019
|
|
|
16020
|
+
// src/pantheon/step-ledger.ts
|
|
16021
|
+
import { existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync12, realpathSync as realpathSync5, writeFileSync as writeFileSync7 } from "node:fs";
|
|
16022
|
+
import { join as join22, resolve as resolve11, sep as sep8 } from "node:path";
|
|
16023
|
+
var SAFE_STEP_KEY_RE = /^[a-zA-Z0-9._:-]{1,128}$/;
|
|
16024
|
+
var stepReflex = new ThemisReflexController({ maxRetries: 2 });
|
|
16025
|
+
function assertSafeStepKey(stepKey) {
|
|
16026
|
+
if (typeof stepKey !== "string" || !SAFE_STEP_KEY_RE.test(stepKey) || stepKey.includes("..")) {
|
|
16027
|
+
throw new Error("stepKey must be a safe alphanumeric identifier (1..128 chars)");
|
|
16028
|
+
}
|
|
16029
|
+
return stepKey;
|
|
16030
|
+
}
|
|
16031
|
+
function resolveLedgerPath(workspaceDir) {
|
|
16032
|
+
const dir = join22(workspaceDir, ".pantheon", "ledger");
|
|
16033
|
+
mkdirSync9(dir, { recursive: true });
|
|
16034
|
+
const canonicalDir = realpathSync5(dir);
|
|
16035
|
+
const filePath = resolve11(canonicalDir, "step-ledger.json");
|
|
16036
|
+
const prefix = canonicalDir.endsWith(sep8) ? canonicalDir : `${canonicalDir}${sep8}`;
|
|
16037
|
+
if (!filePath.startsWith(prefix)) {
|
|
16038
|
+
throw new Error("Path traversal denied for step-ledger.json");
|
|
16039
|
+
}
|
|
16040
|
+
return filePath;
|
|
16041
|
+
}
|
|
16042
|
+
function readStepLedger(workspaceDir) {
|
|
16043
|
+
const filePath = resolveLedgerPath(workspaceDir);
|
|
16044
|
+
if (!existsSync13(filePath)) {
|
|
16045
|
+
return { version: 1, steps: {} };
|
|
16046
|
+
}
|
|
16047
|
+
try {
|
|
16048
|
+
const parsed = JSON.parse(readFileSync12(filePath, "utf8"));
|
|
16049
|
+
if (parsed && typeof parsed.steps === "object" && parsed.steps !== null) {
|
|
16050
|
+
return { version: 1, steps: parsed.steps };
|
|
16051
|
+
}
|
|
16052
|
+
} catch {
|
|
16053
|
+
}
|
|
16054
|
+
return { version: 1, steps: {} };
|
|
16055
|
+
}
|
|
16056
|
+
function writeStepLedger(workspaceDir, store2) {
|
|
16057
|
+
const filePath = resolveLedgerPath(workspaceDir);
|
|
16058
|
+
writeFileSync7(filePath, `${JSON.stringify(store2, null, 2)}
|
|
16059
|
+
`, "utf8");
|
|
16060
|
+
}
|
|
16061
|
+
function canTransitionStepToDone(step) {
|
|
16062
|
+
if (step.verificationExitCode !== 0 || step.lastVerifiedAt === null) {
|
|
16063
|
+
return {
|
|
16064
|
+
allowed: false,
|
|
16065
|
+
reason: `Step "${step.stepKey}" cannot transition to done: no passing verification command (exitCode === 0) has been recorded.`
|
|
16066
|
+
};
|
|
16067
|
+
}
|
|
16068
|
+
if (step.lastMutationAt !== null && step.lastVerifiedAt < step.lastMutationAt) {
|
|
16069
|
+
return {
|
|
16070
|
+
allowed: false,
|
|
16071
|
+
reason: `Step "${step.stepKey}" cannot transition to done: files were mutated after the last verification run. Re-run the verification slice first.`
|
|
16072
|
+
};
|
|
16073
|
+
}
|
|
16074
|
+
return { allowed: true };
|
|
16075
|
+
}
|
|
16076
|
+
function jsonResult4(payload) {
|
|
16077
|
+
return { output: JSON.stringify(payload) };
|
|
16078
|
+
}
|
|
16079
|
+
function createStepLedgerTool(fallbackDir) {
|
|
16080
|
+
return {
|
|
16081
|
+
name: "pantheon_step_ledger",
|
|
16082
|
+
description: "Manage atomic Step-Ledger execution contracts with hard verification gates: a step can transition to done ONLY after a verification command exits 0 following the last file mutation.",
|
|
16083
|
+
input: {
|
|
16084
|
+
type: "object",
|
|
16085
|
+
additionalProperties: false,
|
|
16086
|
+
required: ["action"],
|
|
16087
|
+
properties: {
|
|
16088
|
+
action: {
|
|
16089
|
+
type: "string",
|
|
16090
|
+
enum: ["init_step", "record_mutation", "record_verification", "complete_step", "status"],
|
|
16091
|
+
description: "Ledger operation to perform"
|
|
16092
|
+
},
|
|
16093
|
+
stepKey: { type: "string", description: "Unique atomic step identifier" },
|
|
16094
|
+
objective: { type: "string", description: "Bounded step objective" },
|
|
16095
|
+
agent: { type: "string", description: "Assigned specialist agent" },
|
|
16096
|
+
files: {
|
|
16097
|
+
type: "array",
|
|
16098
|
+
items: { type: "string" },
|
|
16099
|
+
description: "Mutated file paths for record_mutation"
|
|
16100
|
+
},
|
|
16101
|
+
command: { type: "string", description: "Executed verification slice command" },
|
|
16102
|
+
exitCode: { type: "number", description: "Exit code of the verification command" },
|
|
16103
|
+
durationMs: { type: "number", description: "Duration of verification command in ms" }
|
|
16104
|
+
}
|
|
16105
|
+
},
|
|
16106
|
+
output: {},
|
|
16107
|
+
execute: async (input, context) => {
|
|
16108
|
+
try {
|
|
16109
|
+
const action = typeof input.action === "string" ? input.action : "status";
|
|
16110
|
+
const cwd = resolveToolCwd(context, fallbackDir);
|
|
16111
|
+
const store2 = readStepLedger(cwd);
|
|
16112
|
+
const now = Date.now();
|
|
16113
|
+
const nowIso = new Date(now).toISOString();
|
|
16114
|
+
if (action === "status") {
|
|
16115
|
+
if (typeof input.stepKey === "string" && input.stepKey.trim()) {
|
|
16116
|
+
const key2 = assertSafeStepKey(input.stepKey.trim());
|
|
16117
|
+
const step2 = store2.steps[key2];
|
|
16118
|
+
if (!step2) return jsonResult4({ ok: false, error: "step_not_found", stepKey: key2 });
|
|
16119
|
+
return jsonResult4({ ok: true, step: step2, gate: canTransitionStepToDone(step2) });
|
|
16120
|
+
}
|
|
16121
|
+
return jsonResult4({ ok: true, steps: Object.values(store2.steps) });
|
|
16122
|
+
}
|
|
16123
|
+
const key = assertSafeStepKey(input.stepKey);
|
|
16124
|
+
if (action === "init_step") {
|
|
16125
|
+
const objective = typeof input.objective === "string" ? input.objective.trim() : "";
|
|
16126
|
+
if (!objective) return jsonResult4({ ok: false, error: "objective is required" });
|
|
16127
|
+
const agent = typeof input.agent === "string" && input.agent.trim() ? input.agent.trim() : "specialist";
|
|
16128
|
+
const entry = {
|
|
16129
|
+
stepKey: key,
|
|
16130
|
+
objective,
|
|
16131
|
+
agent,
|
|
16132
|
+
state: "in_progress",
|
|
16133
|
+
mutatedFiles: [],
|
|
16134
|
+
lastMutationAt: null,
|
|
16135
|
+
lastVerifiedAt: null,
|
|
16136
|
+
updatedAt: nowIso
|
|
16137
|
+
};
|
|
16138
|
+
store2.steps[key] = entry;
|
|
16139
|
+
writeStepLedger(cwd, store2);
|
|
16140
|
+
return jsonResult4({ ok: true, step: entry });
|
|
16141
|
+
}
|
|
16142
|
+
const step = store2.steps[key];
|
|
16143
|
+
if (!step) {
|
|
16144
|
+
return jsonResult4({ ok: false, error: `Step "${key}" is not initialized` });
|
|
16145
|
+
}
|
|
16146
|
+
if (action === "record_mutation") {
|
|
16147
|
+
const files = Array.isArray(input.files) ? input.files.map(String) : [];
|
|
16148
|
+
const merged = Array.from(/* @__PURE__ */ new Set([...step.mutatedFiles, ...files]));
|
|
16149
|
+
step.mutatedFiles = merged;
|
|
16150
|
+
step.lastMutationAt = now;
|
|
16151
|
+
if (step.state === "done") step.state = "in_progress";
|
|
16152
|
+
step.updatedAt = nowIso;
|
|
16153
|
+
writeStepLedger(cwd, store2);
|
|
16154
|
+
return jsonResult4({ ok: true, step });
|
|
16155
|
+
}
|
|
16156
|
+
if (action === "record_verification") {
|
|
16157
|
+
const command = typeof input.command === "string" ? input.command.trim() : "";
|
|
16158
|
+
const exitCode = typeof input.exitCode === "number" ? input.exitCode : 1;
|
|
16159
|
+
const durationMs = typeof input.durationMs === "number" ? input.durationMs : 0;
|
|
16160
|
+
if (!command) return jsonResult4({ ok: false, error: "command is required" });
|
|
16161
|
+
step.verificationCommand = command;
|
|
16162
|
+
step.verificationExitCode = exitCode;
|
|
16163
|
+
step.lastVerifiedAt = now;
|
|
16164
|
+
step.updatedAt = nowIso;
|
|
16165
|
+
if (exitCode === 0) {
|
|
16166
|
+
stepReflex.evaluate(key, step.agent, []);
|
|
16167
|
+
const receipt = createExecutionReceipt({
|
|
16168
|
+
taskID: key,
|
|
16169
|
+
agent: step.agent,
|
|
16170
|
+
files: step.mutatedFiles.map((f) => ({ path: f, content: `${key}:${f}:${now}` })),
|
|
16171
|
+
testSlice: { command, exitCode: 0, durationMs }
|
|
16172
|
+
});
|
|
16173
|
+
step.receiptId = receipt.receiptId;
|
|
16174
|
+
writeStepLedger(cwd, store2);
|
|
16175
|
+
return jsonResult4({ ok: true, verified: true, receiptId: receipt.receiptId, step });
|
|
16176
|
+
}
|
|
16177
|
+
const reflex = stepReflex.evaluate(key, step.agent, [
|
|
16178
|
+
{
|
|
16179
|
+
file: step.mutatedFiles[0] ?? key,
|
|
16180
|
+
error: `Verification command "${command}" failed with exit code ${exitCode}`
|
|
16181
|
+
}
|
|
16182
|
+
]);
|
|
16183
|
+
if (reflex.action === "escalate") {
|
|
16184
|
+
step.state = "blocked";
|
|
16185
|
+
}
|
|
16186
|
+
writeStepLedger(cwd, store2);
|
|
16187
|
+
return jsonResult4({ ok: false, verified: false, reflex, step });
|
|
16188
|
+
}
|
|
16189
|
+
if (action === "complete_step") {
|
|
16190
|
+
const gate = canTransitionStepToDone(step);
|
|
16191
|
+
if (!gate.allowed) {
|
|
16192
|
+
return jsonResult4({ ok: false, error: gate.reason, step });
|
|
16193
|
+
}
|
|
16194
|
+
step.state = "done";
|
|
16195
|
+
step.updatedAt = nowIso;
|
|
16196
|
+
writeStepLedger(cwd, store2);
|
|
16197
|
+
return jsonResult4({ ok: true, status: "done", receiptId: step.receiptId, step });
|
|
16198
|
+
}
|
|
16199
|
+
return jsonResult4({ ok: false, error: `Unsupported action: ${action}` });
|
|
16200
|
+
} catch (err) {
|
|
16201
|
+
return jsonResult4({
|
|
16202
|
+
ok: false,
|
|
16203
|
+
error: err instanceof Error ? err.message : String(err)
|
|
16204
|
+
});
|
|
16205
|
+
}
|
|
16206
|
+
}
|
|
16207
|
+
};
|
|
16208
|
+
}
|
|
16209
|
+
|
|
14435
16210
|
// src/pantheon/tools.ts
|
|
14436
16211
|
function toolContext(context) {
|
|
14437
16212
|
const ctx = context ?? {};
|
|
@@ -14552,11 +16327,18 @@ function coerceHashlineEditArgs(input) {
|
|
|
14552
16327
|
}
|
|
14553
16328
|
var hashlineEdit = createHashlineEditTool();
|
|
14554
16329
|
async function executeHashlineEdit(input, context) {
|
|
16330
|
+
const ctx = toolContext(context);
|
|
16331
|
+
const callerAgent = (ctx.agent ?? "").toLowerCase().trim();
|
|
16332
|
+
if (callerAgent && callerAgent !== "zeus" && NON_EDIT_AGENTS.has(callerAgent)) {
|
|
16333
|
+
return {
|
|
16334
|
+
output: `hashline_edit denied: agent '${callerAgent}' is not permitted to edit files directly.`
|
|
16335
|
+
};
|
|
16336
|
+
}
|
|
14555
16337
|
const coerced = coerceHashlineEditArgs(input);
|
|
14556
16338
|
if (!coerced.ok) return { output: coerced.error };
|
|
14557
16339
|
let result;
|
|
14558
16340
|
try {
|
|
14559
|
-
result = await hashlineEdit.execute(coerced.args,
|
|
16341
|
+
result = await hashlineEdit.execute(coerced.args, ctx);
|
|
14560
16342
|
} catch (err) {
|
|
14561
16343
|
return { output: errorText("hashline_edit failed", err) };
|
|
14562
16344
|
}
|
|
@@ -14688,15 +16470,41 @@ var TODOWRITE_INPUT = {
|
|
|
14688
16470
|
}
|
|
14689
16471
|
};
|
|
14690
16472
|
var latestSessionTodos = [];
|
|
16473
|
+
var sessionTodosBySession = /* @__PURE__ */ new Map();
|
|
16474
|
+
function resolveTodoSessionKey(context) {
|
|
16475
|
+
if (!context || typeof context !== "object") return void 0;
|
|
16476
|
+
const ctx = context;
|
|
16477
|
+
if (typeof ctx.sessionID === "string" && ctx.sessionID.trim() !== "") {
|
|
16478
|
+
return ctx.sessionID.trim();
|
|
16479
|
+
}
|
|
16480
|
+
const sessionObj = ctx.session;
|
|
16481
|
+
if (typeof sessionObj?.id === "string" && sessionObj.id.trim() !== "") {
|
|
16482
|
+
return sessionObj.id.trim();
|
|
16483
|
+
}
|
|
16484
|
+
return void 0;
|
|
16485
|
+
}
|
|
16486
|
+
function getLatestSessionTodos(sessionID) {
|
|
16487
|
+
if (sessionID && sessionTodosBySession.has(sessionID)) {
|
|
16488
|
+
return sessionTodosBySession.get(sessionID) ?? [];
|
|
16489
|
+
}
|
|
16490
|
+
return latestSessionTodos;
|
|
16491
|
+
}
|
|
16492
|
+
function setLatestSessionTodos(todos, sessionID) {
|
|
16493
|
+
latestSessionTodos = todos;
|
|
16494
|
+
if (sessionID) {
|
|
16495
|
+
sessionTodosBySession.set(sessionID, todos);
|
|
16496
|
+
}
|
|
16497
|
+
}
|
|
14691
16498
|
var todowriteTool = {
|
|
14692
16499
|
name: "todowrite",
|
|
14693
16500
|
description: "Write the session task checklist (full replace). The TUI todo panel renders the newest list; mark each item in_progress/completed as soon as its state changes.",
|
|
14694
16501
|
input: TODOWRITE_INPUT,
|
|
14695
16502
|
output: {},
|
|
14696
|
-
execute: async (input) => {
|
|
16503
|
+
execute: async (input, context) => {
|
|
14697
16504
|
const rawTodos = input.todos;
|
|
14698
16505
|
const todos = Array.isArray(rawTodos) ? rawTodos : [];
|
|
14699
|
-
|
|
16506
|
+
const sessionKey = resolveTodoSessionKey(context);
|
|
16507
|
+
setLatestSessionTodos(todos, sessionKey);
|
|
14700
16508
|
return { ok: true, todos, output: JSON.stringify({ todos }) };
|
|
14701
16509
|
}
|
|
14702
16510
|
};
|
|
@@ -14715,9 +16523,10 @@ var todoreadTool = {
|
|
|
14715
16523
|
description: "Read the active session task checklist. Returns the newest list of tasks written via todowrite.",
|
|
14716
16524
|
input: TODOREAD_INPUT,
|
|
14717
16525
|
output: {},
|
|
14718
|
-
execute: async (input) => {
|
|
16526
|
+
execute: async (input, context) => {
|
|
14719
16527
|
const statusFilter = input?.status;
|
|
14720
|
-
|
|
16528
|
+
const sessionKey = resolveTodoSessionKey(context);
|
|
16529
|
+
let todos = getLatestSessionTodos(sessionKey);
|
|
14721
16530
|
if (typeof statusFilter === "string" && statusFilter.trim() !== "") {
|
|
14722
16531
|
todos = todos.filter(
|
|
14723
16532
|
(t) => typeof t === "object" && t !== null && t.status === statusFilter
|
|
@@ -14731,6 +16540,7 @@ var todoreadTool = {
|
|
|
14731
16540
|
}
|
|
14732
16541
|
};
|
|
14733
16542
|
var execAsync = promisify(exec);
|
|
16543
|
+
var SHELL_TIMEOUT_MS = 12e4;
|
|
14734
16544
|
var SHELL_INPUT = {
|
|
14735
16545
|
type: "object",
|
|
14736
16546
|
required: ["command"],
|
|
@@ -14748,16 +16558,27 @@ function createShellTool(fallbackDir) {
|
|
|
14748
16558
|
input: SHELL_INPUT,
|
|
14749
16559
|
output: {},
|
|
14750
16560
|
execute: async (input, context) => {
|
|
16561
|
+
const ctx = toolContext(context);
|
|
16562
|
+
const callerAgent = (ctx.agent ?? "").toLowerCase().trim();
|
|
16563
|
+
if (callerAgent && NON_SHELL_AGENTS.has(callerAgent)) {
|
|
16564
|
+
const msg = `shell denied: agent '${callerAgent}' is not permitted to execute shell commands`;
|
|
16565
|
+
return { output: msg, ok: false, error: msg };
|
|
16566
|
+
}
|
|
14751
16567
|
const raw = input ?? {};
|
|
14752
16568
|
const command = String(raw.command ?? raw.cmd ?? "");
|
|
14753
16569
|
if (!command.trim()) {
|
|
14754
16570
|
return { output: "", ok: false, error: "Command cannot be empty" };
|
|
14755
16571
|
}
|
|
16572
|
+
if (isDangerousCommand(command)) {
|
|
16573
|
+
const msg = "shell denied: destructive or privilege-escalation command blocked by safety guard";
|
|
16574
|
+
return { output: msg, ok: false, error: msg };
|
|
16575
|
+
}
|
|
14756
16576
|
const cwd = resolveToolCwd(context, fallbackDir);
|
|
14757
16577
|
try {
|
|
14758
16578
|
const { stdout, stderr } = await execAsync(command, {
|
|
14759
16579
|
cwd,
|
|
14760
16580
|
maxBuffer: 10 * 1024 * 1024,
|
|
16581
|
+
timeout: SHELL_TIMEOUT_MS,
|
|
14761
16582
|
shell: "/bin/bash"
|
|
14762
16583
|
});
|
|
14763
16584
|
const output = [stdout, stderr].filter(Boolean).join("\n");
|
|
@@ -14805,6 +16626,10 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime, hostLoc
|
|
|
14805
16626
|
definitions.push(createShellTool(hostLocationDirectory));
|
|
14806
16627
|
definitions.push(createV2SkillSearchDefinition(hostLocationDirectory));
|
|
14807
16628
|
definitions.push(createDeepworkTool(hostLocationDirectory));
|
|
16629
|
+
definitions.push(createStepLedgerTool(hostLocationDirectory));
|
|
16630
|
+
definitions.push(createAgentForgeTool(hostLocationDirectory));
|
|
16631
|
+
definitions.push(...createNativeMemoryAndPersistenceTools(hostLocationDirectory));
|
|
16632
|
+
definitions.push(...createCodemapTools(hostLocationDirectory));
|
|
14808
16633
|
if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime));
|
|
14809
16634
|
if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime));
|
|
14810
16635
|
return definitions;
|
|
@@ -14928,17 +16753,15 @@ function loadRuntimeOverrides() {
|
|
|
14928
16753
|
if (runtimeOverridesLoaded) return;
|
|
14929
16754
|
runtimeOverridesLoaded = true;
|
|
14930
16755
|
try {
|
|
14931
|
-
const read = (
|
|
14932
|
-
const fs = __require("node:fs");
|
|
16756
|
+
const read = (filePath) => {
|
|
14933
16757
|
try {
|
|
14934
|
-
return
|
|
16758
|
+
return readFileSync13(filePath, "utf8");
|
|
14935
16759
|
} catch {
|
|
14936
16760
|
return void 0;
|
|
14937
16761
|
}
|
|
14938
16762
|
};
|
|
14939
|
-
const
|
|
14940
|
-
const
|
|
14941
|
-
const projectRaw = read(path5.join(process.cwd(), ".pantheon", "overrides.json"));
|
|
16763
|
+
const globalRaw = read(path4.join(resolveGlobalOverrideDir(), "pantheon-overrides.json"));
|
|
16764
|
+
const projectRaw = read(path4.join(process.cwd(), ".pantheon", "overrides.json"));
|
|
14942
16765
|
runtimeOverrides = mergeOverrides(globalRaw, projectRaw).entries;
|
|
14943
16766
|
} catch {
|
|
14944
16767
|
runtimeOverrides = {};
|
|
@@ -14984,6 +16807,25 @@ function installV2TodoEnforcer(context) {
|
|
|
14984
16807
|
idleTodoEnforcer = todoEnforcer;
|
|
14985
16808
|
return todoEnforcer;
|
|
14986
16809
|
}
|
|
16810
|
+
function readCanonicalRoster() {
|
|
16811
|
+
try {
|
|
16812
|
+
const candidates = [
|
|
16813
|
+
fileURLToPath5(new URL("agents/roster.json", import.meta.url)),
|
|
16814
|
+
fileURLToPath5(new URL("../src/agents/roster.json", import.meta.url)),
|
|
16815
|
+
fileURLToPath5(new URL("src/agents/roster.json", import.meta.url)),
|
|
16816
|
+
path4.join(process.cwd(), "src", "agents", "roster.json")
|
|
16817
|
+
];
|
|
16818
|
+
for (const p of candidates) {
|
|
16819
|
+
if (existsSync14(p)) {
|
|
16820
|
+
const raw = readFileSync13(p, "utf8");
|
|
16821
|
+
const data = JSON.parse(raw);
|
|
16822
|
+
if (data && typeof data.agents === "object") return data.agents;
|
|
16823
|
+
}
|
|
16824
|
+
}
|
|
16825
|
+
} catch {
|
|
16826
|
+
}
|
|
16827
|
+
return {};
|
|
16828
|
+
}
|
|
14987
16829
|
function transformAgents(draft) {
|
|
14988
16830
|
let agents;
|
|
14989
16831
|
try {
|
|
@@ -15002,8 +16844,10 @@ function transformAgents(draft) {
|
|
|
15002
16844
|
markUnsupported("agent-transform-list");
|
|
15003
16845
|
return;
|
|
15004
16846
|
}
|
|
16847
|
+
let configuredOverrides = {};
|
|
15005
16848
|
try {
|
|
15006
16849
|
const modelConfiguration = readV2ModelConfiguration();
|
|
16850
|
+
configuredOverrides = modelConfiguration.overrides;
|
|
15007
16851
|
if (modelConfiguration.warnings.length > 0) {
|
|
15008
16852
|
markUnsupported("agent-model-overrides");
|
|
15009
16853
|
}
|
|
@@ -15012,6 +16856,37 @@ function transformAgents(draft) {
|
|
|
15012
16856
|
markUnsupported("agent-model-overrides");
|
|
15013
16857
|
}
|
|
15014
16858
|
try {
|
|
16859
|
+
const roster = readCanonicalRoster();
|
|
16860
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
16861
|
+
for (const agent of agents) {
|
|
16862
|
+
if (agent?.id) seenIds.add(agent.id);
|
|
16863
|
+
}
|
|
16864
|
+
for (const [id, def] of Object.entries(roster)) {
|
|
16865
|
+
if (!seenIds.has(id) && typeof draft.update === "function") {
|
|
16866
|
+
try {
|
|
16867
|
+
draft.update(id, (current) => {
|
|
16868
|
+
if (current.id && current.id !== id) return;
|
|
16869
|
+
current.id = id;
|
|
16870
|
+
current.name = def.name ?? id;
|
|
16871
|
+
current.description = def.description ?? "";
|
|
16872
|
+
current.mode = id === "zeus" ? "primary" : def.mode ?? "subagent";
|
|
16873
|
+
if (def.temperature !== void 0) current.temperature = def.temperature;
|
|
16874
|
+
const override = configuredOverrides[id];
|
|
16875
|
+
if (override?.model) {
|
|
16876
|
+
current.model = override.model;
|
|
16877
|
+
if (override.variant !== void 0) current.variant = override.variant;
|
|
16878
|
+
}
|
|
16879
|
+
const body = typeof def.body === "string" ? def.body.trim() : "";
|
|
16880
|
+
current.system = body ? buildPrefixCachedPrompt({ identity: body, currentTurn: POLICY }).prompt : POLICY;
|
|
16881
|
+
});
|
|
16882
|
+
} catch {
|
|
16883
|
+
}
|
|
16884
|
+
}
|
|
16885
|
+
}
|
|
16886
|
+
try {
|
|
16887
|
+
if (typeof draft.default === "function") draft.default("zeus");
|
|
16888
|
+
} catch {
|
|
16889
|
+
}
|
|
15015
16890
|
for (const agent of agents) {
|
|
15016
16891
|
draft.update(agent.id, (current) => {
|
|
15017
16892
|
try {
|
|
@@ -15036,7 +16911,58 @@ ${POLICY}`;
|
|
|
15036
16911
|
markUnsupported("agent-transform");
|
|
15037
16912
|
}
|
|
15038
16913
|
}
|
|
16914
|
+
var CANONICAL_SLASH_COMMANDS = [
|
|
16915
|
+
{
|
|
16916
|
+
name: "pantheon",
|
|
16917
|
+
description: "Dispatch inline multi-specialist Council synthesis for architectural trade-offs"
|
|
16918
|
+
},
|
|
16919
|
+
{
|
|
16920
|
+
name: "pantheon-deepwork",
|
|
16921
|
+
description: "Execute multi-phase Deepwork plan with DAG checkpoints and verification gates"
|
|
16922
|
+
},
|
|
16923
|
+
{
|
|
16924
|
+
name: "pantheon-audit",
|
|
16925
|
+
description: "Run zero-token heuristic static scan and Themis 3-layer security review"
|
|
16926
|
+
},
|
|
16927
|
+
{
|
|
16928
|
+
name: "pantheon-focus",
|
|
16929
|
+
description: "Manage persistent session goals and focus boundaries across compactions"
|
|
16930
|
+
},
|
|
16931
|
+
{
|
|
16932
|
+
name: "pantheon-model",
|
|
16933
|
+
description: "Inspect or configure per-agent model overrides in active-preset.json"
|
|
16934
|
+
},
|
|
16935
|
+
{
|
|
16936
|
+
name: "pantheon-optimize",
|
|
16937
|
+
description: "Analyze and prune stale artifacts, worktrees, and context overhead"
|
|
16938
|
+
},
|
|
16939
|
+
{
|
|
16940
|
+
name: "pantheon-settings",
|
|
16941
|
+
description: "Open the interactive Pantheon TUI settings and Quotas & Spend window"
|
|
16942
|
+
},
|
|
16943
|
+
{
|
|
16944
|
+
name: "pantheon-vision",
|
|
16945
|
+
description: "Inspect or configure multimodal vision gateway and model status"
|
|
16946
|
+
}
|
|
16947
|
+
];
|
|
15039
16948
|
function transformCommands(draft) {
|
|
16949
|
+
try {
|
|
16950
|
+
const maybeAdd = draft.add;
|
|
16951
|
+
if (typeof maybeAdd === "function") {
|
|
16952
|
+
for (const cmd of CANONICAL_SLASH_COMMANDS) {
|
|
16953
|
+
try {
|
|
16954
|
+
maybeAdd.call(draft, {
|
|
16955
|
+
name: cmd.name,
|
|
16956
|
+
description: cmd.description,
|
|
16957
|
+
execute: async () => {
|
|
16958
|
+
}
|
|
16959
|
+
});
|
|
16960
|
+
} catch {
|
|
16961
|
+
}
|
|
16962
|
+
}
|
|
16963
|
+
}
|
|
16964
|
+
} catch {
|
|
16965
|
+
}
|
|
15040
16966
|
let commands;
|
|
15041
16967
|
try {
|
|
15042
16968
|
const maybeList = draft.list;
|
|
@@ -15067,9 +16993,11 @@ function transformCommands(draft) {
|
|
|
15067
16993
|
}
|
|
15068
16994
|
}
|
|
15069
16995
|
function transformReferences(draft) {
|
|
16996
|
+
const globalAgentsPath = fileURLToPath5(new URL("../AGENTS.global.md", import.meta.url));
|
|
16997
|
+
const fallbackAgentsPath = fileURLToPath5(new URL("../AGENTS.md", import.meta.url));
|
|
15070
16998
|
draft.add("pantheon-agents", {
|
|
15071
16999
|
type: "local",
|
|
15072
|
-
path:
|
|
17000
|
+
path: existsSync14(globalAgentsPath) ? globalAgentsPath : fallbackAgentsPath,
|
|
15073
17001
|
description: "Pantheon agent and execution policy"
|
|
15074
17002
|
});
|
|
15075
17003
|
}
|
|
@@ -15222,11 +17150,12 @@ function subscribeV2Events(context, onTurnEnd) {
|
|
|
15222
17150
|
loopPoint.observe(event);
|
|
15223
17151
|
} catch {
|
|
15224
17152
|
}
|
|
15225
|
-
if (event.type === "session.idle" || event.type === "session.deleted") {
|
|
17153
|
+
if (event.type === "session.idle" || event.type === "session.deleted" || event.type === "session.execution.succeeded") {
|
|
15226
17154
|
const properties = event.properties ?? {};
|
|
17155
|
+
const data = event.data ?? {};
|
|
15227
17156
|
const info = properties.info;
|
|
15228
17157
|
const infoID = info !== null && typeof info === "object" ? info.id : void 0;
|
|
15229
|
-
const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : typeof infoID === "string" ? infoID : void 0;
|
|
17158
|
+
const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : typeof data.sessionID === "string" ? data.sessionID : typeof infoID === "string" ? infoID : void 0;
|
|
15230
17159
|
if (sessionID) onTurnEnd?.(sessionID);
|
|
15231
17160
|
}
|
|
15232
17161
|
}
|
|
@@ -15243,15 +17172,19 @@ async function handleV2SessionEvent(event) {
|
|
|
15243
17172
|
await onSessionCreated(event);
|
|
15244
17173
|
break;
|
|
15245
17174
|
case "session.idle":
|
|
17175
|
+
case "session.execution.succeeded":
|
|
15246
17176
|
await onSessionIdle(event);
|
|
15247
17177
|
break;
|
|
15248
17178
|
case "session.deleted":
|
|
15249
17179
|
await onSessionDeleted(event);
|
|
15250
17180
|
break;
|
|
15251
17181
|
case "session.error":
|
|
17182
|
+
case "session.execution.failed":
|
|
17183
|
+
case "session.step.failed":
|
|
15252
17184
|
await onSessionError(event);
|
|
15253
17185
|
break;
|
|
15254
17186
|
case "session.compacted":
|
|
17187
|
+
case "session.compaction.ended":
|
|
15255
17188
|
await onSessionCompacted(event);
|
|
15256
17189
|
break;
|
|
15257
17190
|
default:
|
|
@@ -15436,6 +17369,18 @@ ${visualContext}`;
|
|
|
15436
17369
|
}
|
|
15437
17370
|
}
|
|
15438
17371
|
await applyDecisionRouterToPrompt(admission, userRequest);
|
|
17372
|
+
try {
|
|
17373
|
+
const sid = admission?.sessionID;
|
|
17374
|
+
const instrEntry = sessionCtx.instructions?.entry;
|
|
17375
|
+
if (typeof sid === "string" && typeof instrEntry?.put === "function") {
|
|
17376
|
+
await instrEntry.put({
|
|
17377
|
+
sessionID: sid,
|
|
17378
|
+
key: "pantheon.policy",
|
|
17379
|
+
text: POLICY
|
|
17380
|
+
});
|
|
17381
|
+
}
|
|
17382
|
+
} catch {
|
|
17383
|
+
}
|
|
15439
17384
|
observePromptSurface(admission, (record2) => {
|
|
15440
17385
|
promptSurfaceSink.emit({ ...record2, mode: "shadow" });
|
|
15441
17386
|
});
|
|
@@ -15461,7 +17406,7 @@ function appendV2HookLog(line) {
|
|
|
15461
17406
|
if (body === "") return false;
|
|
15462
17407
|
try {
|
|
15463
17408
|
const dir = path4.join(process.cwd(), ".pantheon", "logs");
|
|
15464
|
-
|
|
17409
|
+
mkdirSync10(dir, { recursive: true });
|
|
15465
17410
|
appendFileSync2(path4.join(dir, "hooks.log"), `${body}
|
|
15466
17411
|
`, "utf8");
|
|
15467
17412
|
return true;
|
|
@@ -16116,10 +18061,17 @@ function v2Dispose() {
|
|
|
16116
18061
|
function getUnsupportedFeatures() {
|
|
16117
18062
|
return V2_UNSUPPORTED_FEATURES;
|
|
16118
18063
|
}
|
|
18064
|
+
var UNSUPPORTED_FEATURES = V2_UNSUPPORTED_FEATURES;
|
|
18065
|
+
var disposePlugin = v2Dispose;
|
|
18066
|
+
var resetIdleEnforcerForTests = resetV2IdleEnforcerForTests;
|
|
18067
|
+
var setSecretScanRunnerForTests = setV2SecretScanRunnerForTests;
|
|
18068
|
+
var setShellRunnerForTests = setV2ShellRunnerForTests;
|
|
16119
18069
|
var plugin_default = plugin;
|
|
16120
18070
|
export {
|
|
18071
|
+
UNSUPPORTED_FEATURES,
|
|
16121
18072
|
V2_UNSUPPORTED_FEATURES,
|
|
16122
18073
|
plugin_default as default,
|
|
18074
|
+
disposePlugin,
|
|
16123
18075
|
getJ1TelemetrySinkForTests,
|
|
16124
18076
|
getJ3TelemetrySinkForTests,
|
|
16125
18077
|
getJ4TelemetrySinkForTests,
|
|
@@ -16131,7 +18083,10 @@ export {
|
|
|
16131
18083
|
getPromptSurfaceTelemetrySinkForTests,
|
|
16132
18084
|
getUnsupportedFeatures,
|
|
16133
18085
|
plugin,
|
|
18086
|
+
resetIdleEnforcerForTests,
|
|
16134
18087
|
resetV2IdleEnforcerForTests,
|
|
18088
|
+
setSecretScanRunnerForTests,
|
|
18089
|
+
setShellRunnerForTests,
|
|
16135
18090
|
setV2SecretScanRunnerForTests,
|
|
16136
18091
|
setV2ShellRunnerForTests,
|
|
16137
18092
|
v2Dispose
|