@eddyskywalker/dsh-chatgpt-subscription 0.99.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/lib/client.js +1562 -578
- package/lib/client.js.map +1 -1
- package/lib/codemode.js +1 -1
- package/lib/index.js +3391 -946
- package/lib/{preset-sync-CF9xlG1l.js → preset-sync-DWOAwSyl.js} +5 -4
- package/lib/reverse-board.js +1726 -0
- package/lib/{tool-result-pruner-Ds--y6hJ.js → tool-result-pruner-C6CDvZtG.js} +2 -1
- package/lib/tool-result-pruner.js +1 -1
- package/lib/types/client/common/ModelChecklist.d.ts +3 -3
- package/lib/types/client/common/ModelChecklist.d.ts.map +1 -1
- package/lib/types/client/common/format.d.ts +10 -0
- package/lib/types/client/common/format.d.ts.map +1 -1
- package/lib/types/client/features/progress-updates/locales.d.ts +8 -2
- package/lib/types/client/features/progress-updates/locales.d.ts.map +1 -1
- package/lib/types/client/features/progress-updates/settings-binding.d.ts +3 -1
- package/lib/types/client/features/progress-updates/settings-binding.d.ts.map +1 -1
- package/lib/types/client/features/progress-updates/settings-section.d.ts +2 -0
- package/lib/types/client/features/progress-updates/settings-section.d.ts.map +1 -1
- package/lib/types/client/hub/brand-icons.d.ts +1 -1
- package/lib/types/client/hub/brand-icons.d.ts.map +1 -1
- package/lib/types/client/hub/providers.d.ts.map +1 -1
- package/lib/types/client/index.d.ts +2 -0
- package/lib/types/client/index.d.ts.map +1 -1
- package/lib/types/client/locales-ru/claude-api.d.ts.map +1 -1
- package/lib/types/client/locales-ru/claude.d.ts.map +1 -1
- package/lib/types/client/locales-ru/hub.d.ts.map +1 -1
- package/lib/types/client/locales-ru/index.d.ts.map +1 -1
- package/lib/types/client/locales-ru/kimi-code.d.ts.map +1 -1
- package/lib/types/client/locales-ru/progress-updates.d.ts.map +1 -1
- package/lib/types/client/locales-ru/sub2api.d.ts +3 -0
- package/lib/types/client/locales-ru/sub2api.d.ts.map +1 -0
- package/lib/types/client/providers/claude/ClaudeSection.d.ts.map +1 -1
- package/lib/types/client/providers/claude/locales.d.ts +8 -2
- package/lib/types/client/providers/claude/locales.d.ts.map +1 -1
- package/lib/types/client/providers/claude/useClaudeSection.d.ts +1 -0
- package/lib/types/client/providers/claude/useClaudeSection.d.ts.map +1 -1
- package/lib/types/client/providers/claude-api/ClaudeApiSection.d.ts.map +1 -1
- package/lib/types/client/providers/claude-api/locales.d.ts +5 -1
- package/lib/types/client/providers/claude-api/locales.d.ts.map +1 -1
- package/lib/types/client/providers/claude-api/useClaudeApiSection.d.ts +1 -0
- package/lib/types/client/providers/claude-api/useClaudeApiSection.d.ts.map +1 -1
- package/lib/types/client/providers/codex-chatgpt/CodexSubscriptionSection.d.ts.map +1 -1
- package/lib/types/client/providers/codex-chatgpt/locales.d.ts +5 -3
- package/lib/types/client/providers/codex-chatgpt/locales.d.ts.map +1 -1
- package/lib/types/client/providers/codex-chatgpt/styles.d.ts.map +1 -1
- package/lib/types/client/providers/command-code/CommandCodeSection.d.ts.map +1 -1
- package/lib/types/client/providers/command-code/locales.d.ts +2 -2
- package/lib/types/client/providers/glm-coding-plan/GlmCodingPlanSection.d.ts.map +1 -1
- package/lib/types/client/providers/kimi-code/KimiCodeSection.d.ts.map +1 -1
- package/lib/types/client/providers/kimi-code/locales.d.ts +8 -2
- package/lib/types/client/providers/kimi-code/locales.d.ts.map +1 -1
- package/lib/types/client/providers/minimax-code/MinimaxCodeSection.d.ts.map +1 -1
- package/lib/types/client/providers/opencode-zen/useZenSection.d.ts +1 -0
- package/lib/types/client/providers/opencode-zen/useZenSection.d.ts.map +1 -1
- package/lib/types/client/providers/relayone/locales.d.ts +12 -12
- package/lib/types/client/providers/step-code/StepCodeSection.d.ts.map +1 -1
- package/lib/types/client/providers/sub2api/Sub2ApiSection.d.ts +7 -0
- package/lib/types/client/providers/sub2api/Sub2ApiSection.d.ts.map +1 -0
- package/lib/types/client/providers/sub2api/locales.d.ts +212 -0
- package/lib/types/client/providers/sub2api/locales.d.ts.map +1 -0
- package/lib/types/client/providers/sub2api/styles.d.ts +3 -0
- package/lib/types/client/providers/sub2api/styles.d.ts.map +1 -0
- package/lib/types/compat.d.ts +1 -1
- package/lib/types/compat.d.ts.map +1 -1
- package/lib/types/entries/reverse-board.d.ts +6 -0
- package/lib/types/entries/reverse-board.d.ts.map +1 -0
- package/lib/types/entries/tool-result-pruner.d.ts.map +1 -1
- package/lib/types/host/common/i18n/zh.d.ts +1 -1
- package/lib/types/host/common/model-request-control.d.ts +1 -1
- package/lib/types/host/common/model-request-control.d.ts.map +1 -1
- package/lib/types/host/common/prompt-cache-policy.d.ts.map +1 -1
- package/lib/types/host/common/request-diagnostics.d.ts +1 -1
- package/lib/types/host/common/request-diagnostics.d.ts.map +1 -1
- package/lib/types/host/providers/claude/routes.d.ts.map +1 -1
- package/lib/types/host/providers/claude/token-store.d.ts +3 -0
- package/lib/types/host/providers/claude/token-store.d.ts.map +1 -1
- package/lib/types/host/providers/claude-api/routes.d.ts.map +1 -1
- package/lib/types/host/providers/claude-api/token-store.d.ts +3 -0
- package/lib/types/host/providers/claude-api/token-store.d.ts.map +1 -1
- package/lib/types/host/providers/kimi-code/cache-wait.d.ts +12 -0
- package/lib/types/host/providers/kimi-code/cache-wait.d.ts.map +1 -1
- package/lib/types/host/providers/kimi-code/routes.d.ts.map +1 -1
- package/lib/types/host/providers/kimi-code/token-store.d.ts +4 -0
- package/lib/types/host/providers/kimi-code/token-store.d.ts.map +1 -1
- package/lib/types/host/providers/opendesign/adapter.d.ts.map +1 -1
- package/lib/types/host/providers/opendesign/mapper.d.ts +1 -1
- package/lib/types/host/providers/opendesign/mapper.d.ts.map +1 -1
- package/lib/types/host/providers/relayone/adapter.d.ts.map +1 -1
- package/lib/types/host/providers/relayone/mapper-openai.d.ts.map +1 -1
- package/lib/types/host/providers/relayone/types.d.ts +1 -1
- package/lib/types/host/providers/relayone/types.d.ts.map +1 -1
- package/lib/types/host/providers/sub2api/account-pool.d.ts +34 -0
- package/lib/types/host/providers/sub2api/account-pool.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/adapter.d.ts +59 -0
- package/lib/types/host/providers/sub2api/adapter.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/cache-stats.d.ts +19 -0
- package/lib/types/host/providers/sub2api/cache-stats.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/client.d.ts +6 -0
- package/lib/types/host/providers/sub2api/client.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/mapper-gemini.d.ts +10 -0
- package/lib/types/host/providers/sub2api/mapper-gemini.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/mapper-messages.d.ts +14 -0
- package/lib/types/host/providers/sub2api/mapper-messages.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/mapper-responses.d.ts +7 -0
- package/lib/types/host/providers/sub2api/mapper-responses.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/mapper.d.ts +34 -0
- package/lib/types/host/providers/sub2api/mapper.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/model-catalog.d.ts +72 -0
- package/lib/types/host/providers/sub2api/model-catalog.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/remote-compaction.d.ts +32 -0
- package/lib/types/host/providers/sub2api/remote-compaction.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/routes.d.ts +16 -0
- package/lib/types/host/providers/sub2api/routes.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/token-store.d.ts +43 -0
- package/lib/types/host/providers/sub2api/token-store.d.ts.map +1 -0
- package/lib/types/host/providers/sub2api/types.d.ts +14 -0
- package/lib/types/host/providers/sub2api/types.d.ts.map +1 -0
- package/lib/types/host/runtime/compact-after-turn/index.d.ts +15 -0
- package/lib/types/host/runtime/compact-after-turn/index.d.ts.map +1 -1
- package/lib/types/host/runtime/compaction-gate.d.ts +67 -0
- package/lib/types/host/runtime/compaction-gate.d.ts.map +1 -0
- package/lib/types/host/runtime/deepseek-v41-flash/progress-governor.d.ts +0 -1
- package/lib/types/host/runtime/deepseek-v41-flash/progress-governor.d.ts.map +1 -1
- package/lib/types/host/runtime/deepseek-v41-flash/reasoning-seed.d.ts +2 -1
- package/lib/types/host/runtime/deepseek-v41-flash/reasoning-seed.d.ts.map +1 -1
- package/lib/types/host/runtime/deepseek-v41-flash/state-anchor.d.ts +0 -1
- package/lib/types/host/runtime/deepseek-v41-flash/state-anchor.d.ts.map +1 -1
- package/lib/types/host/runtime/guards/compaction-policy-guard.d.ts +1 -0
- package/lib/types/host/runtime/guards/compaction-policy-guard.d.ts.map +1 -1
- package/lib/types/host/runtime/guards/ptc-sdk-cache-guard.d.ts.map +1 -1
- package/lib/types/host/runtime/guards/timeline-cache-guard.d.ts.map +1 -1
- package/lib/types/host/runtime/open-models/state-anchor.d.ts +0 -1
- package/lib/types/host/runtime/open-models/state-anchor.d.ts.map +1 -1
- package/lib/types/host/runtime/presets/agent-preset.d.ts +10 -25
- package/lib/types/host/runtime/presets/agent-preset.d.ts.map +1 -1
- package/lib/types/host/runtime/presets/preset-sync.d.ts +2 -0
- package/lib/types/host/runtime/presets/preset-sync.d.ts.map +1 -1
- package/lib/types/host/runtime/presets/reverse-persona.d.ts +3 -0
- package/lib/types/host/runtime/presets/reverse-persona.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/frontier.d.ts +10 -0
- package/lib/types/host/runtime/reverse/frontier.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/ids.d.ts +8 -0
- package/lib/types/host/runtime/reverse/ids.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/index.d.ts +20 -0
- package/lib/types/host/runtime/reverse/index.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/indexer.d.ts +9 -0
- package/lib/types/host/runtime/reverse/indexer.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/policy.d.ts +5 -0
- package/lib/types/host/runtime/reverse/policy.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/route-policy.d.ts +10 -0
- package/lib/types/host/runtime/reverse/route-policy.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/store.d.ts +91 -0
- package/lib/types/host/runtime/reverse/store.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/templates.d.ts +10 -0
- package/lib/types/host/runtime/reverse/templates.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/tool.d.ts +25 -0
- package/lib/types/host/runtime/reverse/tool.d.ts.map +1 -0
- package/lib/types/host/runtime/reverse/types.d.ts +182 -0
- package/lib/types/host/runtime/reverse/types.d.ts.map +1 -0
- package/lib/types/index.d.ts +13 -0
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/shared/claude-api-contracts.d.ts +2 -0
- package/lib/types/shared/claude-api-contracts.d.ts.map +1 -1
- package/lib/types/shared/claude-contracts.d.ts +3 -0
- package/lib/types/shared/claude-contracts.d.ts.map +1 -1
- package/lib/types/shared/contracts.d.ts +1 -1
- package/lib/types/shared/contracts.d.ts.map +1 -1
- package/lib/types/shared/kimi-code-contracts.d.ts +3 -0
- package/lib/types/shared/kimi-code-contracts.d.ts.map +1 -1
- package/lib/types/shared/relayone-contracts.d.ts +2 -2
- package/lib/types/shared/relayone-contracts.d.ts.map +1 -1
- package/lib/types/shared/sub2api-contracts.d.ts +103 -0
- package/lib/types/shared/sub2api-contracts.d.ts.map +1 -0
- package/package.json +6 -2
- package/presets/reverse/README.md +30 -0
- package/presets/reverse/agent.cordis.yml +228 -0
- package/presets/reverse/preset.yml +3 -0
- package/presets/team/README.md +0 -72
- package/presets/team/agent.cordis.yml +0 -414
- package/presets/team/preset.yml +0 -3
|
@@ -0,0 +1,1726 @@
|
|
|
1
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
2
|
+
import { appendFile, mkdir, open, readFile, stat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { createReadStream } from "node:fs";
|
|
7
|
+
//#region src/host/runtime/reverse/types.ts
|
|
8
|
+
const REVERSE_ERROR_PREFIX = "REVERSE_DENIED";
|
|
9
|
+
var ReverseError = class extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code, message) {
|
|
12
|
+
super(`${REVERSE_ERROR_PREFIX}:${code}: ${message}`);
|
|
13
|
+
this.name = "ReverseError";
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function emptyReverseState(runId) {
|
|
18
|
+
return {
|
|
19
|
+
runId,
|
|
20
|
+
seq: 0,
|
|
21
|
+
lastHash: "",
|
|
22
|
+
lastFactSeq: 0,
|
|
23
|
+
nodes: {},
|
|
24
|
+
edges: {},
|
|
25
|
+
claims: {},
|
|
26
|
+
leases: {},
|
|
27
|
+
members: {},
|
|
28
|
+
handoffs: {},
|
|
29
|
+
evidence: {},
|
|
30
|
+
routes: {},
|
|
31
|
+
watchdog: {
|
|
32
|
+
lastProgressSeq: 0,
|
|
33
|
+
rotationsWithoutProgress: 0,
|
|
34
|
+
recoveryAttempts: 0,
|
|
35
|
+
needsHuman: false
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/host/runtime/reverse/ids.ts
|
|
41
|
+
/** Deterministic graph identifiers. @module */
|
|
42
|
+
function sha256Hex(value) {
|
|
43
|
+
return createHash("sha256").update(value).digest("hex");
|
|
44
|
+
}
|
|
45
|
+
function shortHash(value) {
|
|
46
|
+
return sha256Hex(value).slice(0, 16);
|
|
47
|
+
}
|
|
48
|
+
function cellId(value) {
|
|
49
|
+
const slug = value.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
50
|
+
if (slug.length === 0) throw new ReverseError("INVALID_INPUT", "cell id must contain a letter or number");
|
|
51
|
+
return `cell:${slug}`;
|
|
52
|
+
}
|
|
53
|
+
function artifactIdFromSha(sha) {
|
|
54
|
+
if (!/^[a-f0-9]{64}$/i.test(sha)) throw new ReverseError("INVALID_INPUT", "artifact SHA-256 must contain 64 hex characters");
|
|
55
|
+
return `artifact:sha256:${sha.toLowerCase()}`;
|
|
56
|
+
}
|
|
57
|
+
function functionId(cell, address) {
|
|
58
|
+
const normalized = address.trim().toLowerCase();
|
|
59
|
+
if (normalized.length === 0) throw new ReverseError("INVALID_INPUT", "function needs attrs.address");
|
|
60
|
+
return `fn:${cell}:${normalized}`;
|
|
61
|
+
}
|
|
62
|
+
function findingId(cell, key) {
|
|
63
|
+
if (key.trim().length === 0) throw new ReverseError("INVALID_INPUT", "finding needs a stable key");
|
|
64
|
+
return `finding:${cell}:${shortHash(key)}`;
|
|
65
|
+
}
|
|
66
|
+
function actionId(type, targetId, params) {
|
|
67
|
+
return `action:${shortHash(JSON.stringify([
|
|
68
|
+
type,
|
|
69
|
+
targetId,
|
|
70
|
+
params
|
|
71
|
+
]))}`;
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/host/runtime/reverse/route-policy.ts
|
|
75
|
+
function numberAttr(node, key, fallback) {
|
|
76
|
+
const value = node.attrs[key];
|
|
77
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
78
|
+
}
|
|
79
|
+
function routeIsland(node) {
|
|
80
|
+
if (typeof node.attrs.island === "string" && node.attrs.island.length > 0) return node.attrs.island;
|
|
81
|
+
const text = `${node.key} ${node.label}`.toLowerCase();
|
|
82
|
+
for (const [island, pattern] of [
|
|
83
|
+
["crypto", /crypto|cipher|encrypt|decrypt|aes|rsa|key/],
|
|
84
|
+
["protocol", /protocol|packet|socket|http|tls/],
|
|
85
|
+
["anti-debug", /debug|trace|ptrace|frida/],
|
|
86
|
+
["packer", /pack|unpack|oep|section/],
|
|
87
|
+
["JNI", /jni|java_|nativemethod/],
|
|
88
|
+
["UI", /activity|view|layout|ui/],
|
|
89
|
+
["dataflow", /dataflow|xref|taint/]
|
|
90
|
+
]) if (pattern.test(text)) return island;
|
|
91
|
+
return node.kind === "Function" || node.kind === "Segment" ? "native" : "general";
|
|
92
|
+
}
|
|
93
|
+
function scoreRoute(node, stat, totalAttempts) {
|
|
94
|
+
const attempts = stat?.attempts ?? 0;
|
|
95
|
+
const successes = stat?.successes ?? 0;
|
|
96
|
+
const exploration = Math.sqrt(2 * Math.log(totalAttempts + 2) / (attempts + 1));
|
|
97
|
+
const value = numberAttr(node, "goalProximity", .5) + numberAttr(node, "evidenceValue", .5) + numberAttr(node, "confidence", .25) + numberAttr(node, "novelty", attempts === 0 ? .5 : 0) + successes * .1 - numberAttr(node, "cost", .1) - numberAttr(node, "risk", 0) - numberAttr(node, "duplication", 0);
|
|
98
|
+
return {
|
|
99
|
+
island: routeIsland(node),
|
|
100
|
+
score: value + exploration,
|
|
101
|
+
exploration
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/host/runtime/reverse/frontier.ts
|
|
106
|
+
/** Pure graph-to-frontier projection with deterministic route scoring. @module */
|
|
107
|
+
function draftFor(node) {
|
|
108
|
+
const queued = node.status === "queued" || node.status === "proposed";
|
|
109
|
+
if (node.kind === "Artifact" && queued) return {
|
|
110
|
+
type: "ingest",
|
|
111
|
+
posture: "toolwright",
|
|
112
|
+
priority: 90,
|
|
113
|
+
why: ["artifact is ready to ingest"],
|
|
114
|
+
expectedEvidence: "artifact hash, format and intake notes"
|
|
115
|
+
};
|
|
116
|
+
if (node.kind === "Artifact" && node.status === "observed") return {
|
|
117
|
+
type: "enumerate",
|
|
118
|
+
posture: "toolwright",
|
|
119
|
+
priority: 80,
|
|
120
|
+
why: ["artifact ingested; enumerate entries and symbols"],
|
|
121
|
+
expectedEvidence: "entry/symbol inventory artifact"
|
|
122
|
+
};
|
|
123
|
+
if (node.kind === "Function" && queued) return {
|
|
124
|
+
type: "decompile",
|
|
125
|
+
posture: "deepdive",
|
|
126
|
+
priority: 75,
|
|
127
|
+
why: ["function is queued"],
|
|
128
|
+
expectedEvidence: "decompiler output or disassembly with offsets"
|
|
129
|
+
};
|
|
130
|
+
if (node.kind === "Hypothesis" && queued) return {
|
|
131
|
+
type: "experiment",
|
|
132
|
+
posture: "adversary",
|
|
133
|
+
priority: 70,
|
|
134
|
+
why: ["hypothesis is queued"],
|
|
135
|
+
expectedEvidence: "experiment result with command and hash"
|
|
136
|
+
};
|
|
137
|
+
if (node.kind === "Finding" && (node.status === "observed" || node.status === "reproduced")) return {
|
|
138
|
+
type: "verify",
|
|
139
|
+
posture: "weaver",
|
|
140
|
+
priority: 85,
|
|
141
|
+
why: ["finding needs independent reproduction"],
|
|
142
|
+
expectedEvidence: "independent reproduction artifact"
|
|
143
|
+
};
|
|
144
|
+
if ((node.kind === "Step" || node.kind === "Fact") && queued) {
|
|
145
|
+
const requested = typeof node.attrs.actionType === "string" ? node.attrs.actionType : "trace";
|
|
146
|
+
return {
|
|
147
|
+
type: requested,
|
|
148
|
+
posture: typeof node.attrs.posture === "string" ? node.attrs.posture : "shortest",
|
|
149
|
+
priority: 65,
|
|
150
|
+
why: ["step/fact is queued"],
|
|
151
|
+
expectedEvidence: "command, input/output hashes and reproduction notes",
|
|
152
|
+
params: { requestedAction: requested }
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function project(node, state) {
|
|
157
|
+
const draft = draftFor(node);
|
|
158
|
+
if (draft === void 0) return [];
|
|
159
|
+
const cell = String(node.attrs.cell ?? "root");
|
|
160
|
+
const params = {
|
|
161
|
+
nodeId: node.id,
|
|
162
|
+
...draft.params ?? {}
|
|
163
|
+
};
|
|
164
|
+
const id = actionId(draft.type, node.id, params);
|
|
165
|
+
const totalAttempts = Object.values(state.routes).reduce((sum, stat) => sum + stat.attempts, 0);
|
|
166
|
+
const route = scoreRoute(node, state.routes[id], totalAttempts);
|
|
167
|
+
return [{
|
|
168
|
+
actionId: id,
|
|
169
|
+
actionType: draft.type,
|
|
170
|
+
cell,
|
|
171
|
+
targetId: node.id,
|
|
172
|
+
posture: draft.posture,
|
|
173
|
+
island: route.island,
|
|
174
|
+
priority: draft.priority,
|
|
175
|
+
score: route.score,
|
|
176
|
+
exploration: route.exploration,
|
|
177
|
+
why: draft.why,
|
|
178
|
+
expectedEvidence: draft.expectedEvidence,
|
|
179
|
+
params
|
|
180
|
+
}];
|
|
181
|
+
}
|
|
182
|
+
function computeFrontier(state, options = {}) {
|
|
183
|
+
if (state.goal === void 0) return [];
|
|
184
|
+
let actions = [];
|
|
185
|
+
for (const node of Object.values(state.nodes)) {
|
|
186
|
+
if (options.cell !== void 0 && String(node.attrs.cell ?? "root") !== options.cell) continue;
|
|
187
|
+
actions.push(...project(node, state));
|
|
188
|
+
}
|
|
189
|
+
if (actions.length === 0) for (const node of Object.values(state.nodes)) {
|
|
190
|
+
const cell = String(node.attrs.cell ?? "root");
|
|
191
|
+
if (node.kind !== "Cell" || node.status !== "open") continue;
|
|
192
|
+
if (options.cell !== void 0 && cell !== options.cell) continue;
|
|
193
|
+
const params = { cell };
|
|
194
|
+
const route = scoreRoute(node, void 0, 0);
|
|
195
|
+
actions.push({
|
|
196
|
+
actionId: actionId("plan", node.id, params),
|
|
197
|
+
actionType: "plan",
|
|
198
|
+
cell,
|
|
199
|
+
targetId: node.id,
|
|
200
|
+
posture: "weaver",
|
|
201
|
+
island: route.island,
|
|
202
|
+
priority: 50,
|
|
203
|
+
score: route.score,
|
|
204
|
+
exploration: route.exploration,
|
|
205
|
+
why: ["no executable action; choose the next exploration"],
|
|
206
|
+
expectedEvidence: "a plan or intake note",
|
|
207
|
+
params
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
const eliteCap = Math.max(1, Math.min(20, Math.trunc(options.eliteCap ?? 2)));
|
|
211
|
+
const byIsland = /* @__PURE__ */ new Map();
|
|
212
|
+
for (const action of actions) {
|
|
213
|
+
const list = byIsland.get(action.island) ?? [];
|
|
214
|
+
list.push(action);
|
|
215
|
+
byIsland.set(action.island, list);
|
|
216
|
+
}
|
|
217
|
+
actions = [...byIsland.values()].flatMap((list) => list.sort((left, right) => right.score - left.score || right.priority - left.priority || left.actionId.localeCompare(right.actionId)).slice(0, eliteCap));
|
|
218
|
+
if (options.posture !== void 0) actions = actions.filter((action) => action.posture === options.posture);
|
|
219
|
+
if (options.island !== void 0) actions = actions.filter((action) => action.island === options.island);
|
|
220
|
+
actions.sort((left, right) => right.score - left.score || right.priority - left.priority || left.actionId.localeCompare(right.actionId));
|
|
221
|
+
const limit = Math.max(1, Math.min(1e3, Math.trunc(options.limit ?? 20)));
|
|
222
|
+
return actions.slice(0, limit);
|
|
223
|
+
}
|
|
224
|
+
//#endregion
|
|
225
|
+
//#region src/host/runtime/reverse/indexer.ts
|
|
226
|
+
/** Deterministic, streaming artifact indexing. @module */
|
|
227
|
+
async function hashFile(path) {
|
|
228
|
+
const hash = createHash("sha256");
|
|
229
|
+
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
|
230
|
+
return hash.digest("hex");
|
|
231
|
+
}
|
|
232
|
+
async function magic(path) {
|
|
233
|
+
const handle = await open(path, "r");
|
|
234
|
+
try {
|
|
235
|
+
const buffer = Buffer.alloc(16);
|
|
236
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
237
|
+
return buffer.subarray(0, bytesRead).toString("hex");
|
|
238
|
+
} finally {
|
|
239
|
+
await handle.close();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
async function indexArtifact(input, cell) {
|
|
243
|
+
const path = typeof input.attrs?.path === "string" ? input.attrs.path : void 0;
|
|
244
|
+
const key = input.key ?? path ?? input.id;
|
|
245
|
+
if (key === void 0 || key.trim().length === 0) throw new ReverseError("INVALID_INPUT", "artifact needs key, id or attrs.path");
|
|
246
|
+
if (path === void 0) return {
|
|
247
|
+
id: input.id ?? `artifact:${shortHash(key)}`,
|
|
248
|
+
kind: "Artifact",
|
|
249
|
+
key,
|
|
250
|
+
label: input.label ?? key,
|
|
251
|
+
status: "queued",
|
|
252
|
+
attrs: {
|
|
253
|
+
...input.attrs ?? {},
|
|
254
|
+
cell
|
|
255
|
+
},
|
|
256
|
+
evidenceIds: [],
|
|
257
|
+
revision: 1
|
|
258
|
+
};
|
|
259
|
+
const absolute = resolve(path);
|
|
260
|
+
const info = await stat(absolute);
|
|
261
|
+
if (!info.isFile()) throw new ReverseError("INVALID_INPUT", `artifact is not a file: ${absolute}`);
|
|
262
|
+
const [sha256, header] = await Promise.all([hashFile(absolute), magic(absolute)]);
|
|
263
|
+
return {
|
|
264
|
+
id: artifactIdFromSha(sha256),
|
|
265
|
+
kind: "Artifact",
|
|
266
|
+
key: absolute,
|
|
267
|
+
label: input.label ?? basename(absolute),
|
|
268
|
+
status: "queued",
|
|
269
|
+
attrs: {
|
|
270
|
+
...input.attrs ?? {},
|
|
271
|
+
cell,
|
|
272
|
+
path: absolute,
|
|
273
|
+
sha256,
|
|
274
|
+
sizeBytes: info.size,
|
|
275
|
+
extension: extname(absolute).toLowerCase(),
|
|
276
|
+
magic: header
|
|
277
|
+
},
|
|
278
|
+
evidenceIds: [],
|
|
279
|
+
revision: 1
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
//#endregion
|
|
283
|
+
//#region src/host/runtime/reverse/policy.ts
|
|
284
|
+
/** Fail-closed scope checks for reverse actions. @module */
|
|
285
|
+
function contained(root, candidate) {
|
|
286
|
+
const rel = relative(resolve(root), resolve(candidate));
|
|
287
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
288
|
+
}
|
|
289
|
+
function assertPathScope(scope, candidate) {
|
|
290
|
+
if (scope === void 0) throw new ReverseError("SCOPE_NOT_INITIALIZED", "initialize Goal and scope before touching artifacts");
|
|
291
|
+
const target = resolve(candidate);
|
|
292
|
+
if (scope.deny.some((root) => contained(root, target))) throw new ReverseError("SCOPE_PATH_DENIED", `path is denied: ${target}`);
|
|
293
|
+
if (scope.roots.length === 0 || !scope.roots.some((root) => contained(root, target))) throw new ReverseError("SCOPE_PATH_DENIED", `path is outside the authorized roots: ${target}; add its root through init`);
|
|
294
|
+
}
|
|
295
|
+
function resourceMatches(rule, resource) {
|
|
296
|
+
return rule.endsWith("*") ? resource.startsWith(rule.slice(0, -1)) : resource === rule;
|
|
297
|
+
}
|
|
298
|
+
function assertResourceScope(scope, resource) {
|
|
299
|
+
if (scope === void 0) throw new ReverseError("SCOPE_NOT_INITIALIZED", "initialize Goal and scope before leasing resources");
|
|
300
|
+
if (resource.trim().length === 0) throw new ReverseError("INVALID_INPUT", "resource must not be empty");
|
|
301
|
+
if (!scope.resources.some((rule) => resourceMatches(rule, resource))) throw new ReverseError("SCOPE_RESOURCE_DENIED", `resource is outside scope: ${resource}; add an exact key or prefix* through init`);
|
|
302
|
+
}
|
|
303
|
+
function assertSameCell(expected, actual) {
|
|
304
|
+
if (expected !== actual) throw new ReverseError("CELL_MISMATCH", `action belongs to cell ${expected}, not ${actual}`);
|
|
305
|
+
}
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/host/runtime/reverse/templates.ts
|
|
308
|
+
function goalFromTemplate(input) {
|
|
309
|
+
const engagement = input.engagement ?? "reverse";
|
|
310
|
+
if (engagement === "jeopardy") {
|
|
311
|
+
const flagFormat = input.flagFormat?.trim() || "flag{...}";
|
|
312
|
+
return {
|
|
313
|
+
text: input.goal,
|
|
314
|
+
acceptance: input.acceptance?.trim() || `Submit a flag matching ${flagFormat}; reproduce the derivation from the original artifact and independently verify it.`,
|
|
315
|
+
engagement,
|
|
316
|
+
flagFormat
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
text: input.goal,
|
|
321
|
+
acceptance: input.acceptance ?? "",
|
|
322
|
+
engagement
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/host/runtime/reverse/store.ts
|
|
327
|
+
/** Append-only reverse graph, claims, evidence and recovery protocols. @module */
|
|
328
|
+
function isRecord$1(value) {
|
|
329
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
330
|
+
}
|
|
331
|
+
function dshHome() {
|
|
332
|
+
return process.env.DSH_HOME?.trim() || join(homedir(), ".dsh");
|
|
333
|
+
}
|
|
334
|
+
function safeSegment(value) {
|
|
335
|
+
const text = value.trim();
|
|
336
|
+
if (text.length === 0) throw new ReverseError("NO_SESSION", "id must not be empty");
|
|
337
|
+
return encodeURIComponent(text);
|
|
338
|
+
}
|
|
339
|
+
function eventHash(event) {
|
|
340
|
+
return `sha256:${sha256Hex(JSON.stringify(event))}`;
|
|
341
|
+
}
|
|
342
|
+
function claimFromEvent(event) {
|
|
343
|
+
const claim = event.payload.claim;
|
|
344
|
+
return isRecord$1(claim) ? claim : void 0;
|
|
345
|
+
}
|
|
346
|
+
async function acquireRunLock(root) {
|
|
347
|
+
const path = join(root, "run.lock");
|
|
348
|
+
const body = JSON.stringify({
|
|
349
|
+
pid: process.pid,
|
|
350
|
+
time: (/* @__PURE__ */ new Date()).toISOString()
|
|
351
|
+
}) + "\n";
|
|
352
|
+
try {
|
|
353
|
+
await writeFile(path, body, {
|
|
354
|
+
encoding: "utf8",
|
|
355
|
+
flag: "wx"
|
|
356
|
+
});
|
|
357
|
+
return;
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if (error.code !== "EEXIST") throw error;
|
|
360
|
+
}
|
|
361
|
+
let pid = 0;
|
|
362
|
+
try {
|
|
363
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
364
|
+
pid = typeof parsed.pid === "number" ? parsed.pid : 0;
|
|
365
|
+
} catch {
|
|
366
|
+
throw new ReverseError("RUN_LOCKED", `cannot validate ${path}; inspect it before retrying`);
|
|
367
|
+
}
|
|
368
|
+
if (pid === process.pid) return;
|
|
369
|
+
let alive = pid > 0;
|
|
370
|
+
if (alive) try {
|
|
371
|
+
process.kill(pid, 0);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
alive = error.code === "EPERM";
|
|
374
|
+
}
|
|
375
|
+
if (alive) throw new ReverseError("RUN_LOCKED", `run is owned by live pid ${pid}`);
|
|
376
|
+
await unlink(path);
|
|
377
|
+
await writeFile(path, body, {
|
|
378
|
+
encoding: "utf8",
|
|
379
|
+
flag: "wx"
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
/** Fold one event into state; this pure function is the rebuild contract. */
|
|
383
|
+
function foldReverseEvent(state, event) {
|
|
384
|
+
let next = {
|
|
385
|
+
...state,
|
|
386
|
+
seq: event.seq,
|
|
387
|
+
lastHash: event.hash
|
|
388
|
+
};
|
|
389
|
+
const payload = event.payload;
|
|
390
|
+
if (event.kind === "node" || event.kind === "edge" || event.kind === "evidence") next = {
|
|
391
|
+
...next,
|
|
392
|
+
lastFactSeq: event.seq
|
|
393
|
+
};
|
|
394
|
+
if (event.kind === "goal" && isRecord$1(payload.goal)) next = {
|
|
395
|
+
...next,
|
|
396
|
+
goal: payload.goal
|
|
397
|
+
};
|
|
398
|
+
else if (event.kind === "scope" && isRecord$1(payload.scope)) next = {
|
|
399
|
+
...next,
|
|
400
|
+
scope: payload.scope
|
|
401
|
+
};
|
|
402
|
+
else if (event.kind === "budget" && isRecord$1(payload.budget)) next = {
|
|
403
|
+
...next,
|
|
404
|
+
budget: payload.budget
|
|
405
|
+
};
|
|
406
|
+
else if (event.kind === "node" && isRecord$1(payload.node) && typeof payload.node.id === "string") {
|
|
407
|
+
const node = payload.node;
|
|
408
|
+
next = {
|
|
409
|
+
...next,
|
|
410
|
+
nodes: {
|
|
411
|
+
...next.nodes,
|
|
412
|
+
[node.id]: node
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
if (node.kind === "Finding" && node.status === "verified") {
|
|
416
|
+
const routeId = actionId("verify", node.id, { nodeId: node.id });
|
|
417
|
+
const old = next.routes[routeId] ?? {
|
|
418
|
+
attempts: 0,
|
|
419
|
+
successes: 0
|
|
420
|
+
};
|
|
421
|
+
next = {
|
|
422
|
+
...next,
|
|
423
|
+
routes: {
|
|
424
|
+
...next.routes,
|
|
425
|
+
[routeId]: {
|
|
426
|
+
...old,
|
|
427
|
+
successes: old.successes + 1
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
} else if (event.kind === "edge" && isRecord$1(payload.edge) && typeof payload.edge.id === "string") {
|
|
433
|
+
const edge = payload.edge;
|
|
434
|
+
next = {
|
|
435
|
+
...next,
|
|
436
|
+
edges: {
|
|
437
|
+
...next.edges,
|
|
438
|
+
[edge.id]: edge
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
} else if ((event.kind === "claim" || event.kind === "release") && isRecord$1(payload.claim) && typeof payload.claim.actionId === "string") {
|
|
442
|
+
const claim = payload.claim;
|
|
443
|
+
next = {
|
|
444
|
+
...next,
|
|
445
|
+
claims: {
|
|
446
|
+
...next.claims,
|
|
447
|
+
[claim.actionId]: claim
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
if (event.kind === "claim" && payload.operation === "acquire") {
|
|
451
|
+
const old = next.routes[claim.actionId] ?? {
|
|
452
|
+
attempts: 0,
|
|
453
|
+
successes: 0
|
|
454
|
+
};
|
|
455
|
+
next = {
|
|
456
|
+
...next,
|
|
457
|
+
routes: {
|
|
458
|
+
...next.routes,
|
|
459
|
+
[claim.actionId]: {
|
|
460
|
+
...old,
|
|
461
|
+
attempts: old.attempts + 1
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
} else if (event.kind === "lease" && isRecord$1(payload.lease) && typeof payload.lease.resource === "string") {
|
|
467
|
+
const lease = payload.lease;
|
|
468
|
+
next = {
|
|
469
|
+
...next,
|
|
470
|
+
leases: {
|
|
471
|
+
...next.leases,
|
|
472
|
+
[lease.resource]: lease
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
} else if (event.kind === "member" && isRecord$1(payload.member) && typeof payload.member.actor === "string") {
|
|
476
|
+
const member = payload.member;
|
|
477
|
+
next = {
|
|
478
|
+
...next,
|
|
479
|
+
members: {
|
|
480
|
+
...next.members,
|
|
481
|
+
[member.actor]: member
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
} else if (event.kind === "handoff" && isRecord$1(payload.handoff) && typeof payload.handoff.id === "string") {
|
|
485
|
+
const handoff = payload.handoff;
|
|
486
|
+
next = {
|
|
487
|
+
...next,
|
|
488
|
+
handoffs: {
|
|
489
|
+
...next.handoffs,
|
|
490
|
+
[handoff.id]: handoff
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
} else if (event.kind === "watchdog" && isRecord$1(payload.watchdog)) next = {
|
|
494
|
+
...next,
|
|
495
|
+
watchdog: payload.watchdog
|
|
496
|
+
};
|
|
497
|
+
else if (event.kind === "evidence" && isRecord$1(payload.evidence) && typeof payload.evidence.id === "string") {
|
|
498
|
+
const item = payload.evidence;
|
|
499
|
+
const finding = next.nodes[item.findingId];
|
|
500
|
+
const nodes = finding === void 0 ? next.nodes : {
|
|
501
|
+
...next.nodes,
|
|
502
|
+
[item.findingId]: {
|
|
503
|
+
...finding,
|
|
504
|
+
evidenceIds: finding.evidenceIds.includes(item.id) ? finding.evidenceIds : [...finding.evidenceIds, item.id],
|
|
505
|
+
status: finding.status === "proposed" || finding.status === "queued" ? "observed" : finding.status
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
next = {
|
|
509
|
+
...next,
|
|
510
|
+
nodes,
|
|
511
|
+
evidence: {
|
|
512
|
+
...next.evidence,
|
|
513
|
+
[item.id]: item
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
} else if (event.kind === "finish" && isRecord$1(payload.finish)) next = {
|
|
517
|
+
...next,
|
|
518
|
+
finish: payload.finish
|
|
519
|
+
};
|
|
520
|
+
else if (event.kind === "merge") {
|
|
521
|
+
const from = String(payload.from ?? "");
|
|
522
|
+
const to = String(payload.to ?? "");
|
|
523
|
+
if (from && to) {
|
|
524
|
+
const nodes = Object.fromEntries(Object.entries(next.nodes).map(([id, node]) => [id, String(node.attrs.cell ?? "root") === from ? {
|
|
525
|
+
...node,
|
|
526
|
+
attrs: {
|
|
527
|
+
...node.attrs,
|
|
528
|
+
cell: to
|
|
529
|
+
},
|
|
530
|
+
revision: node.revision + 1
|
|
531
|
+
} : node]));
|
|
532
|
+
next = {
|
|
533
|
+
...next,
|
|
534
|
+
nodes
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (next.finish?.status === "proposed" && event.seq > next.finish.proposedSeq && (event.kind === "node" || event.kind === "edge" || event.kind === "evidence")) next = {
|
|
539
|
+
...next,
|
|
540
|
+
finish: {
|
|
541
|
+
...next.finish,
|
|
542
|
+
status: "invalidated"
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
return next;
|
|
546
|
+
}
|
|
547
|
+
var ReverseStore = class ReverseStore {
|
|
548
|
+
runId;
|
|
549
|
+
root;
|
|
550
|
+
eventsPath;
|
|
551
|
+
stateValue;
|
|
552
|
+
eventsValue;
|
|
553
|
+
chain = Promise.resolve();
|
|
554
|
+
constructor(runId, root, state, events) {
|
|
555
|
+
this.runId = runId;
|
|
556
|
+
this.root = root;
|
|
557
|
+
this.eventsPath = join(root, "graph.jsonl");
|
|
558
|
+
this.stateValue = state;
|
|
559
|
+
this.eventsValue = events;
|
|
560
|
+
}
|
|
561
|
+
static async open(runId, baseDir) {
|
|
562
|
+
const root = join(baseDir ?? join(dshHome(), "reverse"), safeSegment(runId));
|
|
563
|
+
await Promise.all([
|
|
564
|
+
"cells",
|
|
565
|
+
"evidence",
|
|
566
|
+
"briefs"
|
|
567
|
+
].map((dir) => mkdir(join(root, dir), { recursive: true })));
|
|
568
|
+
await acquireRunLock(root);
|
|
569
|
+
let raw = "";
|
|
570
|
+
try {
|
|
571
|
+
raw = await readFile(join(root, "graph.jsonl"), "utf8");
|
|
572
|
+
} catch (error) {
|
|
573
|
+
if (error.code !== "ENOENT") throw error;
|
|
574
|
+
}
|
|
575
|
+
let state = emptyReverseState(runId);
|
|
576
|
+
const events = [];
|
|
577
|
+
for (const line of raw.split("\n")) {
|
|
578
|
+
if (line.trim() === "") continue;
|
|
579
|
+
let event;
|
|
580
|
+
try {
|
|
581
|
+
event = JSON.parse(line);
|
|
582
|
+
} catch {
|
|
583
|
+
throw new ReverseError("CORRUPT_GRAPH", "graph.jsonl contains a non-JSON line");
|
|
584
|
+
}
|
|
585
|
+
if (event.v !== 1 || typeof event.seq !== "number" || event.seq !== events.length + 1) throw new ReverseError("CORRUPT_GRAPH", `invalid event sequence at line ${events.length + 1}`);
|
|
586
|
+
const { hash: _hash, ...unsigned } = event;
|
|
587
|
+
if (event.hash !== eventHash(unsigned) || event.prev !== state.lastHash) throw new ReverseError("CORRUPT_GRAPH", `hash-chain mismatch at event ${event.seq}`);
|
|
588
|
+
state = foldReverseEvent(state, event);
|
|
589
|
+
events.push(event);
|
|
590
|
+
}
|
|
591
|
+
const evidenceRoot = resolve(root, "evidence") + sep;
|
|
592
|
+
for (const item of Object.values(state.evidence)) {
|
|
593
|
+
if (item.contentPath === void 0) continue;
|
|
594
|
+
const path = resolve(root, item.contentPath);
|
|
595
|
+
if (!path.startsWith(evidenceRoot)) throw new ReverseError("CORRUPT_EVIDENCE", `evidence path escapes its directory: ${item.id}`);
|
|
596
|
+
try {
|
|
597
|
+
const content = await readFile(path, "utf8");
|
|
598
|
+
if (Buffer.byteLength(content, "utf8") !== item.sizeBytes || `sha256:${sha256Hex(content)}` !== item.outputHash) throw new ReverseError("CORRUPT_EVIDENCE", `evidence hash mismatch: ${item.id}`);
|
|
599
|
+
} catch (error) {
|
|
600
|
+
if (error instanceof ReverseError) throw error;
|
|
601
|
+
throw new ReverseError("CORRUPT_EVIDENCE", `evidence content is unreadable: ${item.id}`);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return new ReverseStore(runId, root, state, events);
|
|
605
|
+
}
|
|
606
|
+
get state() {
|
|
607
|
+
return this.stateValue;
|
|
608
|
+
}
|
|
609
|
+
get events() {
|
|
610
|
+
return this.eventsValue;
|
|
611
|
+
}
|
|
612
|
+
async withLock(run) {
|
|
613
|
+
const previous = this.chain;
|
|
614
|
+
let release;
|
|
615
|
+
this.chain = new Promise((resolvePromise) => {
|
|
616
|
+
release = resolvePromise;
|
|
617
|
+
});
|
|
618
|
+
await previous.catch(() => void 0);
|
|
619
|
+
try {
|
|
620
|
+
return await run();
|
|
621
|
+
} finally {
|
|
622
|
+
release();
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
async append(kind, payload, actor, cell) {
|
|
626
|
+
return this.withLock(() => this.appendUnlocked(kind, payload, actor, cell));
|
|
627
|
+
}
|
|
628
|
+
async appendUnlocked(kind, payload, actor, cell) {
|
|
629
|
+
const base = {
|
|
630
|
+
v: 1,
|
|
631
|
+
seq: this.stateValue.seq + 1,
|
|
632
|
+
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
633
|
+
runId: this.runId,
|
|
634
|
+
...cell === void 0 ? {} : { cell },
|
|
635
|
+
actor,
|
|
636
|
+
kind,
|
|
637
|
+
payload,
|
|
638
|
+
prev: this.stateValue.lastHash
|
|
639
|
+
};
|
|
640
|
+
const event = {
|
|
641
|
+
...base,
|
|
642
|
+
hash: eventHash(base)
|
|
643
|
+
};
|
|
644
|
+
const line = JSON.stringify(event) + "\n";
|
|
645
|
+
await appendFile(this.eventsPath, line, "utf8");
|
|
646
|
+
if (cell !== void 0) await appendFile(join(this.root, "cells", `${safeSegment(cell)}.jsonl`), line, "utf8");
|
|
647
|
+
if (kind === "claim" || kind === "release") await appendFile(join(this.root, "claims.jsonl"), line, "utf8");
|
|
648
|
+
if (kind === "lease") await appendFile(join(this.root, "leases.jsonl"), line, "utf8");
|
|
649
|
+
if (kind === "denied" || kind === "handoff" || kind === "watchdog") await appendFile(join(this.root, "audit.jsonl"), line, "utf8");
|
|
650
|
+
this.eventsValue.push(event);
|
|
651
|
+
this.stateValue = foldReverseEvent(this.stateValue, event);
|
|
652
|
+
return event;
|
|
653
|
+
}
|
|
654
|
+
async init(input, actor) {
|
|
655
|
+
return this.withLock(async () => {
|
|
656
|
+
if (this.stateValue.goal !== void 0) throw new ReverseError("ALREADY_INITIALIZED", "this run already has a goal");
|
|
657
|
+
if ((input.goal ?? "").trim().length === 0) throw new ReverseError("INVALID_INPUT", "goal must not be empty");
|
|
658
|
+
if ((input.authorization ?? "").trim().length === 0) throw new ReverseError("SCOPE_REQUIRED", "init needs an explicit authorization reference");
|
|
659
|
+
const goal = goalFromTemplate(input);
|
|
660
|
+
const scope = {
|
|
661
|
+
authorization: input.authorization,
|
|
662
|
+
roots: (input.roots ?? []).map((root) => resolve(root)),
|
|
663
|
+
resources: input.resources ?? [],
|
|
664
|
+
deny: (input.deny ?? []).map((root) => resolve(root))
|
|
665
|
+
};
|
|
666
|
+
const artifacts = [];
|
|
667
|
+
for (const artifact of input.artifacts ?? []) {
|
|
668
|
+
if (typeof artifact.attrs?.path === "string") assertPathScope(scope, artifact.attrs.path);
|
|
669
|
+
artifacts.push(await indexArtifact(artifact, "root"));
|
|
670
|
+
}
|
|
671
|
+
await this.appendUnlocked("goal", { goal }, actor);
|
|
672
|
+
await this.appendUnlocked("scope", { scope }, actor);
|
|
673
|
+
if (input.budget !== void 0) await this.appendUnlocked("budget", { budget: input.budget }, actor);
|
|
674
|
+
const rootCell = {
|
|
675
|
+
id: cellId("root"),
|
|
676
|
+
kind: "Cell",
|
|
677
|
+
key: "root",
|
|
678
|
+
label: "root cell",
|
|
679
|
+
status: "open",
|
|
680
|
+
attrs: { cell: "root" },
|
|
681
|
+
evidenceIds: [],
|
|
682
|
+
revision: 1
|
|
683
|
+
};
|
|
684
|
+
await this.appendUnlocked("node", { node: rootCell }, actor, "root");
|
|
685
|
+
const steward = {
|
|
686
|
+
actor,
|
|
687
|
+
plane: "steward",
|
|
688
|
+
cell: "root",
|
|
689
|
+
boundAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
690
|
+
};
|
|
691
|
+
await this.appendUnlocked("member", { member: steward }, actor);
|
|
692
|
+
for (const node of artifacts) await this.appendUnlocked("node", { node }, actor, "root");
|
|
693
|
+
return this.stateValue;
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
async bindMember(actor, plane, parentActor, requestedCell) {
|
|
697
|
+
return this.withLock(async () => {
|
|
698
|
+
const existing = this.stateValue.members[actor];
|
|
699
|
+
if (existing !== void 0) {
|
|
700
|
+
if (existing.plane !== plane) throw new ReverseError("PLANE_CHANGED", `actor is already bound as ${existing.plane}`);
|
|
701
|
+
if (requestedCell !== void 0) assertSameCell(existing.cell, requestedCell);
|
|
702
|
+
return existing;
|
|
703
|
+
}
|
|
704
|
+
let cell = "root";
|
|
705
|
+
if (plane === "cell") {
|
|
706
|
+
cell = requestedCell ?? "root";
|
|
707
|
+
const target = this.stateValue.nodes[cellId(cell)];
|
|
708
|
+
if (target === void 0 || target.kind !== "Cell" || target.status !== "open") throw new ReverseError("CELL_NOT_OPEN", `cell ${cell} does not exist or is not open`);
|
|
709
|
+
} else if (plane === "worker" || plane === "subworker") {
|
|
710
|
+
const parent = parentActor === void 0 ? void 0 : this.stateValue.members[parentActor];
|
|
711
|
+
if (parent === void 0) throw new ReverseError("CELL_UNKNOWN", "parent must bind to a Cell before spawning a worker");
|
|
712
|
+
cell = parent.cell;
|
|
713
|
+
}
|
|
714
|
+
const members = Object.values(this.stateValue.members);
|
|
715
|
+
if (plane === "cell") {
|
|
716
|
+
const cells = new Set(members.filter((item) => item.plane === "cell").map((item) => item.cell));
|
|
717
|
+
if (!cells.has(cell) && cells.size >= 3) throw new ReverseError("CELL_LIMIT", "at most three Cells may be active in one run");
|
|
718
|
+
}
|
|
719
|
+
const maxAgents = this.stateValue.budget?.maxAgents;
|
|
720
|
+
if (plane !== "steward" && maxAgents !== void 0 && members.filter((item) => item.plane !== "steward").length >= maxAgents) throw new ReverseError("AGENT_BUDGET", `maxAgents=${maxAgents} reached; stop or release an agent before binding another`);
|
|
721
|
+
const member = {
|
|
722
|
+
actor,
|
|
723
|
+
plane,
|
|
724
|
+
cell,
|
|
725
|
+
...parentActor === void 0 ? {} : { parentActor },
|
|
726
|
+
boundAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
727
|
+
};
|
|
728
|
+
await this.appendUnlocked("member", { member }, actor, cell);
|
|
729
|
+
return member;
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
cellFor(actor) {
|
|
733
|
+
return this.stateValue.members[actor]?.cell ?? "root";
|
|
734
|
+
}
|
|
735
|
+
frontier(options = {}) {
|
|
736
|
+
return computeFrontier(this.stateValue, options);
|
|
737
|
+
}
|
|
738
|
+
async claim(actionId, actor, ttlSeconds = 900, operation = "acquire", token) {
|
|
739
|
+
return this.withLock(async () => {
|
|
740
|
+
const cell = this.cellFor(actor);
|
|
741
|
+
const existing = this.stateValue.claims[actionId];
|
|
742
|
+
const now = Date.now();
|
|
743
|
+
if (operation === "renew" || operation === "release") {
|
|
744
|
+
if (existing === void 0 || existing.token !== token || existing.actor !== actor) throw new ReverseError("CLAIM_NOT_HELD", "claim token does not match this actor/action");
|
|
745
|
+
if (operation === "renew" && (existing.status !== "active" || existing.expiresAt <= now)) throw new ReverseError("CLAIM_EXPIRED", "expired claims must be reacquired, not renewed");
|
|
746
|
+
const claim = operation === "renew" ? {
|
|
747
|
+
...existing,
|
|
748
|
+
expiresAt: now + this.ttl(ttlSeconds)
|
|
749
|
+
} : {
|
|
750
|
+
...existing,
|
|
751
|
+
status: "released"
|
|
752
|
+
};
|
|
753
|
+
await this.appendUnlocked(operation === "release" ? "release" : "claim", {
|
|
754
|
+
claim,
|
|
755
|
+
operation
|
|
756
|
+
}, actor, cell);
|
|
757
|
+
return claim;
|
|
758
|
+
}
|
|
759
|
+
const maxActions = this.stateValue.budget?.maxActions;
|
|
760
|
+
const usedActions = Object.values(this.stateValue.routes).reduce((sum, route) => sum + route.attempts, 0);
|
|
761
|
+
if (maxActions !== void 0 && usedActions >= maxActions) throw new ReverseError("BUDGET_EXHAUSTED", `maxActions=${maxActions} reached`);
|
|
762
|
+
const action = computeFrontier(this.stateValue, {
|
|
763
|
+
cell,
|
|
764
|
+
limit: 1e3,
|
|
765
|
+
eliteCap: 1e3
|
|
766
|
+
}).find((item) => item.actionId === actionId);
|
|
767
|
+
if (action === void 0) throw new ReverseError("ACTION_NOT_FOUND", `action is not in the frontier for cell ${cell}`);
|
|
768
|
+
if (action.actionType === "verify") {
|
|
769
|
+
if (this.stateValue.nodes[action.targetId]?.attrs.producedBy === actor) throw new ReverseError("VERIFIER_INDEPENDENCE", "the producer cannot claim verification of its own finding");
|
|
770
|
+
}
|
|
771
|
+
if (existing?.status === "active" && existing.expiresAt > now) throw new ReverseError("CLAIM_CONFLICT", `held by ${existing.actor} until ${new Date(existing.expiresAt).toISOString()}`);
|
|
772
|
+
const fencing = (existing?.fencing ?? 0) + 1;
|
|
773
|
+
const claim = {
|
|
774
|
+
actionId,
|
|
775
|
+
actor,
|
|
776
|
+
cell,
|
|
777
|
+
fencing,
|
|
778
|
+
expiresAt: now + this.ttl(ttlSeconds),
|
|
779
|
+
createdAt: now,
|
|
780
|
+
status: "active",
|
|
781
|
+
token: `claim:${actionId}:${fencing}:${actor}`
|
|
782
|
+
};
|
|
783
|
+
await this.appendUnlocked("claim", {
|
|
784
|
+
claim,
|
|
785
|
+
operation
|
|
786
|
+
}, actor, cell);
|
|
787
|
+
return claim;
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
ttl(seconds) {
|
|
791
|
+
return Math.max(10, Math.min(86400, Math.trunc(seconds))) * 1e3;
|
|
792
|
+
}
|
|
793
|
+
activeClaim(token, actor) {
|
|
794
|
+
const current = Object.values(this.stateValue.claims).find((item) => item.token === token);
|
|
795
|
+
if (current === void 0) {
|
|
796
|
+
const historic = this.eventsValue.map(claimFromEvent).find((claim) => claim?.token === token);
|
|
797
|
+
if (historic !== void 0) {
|
|
798
|
+
const latest = this.stateValue.claims[historic.actionId];
|
|
799
|
+
if (latest !== void 0 && latest.fencing > historic.fencing) throw new ReverseError("STALE_FENCING", "a newer fencing token owns this action");
|
|
800
|
+
}
|
|
801
|
+
throw new ReverseError("CLAIM_NOT_HELD", "claim token does not belong to this run");
|
|
802
|
+
}
|
|
803
|
+
if (current.actor !== actor) throw new ReverseError("CLAIM_NOT_HELD", "claim belongs to another actor");
|
|
804
|
+
if (current.status !== "active") throw new ReverseError("CLAIM_NOT_HELD", `claim is ${current.status}`);
|
|
805
|
+
if (current.expiresAt <= Date.now()) throw new ReverseError("CLAIM_EXPIRED", "claim expired; reacquire it before writing");
|
|
806
|
+
return current;
|
|
807
|
+
}
|
|
808
|
+
findingTransition(node, existing, actor) {
|
|
809
|
+
if (existing === void 0) {
|
|
810
|
+
if (node.status !== "proposed" && node.status !== "queued") throw new ReverseError("EVIDENCE_REQUIRED", "a new Finding starts as proposed/queued; use evidence to observe it");
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
if (node.status === existing.status) return;
|
|
814
|
+
if (node.status === "observed") throw new ReverseError("USE_EVIDENCE", "Finding observed status is written by the evidence action");
|
|
815
|
+
if (node.status === "reproduced") {
|
|
816
|
+
if (existing.status !== "observed" || existing.evidenceIds.length === 0) throw new ReverseError("EVIDENCE_REQUIRED", "reproduce requires an observed Finding with evidence");
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
if (node.status === "verified") {
|
|
820
|
+
if (existing.status !== "reproduced") throw new ReverseError("EVIDENCE_REQUIRED", "verify requires a reproduced Finding");
|
|
821
|
+
if (String(existing.attrs.producedBy ?? "") === actor) throw new ReverseError("VERIFIER_INDEPENDENCE", "the Finding producer cannot verify it");
|
|
822
|
+
if (!existing.evidenceIds.some((id) => {
|
|
823
|
+
const item = this.stateValue.evidence[id];
|
|
824
|
+
return item?.producer === actor && item.verifier === actor && item.reproduction.length > 0;
|
|
825
|
+
})) throw new ReverseError("VERIFIER_INDEPENDENCE", "verification needs independent evidence with reproduction steps from this actor");
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
async record(token, actor, input) {
|
|
829
|
+
return this.withLock(async () => {
|
|
830
|
+
const cell = this.activeClaim(token, actor).cell;
|
|
831
|
+
if (input.node === void 0 && input.edge === void 0) throw new ReverseError("INVALID_INPUT", "record needs a node or edge");
|
|
832
|
+
if (input.node !== void 0) {
|
|
833
|
+
const source = input.node;
|
|
834
|
+
const key = source.key ?? source.id ?? source.label ?? "";
|
|
835
|
+
const id = source.id ?? (source.kind === "Function" ? functionId(cell, String(source.attrs?.address ?? "")) : source.kind === "Finding" ? findingId(cell, key) : source.kind === "Cell" ? cellId(key) : `${source.kind.toLowerCase()}:${cell}:${shortHash(key)}`);
|
|
836
|
+
const existing = this.stateValue.nodes[id];
|
|
837
|
+
if (existing !== void 0 && existing.kind !== source.kind) throw new ReverseError("NODE_KIND_MISMATCH", `node ${id} is already ${existing.kind}`);
|
|
838
|
+
if (typeof source.attrs?.path === "string") assertPathScope(this.stateValue.scope, source.attrs.path);
|
|
839
|
+
if (source.attrs?.cell !== void 0) assertSameCell(cell, String(source.attrs.cell));
|
|
840
|
+
if (existing !== void 0 && existing.attrs.cell !== void 0) assertSameCell(cell, String(existing.attrs.cell));
|
|
841
|
+
const status = source.status ?? existing?.status ?? "proposed";
|
|
842
|
+
const attrs = {
|
|
843
|
+
...existing?.attrs ?? {},
|
|
844
|
+
...source.attrs ?? {},
|
|
845
|
+
cell
|
|
846
|
+
};
|
|
847
|
+
if (source.kind === "Finding" && existing === void 0) attrs.producedBy = actor;
|
|
848
|
+
const node = {
|
|
849
|
+
id,
|
|
850
|
+
kind: source.kind,
|
|
851
|
+
key: source.key ?? existing?.key ?? id,
|
|
852
|
+
label: source.label ?? existing?.label ?? source.key ?? id,
|
|
853
|
+
status,
|
|
854
|
+
attrs,
|
|
855
|
+
evidenceIds: source.evidenceIds ?? existing?.evidenceIds ?? [],
|
|
856
|
+
revision: (existing?.revision ?? 0) + 1
|
|
857
|
+
};
|
|
858
|
+
if (source.kind === "Finding") this.findingTransition(node, existing, actor);
|
|
859
|
+
await this.appendUnlocked("node", { node }, actor, cell);
|
|
860
|
+
}
|
|
861
|
+
if (input.edge !== void 0) {
|
|
862
|
+
const edge = input.edge;
|
|
863
|
+
if (this.stateValue.nodes[edge.from] === void 0 || this.stateValue.nodes[edge.to] === void 0) throw new ReverseError("EDGE_ENDPOINT_MISSING", "both edge endpoints must already exist");
|
|
864
|
+
const record = {
|
|
865
|
+
id: edge.id ?? `edge:${shortHash(`${edge.from}|${edge.kind}|${edge.to}`)}`,
|
|
866
|
+
from: edge.from,
|
|
867
|
+
to: edge.to,
|
|
868
|
+
kind: edge.kind,
|
|
869
|
+
confidence: edge.confidence ?? .5,
|
|
870
|
+
evidenceIds: edge.evidenceIds ?? []
|
|
871
|
+
};
|
|
872
|
+
await this.appendUnlocked("edge", { edge: record }, actor, cell);
|
|
873
|
+
}
|
|
874
|
+
return this.stateValue;
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
async evidence(token, actor, input) {
|
|
878
|
+
return this.withLock(async () => {
|
|
879
|
+
const claim = this.activeClaim(token, actor);
|
|
880
|
+
const finding = this.stateValue.nodes[input.findingId];
|
|
881
|
+
if (finding === void 0 || finding.kind !== "Finding") throw new ReverseError("FINDING_NOT_FOUND", "evidence must reference an existing Finding");
|
|
882
|
+
assertSameCell(claim.cell, String(finding.attrs.cell ?? "root"));
|
|
883
|
+
if (!input.tool.trim() || !input.command.trim() || !input.inputHash.trim()) throw new ReverseError("INVALID_INPUT", "evidence needs tool, command and inputHash");
|
|
884
|
+
if (input.content === void 0 && !input.outputHash?.trim()) throw new ReverseError("INVALID_INPUT", "evidence needs outputHash or content");
|
|
885
|
+
if (input.artifactPath !== void 0) assertPathScope(this.stateValue.scope, input.artifactPath);
|
|
886
|
+
const content = input.content;
|
|
887
|
+
if (content !== void 0 && Buffer.byteLength(content, "utf8") > 4 * 1024 * 1024) throw new ReverseError("EVIDENCE_TOO_LARGE", "inline evidence content is capped at 4 MiB");
|
|
888
|
+
const id = `evidence:${shortHash(JSON.stringify([
|
|
889
|
+
input.findingId,
|
|
890
|
+
actor,
|
|
891
|
+
input.tool,
|
|
892
|
+
input.command,
|
|
893
|
+
input.inputHash,
|
|
894
|
+
input.outputHash,
|
|
895
|
+
content
|
|
896
|
+
]))}`;
|
|
897
|
+
let contentPath;
|
|
898
|
+
if (content !== void 0) {
|
|
899
|
+
const filename = `${safeSegment(id)}.txt`;
|
|
900
|
+
await writeFile(join(this.root, "evidence", filename), content, {
|
|
901
|
+
encoding: "utf8",
|
|
902
|
+
flag: "wx"
|
|
903
|
+
}).catch((error) => {
|
|
904
|
+
if (error.code !== "EEXIST") throw error;
|
|
905
|
+
});
|
|
906
|
+
contentPath = `evidence/${filename}`;
|
|
907
|
+
}
|
|
908
|
+
const producer = String(finding.attrs.producedBy ?? "");
|
|
909
|
+
const item = {
|
|
910
|
+
id,
|
|
911
|
+
findingId: input.findingId,
|
|
912
|
+
tool: input.tool,
|
|
913
|
+
command: input.command,
|
|
914
|
+
toolVersion: input.toolVersion ?? "",
|
|
915
|
+
inputHash: input.inputHash,
|
|
916
|
+
outputHash: content === void 0 ? input.outputHash : `sha256:${sha256Hex(content)}`,
|
|
917
|
+
...input.offset === void 0 ? {} : { offset: input.offset },
|
|
918
|
+
...input.artifactPath === void 0 ? {} : { artifactPath: resolve(input.artifactPath) },
|
|
919
|
+
...contentPath === void 0 ? {} : { contentPath },
|
|
920
|
+
sizeBytes: content === void 0 ? 0 : Buffer.byteLength(content, "utf8"),
|
|
921
|
+
reproduction: input.reproduction ?? [],
|
|
922
|
+
producer: actor,
|
|
923
|
+
...producer !== actor ? { verifier: actor } : {},
|
|
924
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
925
|
+
};
|
|
926
|
+
await this.appendUnlocked("evidence", { evidence: item }, actor, claim.cell);
|
|
927
|
+
return item;
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
async cell(operation, cell, actor, targetCell, brief) {
|
|
931
|
+
return this.withLock(async () => {
|
|
932
|
+
const member = this.stateValue.members[actor];
|
|
933
|
+
if (member?.plane === "cell") assertSameCell(member.cell, cell);
|
|
934
|
+
const id = cellId(cell);
|
|
935
|
+
const existing = this.stateValue.nodes[id];
|
|
936
|
+
if (operation === "close") {
|
|
937
|
+
if (Object.values(this.stateValue.claims).some((claim) => claim.cell === cell && claim.status === "active" && claim.expiresAt > Date.now())) throw new ReverseError("CELL_BUSY", "close requires all active claims to be released or expired");
|
|
938
|
+
}
|
|
939
|
+
if (operation === "merge") {
|
|
940
|
+
if (targetCell === void 0 || this.stateValue.nodes[cellId(targetCell)]?.status !== "open") throw new ReverseError("CELL_NOT_OPEN", "merge needs an open targetCell");
|
|
941
|
+
await this.appendUnlocked("merge", {
|
|
942
|
+
from: cell,
|
|
943
|
+
to: targetCell
|
|
944
|
+
}, actor, cell);
|
|
945
|
+
}
|
|
946
|
+
const node = {
|
|
947
|
+
id,
|
|
948
|
+
kind: "Cell",
|
|
949
|
+
key: cell,
|
|
950
|
+
label: cell,
|
|
951
|
+
status: operation === "open" ? "open" : operation === "merge" ? "merged" : "closed",
|
|
952
|
+
attrs: {
|
|
953
|
+
...existing?.attrs ?? {},
|
|
954
|
+
cell,
|
|
955
|
+
...operation === "merge" ? { mergedInto: targetCell } : {}
|
|
956
|
+
},
|
|
957
|
+
evidenceIds: existing?.evidenceIds ?? [],
|
|
958
|
+
revision: (existing?.revision ?? 0) + 1
|
|
959
|
+
};
|
|
960
|
+
await this.appendUnlocked("node", { node }, actor, cell);
|
|
961
|
+
const markdown = brief ?? [
|
|
962
|
+
`# Cell ${cell}`,
|
|
963
|
+
"",
|
|
964
|
+
`Goal: ${this.stateValue.goal?.text ?? ""}`,
|
|
965
|
+
`Status: ${node.status}`,
|
|
966
|
+
""
|
|
967
|
+
].join("\n");
|
|
968
|
+
await writeFile(join(this.root, "briefs", `${safeSegment(cell)}.md`), markdown, "utf8");
|
|
969
|
+
return this.stateValue;
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
async lease(operation, resource, actor, ttlSeconds = 600, token) {
|
|
973
|
+
return this.withLock(async () => {
|
|
974
|
+
assertResourceScope(this.stateValue.scope, resource);
|
|
975
|
+
const cell = this.cellFor(actor);
|
|
976
|
+
const now = Date.now();
|
|
977
|
+
const existing = this.stateValue.leases[resource];
|
|
978
|
+
if (operation === "acquire") {
|
|
979
|
+
if (existing?.status === "active" && existing.expiresAt > now) throw new ReverseError("LEASE_BUSY", `held by ${existing.actor} until ${new Date(existing.expiresAt).toISOString()}`);
|
|
980
|
+
const fencing = (existing?.fencing ?? 0) + 1;
|
|
981
|
+
const lease = {
|
|
982
|
+
resource,
|
|
983
|
+
actor,
|
|
984
|
+
cell,
|
|
985
|
+
fencing,
|
|
986
|
+
expiresAt: now + this.ttl(ttlSeconds),
|
|
987
|
+
createdAt: now,
|
|
988
|
+
status: "active",
|
|
989
|
+
token: `lease:${resource}:${fencing}:${actor}`
|
|
990
|
+
};
|
|
991
|
+
await this.appendUnlocked("lease", {
|
|
992
|
+
lease,
|
|
993
|
+
operation
|
|
994
|
+
}, actor, cell);
|
|
995
|
+
return lease;
|
|
996
|
+
}
|
|
997
|
+
if (existing === void 0 || existing.token !== token || existing.actor !== actor) throw new ReverseError("LEASE_NOT_HELD", "resource lease token does not match this actor");
|
|
998
|
+
if (existing.status !== "active" || existing.expiresAt <= now) throw new ReverseError("LEASE_EXPIRED", "resource lease expired");
|
|
999
|
+
const lease = operation === "renew" ? {
|
|
1000
|
+
...existing,
|
|
1001
|
+
expiresAt: now + this.ttl(ttlSeconds)
|
|
1002
|
+
} : {
|
|
1003
|
+
...existing,
|
|
1004
|
+
status: "released"
|
|
1005
|
+
};
|
|
1006
|
+
await this.appendUnlocked("lease", {
|
|
1007
|
+
lease,
|
|
1008
|
+
operation
|
|
1009
|
+
}, actor, cell);
|
|
1010
|
+
return lease;
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
async finish(operation, actor, findingIds = [], note = "") {
|
|
1014
|
+
return this.withLock(async () => {
|
|
1015
|
+
if (operation === "propose") {
|
|
1016
|
+
if (findingIds.length === 0) throw new ReverseError("INVALID_INPUT", "finish needs at least one finding id");
|
|
1017
|
+
for (const id of findingIds) {
|
|
1018
|
+
const node = this.stateValue.nodes[id];
|
|
1019
|
+
if (node === void 0 || node.kind !== "Finding") throw new ReverseError("FINDING_NOT_FOUND", `no finding ${id}`);
|
|
1020
|
+
if (node.status !== "verified") throw new ReverseError("FINDING_NOT_READY", `finding ${id} is ${node.status}, not verified`);
|
|
1021
|
+
}
|
|
1022
|
+
const finish = {
|
|
1023
|
+
status: "proposed",
|
|
1024
|
+
findingIds,
|
|
1025
|
+
note,
|
|
1026
|
+
proposedSeq: this.stateValue.seq + 1,
|
|
1027
|
+
proposedBy: actor
|
|
1028
|
+
};
|
|
1029
|
+
await this.appendUnlocked("finish", { finish }, actor, this.cellFor(actor));
|
|
1030
|
+
return finish;
|
|
1031
|
+
}
|
|
1032
|
+
const current = this.stateValue.finish;
|
|
1033
|
+
if (current === void 0 || current.status !== "proposed") throw new ReverseError("FINISH_NOT_PROPOSED", `finish is ${current?.status ?? "absent"}`);
|
|
1034
|
+
if (this.stateValue.lastFactSeq > current.proposedSeq) throw new ReverseError("FINISH_INVALIDATED", "later facts invalidated finish; propose again");
|
|
1035
|
+
const finish = {
|
|
1036
|
+
...current,
|
|
1037
|
+
status: "settled",
|
|
1038
|
+
settledSeq: this.stateValue.seq + 1
|
|
1039
|
+
};
|
|
1040
|
+
await this.appendUnlocked("finish", { finish }, actor);
|
|
1041
|
+
return finish;
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
async requestHandoff(actionId, actor, note = "") {
|
|
1045
|
+
return this.withLock(async () => {
|
|
1046
|
+
const claim = this.stateValue.claims[actionId];
|
|
1047
|
+
if (claim === void 0 || claim.status !== "active") throw new ReverseError("CLAIM_NOT_HELD", "handoff needs an active claim");
|
|
1048
|
+
const handoff = {
|
|
1049
|
+
id: `handoff:${shortHash(`${actionId}:${claim.fencing}:${this.stateValue.seq + 1}`)}`,
|
|
1050
|
+
actionId,
|
|
1051
|
+
actor: claim.actor,
|
|
1052
|
+
cell: claim.cell,
|
|
1053
|
+
status: "requested",
|
|
1054
|
+
note,
|
|
1055
|
+
factsWritten: [],
|
|
1056
|
+
leases: [],
|
|
1057
|
+
nextStep: "",
|
|
1058
|
+
safeToStop: false,
|
|
1059
|
+
requestedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1060
|
+
};
|
|
1061
|
+
await this.appendUnlocked("handoff", { handoff }, actor, claim.cell);
|
|
1062
|
+
return handoff;
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
async completeHandoff(token, actor, input) {
|
|
1066
|
+
return this.withLock(async () => {
|
|
1067
|
+
const claim = Object.values(this.stateValue.claims).find((item) => item.token === token);
|
|
1068
|
+
if (claim === void 0 || claim.actor !== actor) throw new ReverseError("CLAIM_NOT_HELD", "only the latest claim holder can complete handoff");
|
|
1069
|
+
const requested = Object.values(this.stateValue.handoffs).find((item) => item.actionId === claim.actionId && item.actor === actor && item.status === "requested");
|
|
1070
|
+
if (requested === void 0) throw new ReverseError("HANDOFF_NOT_REQUESTED", "completeHandoff needs a pending request");
|
|
1071
|
+
const handoff = {
|
|
1072
|
+
...requested,
|
|
1073
|
+
status: "completed",
|
|
1074
|
+
note: input.note ?? requested.note,
|
|
1075
|
+
factsWritten: input.factsWritten ?? [],
|
|
1076
|
+
leases: input.leases ?? [],
|
|
1077
|
+
nextStep: input.nextStep ?? "",
|
|
1078
|
+
safeToStop: input.safeToStop,
|
|
1079
|
+
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1080
|
+
};
|
|
1081
|
+
await this.appendUnlocked("handoff", { handoff }, actor, claim.cell);
|
|
1082
|
+
await this.appendUnlocked("release", {
|
|
1083
|
+
claim: {
|
|
1084
|
+
...claim,
|
|
1085
|
+
status: "released"
|
|
1086
|
+
},
|
|
1087
|
+
operation: "release"
|
|
1088
|
+
}, actor, claim.cell);
|
|
1089
|
+
return handoff;
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
async watchdog(actor) {
|
|
1093
|
+
return this.withLock(async () => {
|
|
1094
|
+
const previous = this.stateValue.watchdog;
|
|
1095
|
+
const noProgress = this.stateValue.lastFactSeq === previous.lastProgressSeq;
|
|
1096
|
+
let rotations = noProgress ? previous.rotationsWithoutProgress + 1 : 0;
|
|
1097
|
+
let attempts = noProgress ? previous.recoveryAttempts : 0;
|
|
1098
|
+
const requests = [];
|
|
1099
|
+
if (rotations >= 3 && attempts < 2) {
|
|
1100
|
+
for (const claim of Object.values(this.stateValue.claims)) {
|
|
1101
|
+
if (claim.status !== "active") continue;
|
|
1102
|
+
if (Object.values(this.stateValue.handoffs).some((item) => item.actionId === claim.actionId && item.status === "requested")) continue;
|
|
1103
|
+
const handoff = {
|
|
1104
|
+
id: `handoff:${shortHash(`${claim.actionId}:${claim.fencing}:${this.stateValue.seq + 1}`)}`,
|
|
1105
|
+
actionId: claim.actionId,
|
|
1106
|
+
actor: claim.actor,
|
|
1107
|
+
cell: claim.cell,
|
|
1108
|
+
status: "requested",
|
|
1109
|
+
note: "watchdog: three rotations without graph progress; steer or hand off",
|
|
1110
|
+
factsWritten: [],
|
|
1111
|
+
leases: [],
|
|
1112
|
+
nextStep: "",
|
|
1113
|
+
safeToStop: false,
|
|
1114
|
+
requestedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1115
|
+
};
|
|
1116
|
+
await this.appendUnlocked("handoff", { handoff }, actor, claim.cell);
|
|
1117
|
+
requests.push(handoff);
|
|
1118
|
+
}
|
|
1119
|
+
attempts += 1;
|
|
1120
|
+
rotations = 0;
|
|
1121
|
+
}
|
|
1122
|
+
const watchdog = {
|
|
1123
|
+
lastProgressSeq: this.stateValue.lastFactSeq,
|
|
1124
|
+
rotationsWithoutProgress: rotations,
|
|
1125
|
+
recoveryAttempts: attempts,
|
|
1126
|
+
needsHuman: noProgress && attempts >= 2
|
|
1127
|
+
};
|
|
1128
|
+
await this.appendUnlocked("watchdog", {
|
|
1129
|
+
watchdog,
|
|
1130
|
+
requestIds: requests.map((item) => item.id)
|
|
1131
|
+
}, actor);
|
|
1132
|
+
return {
|
|
1133
|
+
watchdog,
|
|
1134
|
+
requests
|
|
1135
|
+
};
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
async denied(actor, action, code, message) {
|
|
1139
|
+
await this.append("denied", {
|
|
1140
|
+
action,
|
|
1141
|
+
code,
|
|
1142
|
+
message
|
|
1143
|
+
}, actor, this.cellFor(actor));
|
|
1144
|
+
}
|
|
1145
|
+
reportData() {
|
|
1146
|
+
const state = this.stateValue;
|
|
1147
|
+
const nodes = Object.values(state.nodes);
|
|
1148
|
+
const pendingHandoffs = Object.values(state.handoffs).filter((item) => item.status === "requested");
|
|
1149
|
+
const openQuestions = nodes.filter((node) => node.kind === "Question" && node.status !== "closed" && node.status !== "cancelled");
|
|
1150
|
+
const residualRisk = [];
|
|
1151
|
+
if (nodes.filter((node) => node.kind === "Finding" && node.status === "verified").length === 0) residualRisk.push("no independently verified findings");
|
|
1152
|
+
if (pendingHandoffs.length > 0) residualRisk.push(`${pendingHandoffs.length} pending handoff(s)`);
|
|
1153
|
+
if (openQuestions.length > 0) residualRisk.push(`${openQuestions.length} open question(s)`);
|
|
1154
|
+
if (state.watchdog.needsHuman) residualRisk.push("watchdog exhausted two recovery attempts");
|
|
1155
|
+
return {
|
|
1156
|
+
runId: this.runId,
|
|
1157
|
+
goal: state.goal,
|
|
1158
|
+
status: state.finish?.status ?? "open",
|
|
1159
|
+
cells: nodes.filter((node) => node.kind === "Cell"),
|
|
1160
|
+
findings: nodes.filter((node) => node.kind === "Finding" && node.status === "verified"),
|
|
1161
|
+
deadEnds: nodes.filter((node) => node.kind === "DeadEnd"),
|
|
1162
|
+
openQuestions,
|
|
1163
|
+
evidence: Object.values(state.evidence),
|
|
1164
|
+
pendingHandoffs,
|
|
1165
|
+
watchdog: state.watchdog,
|
|
1166
|
+
residualRisk
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
report(format = "markdown") {
|
|
1170
|
+
const data = this.reportData();
|
|
1171
|
+
if (format === "json") return data;
|
|
1172
|
+
return [
|
|
1173
|
+
`# Reverse run ${this.runId}`,
|
|
1174
|
+
"",
|
|
1175
|
+
`Goal: ${data.goal?.text ?? "(not initialized)"}`,
|
|
1176
|
+
`Acceptance: ${data.goal?.acceptance ?? ""}`,
|
|
1177
|
+
`Engagement: ${data.goal?.engagement ?? "reverse"}`,
|
|
1178
|
+
...data.goal?.flagFormat === void 0 ? [] : [`Flag format: ${data.goal.flagFormat}`],
|
|
1179
|
+
`State: ${data.status}`,
|
|
1180
|
+
"",
|
|
1181
|
+
"## Cells",
|
|
1182
|
+
...data.cells.length === 0 ? ["- none"] : data.cells.map((node) => `- ${node.id}: ${node.status}`),
|
|
1183
|
+
"",
|
|
1184
|
+
"## Verified findings",
|
|
1185
|
+
...data.findings.length === 0 ? ["- none"] : data.findings.map((node) => `- ${node.id}: ${node.label}`),
|
|
1186
|
+
"",
|
|
1187
|
+
"## Evidence",
|
|
1188
|
+
...data.evidence.length === 0 ? ["- none"] : data.evidence.map((item) => `- ${item.id} -> ${item.findingId}: ${item.outputHash} (${item.contentPath ?? "external hash"})`),
|
|
1189
|
+
"",
|
|
1190
|
+
"## Dead ends",
|
|
1191
|
+
...data.deadEnds.length === 0 ? ["- none"] : data.deadEnds.map((node) => `- ${node.id}: ${node.label}`),
|
|
1192
|
+
"",
|
|
1193
|
+
"## Open questions",
|
|
1194
|
+
...data.openQuestions.length === 0 ? ["- none"] : data.openQuestions.map((node) => `- ${node.id}: ${node.label}`),
|
|
1195
|
+
"",
|
|
1196
|
+
"## Residual risk",
|
|
1197
|
+
...data.residualRisk.length === 0 ? ["- none"] : data.residualRisk.map((item) => `- ${item}`),
|
|
1198
|
+
""
|
|
1199
|
+
].join("\n");
|
|
1200
|
+
}
|
|
1201
|
+
audit(limit = 50) {
|
|
1202
|
+
return this.eventsValue.slice(-Math.max(1, Math.min(1e3, Math.trunc(limit))));
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
const registry = /* @__PURE__ */ new Map();
|
|
1206
|
+
function openReverseStore(runId, baseDir) {
|
|
1207
|
+
const root = resolve(baseDir ?? join(dshHome(), "reverse"), safeSegment(runId));
|
|
1208
|
+
const existing = registry.get(root);
|
|
1209
|
+
if (existing !== void 0) return existing;
|
|
1210
|
+
const opened = ReverseStore.open(runId, baseDir).catch((error) => {
|
|
1211
|
+
registry.delete(root);
|
|
1212
|
+
throw error;
|
|
1213
|
+
});
|
|
1214
|
+
registry.set(root, opened);
|
|
1215
|
+
return opened;
|
|
1216
|
+
}
|
|
1217
|
+
//#endregion
|
|
1218
|
+
//#region src/host/runtime/reverse/tool.ts
|
|
1219
|
+
const REVERSE_BOARD_TOOL = "reverse_board";
|
|
1220
|
+
const REVERSE_BOARD_DESCRIPTION = "Operate a scoped reverse graph: init, frontier, claim/renew/release, record, evidence, cells, leases, handoff, watchdog, finish, Markdown/JSON report and audit. Mounted only by the reverse preset.";
|
|
1221
|
+
function asString(value) {
|
|
1222
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1223
|
+
}
|
|
1224
|
+
function isRecord(value) {
|
|
1225
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1226
|
+
}
|
|
1227
|
+
function asJson(value) {
|
|
1228
|
+
return JSON.parse(JSON.stringify(value));
|
|
1229
|
+
}
|
|
1230
|
+
function reply(data) {
|
|
1231
|
+
return {
|
|
1232
|
+
ok: true,
|
|
1233
|
+
data: asJson(data)
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
function sessionOf(agent) {
|
|
1237
|
+
if (!isRecord(agent)) return void 0;
|
|
1238
|
+
return isRecord(agent.session) ? agent.session : void 0;
|
|
1239
|
+
}
|
|
1240
|
+
function sessionDepth(session, sessions) {
|
|
1241
|
+
const declared = session.header?.delegationDepth;
|
|
1242
|
+
if (typeof declared === "number" && Number.isFinite(declared) && declared >= 0) return Math.trunc(declared);
|
|
1243
|
+
let depth = 0;
|
|
1244
|
+
let current = session;
|
|
1245
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1246
|
+
while (current !== void 0 && depth < 8) {
|
|
1247
|
+
const parent = asString(current.header?.parentSession);
|
|
1248
|
+
if (parent === void 0 || seen.has(parent)) break;
|
|
1249
|
+
seen.add(parent);
|
|
1250
|
+
depth += 1;
|
|
1251
|
+
current = sessions?.get(parent);
|
|
1252
|
+
}
|
|
1253
|
+
return depth;
|
|
1254
|
+
}
|
|
1255
|
+
function rootSessionId(session, sessions) {
|
|
1256
|
+
let current = session;
|
|
1257
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1258
|
+
while (true) {
|
|
1259
|
+
const parent = asString(current.header?.parentSession);
|
|
1260
|
+
if (parent === void 0 || seen.has(parent)) break;
|
|
1261
|
+
seen.add(parent);
|
|
1262
|
+
const next = sessions?.get(parent);
|
|
1263
|
+
if (next === void 0) return parent;
|
|
1264
|
+
current = next;
|
|
1265
|
+
}
|
|
1266
|
+
return asString(current.id) ?? asString(session.id) ?? "";
|
|
1267
|
+
}
|
|
1268
|
+
function planeOfDepth(depth) {
|
|
1269
|
+
if (depth <= 0) return "steward";
|
|
1270
|
+
if (depth === 1) return "cell";
|
|
1271
|
+
if (depth === 2) return "worker";
|
|
1272
|
+
return "subworker";
|
|
1273
|
+
}
|
|
1274
|
+
function requirePlane(plane, allowed) {
|
|
1275
|
+
if (!allowed.includes(plane)) throw new ReverseError("PLANE_DENIED", `the ${plane} plane cannot run this action`);
|
|
1276
|
+
}
|
|
1277
|
+
function arrayOfRecords(value) {
|
|
1278
|
+
return Array.isArray(value) ? value.filter(isRecord) : [];
|
|
1279
|
+
}
|
|
1280
|
+
function stringArray(value) {
|
|
1281
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
1282
|
+
}
|
|
1283
|
+
const workerPlanes = [
|
|
1284
|
+
"cell",
|
|
1285
|
+
"worker",
|
|
1286
|
+
"subworker"
|
|
1287
|
+
];
|
|
1288
|
+
function createReverseTool(deps = {}) {
|
|
1289
|
+
const storeFor = deps.storeFor ?? ((runId) => openReverseStore(runId));
|
|
1290
|
+
return defineTool({
|
|
1291
|
+
name: REVERSE_BOARD_TOOL,
|
|
1292
|
+
description: REVERSE_BOARD_DESCRIPTION,
|
|
1293
|
+
parameters: {
|
|
1294
|
+
action: {
|
|
1295
|
+
type: "string",
|
|
1296
|
+
required: true,
|
|
1297
|
+
enum: [
|
|
1298
|
+
"init",
|
|
1299
|
+
"frontier",
|
|
1300
|
+
"claim",
|
|
1301
|
+
"record",
|
|
1302
|
+
"evidence",
|
|
1303
|
+
"cell",
|
|
1304
|
+
"lease",
|
|
1305
|
+
"handoff",
|
|
1306
|
+
"watchdog",
|
|
1307
|
+
"finish",
|
|
1308
|
+
"report",
|
|
1309
|
+
"audit"
|
|
1310
|
+
],
|
|
1311
|
+
description: "Graph operation. Claim supports acquire/renew/release through operation."
|
|
1312
|
+
},
|
|
1313
|
+
goal: {
|
|
1314
|
+
type: "string",
|
|
1315
|
+
description: "init: goal."
|
|
1316
|
+
},
|
|
1317
|
+
acceptance: {
|
|
1318
|
+
type: "string",
|
|
1319
|
+
description: "init: acceptance criteria; Jeopardy gets a flag/reproduction default."
|
|
1320
|
+
},
|
|
1321
|
+
engagement: {
|
|
1322
|
+
type: "string",
|
|
1323
|
+
enum: ["reverse", "jeopardy"],
|
|
1324
|
+
description: "init: engagement template."
|
|
1325
|
+
},
|
|
1326
|
+
flagFormat: {
|
|
1327
|
+
type: "string",
|
|
1328
|
+
description: "init: Jeopardy flag format."
|
|
1329
|
+
},
|
|
1330
|
+
authorization: {
|
|
1331
|
+
type: "string",
|
|
1332
|
+
description: "init: required authorization reference."
|
|
1333
|
+
},
|
|
1334
|
+
roots: {
|
|
1335
|
+
type: "array",
|
|
1336
|
+
items: { type: "string" },
|
|
1337
|
+
description: "init: allowed artifact roots; paths outside are rejected."
|
|
1338
|
+
},
|
|
1339
|
+
resources: {
|
|
1340
|
+
type: "array",
|
|
1341
|
+
items: { type: "string" },
|
|
1342
|
+
description: "init: allowed resource keys or prefix* patterns; empty denies all leases."
|
|
1343
|
+
},
|
|
1344
|
+
deny: {
|
|
1345
|
+
type: "array",
|
|
1346
|
+
items: { type: "string" },
|
|
1347
|
+
description: "init: denied path roots."
|
|
1348
|
+
},
|
|
1349
|
+
artifacts: {
|
|
1350
|
+
type: "array",
|
|
1351
|
+
items: {
|
|
1352
|
+
type: "object",
|
|
1353
|
+
additionalProperties: true
|
|
1354
|
+
},
|
|
1355
|
+
description: "init: artifact descriptors; attrs.path is indexed and scope checked."
|
|
1356
|
+
},
|
|
1357
|
+
budget: {
|
|
1358
|
+
type: "object",
|
|
1359
|
+
additionalProperties: true,
|
|
1360
|
+
description: "init: deadline/maxActions/maxAgents."
|
|
1361
|
+
},
|
|
1362
|
+
cell: {
|
|
1363
|
+
type: "string",
|
|
1364
|
+
description: "Cell id; a Cell binds on first use and workers inherit the parent Cell."
|
|
1365
|
+
},
|
|
1366
|
+
targetCell: {
|
|
1367
|
+
type: "string",
|
|
1368
|
+
description: "cell merge: open destination Cell."
|
|
1369
|
+
},
|
|
1370
|
+
brief: {
|
|
1371
|
+
type: "string",
|
|
1372
|
+
description: "cell: Markdown brief persisted under briefs/<cell>.md."
|
|
1373
|
+
},
|
|
1374
|
+
posture: {
|
|
1375
|
+
type: "string",
|
|
1376
|
+
description: "frontier: posture filter."
|
|
1377
|
+
},
|
|
1378
|
+
island: {
|
|
1379
|
+
type: "string",
|
|
1380
|
+
description: "frontier: route-island filter."
|
|
1381
|
+
},
|
|
1382
|
+
limit: {
|
|
1383
|
+
type: "number",
|
|
1384
|
+
description: "frontier/audit: result cap."
|
|
1385
|
+
},
|
|
1386
|
+
actionId: {
|
|
1387
|
+
type: "string",
|
|
1388
|
+
description: "claim/handoff: action id."
|
|
1389
|
+
},
|
|
1390
|
+
ttlSeconds: {
|
|
1391
|
+
type: "number",
|
|
1392
|
+
description: "claim/lease: TTL seconds, 10..86400."
|
|
1393
|
+
},
|
|
1394
|
+
operation: {
|
|
1395
|
+
type: "string",
|
|
1396
|
+
enum: [
|
|
1397
|
+
"acquire",
|
|
1398
|
+
"renew",
|
|
1399
|
+
"release",
|
|
1400
|
+
"open",
|
|
1401
|
+
"close",
|
|
1402
|
+
"merge",
|
|
1403
|
+
"request",
|
|
1404
|
+
"complete",
|
|
1405
|
+
"propose",
|
|
1406
|
+
"settle"
|
|
1407
|
+
],
|
|
1408
|
+
description: "claim/lease/cell/handoff/finish operation."
|
|
1409
|
+
},
|
|
1410
|
+
claimToken: {
|
|
1411
|
+
type: "string",
|
|
1412
|
+
description: "record/evidence/claim renew/release/handoff complete token."
|
|
1413
|
+
},
|
|
1414
|
+
token: {
|
|
1415
|
+
type: "string",
|
|
1416
|
+
description: "lease renew/release token; claimToken is preferred for claims."
|
|
1417
|
+
},
|
|
1418
|
+
node: {
|
|
1419
|
+
type: "object",
|
|
1420
|
+
additionalProperties: true,
|
|
1421
|
+
description: "record: node; Function/Finding ids are deterministic when omitted."
|
|
1422
|
+
},
|
|
1423
|
+
edge: {
|
|
1424
|
+
type: "object",
|
|
1425
|
+
additionalProperties: true,
|
|
1426
|
+
description: "record: edge; both endpoints must exist."
|
|
1427
|
+
},
|
|
1428
|
+
findingId: {
|
|
1429
|
+
type: "string",
|
|
1430
|
+
description: "evidence: Finding node id."
|
|
1431
|
+
},
|
|
1432
|
+
evidence: {
|
|
1433
|
+
type: "object",
|
|
1434
|
+
additionalProperties: true,
|
|
1435
|
+
description: "evidence: tool/command/inputHash plus outputHash or content; optional reproduction/artifactPath."
|
|
1436
|
+
},
|
|
1437
|
+
resource: {
|
|
1438
|
+
type: "string",
|
|
1439
|
+
description: "lease: resource key, checked against scope.resources."
|
|
1440
|
+
},
|
|
1441
|
+
findingIds: {
|
|
1442
|
+
type: "array",
|
|
1443
|
+
items: { type: "string" },
|
|
1444
|
+
description: "finish propose: independently verified finding ids."
|
|
1445
|
+
},
|
|
1446
|
+
note: {
|
|
1447
|
+
type: "string",
|
|
1448
|
+
description: "finish/handoff note."
|
|
1449
|
+
},
|
|
1450
|
+
factsWritten: {
|
|
1451
|
+
type: "array",
|
|
1452
|
+
items: { type: "string" },
|
|
1453
|
+
description: "handoff complete: fact/finding ids written."
|
|
1454
|
+
},
|
|
1455
|
+
leases: {
|
|
1456
|
+
type: "array",
|
|
1457
|
+
items: { type: "string" },
|
|
1458
|
+
description: "handoff complete: resource leases still held."
|
|
1459
|
+
},
|
|
1460
|
+
nextStep: {
|
|
1461
|
+
type: "string",
|
|
1462
|
+
description: "handoff complete: next safe action."
|
|
1463
|
+
},
|
|
1464
|
+
safeToStop: {
|
|
1465
|
+
type: "boolean",
|
|
1466
|
+
description: "handoff complete: whether the actor can stop safely."
|
|
1467
|
+
},
|
|
1468
|
+
format: {
|
|
1469
|
+
type: "string",
|
|
1470
|
+
enum: ["markdown", "json"],
|
|
1471
|
+
description: "report: output format."
|
|
1472
|
+
}
|
|
1473
|
+
},
|
|
1474
|
+
output: {
|
|
1475
|
+
schema: {
|
|
1476
|
+
type: "object",
|
|
1477
|
+
additionalProperties: false,
|
|
1478
|
+
properties: {
|
|
1479
|
+
ok: {
|
|
1480
|
+
type: "boolean",
|
|
1481
|
+
required: true
|
|
1482
|
+
},
|
|
1483
|
+
data: {
|
|
1484
|
+
type: "object",
|
|
1485
|
+
additionalProperties: true
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
},
|
|
1489
|
+
render(_args, value) {
|
|
1490
|
+
return [{
|
|
1491
|
+
type: "text",
|
|
1492
|
+
text: JSON.stringify(value, null, 2)
|
|
1493
|
+
}];
|
|
1494
|
+
}
|
|
1495
|
+
},
|
|
1496
|
+
async execute(args, exec) {
|
|
1497
|
+
const session = sessionOf(exec.agent);
|
|
1498
|
+
if (session === void 0) throw new ReverseError("NO_SESSION", "tool call has no session");
|
|
1499
|
+
const actor = asString(session.id);
|
|
1500
|
+
if (actor === void 0) throw new ReverseError("NO_SESSION", "calling session has no id");
|
|
1501
|
+
const sessions = deps.sessions?.();
|
|
1502
|
+
const plane = planeOfDepth(sessionDepth(session, sessions));
|
|
1503
|
+
const runId = rootSessionId(session, sessions);
|
|
1504
|
+
if (runId.length === 0) throw new ReverseError("NO_SESSION", "cannot find root session");
|
|
1505
|
+
const store = await storeFor(runId);
|
|
1506
|
+
const action = String(args.action ?? "");
|
|
1507
|
+
const parentActor = asString(session.header?.parentSession);
|
|
1508
|
+
const requestedCell = typeof args.cell === "string" ? args.cell : void 0;
|
|
1509
|
+
const bind = () => store.bindMember(actor, plane, parentActor, requestedCell);
|
|
1510
|
+
try {
|
|
1511
|
+
if (action === "init") {
|
|
1512
|
+
requirePlane(plane, ["steward"]);
|
|
1513
|
+
const goal = String(args.goal ?? "").trim();
|
|
1514
|
+
if (!goal) throw new ReverseError("INVALID_INPUT", "init needs a goal");
|
|
1515
|
+
return reply({
|
|
1516
|
+
runId,
|
|
1517
|
+
seq: (await store.init({
|
|
1518
|
+
goal,
|
|
1519
|
+
acceptance: typeof args.acceptance === "string" ? args.acceptance : "",
|
|
1520
|
+
engagement: args.engagement === "jeopardy" ? "jeopardy" : "reverse",
|
|
1521
|
+
flagFormat: typeof args.flagFormat === "string" ? args.flagFormat : void 0,
|
|
1522
|
+
authorization: typeof args.authorization === "string" ? args.authorization : "",
|
|
1523
|
+
roots: stringArray(args.roots),
|
|
1524
|
+
resources: stringArray(args.resources),
|
|
1525
|
+
deny: stringArray(args.deny),
|
|
1526
|
+
artifacts: arrayOfRecords(args.artifacts),
|
|
1527
|
+
budget: isRecord(args.budget) ? args.budget : void 0
|
|
1528
|
+
}, actor)).seq,
|
|
1529
|
+
frontier: store.frontier({ limit: 20 })
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
if (action === "frontier") {
|
|
1533
|
+
requirePlane(plane, workerPlanes);
|
|
1534
|
+
const member = await bind();
|
|
1535
|
+
return reply({
|
|
1536
|
+
runId,
|
|
1537
|
+
cell: member.cell,
|
|
1538
|
+
actions: store.frontier({
|
|
1539
|
+
cell: member.cell,
|
|
1540
|
+
posture: typeof args.posture === "string" ? args.posture : void 0,
|
|
1541
|
+
island: typeof args.island === "string" ? args.island : void 0,
|
|
1542
|
+
limit: typeof args.limit === "number" ? args.limit : void 0
|
|
1543
|
+
})
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
if (action === "claim") {
|
|
1547
|
+
requirePlane(plane, workerPlanes);
|
|
1548
|
+
await bind();
|
|
1549
|
+
const actionId = String(args.actionId ?? "");
|
|
1550
|
+
if (!actionId) throw new ReverseError("INVALID_INPUT", "claim needs actionId");
|
|
1551
|
+
const operation = args.operation === "renew" || args.operation === "release" ? args.operation : "acquire";
|
|
1552
|
+
return reply({
|
|
1553
|
+
runId,
|
|
1554
|
+
claim: await store.claim(actionId, actor, typeof args.ttlSeconds === "number" ? args.ttlSeconds : 900, operation, typeof args.claimToken === "string" ? args.claimToken : typeof args.token === "string" ? args.token : void 0)
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
if (action === "record") {
|
|
1558
|
+
requirePlane(plane, workerPlanes);
|
|
1559
|
+
await bind();
|
|
1560
|
+
const token = String(args.claimToken ?? "");
|
|
1561
|
+
const node = isRecord(args.node) ? args.node : void 0;
|
|
1562
|
+
const edge = isRecord(args.edge) ? args.edge : void 0;
|
|
1563
|
+
if (!token || !node && !edge) throw new ReverseError("INVALID_INPUT", "record needs claimToken and node/edge");
|
|
1564
|
+
return reply({
|
|
1565
|
+
runId,
|
|
1566
|
+
seq: (await store.record(token, actor, {
|
|
1567
|
+
node,
|
|
1568
|
+
edge
|
|
1569
|
+
})).seq
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
if (action === "evidence") {
|
|
1573
|
+
requirePlane(plane, workerPlanes);
|
|
1574
|
+
await bind();
|
|
1575
|
+
const token = String(args.claimToken ?? "");
|
|
1576
|
+
if (!token || !isRecord(args.evidence) || typeof args.findingId !== "string") throw new ReverseError("INVALID_INPUT", "evidence needs claimToken, findingId and evidence");
|
|
1577
|
+
const evidence = args.evidence;
|
|
1578
|
+
return reply({
|
|
1579
|
+
runId,
|
|
1580
|
+
evidence: await store.evidence(token, actor, {
|
|
1581
|
+
findingId: args.findingId,
|
|
1582
|
+
tool: String(evidence.tool ?? ""),
|
|
1583
|
+
command: String(evidence.command ?? ""),
|
|
1584
|
+
toolVersion: String(evidence.toolVersion ?? ""),
|
|
1585
|
+
inputHash: String(evidence.inputHash ?? ""),
|
|
1586
|
+
outputHash: typeof evidence.outputHash === "string" ? evidence.outputHash : void 0,
|
|
1587
|
+
offset: typeof evidence.offset === "string" ? evidence.offset : void 0,
|
|
1588
|
+
artifactPath: typeof evidence.artifactPath === "string" ? evidence.artifactPath : void 0,
|
|
1589
|
+
content: typeof evidence.content === "string" ? evidence.content : void 0,
|
|
1590
|
+
reproduction: stringArray(evidence.reproduction)
|
|
1591
|
+
})
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
if (action === "cell") {
|
|
1595
|
+
requirePlane(plane, ["steward", "cell"]);
|
|
1596
|
+
if (plane === "cell") await bind();
|
|
1597
|
+
const operation = String(args.operation ?? "");
|
|
1598
|
+
if (![
|
|
1599
|
+
"open",
|
|
1600
|
+
"close",
|
|
1601
|
+
"merge"
|
|
1602
|
+
].includes(operation) || !requestedCell) throw new ReverseError("INVALID_INPUT", "cell needs cell and open/close/merge");
|
|
1603
|
+
return reply({
|
|
1604
|
+
runId,
|
|
1605
|
+
seq: (await store.cell(operation, requestedCell, actor, typeof args.targetCell === "string" ? args.targetCell : void 0, typeof args.brief === "string" ? args.brief : void 0)).seq
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
if (action === "lease") {
|
|
1609
|
+
requirePlane(plane, workerPlanes);
|
|
1610
|
+
await bind();
|
|
1611
|
+
const operation = String(args.operation ?? "");
|
|
1612
|
+
const resource = String(args.resource ?? "");
|
|
1613
|
+
if (![
|
|
1614
|
+
"acquire",
|
|
1615
|
+
"renew",
|
|
1616
|
+
"release"
|
|
1617
|
+
].includes(operation) || !resource) throw new ReverseError("INVALID_INPUT", "lease needs resource and acquire/renew/release");
|
|
1618
|
+
return reply({
|
|
1619
|
+
runId,
|
|
1620
|
+
lease: await store.lease(operation, resource, actor, typeof args.ttlSeconds === "number" ? args.ttlSeconds : 600, typeof args.token === "string" ? args.token : void 0)
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
if (action === "handoff") {
|
|
1624
|
+
const operation = String(args.operation ?? "");
|
|
1625
|
+
if (operation === "request") {
|
|
1626
|
+
requirePlane(plane, ["steward"]);
|
|
1627
|
+
return reply({
|
|
1628
|
+
runId,
|
|
1629
|
+
handoff: await store.requestHandoff(String(args.actionId ?? ""), actor, typeof args.note === "string" ? args.note : "")
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
requirePlane(plane, workerPlanes);
|
|
1633
|
+
await bind();
|
|
1634
|
+
if (operation !== "complete") throw new ReverseError("INVALID_INPUT", "handoff needs request/complete");
|
|
1635
|
+
return reply({
|
|
1636
|
+
runId,
|
|
1637
|
+
handoff: await store.completeHandoff(String(args.claimToken ?? ""), actor, {
|
|
1638
|
+
note: typeof args.note === "string" ? args.note : void 0,
|
|
1639
|
+
factsWritten: stringArray(args.factsWritten),
|
|
1640
|
+
leases: stringArray(args.leases),
|
|
1641
|
+
nextStep: typeof args.nextStep === "string" ? args.nextStep : "",
|
|
1642
|
+
safeToStop: args.safeToStop === true
|
|
1643
|
+
})
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
if (action === "watchdog") {
|
|
1647
|
+
requirePlane(plane, ["steward"]);
|
|
1648
|
+
return reply({
|
|
1649
|
+
runId,
|
|
1650
|
+
...await store.watchdog(actor)
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
if (action === "finish") {
|
|
1654
|
+
const operation = String(args.operation ?? "");
|
|
1655
|
+
if (operation === "settle") {
|
|
1656
|
+
requirePlane(plane, ["steward"]);
|
|
1657
|
+
return reply({
|
|
1658
|
+
runId,
|
|
1659
|
+
finish: await store.finish("settle", actor)
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
requirePlane(plane, workerPlanes);
|
|
1663
|
+
await bind();
|
|
1664
|
+
if (operation !== "propose") throw new ReverseError("INVALID_INPUT", "finish needs propose/settle");
|
|
1665
|
+
return reply({
|
|
1666
|
+
runId,
|
|
1667
|
+
finish: await store.finish("propose", actor, stringArray(args.findingIds), typeof args.note === "string" ? args.note : "")
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
if (action === "report") {
|
|
1671
|
+
requirePlane(plane, ["steward"]);
|
|
1672
|
+
const format = args.format === "json" ? "json" : "markdown";
|
|
1673
|
+
return reply({
|
|
1674
|
+
runId,
|
|
1675
|
+
format,
|
|
1676
|
+
report: store.report(format)
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
if (action === "audit") {
|
|
1680
|
+
requirePlane(plane, ["steward"]);
|
|
1681
|
+
return reply({
|
|
1682
|
+
runId,
|
|
1683
|
+
events: store.audit(typeof args.limit === "number" ? args.limit : 50)
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
throw new ReverseError("INVALID_INPUT", `unknown action ${action}`);
|
|
1687
|
+
} catch (error) {
|
|
1688
|
+
if (error instanceof ReverseError) await store.denied(actor, action, error.code, error.message).catch(() => void 0);
|
|
1689
|
+
throw error;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
//#endregion
|
|
1695
|
+
//#region src/host/runtime/reverse/index.ts
|
|
1696
|
+
/**
|
|
1697
|
+
* Host installer for the reverse preset row.
|
|
1698
|
+
*
|
|
1699
|
+
* This module is imported only by src/entries/reverse-board.ts, which is mounted
|
|
1700
|
+
* only by presets/reverse. It is not imported by src/index.ts, so reverse_board
|
|
1701
|
+
* never appears in another preset's tool catalog.
|
|
1702
|
+
*
|
|
1703
|
+
* @module dsh-chatgpt-subscription/host/runtime/reverse/index
|
|
1704
|
+
*/
|
|
1705
|
+
function installReverseBoard(host) {
|
|
1706
|
+
const tools = host.get("tools");
|
|
1707
|
+
if (tools === void 0 || typeof tools.register !== "function") {
|
|
1708
|
+
host.logger?.info?.("[dsh-chatgpt-subscription] reverse-board inactive: no tools registry");
|
|
1709
|
+
return () => void 0;
|
|
1710
|
+
}
|
|
1711
|
+
const sessions = () => host.get("sessions");
|
|
1712
|
+
const dispose = tools.register(createReverseTool({ sessions }));
|
|
1713
|
+
host.logger?.info?.(`[dsh-chatgpt-subscription] ${REVERSE_BOARD_TOOL} mounted by the reverse preset`);
|
|
1714
|
+
return () => {
|
|
1715
|
+
if (typeof dispose === "function") dispose();
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/entries/reverse-board.ts
|
|
1720
|
+
const name = "dsh-chatgpt-subscription-reverse-board";
|
|
1721
|
+
const inject = [];
|
|
1722
|
+
function apply(ctx) {
|
|
1723
|
+
ctx.effect(() => installReverseBoard(ctx), "dsh-chatgpt-subscription: reverse-board");
|
|
1724
|
+
}
|
|
1725
|
+
//#endregion
|
|
1726
|
+
export { apply, inject, name };
|