@topolo/cli 0.13.8 → 0.13.10

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.
@@ -1,1207 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/lib/claude-pack-backend.ts
4
- import { createHash, randomBytes, randomUUID } from "crypto";
5
- import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "fs";
6
- import * as filesystem from "fs";
7
- import * as cryptography from "crypto";
8
- import * as paths from "path";
9
- import { spawn, spawnSync } from "child_process";
10
- import { dirname, resolve, sep } from "path";
11
- import { fileURLToPath } from "url";
12
- import { createConnection } from "net";
13
- import { WebSocket } from "undici";
14
-
15
- // src/lib/claude-native-pack.ts
16
- async function nativeClaudePackOperation(manager, sidebar, plan, apply, checkpoint, verifyContext = () => {
17
- }) {
18
- const fenceKey = /* @__PURE__ */ Symbol.for("topolo.agent-pack.native-operation.v1");
19
- const previous = manager[fenceKey];
20
- const operationId = plan.operationId ?? "legacy-configuration";
21
- if (apply && previous) throw new Error("Native operation is unresolved; reconcile its journal before another mutation.");
22
- if (plan.mode === "recover" && previous && (previous.operationId !== operationId || previous.running))
23
- throw new Error("Native recovery identity differs or the operation is still running.");
24
- if (plan.noEffects && (plan.mode !== "recover" || previous?.effectAttempted)) throw new Error("No-effect recovery is not qualified.");
25
- if (apply) manager[fenceKey] = { operationId, running: true, effectAttempted: false };
26
- try {
27
- verifyContext();
28
- const checkDeadline = () => {
29
- if (Date.now() >= plan.deadline) throw new Error("Native operation deadline expired; reconcile journal before retry.");
30
- };
31
- const command = async (value) => {
32
- checkDeadline();
33
- const result = await sidebar(value);
34
- if (!result.ok) throw new Error(result.error || "Native sidebar acknowledgement refused.");
35
- return result;
36
- };
37
- if (!["configure", "switch", "recover"].includes(plan.mode ?? "configure") || plan.mode === "recover" && apply || plan.outgoing?.length && !["switch", "recover"].includes(plan.mode ?? "configure"))
38
- throw new Error("Unqualified native operation mode.");
39
- if (plan.mode === "switch" || plan.mode === "recover") {
40
- if (typeof manager.ensureArchivedSessionsLoaded !== "function") throw new Error("Archived ownership inventory is unavailable.");
41
- await manager.ensureArchivedSessionsLoaded("ownership");
42
- }
43
- if (!plan.members.length || plan.members.length > 100 || (plan.outgoing?.length ?? 0) > 100 || new Set(plan.members.map((m) => m.sessionId)).size !== plan.members.length || new Set(plan.members.map((m) => m.key)).size !== plan.members.length)
44
- throw new Error("A unique owned roster of 1\u2013100 sessions is required.");
45
- const models = manager.getAvailableCodeModels();
46
- const groups = manager.listCustomGroups();
47
- if (!groups) throw new Error("Native sidebar groups have not been reported by the running window.");
48
- for (const member of plan.members) {
49
- if (!/^local_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(member.sessionId) || !plan.noEffects && (!["claude-opus-5-5", "claude-sonnet-5-5"].includes(member.model) || !["medium", "high"].includes(member.effort) || !["default", "acceptEdits", "bypassPermissions"].includes(member.permissionMode) || member.permissionMode === "bypassPermissions" && (!member.permissionConsent?.contextKey.startsWith("org:") || !member.permissionConsent.intakeKey)))
50
- throw new Error("Unqualified session settings in plan.");
51
- if (!plan.noEffects && !models.includes(member.model)) throw new Error("Requested model is absent from the native account catalog: " + member.model);
52
- if (!plan.noEffects && member.group !== null && groups.filter((g) => g.name === member.group).length > 1)
53
- throw new Error("Ambiguous native sidebar group: " + member.group);
54
- }
55
- const nativeDescriptor = async (member) => {
56
- if (typeof manager.getSessionWhenLoaded !== "function") throw new Error("Qualified native session descriptor API is unavailable.");
57
- const descriptor = await manager.getSessionWhenLoaded(member.sessionId, "topolo-agent-pack", { warnOnMiss: false });
58
- checkDeadline();
59
- if (!descriptor || descriptor.sessionId !== member.sessionId || descriptor.cwd !== member.cwd || descriptor.title !== member.title)
60
- throw new Error("Owned native session descriptor identity changed: " + member.key);
61
- return descriptor;
62
- };
63
- const snapshot = async (members = plan.members) => {
64
- const result = [];
65
- for (const member of members) {
66
- checkDeadline();
67
- const session = await manager.getSession(member.sessionId);
68
- if (!session || session.sessionId !== member.sessionId || session.cwd !== member.cwd || session.title !== member.title || session.isArchived && !["switch", "recover"].includes(plan.mode ?? "configure"))
69
- throw new Error("Owned session identity or active membership changed: " + member.key);
70
- if (manager.hasLosableWork(member.sessionId) || session.isRunning || session.starting || session.pendingToolPermissions?.length)
71
- throw new Error("Session has live or pending work; no changes permitted: " + member.key);
72
- if (!plan.noEffects) {
73
- const descriptor = await nativeDescriptor(member);
74
- if (manager.hasLosableWork(member.sessionId) || descriptor.isRunning || descriptor.starting || descriptor.pendingToolPermissions?.length)
75
- throw new Error("Session has live or pending work; no changes permitted: " + member.key);
76
- if (descriptor.backend?.kind !== "local" || descriptor.backend.remoteTarget || descriptor.worktreePath || descriptor.worktreeLazy || descriptor.spawnedFrom)
77
- throw new Error("Incoming session is not a qualified local role.");
78
- }
79
- result.push({
80
- key: member.key,
81
- sessionId: session.sessionId,
82
- cwd: session.cwd,
83
- title: session.title,
84
- group: manager.getSessionCustomGroup(member.sessionId)?.name ?? null,
85
- pinned: session.isStarred === true,
86
- model: session.model ?? null,
87
- effort: session.effort ?? null,
88
- permissionMode: session.permissionMode ?? null,
89
- archived: session.isArchived === true
90
- });
91
- }
92
- return result;
93
- };
94
- const before = await snapshot();
95
- const outgoing = plan.outgoing ?? [];
96
- const identities = [...plan.members, ...outgoing].map((m) => m.sessionId);
97
- if (new Set(identities).size !== identities.length) throw new Error("Incoming and outgoing native identities overlap.");
98
- const outgoingSnapshot = async (members = outgoing) => {
99
- const result = [];
100
- for (const member of members) {
101
- checkDeadline();
102
- const session = await manager.getSession(member.sessionId);
103
- if (!/^local_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(member.sessionId) || !session || session.sessionId !== member.sessionId || session.cwd !== member.cwd || session.title !== member.title)
104
- throw new Error("Outgoing native identity differs.");
105
- if (manager.hasLosableWork(member.sessionId) || session.isRunning || session.starting || session.pendingToolPermissions?.length)
106
- throw new Error("Outgoing session has live or pending work.");
107
- if (!plan.noEffects) {
108
- const descriptor = await nativeDescriptor(member);
109
- if (manager.hasLosableWork(member.sessionId) || descriptor.isRunning || descriptor.starting || descriptor.pendingToolPermissions?.length)
110
- throw new Error("Outgoing session has live or pending work.");
111
- if (descriptor.backend?.kind !== "local" || descriptor.backend.remoteTarget || descriptor.worktreePath || descriptor.worktreeLazy || descriptor.spawnedFrom || !manager.archiveCascadeClosureOf || manager.archiveCascadeClosureOf(descriptor).length)
112
- throw new Error("Outgoing native archive closure is not qualified.");
113
- }
114
- result.push({ key: member.key, sessionId: member.sessionId, cwd: session.cwd, title: session.title, archived: session.isArchived === true });
115
- }
116
- return result;
117
- };
118
- const outgoingBefore = await outgoingSnapshot();
119
- const sections = await command({ kind: "list_sections" });
120
- checkpoint({ kind: "baseline", before, outgoingBefore, sections: sections.sections, at: Date.now() });
121
- if (plan.mode === "recover") {
122
- if (plan.noEffects) {
123
- verifyContext();
124
- checkpoint({ kind: "reconciled-no-effects", after: before, at: Date.now() });
125
- delete manager[fenceKey];
126
- return { state: "native-reconciled-no-effects", after: before, applied: false, nativeEffectsReplayed: false };
127
- }
128
- for (let i = 0; i < plan.members.length; i++) {
129
- const wanted = plan.members[i];
130
- const actual = before[i];
131
- for (const setting of ["group", "pinned", "model", "effort", "permissionMode"])
132
- if (actual[setting] !== wanted[setting]) throw new Error("Recovery read-back is incomplete; no native effects replayed.");
133
- if (actual.archived) throw new Error("Recovery incoming session is still archived.");
134
- }
135
- if (outgoingBefore.some((s) => !s.archived)) throw new Error("Recovery outgoing roster is incomplete.");
136
- verifyContext();
137
- checkpoint({ kind: "reconciled", after: before, outgoingAfter: outgoingBefore, at: Date.now() });
138
- delete manager[fenceKey];
139
- return { state: "native-reconciled", after: before, outgoingAfter: outgoingBefore, applied: false, nativeEffectsReplayed: false };
140
- }
141
- if (!apply) return { state: "preflight", before, outgoingBefore, sections: sections.sections, availableModels: models, applied: false };
142
- const effect = async (description, run) => {
143
- checkDeadline();
144
- verifyContext();
145
- const affected = description.sessionIds ?? (description.sessionId ? [description.sessionId] : null);
146
- await snapshot(affected ? plan.members.filter((m) => affected.includes(m.sessionId)) : plan.members);
147
- await outgoingSnapshot(affected ? outgoing.filter((m) => affected.includes(m.sessionId)) : outgoing);
148
- checkpoint({ kind: "attempt", ...description, at: Date.now() });
149
- manager[fenceKey].effectAttempted = true;
150
- await run();
151
- checkpoint({ kind: "acknowledged", ...description, at: Date.now() });
152
- };
153
- const groupIds = new Map(groups.map((g) => [g.name, g.id]));
154
- if (plan.mode === "switch") {
155
- for (const member of outgoing) {
156
- if (!(await manager.getSession(member.sessionId)).isArchived)
157
- await effect({ operation: "archive", sessionId: member.sessionId }, () => manager.archiveSession(
158
- member.sessionId,
159
- { cleanupWorktree: false, forceWorktreeCleanup: false, discardUntracked: false, isAutomatic: true }
160
- ));
161
- }
162
- for (const member of plan.members) {
163
- const session = await manager.getSession(member.sessionId);
164
- if (session.isArchived) {
165
- const descriptor = await nativeDescriptor(member);
166
- if (descriptor.backend?.kind !== "local" || descriptor.backend.remoteTarget || descriptor.worktreePath || descriptor.worktreeLazy || descriptor.spawnedFrom)
167
- throw new Error("Incoming session is not a qualified local role.");
168
- await effect({ operation: "unarchive", sessionId: member.sessionId }, async () => {
169
- await manager.unarchiveSession(member.sessionId);
170
- });
171
- }
172
- }
173
- }
174
- for (const name of new Set(plan.members.map((m) => m.group).filter((g) => g !== null))) {
175
- if (!groupIds.has(name)) await effect({ operation: "create_group", name }, async () => {
176
- const result = await command({ kind: "create_group", name });
177
- if (!result.groupId) throw new Error("Native create_group did not return an identity.");
178
- groupIds.set(name, result.groupId);
179
- });
180
- }
181
- await effect({ operation: "set_view" }, () => command({
182
- kind: "set_view",
183
- view: { groupBy: "custom", status: "active", sortBy: "recency", lastActivityDays: 0 }
184
- }));
185
- for (const group of new Set(plan.members.map((m) => m.group))) {
186
- const sessionIds = plan.members.filter((m) => m.group === group).map((m) => m.sessionId);
187
- await effect({ operation: "move_sessions", group, sessionIds }, () => command({
188
- kind: "move_sessions",
189
- sessionIds,
190
- ...group === null ? {} : { groupId: groupIds.get(group) }
191
- }));
192
- }
193
- for (const member of plan.members) {
194
- await effect({ operation: "set_pinned", sessionId: member.sessionId }, () => command({ kind: "set_pinned", sessionId: member.sessionId, pinned: member.pinned }));
195
- await effect({ operation: "set_model", sessionId: member.sessionId }, () => manager.setModel(member.sessionId, member.model));
196
- await effect({ operation: "set_effort", sessionId: member.sessionId }, () => manager.setEffort(member.sessionId, member.effort));
197
- await effect({ operation: "set_permission_mode", sessionId: member.sessionId }, async () => {
198
- if (!await manager.setPermissionMode(member.sessionId, member.permissionMode, "picker"))
199
- throw new Error("Native permission mode was refused: " + member.key);
200
- });
201
- }
202
- const after = await snapshot();
203
- const outgoingAfter = await outgoingSnapshot();
204
- if (after.some((s) => s.archived) || outgoingAfter.some((s) => !s.archived)) throw new Error("Native archive membership read-back mismatch.");
205
- for (let i = 0; i < plan.members.length; i++) {
206
- const wanted = plan.members[i];
207
- const actual = after[i];
208
- for (const setting of ["group", "pinned", "model", "effort", "permissionMode"])
209
- if (actual[setting] !== wanted[setting]) throw new Error("Native read-back mismatch: " + wanted.key + " / " + setting);
210
- }
211
- verifyContext();
212
- checkpoint({ kind: "verified", after, outgoingAfter, at: Date.now() });
213
- delete manager[fenceKey];
214
- return {
215
- state: "native-settings-verified",
216
- before,
217
- after,
218
- outgoingAfter,
219
- verifiedAgents: after.length,
220
- applied: true,
221
- modelInferenceVerified: false,
222
- readOnlyConfinementVerified: false,
223
- fullPackSwitchSupported: plan.mode === "switch"
224
- };
225
- } catch (error) {
226
- if (apply) manager[fenceKey] = {
227
- operationId,
228
- running: false,
229
- recoveryRequired: true,
230
- effectAttempted: manager[fenceKey]?.effectAttempted === true
231
- };
232
- throw error;
233
- }
234
- }
235
-
236
- // src/lib/claude-pack-approvals.ts
237
- async function nativeClaudeApprovalControl(manager, descriptor, token, net, fs, invoke, qualify, checkpoint) {
238
- const key = /* @__PURE__ */ Symbol.for("topolo.agent-pack.approval-control.v1");
239
- qualify();
240
- if (!Number.isSafeInteger(descriptor.pid) || descriptor.pid < 1 || !/^[a-f0-9]{64}$/.test(token) || !/^[a-f0-9]{64}$/.test(descriptor.identity)) throw new Error("Unqualified native control identity.");
241
- const previous = manager[key];
242
- if (fs.existsSync(descriptor.socket)) throw new Error("Native control socket path already exists; no unowned takeover.");
243
- if (previous) {
244
- if (previous.active) throw new Error("Native approval control requests are still in flight.");
245
- await new Promise((done, fail) => previous.server.close((error) => error ? fail(error) : done()));
246
- delete manager[key];
247
- }
248
- const control = { active: 0, server: null, descriptor };
249
- const server = net.createServer((connection) => {
250
- let buffer = "";
251
- let dispatched = false;
252
- connection.setEncoding("utf8");
253
- connection.setTimeout(5e3, () => connection.destroy());
254
- connection.on("error", () => connection.destroy());
255
- connection.on("data", async (chunk) => {
256
- if (dispatched) return;
257
- buffer += chunk;
258
- if (Buffer.byteLength(buffer) > 65536) {
259
- dispatched = true;
260
- connection.destroy();
261
- return;
262
- }
263
- if (!buffer.includes("\n")) return;
264
- dispatched = true;
265
- control.active++;
266
- try {
267
- if (control.failure) throw new Error(control.failure);
268
- qualify();
269
- const request = JSON.parse(buffer);
270
- if (Object.keys(request).sort().join(",") !== "identity,operation,pid,token" || request.token !== token || request.pid !== descriptor.pid || request.identity !== descriptor.identity)
271
- throw new Error("Native approval control authentication or process identity differs.");
272
- const op = request.operation;
273
- const fields = op?.kind === "smoke-start" ? ["kind", "key", "caseId", "operationId"] : op?.kind === "smoke-read" ? ["kind", "operationId"] : ["kind", "key", "intake", "fingerprint", "decision", "humanDecisionRecorded"];
274
- if (!op || !["list", "details", "respond", "smoke-start", "smoke-read"].includes(op.kind) || Object.keys(op).some((k) => !fields.includes(k)))
275
- throw new Error("Unsupported native control operation.");
276
- const result = await invoke(op);
277
- const reply = JSON.stringify({ result }) + "\n";
278
- if (Buffer.byteLength(reply) > 262144) throw new Error("Native approval details exceed bounded transport; use the original native interaction.");
279
- connection.end(reply);
280
- } catch (error) {
281
- try {
282
- checkpoint({ kind: "approval-control-refused" });
283
- } catch {
284
- control.failure = "Native approval audit unavailable; reconcile through the original interaction.";
285
- }
286
- connection.end(JSON.stringify({ error: control.failure || (error instanceof Error ? error.message : "Native approval control refused.") }) + "\n");
287
- } finally {
288
- control.active--;
289
- }
290
- });
291
- });
292
- control.server = server;
293
- await new Promise((done, fail) => {
294
- const failed = (error) => fail(error);
295
- server.once("error", failed);
296
- server.listen(descriptor.socket, () => {
297
- server.off("error", failed);
298
- done();
299
- });
300
- });
301
- try {
302
- fs.chmodSync(descriptor.socket, 384);
303
- checkpoint({ kind: "approval-control-installed", ...descriptor });
304
- } catch (error) {
305
- await new Promise((done) => server.close(() => done()));
306
- throw error;
307
- }
308
- server.on("error", () => {
309
- control.failure = "Native approval control failed; reconcile through the original interaction.";
310
- try {
311
- checkpoint({ kind: "approval-control-error" });
312
- } catch {
313
- control.failure = "Native approval audit unavailable; reconcile through the original interaction.";
314
- }
315
- });
316
- manager[key] = control;
317
- return { state: "native-approval-control-installed", ...descriptor };
318
- }
319
- async function nativeClaudeOwnedSmokeOperation(manager, members, operation, helper, fingerprint, nativeIdentity, qualifyNative = () => {
320
- }) {
321
- const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
322
- const fields = operation?.kind === "smoke-start" ? ["kind", "key", "caseId", "operationId"] : ["kind", "operationId"];
323
- if (!operation || !["smoke-start", "smoke-read"].includes(operation.kind) || Object.keys(operation).sort().join() !== fields.sort().join() || !uuid.test(operation.operationId) || operation.kind === "smoke-start" && (!/^[a-z0-9-]+\/[a-z0-9-]+\/[a-z0-9-]+$/.test(operation.key) || !["stg-context-memory-bytes", "stg-peer-ack", "prod-role-context-ack"].includes(operation.caseId)))
324
- throw new Error("Exact closed native smoke operation required.");
325
- if (!members.length || members.length > 70 || new Set(members.map((m) => m.key)).size !== members.length || new Set(members.map((m) => m.sessionId)).size !== members.length) throw new Error("Unique native smoke roster required.");
326
- const owner = /* @__PURE__ */ Symbol.for("topolo.agent-pack.owned-smoke.v1");
327
- const rosterIdentity = fingerprint(members);
328
- const summary = (record) => Object.fromEntries([
329
- "operationId",
330
- "harness",
331
- "caseId",
332
- "key",
333
- "state",
334
- "nativeId",
335
- "hostedUsageVerified",
336
- "operationEffectVerified",
337
- "nativeStatus",
338
- "historyPreserved",
339
- "ack"
340
- ].filter((k) => k in record).map((k) => [k, record[k]]));
341
- const check = (member2, session) => {
342
- if (!session || session.sessionId !== member2.sessionId || session.cwd !== member2.cwd || session.title !== member2.title || session.isArchived || session.backend?.kind !== "local" || session.backend.remoteTarget || session.worktreePath || session.worktreeLazy || session.spawnedFrom || session.isRunning || session.starting || session.pendingToolPermissions?.length || manager.hasLosableWork(member2.sessionId) || session.model !== member2.model || session.effort !== member2.effort || session.permissionMode !== member2.permissionMode || member2.permissionMode !== "bypassPermissions" || !member2.permissionConsent || !manager.getAvailableCodeModels().includes(member2.model)) throw new Error("Exact idle native smoke ownership/settings unavailable.");
343
- };
344
- const current = () => {
345
- qualifyNative();
346
- if (manager[/* @__PURE__ */ Symbol.for("topolo.agent-pack.native-operation.v1")] || fingerprint(members) !== rosterIdentity)
347
- throw new Error("Unresolved native configuration or changed smoke roster remains.");
348
- for (const member2 of members) check(member2, manager.getSession(member2.sessionId));
349
- };
350
- const ready = async () => {
351
- current();
352
- for (const member2 of members) {
353
- const descriptor = await manager.getSessionWhenLoaded(member2.sessionId, "topolo-owned-smoke", { warnOnMiss: false });
354
- check(member2, descriptor);
355
- check(member2, manager.getSession(member2.sessionId));
356
- }
357
- current();
358
- };
359
- if (operation.kind === "smoke-read") {
360
- const record = await helper("read", { operation: operation.operationId });
361
- if (record.state !== "native-delivered") return summary(record);
362
- if (record.nativeIdentity !== nativeIdentity) return { ...summary(record), connectionCurrent: false };
363
- const member2 = members.find((m) => m.key === record.key && m.sessionId === record.row.nativeId && m.cwd === record.row.cwd);
364
- if (!member2) throw new Error("Native smoke read custody differs.");
365
- const session = await manager.getSession(member2.sessionId);
366
- if (session?.isRunning || session?.starting || manager[owner]) return summary(record);
367
- check(member2, session);
368
- const history = await manager.getTranscript(member2.sessionId);
369
- if (!Array.isArray(history)) throw new Error("Qualified native smoke transcript API unavailable.");
370
- const same = fingerprint(history.slice(0, record.historyCount)) === record.historyHash;
371
- const markers = history.map((m, index) => m.uuid === record.operationId ? index : -1).filter((i) => i >= 0);
372
- const marker = markers[0] ?? -1;
373
- const user = markers.length === 1 && marker === record.historyCount && history[marker]?.type === "user" ? marker : -1;
374
- const nextUser = history.findIndex((m, index) => index > user && m.type === "user");
375
- const assistants = user < 0 ? [] : history.slice(user + 1, nextUser < 0 ? history.length : nextUser).filter((m) => m.type === "assistant");
376
- const text = assistants.at(-1)?.message?.content?.filter((b) => b.type === "text").map((b) => b.text).join("");
377
- let ack;
378
- if (typeof text === "string" && text.length <= 2048) {
379
- try {
380
- ack = JSON.parse(text);
381
- } catch {
382
- }
383
- }
384
- const expected = {
385
- operationId: record.operationId,
386
- logicalId: record.row.logicalId,
387
- agentVersionId: record.row.agentVersionId,
388
- contextMarkerHash: record.row.contextMarkerHash,
389
- artifactHash: record.row.artifactHash
390
- };
391
- const valid = same && Number.isSafeInteger(record.historyCount) && record.historyCount >= 0 && ack && typeof ack === "object" && !Array.isArray(ack) && Object.keys(ack).sort().join() === [...Object.keys(expected), "status"].sort().join() && Object.entries(expected).every(([k, v]) => ack[k] === v) && ["ok", "blocked"].includes(ack.status);
392
- await helper("verify", { operation: operation.operationId });
393
- return summary(await helper("mark", {
394
- operation: operation.operationId,
395
- state: "uncertain",
396
- nativeStatus: "terminal-evidence-unavailable",
397
- historyPreserved: same,
398
- ...valid ? { ack } : {}
399
- }));
400
- }
401
- if (manager[owner]) throw new Error("Native smoke dispatch already reserved.");
402
- const member = members.find((m) => m.key === operation.key);
403
- if (!member) throw new Error("Smoke role is not natively owned.");
404
- manager[owner] = operation.operationId;
405
- let prepared = false;
406
- try {
407
- await ready();
408
- const plan = await helper("prepare", {
409
- key: operation.key,
410
- case: operation.caseId,
411
- operation: operation.operationId,
412
- native_identity: nativeIdentity
413
- });
414
- prepared = true;
415
- const actual = plan.roster.map((r) => [r.key, r.nativeId, r.cwd, r.title]).sort();
416
- const wanted = members.map((m) => [m.key, m.sessionId, m.cwd, m.title]).sort();
417
- if (JSON.stringify(actual) !== JSON.stringify(wanted)) throw new Error("Smoke binding must match the complete owned native roster.");
418
- await ready();
419
- await helper("verify", { operation: operation.operationId });
420
- const history = await manager.getTranscript(member.sessionId);
421
- if (!Array.isArray(history)) throw new Error("Qualified native smoke transcript API unavailable.");
422
- await helper("mark", { operation: operation.operationId, state: "prepared", historyCount: history.length, historyHash: fingerprint(history) });
423
- await ready();
424
- const admission = await helper("arm", { operation: operation.operationId, native_identity: nativeIdentity });
425
- current();
426
- if (admission.operationId !== operation.operationId || admission.nativeIdentity !== nativeIdentity || admission.state !== "start-may-have-effects" || admission.bindingHash !== plan.record.bindingHash || !/^[a-f0-9]{64}$/.test(admission.bindingHash) || !Number.isFinite(admission.expiresAt) || admission.expiresAt !== plan.record.dispatchExpiresAt || Date.now() >= admission.expiresAt * 1e3)
427
- throw new Error("Original smoke final dispatch admission expired or differs.");
428
- const ack = await manager.sendMessage(
429
- member.sessionId,
430
- plan.text,
431
- void 0,
432
- { messageUuid: operation.operationId, initiator: "agent", origin: { kind: "task-notification" } }
433
- );
434
- return summary(await helper("mark", {
435
- operation: operation.operationId,
436
- state: ack?.delivered === true ? "native-delivered" : ack?.delivered === false ? "native-refused" : "uncertain",
437
- nativeId: operation.operationId
438
- }));
439
- } catch (error) {
440
- if (prepared) {
441
- const record = await helper("read", { operation: operation.operationId });
442
- await helper("mark", { operation: operation.operationId, state: record.state === "prepared" ? "preflight-refused" : "uncertain" });
443
- }
444
- throw error;
445
- } finally {
446
- delete manager[owner];
447
- }
448
- }
449
- async function nativeClaudeApprovalOperation(manager, routes, operation, fingerprint, checkpoint, history = []) {
450
- const symbol = /* @__PURE__ */ Symbol.for("topolo.agent-pack.approvals.v1");
451
- if (!routes.length || routes.length > 100 || new Set(routes.map((r) => r.sessionId)).size !== routes.length || new Set(routes.map((r) => r.key)).size !== routes.length) throw new Error("Unique owned approval roster required.");
452
- const byId = new Map(routes.map((r) => [r.sessionId, r]));
453
- const byKey = new Map(routes.map((r) => [r.key, r]));
454
- for (const r of routes) {
455
- const intake = byKey.get(r.intakeKey);
456
- if (!/^org:.+$/.test(r.contextKey) || !intake || !intake.key.includes("/intakes/") || intake.contextKey !== r.contextKey || intake.sessionId !== r.intakeSessionId)
457
- throw new Error("Approval route has no same-context owned intake.");
458
- }
459
- const identity = fingerprint(routes);
460
- let state = manager[symbol];
461
- if (state?.auditFailed) throw new Error("Native approval audit unavailable; use the original native interaction.");
462
- const owned = async (route) => {
463
- if (typeof manager.getSessionWhenLoaded !== "function") throw new Error("Qualified native session descriptor API is unavailable.");
464
- const descriptor = await manager.getSessionWhenLoaded(route.sessionId, "topolo-agent-pack-approval", { warnOnMiss: false });
465
- const session = await manager.getSession(route.sessionId);
466
- if (!session || session.sessionId !== route.sessionId || session.cwd !== route.cwd || session.title !== route.title || session.isArchived)
467
- throw new Error("Native approval session identity differs: " + route.key);
468
- if (!descriptor || descriptor.sessionId !== route.sessionId || descriptor.cwd !== route.cwd || descriptor.title !== route.title || descriptor.isArchived || descriptor.backend?.kind !== "local" || descriptor.backend.remoteTarget || descriptor.worktreePath || descriptor.worktreeLazy || descriptor.spawnedFrom)
469
- throw new Error("Native approval session descriptor identity differs: " + route.key);
470
- return session;
471
- };
472
- if (state && state.identity !== identity) {
473
- if (operation.kind !== "install" || state.notifications.size || [...state.entries.values()].some((e) => ["pending", "response-may-have-effects"].includes(e.record.state)))
474
- throw new Error("An existing native approval owner has a different roster.");
475
- for (const r of routes) await owned(r);
476
- for (const route of state.routes) {
477
- const session = await manager.getSession(route.sessionId);
478
- if (!session || session.cwd !== route.cwd || session.title !== route.title || session.isRunning || session.starting || session.pendingToolPermissions?.length || manager.hasLosableWork(route.sessionId))
479
- throw new Error("Outgoing approval owner is not safely idle.");
480
- }
481
- if (typeof manager.off !== "function") throw new Error("Native approval listener ownership cannot be released.");
482
- manager.off("event", state.listener);
483
- delete manager[symbol];
484
- state = void 0;
485
- }
486
- const current = async (entry2) => {
487
- const source2 = await owned(byId.get(entry2.record.sourceSessionId));
488
- const matches = (source2.pendingToolPermissions ?? []).filter((r) => r.requestId === entry2.request.requestId);
489
- if (matches.length !== 1 || fingerprint(matches[0]) !== entry2.record.fingerprint)
490
- throw new Error("Exact native request is no longer pending; no replay.");
491
- return matches[0];
492
- };
493
- if (operation.kind === "install") {
494
- for (const r of routes) await owned(r);
495
- if (!state) {
496
- if (typeof manager.on !== "function" || typeof manager.sendMessage !== "function" || typeof manager.respondToToolPermission !== "function") throw new Error("Native approval transport unavailable.");
497
- state = { identity, routes, entries: /* @__PURE__ */ new Map(), notifications: /* @__PURE__ */ new Set(), deliveryAttempts: 0 };
498
- manager[symbol] = state;
499
- const save = (entry2) => checkpoint({ ...entry2.record });
500
- const deliver = async (entry2) => {
501
- const record = entry2.record;
502
- if (state.notifications.has(record.key) || !["not-delivered", "awaiting-idle-intake"].includes(record.notificationState)) return;
503
- if (record.sourceSessionId === record.intakeSessionId) {
504
- record.notificationState = "native-intake";
505
- save(entry2);
506
- return;
507
- }
508
- state.notifications.add(record.key);
509
- try {
510
- await current(entry2);
511
- const intake = await owned(byId.get(record.intakeSessionId));
512
- if (manager.hasLosableWork(record.intakeSessionId) || intake.isRunning || intake.starting || intake.pendingToolPermissions?.length) {
513
- record.notificationState = "awaiting-idle-intake";
514
- save(entry2);
515
- return;
516
- }
517
- const text = "Permission relay (generated by the Topolo pack adapter). " + record.sourceKey + " awaits a native decision. Request " + record.key + ", fingerprint " + record.fingerprint + ". Read exact live details using topolo agent-packs approvals details " + record.key + " --harness claude --intake " + record.intakeSessionId + " --fingerprint " + record.fingerprint + ". Present this to the human in this intake and relay only the recorded answer. This notification grants no approval." + (record.cardOnly ? " Claude requires approval on the original native card; report this limitation here." : "");
518
- record.notificationState = "may-have-effects";
519
- save(entry2);
520
- state.deliveryAttempts++;
521
- const ack = await manager.sendMessage(
522
- record.intakeSessionId,
523
- text,
524
- void 0,
525
- { initiator: "agent", origin: { kind: "task-notification" } }
526
- );
527
- record.notificationState = ack?.delivered === true ? "delivered" : "delivery-refused";
528
- save(entry2);
529
- } catch {
530
- record.notificationState = record.notificationState === "may-have-effects" ? "delivery-uncertain" : "delivery-failed";
531
- save(entry2);
532
- } finally {
533
- state.notifications.delete(record.key);
534
- }
535
- };
536
- const capture = async (sessionId, request) => {
537
- const route = byId.get(sessionId);
538
- if (!route || !request || typeof request.requestId !== "string") return;
539
- const source2 = await owned(route);
540
- const matches = (source2.pendingToolPermissions ?? []).filter((r) => r.requestId === request.requestId);
541
- if (matches.length !== 1) throw new Error("Native event is not in the owned pending inventory.");
542
- const pending2 = matches[0];
543
- const key = fingerprint([identity, pending2.requestId]);
544
- const hash = fingerprint(pending2);
545
- let entry2 = state.entries.get(key);
546
- if (entry2 && entry2.record.fingerprint !== hash) throw new Error("Native request identity was reused.");
547
- if (!entry2) {
548
- const old = history.filter((row) => row.key === key).at(-1);
549
- if (old && (old.fingerprint !== hash || old.sourceSessionId !== sessionId || old.intakeSessionId !== route.intakeSessionId || old.contextKey !== route.contextKey))
550
- throw new Error("Durable approval identity differs; no replay.");
551
- entry2 = { request: pending2, record: {
552
- key,
553
- fingerprint: hash,
554
- sourceKey: route.key,
555
- sourceSessionId: sessionId,
556
- intakeKey: route.intakeKey,
557
- intakeSessionId: route.intakeSessionId,
558
- contextKey: route.contextKey,
559
- state: "pending",
560
- notificationState: "not-delivered",
561
- cardOnly: pending2.onlyOnCard === true || pending2.noAllowOnNotification === true,
562
- nativeApproved: false,
563
- ...old ? { state: old.state, notificationState: old.notificationState } : {}
564
- } };
565
- state.entries.set(key, entry2);
566
- save(entry2);
567
- }
568
- if (entry2.record.state === "pending") await deliver(entry2);
569
- };
570
- state.listener = async (event) => {
571
- try {
572
- if (event?.type === "tool_permission_request") await capture(event.sessionId, event.request);
573
- else if (event?.type === "session_updated") {
574
- const source2 = byId.get(event.sessionId);
575
- if (source2) {
576
- const session = await owned(source2);
577
- for (const entry2 of state.entries.values())
578
- if (entry2.record.state === "pending" && entry2.record.sourceSessionId === event.sessionId && !(session.pendingToolPermissions ?? []).some((r) => r.requestId === entry2.request.requestId)) {
579
- entry2.record.state = "native-request-no-longer-pending";
580
- delete entry2.request;
581
- save(entry2);
582
- }
583
- }
584
- for (const entry2 of state.entries.values())
585
- if (entry2.record.state === "pending" && entry2.record.intakeSessionId === event.sessionId) await deliver(entry2);
586
- }
587
- } catch {
588
- try {
589
- checkpoint({ kind: "approval-routing-refused", sessionId: event?.sessionId });
590
- } catch {
591
- state.auditFailed = true;
592
- }
593
- }
594
- };
595
- manager.on("event", state.listener);
596
- checkpoint({ kind: "approval-listener-installed", identity, roles: routes.length });
597
- for (const r of routes) for (const request of (await owned(r)).pendingToolPermissions ?? []) await capture(r.sessionId, request);
598
- }
599
- return {
600
- state: "native-approval-listener-installed",
601
- identity,
602
- roles: routes.length,
603
- modelTurnsMayHaveStartedByInstallation: state.deliveryAttempts > 0
604
- };
605
- }
606
- if (!state) throw new Error("Native approval listener is not installed.");
607
- if (operation.kind === "list") return { requests: [...state.entries.values()].map((e) => ({ ...e.record })) };
608
- const entry = state.entries.get(operation.key);
609
- if (!entry || entry.record.state !== "pending" || entry.record.intakeSessionId !== operation.intake || entry.record.fingerprint !== operation.fingerprint) throw new Error("Exact pending request and owning intake required.");
610
- const pending = await current(entry);
611
- if (manager[symbol] !== state || state.entries.get(operation.key) !== entry || entry.record.state !== "pending" || state.auditFailed)
612
- throw new Error("Exact pending request changed during native identity validation; reconcile without replay.");
613
- if (operation.kind === "details") return { record: { ...entry.record }, request: pending };
614
- if (operation.kind !== "respond" || operation.humanDecisionRecorded !== true || !["once", "deny"].includes(operation.decision ?? ""))
615
- throw new Error("Recorded human one-request decision required; never auto-approve.");
616
- if (operation.decision !== "deny" && entry.record.cardOnly) throw new Error("Claude requires the original card; intake cannot impersonate its origin.");
617
- entry.record.state = "response-may-have-effects";
618
- checkpoint({ ...entry.record });
619
- await manager.respondToToolPermission(pending.requestId, operation.decision, void 0, "elsewhere");
620
- const source = await owned(byId.get(entry.record.sourceSessionId));
621
- if (source.pendingToolPermissions?.some((r) => r.requestId === pending.requestId))
622
- throw new Error("Native decision did not settle; reconcile without replay.");
623
- entry.record.state = "native-request-settled";
624
- checkpoint({ ...entry.record });
625
- return { state: entry.record.state, nativeApproved: false, operationEffectVerified: false };
626
- }
627
-
628
- // src/lib/claude-pack-backend.ts
629
- var CLAUDE_NATIVE_QUALIFIER = {
630
- version: "2.37337.1",
631
- manager: "index.chunk-BolytlRP.js",
632
- sidebar: "index.chunk-BoQoqlAs.js",
633
- hashes: {
634
- "index.chunk-BolytlRP.js": "e387edfb06a34a59d99b54c04365f6e32d0108e8710124b4d1a628eea726d030",
635
- "index.chunk-BoQoqlAs.js": "5c07a7e836d98dcd6afcfc2a62619e71d173a136ecb9af847716ea377b58b1df",
636
- "index.chunk-BWk6pVUt.js": "f7d74e113f34761a675816fe2abf65b3ddc190327ee7623d9c822f7b59cceaca"
637
- }
638
- };
639
- function validateInspectorEndpoint(endpoint) {
640
- const url = new URL(endpoint);
641
- if (url.protocol !== "ws:" || url.hostname !== "127.0.0.1" || !url.port || url.username || url.password || url.search || url.hash || !/^\/[0-9a-f-]{36}$/.test(url.pathname))
642
- throw new Error("An explicit ws://127.0.0.1:<port>/<inspector UUID> endpoint is required.");
643
- return url.href;
644
- }
645
- function snapshotClaudeMarkdown(root, fs, crypto, path) {
646
- const inventory = {};
647
- const visit = (directory) => {
648
- const stat = fs.lstatSync(directory);
649
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Owned context directory is not regular: " + directory);
650
- for (const name of fs.readdirSync(directory).sort()) {
651
- const file = path.resolve(directory, name);
652
- const entry = fs.lstatSync(file);
653
- if (entry.isSymbolicLink()) throw new Error("Owned context must not follow symlinks: " + file);
654
- if (entry.isDirectory()) visit(file);
655
- else if (/\.md$/i.test(name)) {
656
- if (!entry.isFile()) throw new Error("Owned Markdown context is not a regular file: " + file);
657
- inventory[file] = crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
658
- }
659
- }
660
- };
661
- visit(root);
662
- return inventory;
663
- }
664
- function prepareClaudeNativePlan(store, pack, policyPath, mode = "configure") {
665
- if (!/^[a-z0-9][a-z0-9-]*$/.test(pack)) throw new Error("Invalid pack name.");
666
- const root = realpathSync(store);
667
- const state = JSON.parse(readFileSync(resolve(root, "claude/state.json"), "utf8"));
668
- const policy = JSON.parse(readFileSync(policyPath, "utf8"));
669
- if (state.harness !== "claude" || policy.format !== "topolo-agent-execution-policy" || policy.pack !== pack)
670
- throw new Error("Claude state and reviewed policy must name the same pack.");
671
- const records = state.agents.filter((a) => a.pack === pack);
672
- if (!records.length || records.length !== policy.agents.length) throw new Error("Reviewed policy must cover the complete installed roster.");
673
- const members = [];
674
- const context = {};
675
- const contextInventories = {};
676
- const captureMarkdown = (cwd) => {
677
- contextInventories[cwd] = snapshotClaudeMarkdown(cwd, filesystem, cryptography, paths);
678
- Object.assign(context, contextInventories[cwd]);
679
- };
680
- for (const record of records) {
681
- const matches = policy.agents.filter((a) => a.key === record.key && a.title === record.title);
682
- if (matches.length !== 1 || record.sourceRevision !== policy.sourceRevision || record.importState !== "desktop-adopted")
683
- throw new Error("Reviewed policy does not match adopted role: " + record.key);
684
- const role = matches[0];
685
- const settings = role.harnesses.claude.nativeSettings;
686
- const cwd = realpathSync(record.workspace);
687
- if (!cwd.startsWith(resolve(root, "claude/workspaces", pack) + sep)) throw new Error("Role workspace is outside the owned pack.");
688
- captureMarkdown(cwd);
689
- const charter = resolve(cwd, "CLAUDE.md");
690
- const transcript = realpathSync(record.transcript);
691
- context[charter] = createHash("sha256").update(readFileSync(charter)).digest("hex");
692
- context[transcript] = createHash("sha256").update(readFileSync(transcript)).digest("hex");
693
- members.push({
694
- key: record.key,
695
- sessionId: record.desktopSessionId,
696
- cwd,
697
- title: record.title,
698
- group: record.pinnedRequested ? null : role.sidebar.group,
699
- pinned: record.pinnedRequested === true,
700
- model: settings.model,
701
- effort: settings.effortLevel,
702
- permissionMode: settings.permissions.defaultMode,
703
- ...policy.installationConsent || settings.permissions.defaultMode === "bypassPermissions" ? {
704
- permissionConsent: qualifyPermissionConsent(policy, record.key, records, settings.permissions.defaultMode === "bypassPermissions")
705
- } : {}
706
- });
707
- }
708
- for (const file of [resolve(root, "claude/state.json"), realpathSync(policyPath)])
709
- context[file] = createHash("sha256").update(readFileSync(file)).digest("hex");
710
- const activePath = resolve(root, "claude/active.json");
711
- const active = existsSync(activePath) ? JSON.parse(readFileSync(activePath, "utf8")) : null;
712
- const target = new Set(members.map((m) => m.key));
713
- const outgoing = [];
714
- if (active) {
715
- if (!Array.isArray(active.keys) || new Set(active.keys).size !== active.keys.length) throw new Error("Invalid verified active roster.");
716
- for (const key of active.keys.filter((key2) => !target.has(key2))) {
717
- if (mode !== "switch") throw new Error("Use a native switch to replace the verified active roster.");
718
- const candidates = state.agents.filter((a) => a.key === key && a.importState === "desktop-adopted");
719
- if (candidates.length !== 1) throw new Error("Outgoing role has no unique owned adoption record.");
720
- const record = candidates[0];
721
- const cwd = realpathSync(record.workspace);
722
- if (!/^[a-z0-9][a-z0-9-]*$/.test(record.pack)) throw new Error("Invalid outgoing pack name.");
723
- if (!cwd.startsWith(resolve(root, "claude/workspaces", record.pack) + sep)) throw new Error("Outgoing workspace is outside the owned pack.");
724
- captureMarkdown(cwd);
725
- for (const file of [resolve(cwd, "CLAUDE.md"), realpathSync(record.transcript)])
726
- context[file] = createHash("sha256").update(readFileSync(file)).digest("hex");
727
- outgoing.push({ key, sessionId: record.desktopSessionId, cwd, title: record.title });
728
- }
729
- } else if (mode === "switch") throw new Error("Configure and verify an initial active roster before switching.");
730
- const approvalRoutes = members.filter((m) => m.permissionConsent).map((m) => {
731
- const intake = members.find((i) => i.key === m.permissionConsent.intakeKey);
732
- if (!intake) throw new Error("Owning intake is not in the native roster.");
733
- return {
734
- key: m.key,
735
- sessionId: m.sessionId,
736
- cwd: m.cwd,
737
- title: m.title,
738
- ...m.permissionConsent,
739
- intakeSessionId: intake.sessionId
740
- };
741
- });
742
- return {
743
- members,
744
- outgoing,
745
- context,
746
- contextInventories,
747
- approvalRoutes,
748
- installationConsent: policy.installationConsent,
749
- libraryRoot: root,
750
- sourceRevision: policy.sourceRevision,
751
- mode,
752
- activeBefore: active
753
- };
754
- }
755
- function qualifyPermissionConsent(policy, key, records, full) {
756
- const consent = policy.installationConsent;
757
- const intakeKey = consent?.intakeRoutes?.[key];
758
- if (consent?.format !== "topolo-pack-installation-consent" || consent.schemaVersion !== 1 || consent.authority !== "local-installation-consent" || consent.approved !== true || consent.pack !== policy.pack || typeof consent.contextKey !== "string" || !/^org:.+$/.test(consent.contextKey) || !consent.principalId || !["manual", "role-default", "full-access"].includes(consent.profile) || full && (consent.overrides?.[key] ?? consent.profile) !== "full-access" || !records.some((record) => record.key === intakeKey && record.key.includes("/intakes/")))
759
- throw new Error("Explicit organization-bound full access and owned intake consent required.");
760
- return { contextKey: consent.contextKey, intakeKey };
761
- }
762
- function nativePackExpression(pid, plan, journal, apply) {
763
- if (!Number.isSafeInteger(pid) || pid < 1) throw new Error("Explicit Claude main-process PID required.");
764
- const qualifier = CLAUDE_NATIVE_QUALIFIER;
765
- const here = dirname(fileURLToPath(import.meta.url));
766
- const smokeSource = [resolve(here, "../../agent-packs/src"), resolve(here, "../agent-packs/src")].find(existsSync);
767
- if (!smokeSource) throw new Error("Bundled owned smoke source unavailable.");
768
- return `(async () => {
769
- const expected = ${JSON.stringify({ pid, qualifier, journal, apply })};
770
- if (process.pid !== expected.pid || typeof process.getBuiltinModule !== 'function') throw new Error('Claude process identity or Node runtime differs.');
771
- const load = process.getBuiltinModule('module').createRequire(process.resourcesPath + '/app.asar/package.json');
772
- if (load('electron').app.getVersion() !== expected.qualifier.version) throw new Error('Unqualified Claude Desktop version.');
773
- const fs = load('node:fs'), crypto = load('node:crypto'), path = load('node:path');
774
- const base = process.resourcesPath + '/app.asar/.vite/build/';
775
- for (const [file, hash] of Object.entries(expected.qualifier.hashes)) {
776
- if (crypto.createHash('sha256').update(fs.readFileSync(base + file)).digest('hex') !== hash) throw new Error('Claude native module hash changed: ' + file);
777
- }
778
- const manager = load(base + expected.qualifier.manager).claudeCodeSessionManager;
779
- const transport = load(base + expected.qualifier.sidebar);
780
- const checkpoint = value => {
781
- const fd = fs.openSync(expected.journal, 'a');
782
- try { fs.writeSync(fd, JSON.stringify(value) + '\\n'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
783
- };
784
- const context = ${JSON.stringify(plan.context)};
785
- const inventories = ${JSON.stringify(plan.contextInventories)};
786
- const snapshotMarkdown = (${snapshotClaudeMarkdown.toString()});
787
- const verifyContext = () => {
788
- if (!inventories || !Object.keys(inventories).length) throw new Error('Complete context inventory proof is unavailable.');
789
- for (const [root, inventory] of Object.entries(inventories))
790
- if (JSON.stringify(snapshotMarkdown(root, fs, crypto, path)) !== JSON.stringify(inventory))
791
- throw new Error('Context or transcript changed during configuration: Markdown inventory ' + root);
792
- for (const [file, hash] of Object.entries(context))
793
- if (crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') !== hash)
794
- throw new Error('Context or transcript changed during configuration: ' + file);
795
- };
796
- const result = await (${nativeClaudePackOperation.toString()})(manager,
797
- value => transport.P(value, transport.M),
798
- { members: ${JSON.stringify(plan.members)}, outgoing: ${JSON.stringify(plan.outgoing)},
799
- operationId: ${JSON.stringify(plan.operationId)}, mode: ${JSON.stringify(plan.recovery ? "recover" : plan.mode)},
800
- noEffects: ${JSON.stringify(plan.noEffects)},
801
- deadline: Date.now() + 45000 }, expected.apply, checkpoint, verifyContext);
802
- ${plan.approvalRoutes.length ? `const routes = ${JSON.stringify(plan.approvalRoutes)};
803
- const fingerprint = value => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
804
- const qualifyNative = () => {
805
- if (process.pid !== expected.pid || load('electron').app.getVersion() !== expected.qualifier.version) throw new Error('Native process changed.');
806
- for (const [file, hash] of Object.entries(expected.qualifier.hashes))
807
- if (crypto.createHash('sha256').update(fs.readFileSync(base + file)).digest('hex') !== hash) throw new Error('Native module changed.');
808
- };
809
- const smokeIdentity = fingerprint({pid: expected.pid, qualifier: expected.qualifier, routes});
810
- const invoke = op => ['smoke-start', 'smoke-read'].includes(op.kind) ?
811
- (${nativeClaudeOwnedSmokeOperation.toString()})(manager, ${JSON.stringify(plan.members)}, op,
812
- (action, payload) => (${runClaudeSmokeHelper.toString()})(${JSON.stringify(plan.libraryRoot)}, action, payload,
813
- ${JSON.stringify(realpathSync(smokeSource))}, load('node:child_process').spawn), fingerprint, smokeIdentity, qualifyNative) :
814
- (${nativeClaudeApprovalOperation.toString()})(manager, routes, op, fingerprint,
815
- row => checkpoint({kind: 'approval', ...row}),
816
- fs.readFileSync(expected.journal, 'utf8').split('\\n').filter(Boolean).map(line => JSON.parse(line)));
817
- if (expected.apply) {
818
- result.approvalRouting = await invoke({kind: 'install'});
819
- const control = ${JSON.stringify(plan.control)};
820
- if (!control) throw new Error('Owned native control setup is unavailable.');
821
- const stat = fs.lstatSync(control.secretPath);
822
- if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 63)) throw new Error('Unowned native control secret.');
823
- const secret = JSON.parse(fs.readFileSync(control.secretPath, 'utf8'));
824
- result.approvalRouting.control = await (${nativeClaudeApprovalControl.toString()})(manager,
825
- {socket: control.socket, pid: expected.pid, identity: fingerprint(routes)}, secret.token,
826
- load('node:net'), fs, invoke, qualifyNative, checkpoint);
827
- } else if (${JSON.stringify(plan.recovery === true && !plan.noEffects)}) {
828
- const current = manager[Symbol.for('topolo.agent-pack.approval-control.v1')];
829
- if (!current || current.descriptor.pid !== expected.pid || current.descriptor.identity !== fingerprint(routes))
830
- throw new Error('Native intake control is not reconciled.');
831
- result.approvalRouting = {state: 'native-approval-listener-installed', roles: routes.length, control: current.descriptor};
832
- }` : ""}
833
- return result;
834
- })()`;
835
- }
836
- function evaluateClaudeMain(endpoint, expression, socketFactory = (url) => new WebSocket(url)) {
837
- const url = validateInspectorEndpoint(endpoint);
838
- return new Promise((resolveResult, reject) => {
839
- const socket = socketFactory(url);
840
- let finished = false;
841
- const finish = (error, result) => {
842
- if (finished) return;
843
- finished = true;
844
- clearTimeout(timer);
845
- socket.close();
846
- if (error) reject(error);
847
- else resolveResult(result);
848
- };
849
- const timer = setTimeout(() => finish(new Error("Claude backend timed out; reconcile the journal before retry.")), 55e3);
850
- socket.addEventListener("open", () => socket.send(JSON.stringify({
851
- id: 1,
852
- method: "Runtime.evaluate",
853
- params: { expression, awaitPromise: true, returnByValue: true }
854
- })));
855
- socket.addEventListener("message", (event) => {
856
- try {
857
- const reply = JSON.parse(String(event.data));
858
- if (reply.id !== 1) return;
859
- if (reply.error || reply.result?.exceptionDetails)
860
- finish(new Error(reply.error?.message || reply.result.exceptionDetails.exception?.description || "Native operation failed; reconcile the journal."));
861
- else finish(void 0, reply.result.result.value);
862
- } catch {
863
- finish(new Error("Invalid Claude backend reply; reconcile the journal."));
864
- }
865
- });
866
- socket.addEventListener("error", () => finish(new Error("Claude backend connection failed.")));
867
- socket.addEventListener("close", () => finish(new Error("Claude backend disconnected; reconcile the journal.")));
868
- });
869
- }
870
- async function lockClaudeLibrary(root) {
871
- const script = 'import os,sys,fcntl\nf=os.open(sys.argv[1],os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600)\nfcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB)\nprint("locked",flush=True)\nsys.stdin.buffer.read()\nos.close(f)';
872
- const child = spawn("python3", ["-c", script, resolve(root, ".lock")], { stdio: ["pipe", "pipe", "pipe"] });
873
- await new Promise((done, fail) => {
874
- let ready = false;
875
- const timer = setTimeout(() => {
876
- child.kill();
877
- fail(new Error("Pack library lock timed out."));
878
- }, 5e3);
879
- child.once("error", (error) => {
880
- clearTimeout(timer);
881
- fail(error);
882
- });
883
- child.stdout.once("data", (data) => {
884
- if (String(data).trim() === "locked") {
885
- ready = true;
886
- clearTimeout(timer);
887
- done();
888
- }
889
- });
890
- child.once("exit", () => {
891
- clearTimeout(timer);
892
- if (!ready) fail(new Error("Another operation owns the pack library, or its lock is unavailable."));
893
- });
894
- child.stderr.resume();
895
- });
896
- return async () => {
897
- await new Promise((done) => {
898
- if (child.exitCode !== null || child.signalCode !== null) done();
899
- else {
900
- child.once("exit", () => done());
901
- child.stdin.end();
902
- }
903
- });
904
- };
905
- }
906
- function durableRecord(path, value, flag = "a") {
907
- const fd = openSync(path, flag, 384);
908
- try {
909
- writeFileSync(fd, JSON.stringify(value) + "\n");
910
- fsyncSync(fd);
911
- } finally {
912
- closeSync(fd);
913
- }
914
- }
915
- function syncDirectory(path) {
916
- const fd = openSync(path, "r");
917
- try {
918
- fsyncSync(fd);
919
- } finally {
920
- closeSync(fd);
921
- }
922
- }
923
- function verifyPlanContext(plan) {
924
- if (!plan.contextInventories || !Object.keys(plan.contextInventories).length) throw new Error("Complete context inventory proof is unavailable.");
925
- for (const [root, inventory] of Object.entries(plan.contextInventories))
926
- if (JSON.stringify(snapshotClaudeMarkdown(root, filesystem, cryptography, paths)) !== JSON.stringify(inventory))
927
- throw new Error("Context or transcript changed during configuration: Markdown inventory " + root);
928
- for (const [file, hash] of Object.entries(plan.context))
929
- if (createHash("sha256").update(readFileSync(file)).digest("hex") !== hash) throw new Error("Context or transcript changed during configuration: " + file);
930
- }
931
- function verifyClaudeOrganizationPolicy(root, pack, consent, run = spawnSync, locate = existsSync) {
932
- const here = dirname(fileURLToPath(import.meta.url));
933
- const bundled = [resolve(here, "../../agent-packs/src"), resolve(here, "../agent-packs/src")].find(locate);
934
- if (!bundled) throw new Error("Bundled organization policy loader unavailable.");
935
- const source = realpathSync(bundled);
936
- const script = 'import json,sys\nsys.path.insert(0,sys.argv[4])\nfrom topolo_agent_pack import permissions,topolo\nfrom topolo_agent_pack.storage import Library\nlib=Library(sys.argv[1]);manifest,_=lib.load(sys.argv[2]);c=permissions.load(lib,sys.argv[2],manifest["agents"])\nif c!=json.loads(sys.argv[3]):raise RuntimeError("Installation consent changed")\np,proof=topolo.organization_execution_policy(topolo.Client(c["environment"],c["contextKey"]),c,manifest["agents"],c.get("agentWorkspaceId"))\npermissions.authorize_native_scope(proof)\nprint(json.dumps(proof))';
937
- const result = run(
938
- "python3",
939
- ["-I", "-B", "-c", script, root, pack, JSON.stringify(consent), source],
940
- { encoding: "utf8", timeout: 2e5, cwd: source, env: { ...process.env } }
941
- );
942
- if (result.error || result.status !== 0) throw new Error("Fresh authenticated organization policy qualification failed; no native permission widening.");
943
- const proof = JSON.parse(result.stdout);
944
- if (proof.profileCeilingVerified !== true || proof.contextKey !== consent.contextKey || proof.scopePolicyMode !== "unrestricted" || proof.toolActionRestrictionRequested !== false)
945
- throw new Error("Organization profile ceiling proof differs.");
946
- return proof;
947
- }
948
- async function configureClaudePack(options, evaluate = evaluateClaudeMain, qualify = verifyClaudeOrganizationPolicy) {
949
- validateInspectorEndpoint(options.endpoint);
950
- const root = realpathSync(options.store);
951
- if (lstatSync(resolve(root, "claude")).isSymbolicLink()) throw new Error("Claude library must not be a symlink.");
952
- const release = await lockClaudeLibrary(root);
953
- try {
954
- const markerPath = resolve(root, "claude/native-operation.json");
955
- const recovering = options.mode === "recover";
956
- if (recovering && options.apply) throw new Error("Recovery is read-only; --apply is not permitted.");
957
- if (!recovering && existsSync(markerPath)) throw new Error("An unresolved Claude operation requires read-only recovery before another operation.");
958
- const directory = resolve(root, "claude/journals");
959
- mkdirSync(directory, { recursive: true, mode: 448 });
960
- if (lstatSync(directory).isSymbolicLink()) throw new Error("Claude journal directory must not be a symlink.");
961
- const operationId = randomUUID();
962
- let plan;
963
- let journal;
964
- let marker;
965
- if (recovering) {
966
- if (!existsSync(markerPath) || lstatSync(markerPath).isSymbolicLink()) throw new Error("No owned unresolved Claude operation is available.");
967
- marker = JSON.parse(readFileSync(markerPath, "utf8"));
968
- journal = realpathSync(marker.journal);
969
- if (!journal.startsWith(realpathSync(directory) + sep)) throw new Error("Recovery journal is outside the owned library.");
970
- const lines = readFileSync(journal, "utf8").split("\n").filter(Boolean);
971
- const line = lines[0];
972
- if (createHash("sha256").update(line).digest("hex") !== marker.planHash) throw new Error("Recovery plan identity changed.");
973
- const record = JSON.parse(line);
974
- if (record.pack !== options.pack || record.operationId !== marker.operationId || !record.apply) throw new Error("Recovery pack or operation identity differs.");
975
- plan = { ...record, approvalRoutes: record.approvalRoutes ?? [], recovery: true, noEffects: marker.format === 2 && marker.dispatchState === "not-dispatched" && !lines.map((line2) => JSON.parse(line2)).some((r) => r.kind === "attempt") };
976
- } else {
977
- plan = { ...prepareClaudeNativePlan(root, options.pack, options.policy, options.mode === "switch" ? "switch" : "configure"), operationId };
978
- if (options.apply && plan.approvalRoutes.length) {
979
- const directory2 = resolve(root, "claude/private");
980
- mkdirSync(directory2, { recursive: true, mode: 448 });
981
- const socketDirectory = resolve("/tmp", "topolo-claude-pack-" + createHash("sha256").update(root).digest("hex").slice(0, 16));
982
- mkdirSync(socketDirectory, { recursive: true, mode: 448 });
983
- for (const path of [directory2, socketDirectory]) {
984
- const stat = lstatSync(path);
985
- if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || stat.mode & 63)
986
- throw new Error("Native control directory must be owned and private.");
987
- }
988
- plan.control = { socket: resolve(socketDirectory, operationId + ".sock"), secretPath: resolve(directory2, operationId + ".json") };
989
- durableRecord(plan.control.secretPath, { token: randomBytes(32).toString("hex") }, "wx");
990
- syncDirectory(directory2);
991
- }
992
- journal = resolve(directory, operationId + ".jsonl");
993
- const record = { kind: "plan", pack: options.pack, ...plan, apply: options.apply };
994
- durableRecord(journal, record, "wx");
995
- marker = { format: 2, dispatchState: "not-dispatched", operationId, journal, planHash: createHash("sha256").update(JSON.stringify(record)).digest("hex") };
996
- if (options.apply) durableRecord(markerPath, marker, "wx");
997
- syncDirectory(directory);
998
- syncDirectory(resolve(root, "claude"));
999
- }
1000
- try {
1001
- verifyPlanContext(plan);
1002
- const organizationPolicy = options.apply && plan.approvalRoutes.length ? qualify(root, options.pack, plan.installationConsent) : null;
1003
- if (options.apply) {
1004
- const dispatched = { ...marker, dispatchState: "may-have-effects" };
1005
- const temporaryMarker = resolve(root, "claude/native-dispatch-" + operationId + ".json");
1006
- durableRecord(temporaryMarker, dispatched, "wx");
1007
- renameSync(temporaryMarker, markerPath);
1008
- syncDirectory(resolve(root, "claude"));
1009
- marker = dispatched;
1010
- }
1011
- const result = await evaluate(options.endpoint, nativePackExpression(options.pid, plan, journal, options.apply));
1012
- verifyPlanContext(plan);
1013
- if (options.apply || recovering) {
1014
- if (plan.noEffects) {
1015
- if (result.state !== "native-reconciled-no-effects" || result.nativeEffectsReplayed !== false || result.after?.length !== plan.members.length || result.after.some((actual, i) => ["key", "sessionId", "cwd", "title"].some((key) => actual[key] !== plan.members[i][key])))
1016
- throw new Error("No-effect recovery has no qualified native acknowledgement.");
1017
- const activePath2 = resolve(root, "claude/active.json");
1018
- const current2 = existsSync(activePath2) ? JSON.parse(readFileSync(activePath2, "utf8")) : null;
1019
- if (JSON.stringify(current2) !== JSON.stringify(plan.activeBefore)) throw new Error("Active roster changed during no-effect recovery.");
1020
- durableRecord(journal, { kind: "context-verified", context: plan.context, nativeEffects: "none-attempted" });
1021
- if (JSON.stringify(JSON.parse(readFileSync(markerPath, "utf8"))) !== JSON.stringify(marker)) throw new Error("Recovery marker identity changed.");
1022
- unlinkSync(markerPath);
1023
- syncDirectory(resolve(root, "claude"));
1024
- return { ...result, journal, contextPreserved: true };
1025
- }
1026
- if (result.state !== (recovering ? "native-reconciled" : "native-settings-verified") || result.after?.length !== plan.members.length) throw new Error("Native result has no complete verified roster.");
1027
- for (let i = 0; i < plan.members.length; i++) {
1028
- const wanted = plan.members[i];
1029
- const actual = result.after[i];
1030
- if (actual.archived !== false || ["key", "sessionId", "cwd", "title", "group", "pinned", "model", "effort", "permissionMode"].some((key) => actual[key] !== wanted[key])) throw new Error("Native result settings do not match the reviewed roster.");
1031
- }
1032
- if (plan.outgoing.length && (result.outgoingAfter?.length !== plan.outgoing.length || result.outgoingAfter.some((actual, i) => actual.archived !== true || ["key", "sessionId", "cwd", "title"].some((key) => actual[key] !== plan.outgoing[i][key]))))
1033
- throw new Error("Native outgoing archive result does not match the reviewed roster.");
1034
- if (plan.approvalRoutes.length && (options.apply || recovering) && (result.approvalRouting?.state !== "native-approval-listener-installed" || result.approvalRouting.roles !== plan.members.length || result.approvalRouting.control?.pid !== options.pid || result.approvalRouting.control?.socket !== plan.control?.socket))
1035
- throw new Error("Complete native intake routing acknowledgement is unavailable.");
1036
- const activePath = resolve(root, "claude/active.json");
1037
- const current = existsSync(activePath) ? JSON.parse(readFileSync(activePath, "utf8")) : null;
1038
- const active = { operationId: plan.operationId, pack: options.pack, keys: plan.members.map((m) => m.key), sourceRevision: plan.sourceRevision };
1039
- if (JSON.stringify(current) !== JSON.stringify(plan.activeBefore) && JSON.stringify(current) !== JSON.stringify(active))
1040
- throw new Error("Verified active roster changed outside this operation.");
1041
- const temporary = resolve(root, "claude/active-" + plan.operationId + ".json");
1042
- if (existsSync(temporary)) {
1043
- if (lstatSync(temporary).isSymbolicLink() || readFileSync(temporary, "utf8") !== JSON.stringify(active) + "\n") throw new Error("Active commit identity changed.");
1044
- } else durableRecord(temporary, active, "wx");
1045
- renameSync(temporary, activePath);
1046
- syncDirectory(resolve(root, "claude"));
1047
- durableRecord(journal, { kind: "context-verified", context: plan.context, active });
1048
- if ((options.apply || recovering) && plan.approvalRoutes.length) {
1049
- const target = resolve(root, "claude/approval-connection.json");
1050
- const temporaryConnection = resolve(root, "claude/approval-connection-" + plan.operationId + ".json");
1051
- durableRecord(temporaryConnection, {
1052
- pid: options.pid,
1053
- socket: plan.control.socket,
1054
- secretPath: plan.control.secretPath,
1055
- identity: result.approvalRouting.control.identity,
1056
- pack: options.pack,
1057
- installationConsent: plan.installationConsent,
1058
- routes: plan.approvalRoutes,
1059
- journal,
1060
- organizationPolicy
1061
- }, "wx");
1062
- renameSync(temporaryConnection, target);
1063
- syncDirectory(resolve(root, "claude"));
1064
- }
1065
- if (JSON.stringify(JSON.parse(readFileSync(markerPath, "utf8"))) !== JSON.stringify(marker)) throw new Error("Recovery marker identity changed.");
1066
- unlinkSync(markerPath);
1067
- syncDirectory(resolve(root, "claude"));
1068
- } else durableRecord(journal, { kind: "context-verified", context: plan.context });
1069
- return { ...result, journal, contextPreserved: true };
1070
- } catch (error) {
1071
- durableRecord(journal, { kind: "recovery-required" });
1072
- throw new Error(`Claude configuration is incomplete. Reconcile ${journal}. ${error instanceof Error ? error.message : String(error)}`);
1073
- }
1074
- } finally {
1075
- await release();
1076
- }
1077
- }
1078
- function runClaudeSmokeHelper(root, action, payload, source, launch = spawn) {
1079
- if (!["prepare", "arm", "mark", "read", "verify"].includes(action) || typeof root !== "string" || typeof source !== "string")
1080
- return Promise.reject(new Error("Closed owned smoke helper required."));
1081
- const script = 'import sys,json\nsys.path.insert(0,sys.argv[3])\nfrom topolo_agent_pack.storage import Library\nfrom topolo_agent_pack.live import OwnedSmoke\ns=OwnedSmoke(Library(sys.argv[1]),"claude")\np=json.loads(sys.stdin.read(16384))\na=sys.argv[2]\nr=s.prepare(**p) if a=="prepare" else s.arm(**p) if a=="arm" else s.mark(**p) if a=="mark" else s.verify(p["operation"]) if a=="verify" else s.read(p["operation"])\nprint(json.dumps(r))';
1082
- return new Promise((done, fail) => {
1083
- const child = launch("python3", ["-I", "-B", "-c", script, root, action, source], { stdio: ["pipe", "pipe", "pipe"] });
1084
- let output = "";
1085
- let settled = false;
1086
- const finish = (error, value) => {
1087
- if (settled) return;
1088
- settled = true;
1089
- clearTimeout(timer);
1090
- error ? fail(error) : done(value);
1091
- };
1092
- const timer = setTimeout(() => {
1093
- child.kill("SIGTERM");
1094
- finish(new Error("Owned smoke helper timed out; reconcile without replay."));
1095
- }, 6e4);
1096
- child.stdout.setEncoding("utf8");
1097
- child.stderr.resume();
1098
- child.stdout.on("data", (data) => {
1099
- output += data;
1100
- if (Buffer.byteLength(output) > 1048576) {
1101
- child.kill("SIGTERM");
1102
- finish(new Error("Owned smoke evidence exceeds bounded transport."));
1103
- }
1104
- });
1105
- child.on("error", () => finish(new Error("Bundled owned smoke helper unavailable.")));
1106
- child.on("close", (code) => {
1107
- if (settled) return;
1108
- if (code !== 0) return finish(new Error("Owned smoke qualification refused; preserve its journal."));
1109
- try {
1110
- finish(void 0, JSON.parse(output));
1111
- } catch {
1112
- finish(new Error("Invalid owned smoke helper result."));
1113
- }
1114
- });
1115
- child.stdin.on("error", () => finish(new Error("Owned smoke helper input failed; reconcile without replay.")));
1116
- child.stdin.end(JSON.stringify(payload));
1117
- });
1118
- }
1119
- function requestClaudeApprovalControl(connection, operation, token, connect = createConnection) {
1120
- const parent = lstatSync(dirname(connection.socket));
1121
- const socket = lstatSync(connection.socket);
1122
- if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.() || parent.mode & 63 || !socket.isSocket() || socket.uid !== process.getuid?.() || socket.mode & 63)
1123
- throw new Error("Unowned native control socket.");
1124
- return new Promise((done, fail) => {
1125
- const client = connect({ path: connection.socket });
1126
- let reply = "";
1127
- let finished = false;
1128
- const finish = (error, result) => {
1129
- if (finished) return;
1130
- finished = true;
1131
- client.destroy();
1132
- error ? fail(error) : done(result);
1133
- };
1134
- client.setEncoding("utf8");
1135
- client.setTimeout(operation.kind === "smoke-start" ? 6e4 : 1e4, () => finish(new Error("Native approval response timed out; reconcile without replay.")));
1136
- client.on("connect", () => client.write(JSON.stringify({ token, pid: connection.pid, identity: connection.identity, operation }) + "\n"));
1137
- client.on("data", (chunk) => {
1138
- reply += chunk;
1139
- if (Buffer.byteLength(reply) > 262144) return finish(new Error("Native approval response exceeds bounded transport."));
1140
- if (!reply.includes("\n")) return;
1141
- try {
1142
- const result = JSON.parse(reply);
1143
- finish(result.error ? new Error(result.error) : void 0, result.result);
1144
- } catch {
1145
- finish(new Error("Invalid native approval response."));
1146
- }
1147
- });
1148
- client.on("error", () => finish(new Error("Existing native approval control is unavailable.")));
1149
- client.on("close", () => finish(new Error("Native approval response was lost; reconcile without replay.")));
1150
- });
1151
- }
1152
- async function operateClaudeApprovals(options, request = requestClaudeApprovalControl, qualify = verifyClaudeOrganizationPolicy) {
1153
- const root = realpathSync(options.store);
1154
- const file = resolve(root, "claude/approval-connection.json");
1155
- if (lstatSync(file).isSymbolicLink()) throw new Error("Unowned approval connection.");
1156
- const connection = JSON.parse(readFileSync(file, "utf8"));
1157
- if (!Number.isSafeInteger(connection.pid) || connection.pid < 1 || !Array.isArray(connection.routes))
1158
- throw new Error("Unqualified native approval connection.");
1159
- if (options.kind === "respond" && options.decision === "once")
1160
- qualify(root, connection.pack, connection.installationConsent);
1161
- const journal = realpathSync(connection.journal);
1162
- if (!journal.startsWith(realpathSync(resolve(root, "claude/journals")) + sep)) throw new Error("Unowned approval journal.");
1163
- const privateDirectory = resolve(root, "claude/private");
1164
- const secretPath = realpathSync(connection.secretPath);
1165
- const stat = lstatSync(connection.secretPath);
1166
- if (!secretPath.startsWith(realpathSync(privateDirectory) + sep) || !stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || stat.mode & 63) throw new Error("Unowned native control secret.");
1167
- const secret = JSON.parse(readFileSync(secretPath, "utf8"));
1168
- if (!/^[a-f0-9]{64}$/.test(secret.token) || !/^[a-f0-9]{64}$/.test(connection.identity)) throw new Error("Native control identity is invalid.");
1169
- if (options.kind === "smoke-start" || options.kind === "smoke-read") return request(
1170
- connection,
1171
- {
1172
- kind: options.kind,
1173
- operationId: options.operationId,
1174
- ...options.kind === "smoke-start" ? { key: options.key, caseId: options.caseId } : {}
1175
- },
1176
- secret.token
1177
- );
1178
- return request(connection, {
1179
- kind: options.kind,
1180
- key: options.key,
1181
- intake: options.intake,
1182
- fingerprint: options.fingerprint,
1183
- decision: options.decision,
1184
- humanDecisionRecorded: options.humanDecisionRecorded
1185
- }, secret.token);
1186
- }
1187
- async function operateClaudeSmoke(options, request = requestClaudeApprovalControl) {
1188
- const fields = options.kind === "smoke-start" ? ["store", "kind", "operationId", "key", "caseId"] : ["store", "kind", "operationId"];
1189
- if (!["smoke-start", "smoke-read"].includes(options.kind) || Object.keys(options).some((k) => !fields.includes(k)) || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(options.operationId) || options.kind === "smoke-start" && (!/^[a-z0-9-]+\/[a-z0-9-]+\/[a-z0-9-]+$/.test(options.key ?? "") || !["stg-context-memory-bytes", "stg-peer-ack", "prod-role-context-ack"].includes(options.caseId ?? "")))
1190
- throw new Error("Exact closed native smoke fields required.");
1191
- return operateClaudeApprovals(options, request);
1192
- }
1193
- export {
1194
- CLAUDE_NATIVE_QUALIFIER,
1195
- configureClaudePack,
1196
- evaluateClaudeMain,
1197
- lockClaudeLibrary,
1198
- nativePackExpression,
1199
- operateClaudeApprovals,
1200
- operateClaudeSmoke,
1201
- prepareClaudeNativePlan,
1202
- requestClaudeApprovalControl,
1203
- runClaudeSmokeHelper,
1204
- snapshotClaudeMarkdown,
1205
- validateInspectorEndpoint,
1206
- verifyClaudeOrganizationPolicy
1207
- };