@primitive.ai/prim 0.1.0-alpha.11 → 0.1.0-alpha.111
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 +450 -38
- package/SKILL.md +366 -0
- package/dist/chunk-2IRLFOEL.js +766 -0
- package/dist/chunk-2Q3OGSTV.js +164 -0
- package/dist/chunk-43ZKL27W.js +258 -0
- package/dist/chunk-4GLVJLEQ.js +55 -0
- package/dist/chunk-5BLGBSDM.js +233 -0
- package/dist/chunk-5LRKJTLA.js +155 -0
- package/dist/chunk-7VIMU2HR.js +209 -0
- package/dist/chunk-AOJ254C2.js +511 -0
- package/dist/chunk-CTRAJCPN.js +964 -0
- package/dist/chunk-EZXEWFDG.js +210 -0
- package/dist/chunk-GA2RXPJL.js +168 -0
- package/dist/chunk-HTRFPXMD.js +135 -0
- package/dist/chunk-IQZA65NV.js +1871 -0
- package/dist/chunk-JJI7FU24.js +439 -0
- package/dist/chunk-KGBMU76T.js +175 -0
- package/dist/chunk-KQ4WBK5R.js +262 -0
- package/dist/chunk-NH3VC7YO.js +264 -0
- package/dist/chunk-OYHYCK4K.js +13 -0
- package/dist/chunk-PO5QAYD7.js +1499 -0
- package/dist/chunk-UDBBJWQH.js +20383 -0
- package/dist/chunk-W4ZEPZLK.js +36 -0
- package/dist/chunk-XG7S3LIL.js +1372 -0
- package/dist/daemon/server.js +24051 -0
- package/dist/hook-runtime/daemon/server.js +24051 -0
- package/dist/hook-runtime/hooks/post-commit.js +21524 -0
- package/dist/hook-runtime/hooks/post-rewrite.js +21423 -0
- package/dist/hook-runtime/hooks/post-tool-use.js +28917 -0
- package/dist/hook-runtime/hooks/pre-commit.js +1657 -0
- package/dist/hook-runtime/hooks/pre-tool-use.js +28425 -0
- package/dist/hook-runtime/hooks/prim-hook.js +28977 -0
- package/dist/hook-runtime/hooks/session-end.js +1176 -0
- package/dist/hook-runtime/hooks/session-start.js +31553 -0
- package/dist/hook-runtime/index.js +59630 -0
- package/dist/hook-runtime/statusline-main.js +886 -0
- package/dist/hooks/post-commit.js +196 -0
- package/dist/hooks/post-rewrite.js +205 -0
- package/dist/hooks/post-tool-use.js +292 -0
- package/dist/hooks/pre-commit.js +15 -108
- package/dist/hooks/pre-tool-use.js +470 -0
- package/dist/hooks/prim-hook.js +242 -0
- package/dist/hooks/session-end.js +64 -0
- package/dist/hooks/session-start.js +309 -0
- package/dist/index.js +10651 -427
- package/dist/statusline-main.js +886 -0
- package/package.json +41 -16
- package/dist/chunk-3APLWTLB.js +0 -165
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isDemoStatusResponse
|
|
3
|
+
} from "./chunk-UDBBJWQH.js";
|
|
4
|
+
import {
|
|
5
|
+
inspectHookRuntime
|
|
6
|
+
} from "./chunk-PO5QAYD7.js";
|
|
7
|
+
import {
|
|
8
|
+
atomicWriteFile,
|
|
9
|
+
primConfigDirectory,
|
|
10
|
+
withFileLock,
|
|
11
|
+
withFileLockSync
|
|
12
|
+
} from "./chunk-XG7S3LIL.js";
|
|
13
|
+
|
|
14
|
+
// src/demo/state.ts
|
|
15
|
+
import { createHash, randomUUID } from "crypto";
|
|
16
|
+
import { existsSync, lstatSync, readFileSync, readdirSync } from "fs";
|
|
17
|
+
import { join, resolve } from "path";
|
|
18
|
+
var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
19
|
+
var demoDirectory = () => join(primConfigDirectory(), "demo");
|
|
20
|
+
var runPath = (id) => {
|
|
21
|
+
if (!RUN_ID.test(id)) throw new Error("invalid demo run ID");
|
|
22
|
+
return join(demoDirectory(), "runs", `${id}.json`);
|
|
23
|
+
};
|
|
24
|
+
function readDemoJson(path) {
|
|
25
|
+
const stat = lstatSync(path);
|
|
26
|
+
if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
|
|
27
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
28
|
+
}
|
|
29
|
+
function saveDemoJson(path, value) {
|
|
30
|
+
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
31
|
+
`, { mode: 384, ensureParent: true });
|
|
32
|
+
}
|
|
33
|
+
function readRun(id) {
|
|
34
|
+
const run = readDemoJson(runPath(id));
|
|
35
|
+
if (![1, 2].includes(run.version) || run.id !== id || ![
|
|
36
|
+
"prepared",
|
|
37
|
+
"proposal",
|
|
38
|
+
"conflict",
|
|
39
|
+
"prompt",
|
|
40
|
+
"approved",
|
|
41
|
+
"applied",
|
|
42
|
+
"cleanup",
|
|
43
|
+
"completed",
|
|
44
|
+
"skipped"
|
|
45
|
+
].includes(run.stage) || run.needsStatus !== void 0 && typeof run.needsStatus !== "boolean" || run.server !== void 0 && !isDemoStatusResponse(run.server) || run.receipt !== void 0 && (!Number.isSafeInteger(run.receipt.revision) || run.receipt.revision < 0 || !/^[a-f0-9]{64}$/u.test(run.receipt.appliedDigest)) || typeof run.terminal !== "boolean" || !Array.isArray(run.launcher) || run.launcher.length !== 2 || run.launcher.some((value) => typeof value !== "string" || !value.startsWith("/")) || run.agent !== void 0 && !["claude_code", "codex", "cursor", "hermes"].includes(run.agent)) {
|
|
46
|
+
throw new Error("invalid demo run state");
|
|
47
|
+
}
|
|
48
|
+
return run;
|
|
49
|
+
}
|
|
50
|
+
var saveRun = (run) => saveDemoJson(runPath(run.id), run);
|
|
51
|
+
var lockRun = (id, action) => withFileLockSync(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
|
|
52
|
+
function prepareRun(agent, terminal = false) {
|
|
53
|
+
const run = {
|
|
54
|
+
version: 2,
|
|
55
|
+
id: randomUUID(),
|
|
56
|
+
stage: "prepared",
|
|
57
|
+
terminal,
|
|
58
|
+
agent,
|
|
59
|
+
preparationKey: preparationKey(agent),
|
|
60
|
+
launcher: [process.execPath, resolve(process.argv[1])]
|
|
61
|
+
};
|
|
62
|
+
saveRun(run);
|
|
63
|
+
return run;
|
|
64
|
+
}
|
|
65
|
+
function preparationKey(agent) {
|
|
66
|
+
return agent === "codex" && process.env.CODEX_THREAD_ID ? sessionKey(agent, `${process.env.CODEX_THREAD_ID}\0${process.cwd()}`) : void 0;
|
|
67
|
+
}
|
|
68
|
+
var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
69
|
+
function demoCommand(run, action, choice, reason) {
|
|
70
|
+
return [
|
|
71
|
+
...run.launcher,
|
|
72
|
+
"demo",
|
|
73
|
+
action,
|
|
74
|
+
run.id,
|
|
75
|
+
...choice === void 0 ? [] : ["--choice", choice],
|
|
76
|
+
...reason === void 0 ? [] : ["--reason", reason]
|
|
77
|
+
].map(quote).join(" ");
|
|
78
|
+
}
|
|
79
|
+
function demoWelcomeCommand(run) {
|
|
80
|
+
return [
|
|
81
|
+
process.execPath,
|
|
82
|
+
resolve(process.argv[1]),
|
|
83
|
+
"welcome",
|
|
84
|
+
"--after-demo",
|
|
85
|
+
...run.agent ? ["--agent", run.agent === "claude_code" ? "claude" : run.agent] : [],
|
|
86
|
+
...run.binding ? ["--capture-excluded"] : []
|
|
87
|
+
].map(quote).join(" ");
|
|
88
|
+
}
|
|
89
|
+
function demoDiagnosticCommand(run) {
|
|
90
|
+
return [process.execPath, resolve(process.argv[1]), "demo", "status", run.id].map(quote).join(" ");
|
|
91
|
+
}
|
|
92
|
+
function demoResumeCommand(run) {
|
|
93
|
+
return [process.execPath, resolve(process.argv[1]), "demo", "resume", run.id].map(quote).join(" ");
|
|
94
|
+
}
|
|
95
|
+
function onboardingFinished() {
|
|
96
|
+
const path = join(demoDirectory(), "onboarding.json");
|
|
97
|
+
if (!existsSync(path)) return false;
|
|
98
|
+
const value = readDemoJson(path);
|
|
99
|
+
if (value.outcome !== "completed" && value.outcome !== "skipped") {
|
|
100
|
+
throw new Error("invalid local onboarding outcome");
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
function finishOnboarding(outcome) {
|
|
105
|
+
saveDemoJson(join(demoDirectory(), "onboarding.json"), { outcome });
|
|
106
|
+
}
|
|
107
|
+
function pendingRuns() {
|
|
108
|
+
const path = join(demoDirectory(), "runs");
|
|
109
|
+
if (!existsSync(path)) return [];
|
|
110
|
+
return readdirSync(path).filter((name) => name.endsWith(".json") && RUN_ID.test(name.slice(0, -5))).map((name) => name.slice(0, -5)).filter((id) => !["completed", "skipped"].includes(readRun(id).stage));
|
|
111
|
+
}
|
|
112
|
+
function sessionKey(agent, session) {
|
|
113
|
+
return createHash("sha256").update(`${agent}\0${session}`).digest("hex");
|
|
114
|
+
}
|
|
115
|
+
function exclusionPath(key) {
|
|
116
|
+
if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
|
|
117
|
+
return join(demoDirectory(), "excluded-sessions", `${key}.json`);
|
|
118
|
+
}
|
|
119
|
+
function sessionExcluded(agent, session) {
|
|
120
|
+
if (typeof session !== "string" || !session) return false;
|
|
121
|
+
const path = exclusionPath(sessionKey(agent, session));
|
|
122
|
+
if (!existsSync(path)) return false;
|
|
123
|
+
const record = readDemoJson(path);
|
|
124
|
+
if (typeof record.runId !== "string" || !RUN_ID.test(record.runId)) {
|
|
125
|
+
throw new Error("invalid demo capture exclusion");
|
|
126
|
+
}
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
var lockRunAsync = (id, action) => withFileLock(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
|
|
130
|
+
function demoArgv(command) {
|
|
131
|
+
const result = [];
|
|
132
|
+
let i = 0;
|
|
133
|
+
while (i < command.length) {
|
|
134
|
+
if (command[i++] !== "'") return;
|
|
135
|
+
let value = "";
|
|
136
|
+
let closed = false;
|
|
137
|
+
while (i < command.length) {
|
|
138
|
+
if (command.slice(i, i + 4) === "'\\''") {
|
|
139
|
+
value += "'";
|
|
140
|
+
i += 4;
|
|
141
|
+
} else if (command[i] === "'") {
|
|
142
|
+
i++;
|
|
143
|
+
closed = true;
|
|
144
|
+
break;
|
|
145
|
+
} else {
|
|
146
|
+
value += command[i++];
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!closed) return;
|
|
150
|
+
result.push(value);
|
|
151
|
+
if (i === command.length) return result;
|
|
152
|
+
if (command[i++] !== " " || i === command.length) return;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/demo/diagnostics.ts
|
|
157
|
+
import { existsSync as existsSync2 } from "fs";
|
|
158
|
+
import { join as join2 } from "path";
|
|
159
|
+
var observationPath = (id) => join2(demoDirectory(), "observations", `${id}.json`);
|
|
160
|
+
function observeRun(id, observation) {
|
|
161
|
+
try {
|
|
162
|
+
saveDemoJson(observationPath(id), observation);
|
|
163
|
+
} catch {
|
|
164
|
+
process.stderr.write(
|
|
165
|
+
"[prim] demo isolation diagnostic could not be saved; check access to Primitive's configuration directory.\n"
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function isolationDiagnostics(run) {
|
|
170
|
+
let observation;
|
|
171
|
+
let observationError;
|
|
172
|
+
try {
|
|
173
|
+
if (existsSync2(observationPath(run.id))) {
|
|
174
|
+
const value = readDemoJson(observationPath(run.id));
|
|
175
|
+
if (!value || !Number.isFinite(value.at) || !["claude_code", "codex", "cursor", "hermes"].includes(value.agent ?? "") || ![
|
|
176
|
+
"acknowledged",
|
|
177
|
+
"tool-mismatch",
|
|
178
|
+
"command-mismatch",
|
|
179
|
+
"session-mismatch",
|
|
180
|
+
"session-missing",
|
|
181
|
+
"write-failed"
|
|
182
|
+
].includes(value.result ?? "") || value.runtimeVersion !== void 0 && !/^[a-zA-Z0-9.+-]{1,80}$/u.test(value.runtimeVersion) || value.session !== void 0 && !/^[a-f0-9]{64}$/u.test(value.session) || value.errorCode !== void 0 && !/^[A-Z0-9_]{1,32}$/u.test(value.errorCode))
|
|
183
|
+
throw new Error("invalid demo observation");
|
|
184
|
+
observation = value;
|
|
185
|
+
}
|
|
186
|
+
} catch {
|
|
187
|
+
observationError = "unreadable";
|
|
188
|
+
}
|
|
189
|
+
const expected = run.agent === "codex" && process.env.CODEX_THREAD_ID ? sessionKey(run.agent, process.env.CODEX_THREAD_ID) : void 0;
|
|
190
|
+
return {
|
|
191
|
+
runtime: inspectHookRuntime(),
|
|
192
|
+
expectedEvent: "PreToolUse",
|
|
193
|
+
expectedTool: run.agent === "cursor" ? "Shell" : run.agent === "hermes" ? "terminal" : "Bash",
|
|
194
|
+
hookObservation: observation ? {
|
|
195
|
+
at: observation.at,
|
|
196
|
+
agent: observation.agent,
|
|
197
|
+
runtimeVersion: observation.runtimeVersion ?? "unknown",
|
|
198
|
+
result: observation.result,
|
|
199
|
+
ageMs: Math.max(0, Date.now() - observation.at),
|
|
200
|
+
sessionMatches: expected ? observation.session === expected : "unknown",
|
|
201
|
+
...observation.errorCode ? { errorCode: observation.errorCode } : {}
|
|
202
|
+
} : null,
|
|
203
|
+
...observationError ? { observationError } : {},
|
|
204
|
+
trust: "unknown",
|
|
205
|
+
capture: run.binding ? "excluded-for-bound-session" : "not-verified"
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export {
|
|
210
|
+
RUN_ID,
|
|
211
|
+
runPath,
|
|
212
|
+
readDemoJson,
|
|
213
|
+
saveDemoJson,
|
|
214
|
+
readRun,
|
|
215
|
+
saveRun,
|
|
216
|
+
lockRun,
|
|
217
|
+
prepareRun,
|
|
218
|
+
preparationKey,
|
|
219
|
+
demoCommand,
|
|
220
|
+
demoWelcomeCommand,
|
|
221
|
+
demoDiagnosticCommand,
|
|
222
|
+
demoResumeCommand,
|
|
223
|
+
onboardingFinished,
|
|
224
|
+
finishOnboarding,
|
|
225
|
+
pendingRuns,
|
|
226
|
+
sessionKey,
|
|
227
|
+
exclusionPath,
|
|
228
|
+
sessionExcluded,
|
|
229
|
+
lockRunAsync,
|
|
230
|
+
demoArgv,
|
|
231
|
+
observeRun,
|
|
232
|
+
isolationDiagnostics
|
|
233
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import {
|
|
2
|
+
decodeJwtPayload,
|
|
3
|
+
primConfigDirectory,
|
|
4
|
+
resolveAuthCredential
|
|
5
|
+
} from "./chunk-XG7S3LIL.js";
|
|
6
|
+
|
|
7
|
+
// src/daemon/client.ts
|
|
8
|
+
import { createConnection } from "net";
|
|
9
|
+
import { join } from "path";
|
|
10
|
+
|
|
11
|
+
// src/daemon/principal.ts
|
|
12
|
+
import { createHash } from "crypto";
|
|
13
|
+
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
14
|
+
function boundedClaim(value) {
|
|
15
|
+
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
16
|
+
}
|
|
17
|
+
function sha256(value) {
|
|
18
|
+
return createHash("sha256").update(value).digest("hex");
|
|
19
|
+
}
|
|
20
|
+
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
21
|
+
if (!token) return void 0;
|
|
22
|
+
const payload = decodeJwtPayload(token);
|
|
23
|
+
const subject = boundedClaim(payload?.sub);
|
|
24
|
+
const organizationId = boundedClaim(payload?.org_id);
|
|
25
|
+
if (!(subject && organizationId)) return void 0;
|
|
26
|
+
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
27
|
+
return {
|
|
28
|
+
principalId: sha256(`${issuer}\0${subject}`),
|
|
29
|
+
organizationId,
|
|
30
|
+
credentialFingerprint: sha256(token)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function daemonPrincipalsMatch(caller, daemon) {
|
|
34
|
+
return caller !== void 0 && daemon !== void 0 && caller.principalId === daemon.principalId && caller.organizationId === daemon.organizationId && caller.credentialFingerprint === daemon.credentialFingerprint;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/daemon/protocol.ts
|
|
38
|
+
var DAEMON_JSON_REQUEST_MAX_BYTES = 64 * 1024;
|
|
39
|
+
var DAEMON_JSON_RESPONSE_MAX_BYTES = 8 * 1024 * 1024;
|
|
40
|
+
function isRecord(value) {
|
|
41
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
42
|
+
}
|
|
43
|
+
function parseDaemonResponseEnvelope(value) {
|
|
44
|
+
if (!isRecord(value)) return void 0;
|
|
45
|
+
if (!(typeof value.id === "number" && Number.isSafeInteger(value.id) && value.id >= 0)) {
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
if (typeof value.ok !== "boolean") return void 0;
|
|
49
|
+
if (value.error !== void 0 && typeof value.error !== "string") return void 0;
|
|
50
|
+
return {
|
|
51
|
+
id: value.id,
|
|
52
|
+
ok: value.ok,
|
|
53
|
+
...value.result === void 0 ? {} : { result: value.result },
|
|
54
|
+
...value.error === void 0 ? {} : { error: value.error }
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/daemon/client.ts
|
|
59
|
+
var SOCK_PATH = join(primConfigDirectory(), "sock");
|
|
60
|
+
var DEFAULT_TIMEOUT_MS = 250;
|
|
61
|
+
var nextRequestId = 1;
|
|
62
|
+
function daemonRequest(method, params = {}, opts = {}) {
|
|
63
|
+
const id = nextRequestId++;
|
|
64
|
+
const caller = resolveDaemonPrincipal();
|
|
65
|
+
const request = {
|
|
66
|
+
id,
|
|
67
|
+
method,
|
|
68
|
+
params,
|
|
69
|
+
...caller ? { caller } : {}
|
|
70
|
+
};
|
|
71
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
72
|
+
return new Promise((resolve) => {
|
|
73
|
+
let settled = false;
|
|
74
|
+
let socket;
|
|
75
|
+
let buffer = Buffer.alloc(0);
|
|
76
|
+
const settle = (value) => {
|
|
77
|
+
if (settled) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
settled = true;
|
|
81
|
+
if (socket) {
|
|
82
|
+
try {
|
|
83
|
+
socket.destroy();
|
|
84
|
+
} catch {
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
resolve(value);
|
|
88
|
+
};
|
|
89
|
+
const timer = setTimeout(() => settle(null), timeoutMs);
|
|
90
|
+
timer.unref();
|
|
91
|
+
try {
|
|
92
|
+
socket = createConnection(SOCK_PATH);
|
|
93
|
+
} catch {
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
settle(null);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
socket.on("error", () => {
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
settle(null);
|
|
101
|
+
});
|
|
102
|
+
socket.on("connect", () => {
|
|
103
|
+
try {
|
|
104
|
+
socket?.write(`${JSON.stringify(request)}
|
|
105
|
+
`);
|
|
106
|
+
} catch {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
settle(null);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
socket.on("data", (chunk) => {
|
|
112
|
+
buffer = Buffer.concat([buffer, Buffer.from(chunk)]);
|
|
113
|
+
if (buffer.length > DAEMON_JSON_RESPONSE_MAX_BYTES) {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
settle(null);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const newlineIdx = buffer.indexOf(10);
|
|
119
|
+
if (newlineIdx === -1) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const line = buffer.subarray(0, newlineIdx).toString("utf8");
|
|
123
|
+
try {
|
|
124
|
+
const res = parseDaemonResponseEnvelope(JSON.parse(line));
|
|
125
|
+
if (!res || res.id !== id) {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
settle(null);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
settle(res.ok && res.result !== void 0 ? res.result : null);
|
|
132
|
+
} catch {
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
settle(null);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
socket.on("end", () => {
|
|
138
|
+
if (!settled) {
|
|
139
|
+
clearTimeout(timer);
|
|
140
|
+
settle(null);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
async function daemonIsLive(timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
146
|
+
const result = await daemonRequest("ping", {}, { timeoutMs });
|
|
147
|
+
return result?.pong === true;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export {
|
|
151
|
+
resolveDaemonPrincipal,
|
|
152
|
+
daemonPrincipalsMatch,
|
|
153
|
+
daemonRequest,
|
|
154
|
+
daemonIsLive
|
|
155
|
+
};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getClient,
|
|
3
|
+
isTerminalSafeText,
|
|
4
|
+
terminalSafeLine,
|
|
5
|
+
terminalSafeText
|
|
6
|
+
} from "./chunk-2IRLFOEL.js";
|
|
7
|
+
|
|
8
|
+
// src/decisions/feedback.ts
|
|
9
|
+
var FEEDBACK_PROTOCOL_VERSION = 2;
|
|
10
|
+
var FEEDBACK_MIN_PROTOCOL_VERSION = 1;
|
|
11
|
+
var FEEDBACK_DEADLINE_MS = 3e3;
|
|
12
|
+
var MAX_FEEDBACK_EVENTS = 40;
|
|
13
|
+
var MAX_FEEDBACK_MESSAGE_CODE_POINTS = 8e3;
|
|
14
|
+
var MAX_FEEDBACK_INTENT_CODE_POINTS = 180;
|
|
15
|
+
var LEASE_PATH = "/api/cli/decisions/feedback/lease";
|
|
16
|
+
var ACK_PATH = "/api/cli/decisions/feedback/ack";
|
|
17
|
+
var STATUS_PATH = "/api/cli/decisions/feedback/status";
|
|
18
|
+
var SHORT_ID = /^[0-9a-f]{8}$/u;
|
|
19
|
+
var MAX_EVENT_ID_CHARS = 128;
|
|
20
|
+
var MAX_RAW_INTENT_CODE_UNITS = 512;
|
|
21
|
+
var MAX_FEEDBACK_WEB_URL_CHARS = 2048;
|
|
22
|
+
var SAFE_PUBLISH_DECISION_ID = /^[A-Za-z0-9_-]+$/u;
|
|
23
|
+
function isRecord(value) {
|
|
24
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
function isSupportedProtocolVersion(value) {
|
|
27
|
+
return Number.isSafeInteger(value) && Number(value) >= FEEDBACK_MIN_PROTOCOL_VERSION && Number(value) <= FEEDBACK_PROTOCOL_VERSION;
|
|
28
|
+
}
|
|
29
|
+
function normalizeFeedbackIntent(value) {
|
|
30
|
+
const withoutControls = terminalSafeLine(value);
|
|
31
|
+
const points = Array.from(withoutControls);
|
|
32
|
+
if (points.length <= MAX_FEEDBACK_INTENT_CODE_POINTS) {
|
|
33
|
+
return withoutControls;
|
|
34
|
+
}
|
|
35
|
+
return `${points.slice(0, MAX_FEEDBACK_INTENT_CODE_POINTS - 1).join("")}\u2026`;
|
|
36
|
+
}
|
|
37
|
+
function parseFeedbackWebUrl(value) {
|
|
38
|
+
if (typeof value !== "string" || value.length === 0 || value.length > MAX_FEEDBACK_WEB_URL_CHARS || !/^https:\/\//iu.test(value) || /\s/u.test(value) || !isTerminalSafeText(value)) {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const url = new URL(value);
|
|
43
|
+
if (url.protocol !== "https:" || !url.hostname || url.username.length > 0 || url.password.length > 0) {
|
|
44
|
+
return void 0;
|
|
45
|
+
}
|
|
46
|
+
} catch {
|
|
47
|
+
return void 0;
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
function parseFeedbackDecisionId(value) {
|
|
52
|
+
if (typeof value !== "string" || value.length === 0 || value.length > MAX_EVENT_ID_CHARS || terminalSafeText(value) !== value || !SAFE_PUBLISH_DECISION_ID.test(value)) {
|
|
53
|
+
return void 0;
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
function parseEvent(value, protocolVersion) {
|
|
58
|
+
if (!isRecord(value)) return void 0;
|
|
59
|
+
if (typeof value.eventId !== "string" || value.eventId.length === 0 || value.eventId.length > MAX_EVENT_ID_CHARS || terminalSafeText(value.eventId) !== value.eventId) {
|
|
60
|
+
return void 0;
|
|
61
|
+
}
|
|
62
|
+
if (!Number.isSafeInteger(value.leaseVersion) || Number(value.leaseVersion) < 1) {
|
|
63
|
+
return void 0;
|
|
64
|
+
}
|
|
65
|
+
if (typeof value.shortId !== "string" || !SHORT_ID.test(value.shortId)) {
|
|
66
|
+
return void 0;
|
|
67
|
+
}
|
|
68
|
+
if (typeof value.intent !== "string" || value.intent.length > MAX_RAW_INTENT_CODE_UNITS) {
|
|
69
|
+
return void 0;
|
|
70
|
+
}
|
|
71
|
+
const intent = normalizeFeedbackIntent(value.intent);
|
|
72
|
+
if (!intent) return void 0;
|
|
73
|
+
const webUrl = value.webUrl === void 0 ? void 0 : parseFeedbackWebUrl(value.webUrl);
|
|
74
|
+
if (value.webUrl !== void 0 && webUrl === void 0) return void 0;
|
|
75
|
+
const kind = value.kind === void 0 && protocolVersion === 1 ? "confirm_prompt" : value.kind;
|
|
76
|
+
if (kind !== "confirm_prompt" && kind !== "publish_prompt") return void 0;
|
|
77
|
+
if (protocolVersion === 1 && kind === "publish_prompt") return void 0;
|
|
78
|
+
const decisionId = value.decisionId === void 0 ? void 0 : parseFeedbackDecisionId(value.decisionId);
|
|
79
|
+
if (value.decisionId !== void 0 && decisionId === void 0) return void 0;
|
|
80
|
+
if (decisionId !== void 0 && (protocolVersion !== 2 || kind !== "publish_prompt")) {
|
|
81
|
+
return void 0;
|
|
82
|
+
}
|
|
83
|
+
if (protocolVersion === 2 && kind === "publish_prompt" && decisionId === void 0) {
|
|
84
|
+
return void 0;
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
eventId: value.eventId,
|
|
88
|
+
leaseVersion: Number(value.leaseVersion),
|
|
89
|
+
shortId: value.shortId,
|
|
90
|
+
intent,
|
|
91
|
+
...webUrl === void 0 ? {} : { webUrl },
|
|
92
|
+
...decisionId === void 0 ? {} : { decisionId },
|
|
93
|
+
kind
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function parseFeedbackLease(value) {
|
|
97
|
+
if (!isRecord(value) || !isSupportedProtocolVersion(value.protocolVersion)) return void 0;
|
|
98
|
+
const protocolVersion = value.protocolVersion;
|
|
99
|
+
if (value.status === "empty") {
|
|
100
|
+
return value.hasMore === false ? { protocolVersion, events: [], hasMore: false } : void 0;
|
|
101
|
+
}
|
|
102
|
+
if (value.status === "unavailable") {
|
|
103
|
+
return value.reason === "organization_unbound" ? { protocolVersion, events: [], hasMore: false } : void 0;
|
|
104
|
+
}
|
|
105
|
+
if (value.status !== "leased" || typeof value.hasMore !== "boolean") return void 0;
|
|
106
|
+
if (!Array.isArray(value.events) || value.events.length === 0 || value.events.length > MAX_FEEDBACK_EVENTS) {
|
|
107
|
+
return void 0;
|
|
108
|
+
}
|
|
109
|
+
const events = value.events.map((event) => parseEvent(event, protocolVersion));
|
|
110
|
+
if (events.some((event) => event === void 0)) return void 0;
|
|
111
|
+
const parsedEvents = events;
|
|
112
|
+
if (new Set(parsedEvents.map((event) => event.eventId)).size !== parsedEvents.length) {
|
|
113
|
+
return void 0;
|
|
114
|
+
}
|
|
115
|
+
return { protocolVersion, events: parsedEvents, hasMore: value.hasMore };
|
|
116
|
+
}
|
|
117
|
+
function renderFeedback(lease) {
|
|
118
|
+
const lines = [];
|
|
119
|
+
const deliveries = [];
|
|
120
|
+
let pointCount = 0;
|
|
121
|
+
for (const event of lease.events) {
|
|
122
|
+
const decisionId = event.kind === "publish_prompt" ? parseFeedbackDecisionId(event.decisionId) : void 0;
|
|
123
|
+
if (event.kind === "publish_prompt" && decisionId === void 0) continue;
|
|
124
|
+
const identifier = `dec_${event.shortId}`;
|
|
125
|
+
const detail = `${event.intent}${event.webUrl ? ` (${event.webUrl})` : ""}`;
|
|
126
|
+
const line = event.kind === "publish_prompt" ? `[prim] publish this Decision draft (${identifier})? ${detail} Run \`prim decisions publish ${decisionId}\` to share it with your team.` : `[prim] response \u2192 created Decision (${identifier}): ${detail}`;
|
|
127
|
+
const extra = Array.from(line).length + (lines.length === 0 ? 0 : 1);
|
|
128
|
+
if (pointCount + extra > MAX_FEEDBACK_MESSAGE_CODE_POINTS) break;
|
|
129
|
+
lines.push(line);
|
|
130
|
+
deliveries.push({ eventId: event.eventId, leaseVersion: event.leaseVersion });
|
|
131
|
+
pointCount += extra;
|
|
132
|
+
}
|
|
133
|
+
if (lines.length === 0) return void 0;
|
|
134
|
+
return { protocolVersion: lease.protocolVersion, systemMessage: lines.join("\n"), deliveries };
|
|
135
|
+
}
|
|
136
|
+
async function leaseDecisionFeedback(input, dependencies = {}) {
|
|
137
|
+
try {
|
|
138
|
+
const response = await (dependencies.client ?? getClient()).post(
|
|
139
|
+
LEASE_PATH,
|
|
140
|
+
{
|
|
141
|
+
protocolVersion: FEEDBACK_PROTOCOL_VERSION,
|
|
142
|
+
workspaceId: input.workspaceId,
|
|
143
|
+
currentSessionId: input.currentSessionId
|
|
144
|
+
},
|
|
145
|
+
{ signal: input.signal, quietRefresh: true }
|
|
146
|
+
);
|
|
147
|
+
const parsed = parseFeedbackLease(response);
|
|
148
|
+
if (!parsed) {
|
|
149
|
+
dependencies.onError?.(
|
|
150
|
+
new Error("server returned an unsupported decision-feedback contract")
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return parsed;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
dependencies.onError?.(error);
|
|
156
|
+
return void 0;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async function acknowledgeDecisionFeedback(input, dependencies = {}) {
|
|
160
|
+
if (!isSupportedProtocolVersion(input.protocolVersion) || input.deliveries.length === 0 || input.deliveries.length > MAX_FEEDBACK_EVENTS) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const response = await (dependencies.client ?? getClient()).post(
|
|
165
|
+
ACK_PATH,
|
|
166
|
+
{
|
|
167
|
+
protocolVersion: input.protocolVersion,
|
|
168
|
+
workspaceId: input.workspaceId,
|
|
169
|
+
deliveries: input.deliveries
|
|
170
|
+
},
|
|
171
|
+
{ signal: input.signal, quietRefresh: true }
|
|
172
|
+
);
|
|
173
|
+
const acknowledgedEventIds = isRecord(response) ? response.acknowledgedEventIds : void 0;
|
|
174
|
+
const expectedEventIds = new Set(input.deliveries.map((delivery) => delivery.eventId));
|
|
175
|
+
const valid = isRecord(response) && response.protocolVersion === input.protocolVersion && response.status === "acked" && Array.isArray(acknowledgedEventIds) && acknowledgedEventIds.length <= input.deliveries.length && acknowledgedEventIds.every(
|
|
176
|
+
(id) => typeof id === "string" && id.length > 0 && id.length <= MAX_EVENT_ID_CHARS && expectedEventIds.has(id)
|
|
177
|
+
) && new Set(acknowledgedEventIds).size === acknowledgedEventIds.length;
|
|
178
|
+
if (!valid) {
|
|
179
|
+
dependencies.onError?.(
|
|
180
|
+
new Error("server returned an unsupported decision-feedback acknowledgement")
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
return valid;
|
|
184
|
+
} catch (error) {
|
|
185
|
+
dependencies.onError?.(error);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function parseFeedbackCapability(value) {
|
|
190
|
+
if (!isRecord(value) || !isSupportedProtocolVersion(value.protocolVersion)) return void 0;
|
|
191
|
+
if (value.status === "available") return { status: "available" };
|
|
192
|
+
if (value.status === "unavailable" && value.reason === "organization_unbound") {
|
|
193
|
+
return { status: "unavailable", reason: "organization_unbound" };
|
|
194
|
+
}
|
|
195
|
+
return void 0;
|
|
196
|
+
}
|
|
197
|
+
async function fetchFeedbackCapability(signal, client = getClient()) {
|
|
198
|
+
const result = parseFeedbackCapability(await client.get(STATUS_PATH, { signal }));
|
|
199
|
+
if (!result) throw new Error("server returned an unsupported decision-feedback contract");
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export {
|
|
204
|
+
FEEDBACK_DEADLINE_MS,
|
|
205
|
+
renderFeedback,
|
|
206
|
+
leaseDecisionFeedback,
|
|
207
|
+
acknowledgeDecisionFeedback,
|
|
208
|
+
fetchFeedbackCapability
|
|
209
|
+
};
|