claude-code-session-manager 0.141.0 → 0.143.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +76 -153
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
- package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
- package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
- package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
- package/dist/assets/Scheduler-CNLjn90m.js +16 -0
- package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
- package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
- package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
- package/dist/assets/Toggle-CYajnSdx.js +1 -0
- package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
- package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
- package/dist/assets/index-CdTppjKR.js +3133 -0
- package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +496 -484
- package/package.json +6 -4
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/hooks/hooks.json +15 -0
- package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
- package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +5 -1
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
- package/scripts/scheduler-mcp-server.cjs +1032 -112
- package/src/main/adminRouteRegistry.cjs +69 -0
- package/src/main/agentLibrary.cjs +72 -4
- package/src/main/agentsIpc.cjs +3 -2
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +336 -23
- package/src/main/config.cjs +35 -1
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +129 -2
- package/src/main/index.cjs +110 -52
- package/src/main/ipcSchemas.cjs +172 -8
- package/src/main/lib/AGENTS.md +1 -1
- package/src/main/lib/chatBootRecovery.cjs +2 -0
- package/src/main/lib/claude/agentModelResolve.cjs +51 -25
- package/src/main/lib/claude/agentSnapshot.cjs +186 -0
- package/src/main/lib/claude/environmentProfiles.cjs +242 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
- package/src/main/lib/claude/personaToolScope.cjs +82 -31
- package/src/main/lib/claude/runClaudeP.cjs +4 -2
- package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
- package/src/main/lib/claude/usageCircuit.cjs +49 -21
- package/src/main/lib/claude/vaultRefs.cjs +277 -0
- package/src/main/lib/demo-video-kit/capture.cjs +282 -12
- package/src/main/lib/demo-video-kit/cast.md +52 -0
- package/src/main/lib/demo-video-kit/character.cjs +778 -30
- package/src/main/lib/demo-video-kit/checks.cjs +120 -1
- package/src/main/lib/demo-video-kit/export.cjs +218 -0
- package/src/main/lib/demo-video-kit/frames.cjs +104 -9
- package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
- package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
- package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
- package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
- package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
- package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
- package/src/main/lib/demo-video-kit/sound.cjs +166 -9
- package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
- package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
- package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
- package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
- package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
- package/src/main/lib/epic/artifactIpc.cjs +153 -0
- package/src/main/lib/epic/artifactNotice.cjs +72 -0
- package/src/main/lib/epic/artifactRetention.cjs +356 -0
- package/src/main/lib/epic/artifactStore.cjs +435 -0
- package/src/main/lib/epic/delegationReadiness.cjs +83 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +258 -0
- package/src/main/lib/epic/epicMint.cjs +43 -1
- package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
- package/src/main/lib/epic/epicOutsideState.cjs +18 -4
- package/src/main/lib/epic/epicPurge.cjs +347 -0
- package/src/main/lib/epic/epicReopen.cjs +5 -2
- package/src/main/lib/epic/epicSettle.cjs +4 -13
- package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
- package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
- package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
- package/src/main/lib/epic/epicTransitions.cjs +139 -0
- package/src/main/lib/epic/epicValidationHook.cjs +94 -4
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +48 -4
- package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
- package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
- package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
- package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
- package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
- package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
- package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
- package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
- package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
- package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
- package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
- package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
- package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
- package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
- package/src/main/lib/git/gitWorktree.cjs +8 -0
- package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
- package/src/main/lib/git/worktreeDeps.cjs +182 -4
- package/src/main/lib/mcpToolCatalog.cjs +399 -29
- package/src/main/lib/opsOwnership.cjs +141 -28
- package/src/main/lib/opsRetentionSettings.cjs +27 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
- package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
- package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
- package/src/main/lib/phaseProjection.cjs +103 -0
- package/src/main/lib/prd/depSlugResolve.cjs +4 -13
- package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
- package/src/main/lib/prd/prdCreate.cjs +387 -228
- package/src/main/lib/prd/prdCriteria.cjs +228 -0
- package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
- package/src/main/lib/prd/prdGateFiles.cjs +125 -49
- package/src/main/lib/prd/prdSizing.cjs +3 -1
- package/src/main/lib/process/cleanEnv.cjs +52 -1
- package/src/main/lib/process/leftoverRenice.cjs +178 -0
- package/src/main/lib/process/memoryScope.cjs +31 -3
- package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
- package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
- package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
- package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
- package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
- package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
- package/src/main/lib/project-pages/voicePreview.cjs +196 -0
- package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
- package/src/main/lib/scheduler/cpuSample.cjs +133 -42
- package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
- package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
- package/src/main/lib/scheduler/queueStore.cjs +16 -0
- package/src/main/lib/scheduler/rcaReport.cjs +79 -15
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
- package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
- package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
- package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
- package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
- package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
- package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
- package/src/main/lib/tasks/mitigationReview.cjs +314 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
- package/src/main/lib/tasks/taskIpc.cjs +22 -18
- package/src/main/lib/tasks/taskLedger.cjs +147 -25
- package/src/main/lib/tasks/taskRun.cjs +186 -17
- package/src/main/lib/tasks/taskSwitch.cjs +85 -12
- package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
- package/src/main/lib/telemetry/auditEvents.cjs +204 -6
- package/src/main/lib/telemetry/auditLog.cjs +6 -2
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
- package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
- package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
- package/src/main/lib/toolUseClassify.cjs +181 -0
- package/src/main/lib/util/atomicFs.cjs +2 -2
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +21 -1
- package/src/main/pty.cjs +77 -0
- package/src/main/queueOps.cjs +33 -14
- package/src/main/runVerify.cjs +74 -9
- package/src/main/scheduler/AGENTS.md +1 -0
- package/src/main/scheduler/budget.cjs +6 -5
- package/src/main/scheduler/prdParser.cjs +46 -13
- package/src/main/scheduler/reviewLadder.cjs +9 -25
- package/src/main/scheduler/utilizationHold.cjs +191 -0
- package/src/main/scheduler.cjs +1932 -213
- package/src/main/templates/PRD_AUTHORING.md +11 -3
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +576 -39
- package/src/preload/apiSurface.json +223 -7
- package/src/preload/index.cjs +48 -1
- package/src/seed/agents/architect.md +6 -1
- package/src/seed/agents/blender-artist.md +2 -1
- package/src/seed/agents/competitive-analyst.md +3 -1
- package/src/seed/agents/competitive-researcher.md +2 -1
- package/src/seed/agents/demo-video-builder.md +98 -87
- package/src/seed/agents/dev-lead.md +3 -3
- package/src/seed/agents/project-home-builder.md +9 -31
- package/src/seed/agents/validator.md +23 -23
- package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
- package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
- package/dist/assets/Scheduler-cyr61UAC.js +0 -16
- package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
- package/dist/assets/index-B2TQz3nd.js +0 -3121
- package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
|
@@ -7,11 +7,58 @@
|
|
|
7
7
|
*/
|
|
8
8
|
'use strict';
|
|
9
9
|
|
|
10
|
+
const fs = require('node:fs');
|
|
11
|
+
const path = require('node:path');
|
|
12
|
+
const { readJsonOrSync, writeJsonAtomicSync } = require('../util/atomicFs.cjs');
|
|
10
13
|
const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
|
|
11
14
|
const { isProvablyDead, DEFAULT_GRACE_MS } = require('./reservationExpiry.cjs');
|
|
12
15
|
|
|
13
16
|
const investigations = new Map(); // slug -> { claimedAt, pid }
|
|
14
17
|
|
|
18
|
+
/*
|
|
19
|
+
* Persisted machine runtime state (survives restarts), unlike the
|
|
20
|
+
* process-local reservations above: <schedulerHome>/scheduler-runtime-state.json.
|
|
21
|
+
* Today it holds one key, `environmentReportSince` — epoch ms of the first
|
|
22
|
+
* time environment enforcement was evaluated on this machine. The report-only
|
|
23
|
+
* week (schedulerConfig.environmentEnforcement) is measured from it. Written
|
|
24
|
+
* once, atomically, and never reset: a restart re-reads the same value.
|
|
25
|
+
*/
|
|
26
|
+
const RUNTIME_STATE_FILE = 'scheduler-runtime-state.json';
|
|
27
|
+
|
|
28
|
+
function runtimeStatePath() {
|
|
29
|
+
const { schedulerHome } = require('./schedulerPaths.cjs');
|
|
30
|
+
return path.join(schedulerHome(), RUNTIME_STATE_FILE);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @type {Map<string, number>} statePath -> environmentReportSince (memo; the value never changes once written) */
|
|
34
|
+
const reportSinceMemo = new Map();
|
|
35
|
+
|
|
36
|
+
function validStamp(v) {
|
|
37
|
+
return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The persisted environmentReportSince (epoch ms), writing `now` first if no
|
|
42
|
+
* valid value is on disk yet. Never overwrites an existing value. Throws only
|
|
43
|
+
* if the state file cannot be written.
|
|
44
|
+
* @param {{ now?: number, statePath?: string }} [opts]
|
|
45
|
+
* @returns {number}
|
|
46
|
+
*/
|
|
47
|
+
function ensureEnvironmentReportSince({ now = Date.now(), statePath = runtimeStatePath() } = {}) {
|
|
48
|
+
const memo = reportSinceMemo.get(statePath);
|
|
49
|
+
if (memo) return memo;
|
|
50
|
+
const state = readJsonOrSync(statePath, null);
|
|
51
|
+
const obj = state && typeof state === 'object' && !Array.isArray(state) ? state : {};
|
|
52
|
+
let since = validStamp(obj.environmentReportSince);
|
|
53
|
+
if (!since) {
|
|
54
|
+
since = now;
|
|
55
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true });
|
|
56
|
+
writeJsonAtomicSync(statePath, { ...obj, environmentReportSince: since });
|
|
57
|
+
}
|
|
58
|
+
reportSinceMemo.set(statePath, since);
|
|
59
|
+
return since;
|
|
60
|
+
}
|
|
61
|
+
|
|
15
62
|
function investigationCount() { return investigations.size; }
|
|
16
63
|
|
|
17
64
|
/** reserveInvestigation(slug) — false if already reserved. Cap checks stay with the caller. */
|
|
@@ -47,7 +94,7 @@ function expireDeadInvestigations({ liveSlugs, pidAlive, now = Date.now(), grace
|
|
|
47
94
|
return expired;
|
|
48
95
|
}
|
|
49
96
|
|
|
50
|
-
function __resetForTests() { investigations.clear(); }
|
|
97
|
+
function __resetForTests() { investigations.clear(); reportSinceMemo.clear(); }
|
|
51
98
|
|
|
52
99
|
module.exports = {
|
|
53
100
|
investigationCount,
|
|
@@ -55,5 +102,7 @@ module.exports = {
|
|
|
55
102
|
stampInvestigationPid,
|
|
56
103
|
releaseInvestigation,
|
|
57
104
|
expireDeadInvestigations,
|
|
105
|
+
runtimeStatePath,
|
|
106
|
+
ensureEnvironmentReportSince,
|
|
58
107
|
__resetForTests,
|
|
59
108
|
};
|
|
@@ -167,8 +167,12 @@ function notify() {
|
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
-
/**
|
|
170
|
+
/**
|
|
171
|
+
* Turn the held interactive slot on/off (default off). Grants any waiter it unblocks.
|
|
172
|
+
* An unchanged value is a no-op (no grants, no listener calls), so callers may re-sync per request.
|
|
173
|
+
*/
|
|
171
174
|
function setInteractiveReserve(on) {
|
|
175
|
+
if (!!on === reserveOn) return reserveOn;
|
|
172
176
|
reserveOn = !!on;
|
|
173
177
|
notify();
|
|
174
178
|
return reserveOn;
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* slotsRoute.cjs — the agent path for the machine-wide session slot cap.
|
|
3
|
+
*
|
|
4
|
+
* GET /admin/scheduler/slots
|
|
5
|
+
* → 200 { ok, cap, min, max, inUse, available } from sessionSlots.cjs.
|
|
6
|
+
*
|
|
7
|
+
* POST /admin/scheduler/slots (body ≤ 64 KiB)
|
|
8
|
+
* { cap, quote, originClaudeSessionId, originProjectRoot?, callerJobSlug? }
|
|
9
|
+
* Changes the cap only on a verbatim quote of what the human typed in the
|
|
10
|
+
* calling chat session. Checks, in order, each refusal writing and auditing
|
|
11
|
+
* nothing:
|
|
12
|
+
* 1. 400 invalid_request — bad body, or cap not an integer in
|
|
13
|
+
* [MIN_SLOTS, MAX_SLOTS];
|
|
14
|
+
* 2. 403 called_from_headless_job — callerJobSlug is set (the MCP tool
|
|
15
|
+
* forwards SM_SCHEDULER_JOB_SLUG): a scheduled job never moves the cap;
|
|
16
|
+
* 3. 403 human_request_unverified — the quote is not in a prompt the
|
|
17
|
+
* human typed in originClaudeSessionId. Same verifier as
|
|
18
|
+
* taskSwitchRoute.cjs (humanPromptLedger.findHumanPromptContaining);
|
|
19
|
+
* headless jobs and Tasks never record prompts there, so they fail here
|
|
20
|
+
* too;
|
|
21
|
+
* 4. 403 quote_does_not_name_slots — no sentence of the quote is the
|
|
22
|
+
* one accepted form (see SLOT_COMMAND), or no whole sentence of the
|
|
23
|
+
* matched human prompt that contains the quote (or that the quote
|
|
24
|
+
* wholly covers) is that form — so "don't raise the limit to 14" or
|
|
25
|
+
* "raise the limit to 14?" never authorize via the quote
|
|
26
|
+
* 'raise the limit to 14'. The reason gives the form, e.g. say
|
|
27
|
+
* 'raise the limit to 14'.
|
|
28
|
+
* Success: sessionSlots.setCap(cap) (persists + wakes waiters), one
|
|
29
|
+
* slot_cap_changed audit event { from, to, epicId, quote, promptAt },
|
|
30
|
+
* 200 { ok, from, to }.
|
|
31
|
+
*
|
|
32
|
+
* Registered from index.cjs next to the other /admin/scheduler/ routes.
|
|
33
|
+
*/
|
|
34
|
+
'use strict';
|
|
35
|
+
|
|
36
|
+
const { z } = require('zod');
|
|
37
|
+
const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
38
|
+
|
|
39
|
+
const MAX_SLOTS_BODY_BYTES = 64 * 1024;
|
|
40
|
+
|
|
41
|
+
const slotsBodySchema = z.object({
|
|
42
|
+
cap: z.unknown(),
|
|
43
|
+
quote: z.string().min(1).max(2000),
|
|
44
|
+
originClaudeSessionId: z.string().min(1).max(128),
|
|
45
|
+
originProjectRoot: z.string().min(1).optional(),
|
|
46
|
+
callerJobSlug: z.string().max(256).optional(),
|
|
47
|
+
}).strict();
|
|
48
|
+
|
|
49
|
+
// The one accepted sentence form, matched against a whole sentence after
|
|
50
|
+
// lowercasing and collapsing spaces:
|
|
51
|
+
// [please|ok|okay|so|now|then[,]] set|raise|increase|bump|lower|reduce|change
|
|
52
|
+
// [the|our] [session|slot|parallel] limit|cap|slots to <digits> [sessions|slots]
|
|
53
|
+
// Nothing else may be in that sentence. Anything else —
|
|
54
|
+
// questions, negations, percentages, number words, extra words — is refused.
|
|
55
|
+
const SLOT_COMMAND = new RegExp(
|
|
56
|
+
'^(?:(?:please|ok|okay|so|now|then),? )?'
|
|
57
|
+
+ '(?:set|raise|increase|bump|lower|reduce|change) '
|
|
58
|
+
+ '(?:(?:the|our) )?'
|
|
59
|
+
+ '(?:(?:session|slot|parallel) )?'
|
|
60
|
+
+ '(?:limit|cap|slots) to (\\d+)'
|
|
61
|
+
+ '(?: (?:sessions|slots))?$',
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
/** The accepted form, as the refusal states it. @param {number} cap */
|
|
65
|
+
function acceptedFormHint(cap) {
|
|
66
|
+
return `say 'raise the limit to ${cap}' (one sentence: [please|ok|okay|so|now|then] `
|
|
67
|
+
+ 'set|raise|increase|bump|lower|reduce|change [the|our] [session|slot|parallel] limit|cap|slots '
|
|
68
|
+
+ 'to <number in digits> [sessions|slots], with nothing else in the sentence, a comma only right after '
|
|
69
|
+
+ 'the lead-in word, and no question mark)';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Sentence spans of `text`: split on . ! ? ; and line breaks, the terminator
|
|
74
|
+
* kept with its sentence; a decimal ("14.5") is not split. Returns the
|
|
75
|
+
* lowercased, whitespace-collapsed body, its trimmed [start, end) in `text`,
|
|
76
|
+
* and the terminator ('' at the end of the text).
|
|
77
|
+
* @param {string} text
|
|
78
|
+
* @returns {Array<{ body: string, start: number, end: number, term: string }>}
|
|
79
|
+
*/
|
|
80
|
+
function splitSentences(text) {
|
|
81
|
+
// Same-length mask keeps indices aligned with `text`.
|
|
82
|
+
const masked = text.toLowerCase().replace(/(\d)[.,](?=\d)/g, '$1#');
|
|
83
|
+
const out = [];
|
|
84
|
+
const sentence = /([^.!?;\r\n]*)([.!?;\r\n]|$)/g;
|
|
85
|
+
let m;
|
|
86
|
+
while ((m = sentence.exec(masked)) !== null) {
|
|
87
|
+
const raw = m[1];
|
|
88
|
+
const lead = raw.length - raw.replace(/^\s+/, '').length;
|
|
89
|
+
const trail = raw.length - raw.replace(/\s+$/, '').length;
|
|
90
|
+
const start = m.index + lead;
|
|
91
|
+
const end = m.index + raw.length - trail;
|
|
92
|
+
if (end > start) out.push({ body: raw.replace(/\s+/g, ' ').trim(), start, end, term: m[2] });
|
|
93
|
+
if (m[2] === '') break; // end of the text
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** @param {string} body @param {string} term @param {number} cap */
|
|
99
|
+
function sentenceNamesCap(body, term, cap) {
|
|
100
|
+
if (term === '?' || !body) return false;
|
|
101
|
+
const hit = SLOT_COMMAND.exec(body);
|
|
102
|
+
return !!hit && hit[1] === String(cap);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* True only when the human prompt `promptText` (the text the ledger matched)
|
|
107
|
+
* has a whole sentence in the strict SLOT_COMMAND form naming `cap` that
|
|
108
|
+
* either contains an occurrence of `quote` or lies wholly inside one. The
|
|
109
|
+
* quote is located the way humanPromptLedger matches it (lowercased,
|
|
110
|
+
* whitespace collapsed). A sentence the quote only partly overlaps never
|
|
111
|
+
* authorizes. Refuses on doubt.
|
|
112
|
+
* @param {unknown} promptText
|
|
113
|
+
* @param {unknown} quote
|
|
114
|
+
* @param {number} cap
|
|
115
|
+
*/
|
|
116
|
+
function promptSentenceNamesSlots(promptText, quote, cap) {
|
|
117
|
+
if (typeof promptText !== 'string' || typeof quote !== 'string') return false;
|
|
118
|
+
if (!Number.isInteger(cap) || cap < 0) return false;
|
|
119
|
+
const q = quote.replace(/\s+/g, ' ').trim().toLowerCase();
|
|
120
|
+
if (!q) return false;
|
|
121
|
+
// Normalized prompt + map from each normalized char to its index in promptText.
|
|
122
|
+
const lower = promptText.toLowerCase();
|
|
123
|
+
let norm = '';
|
|
124
|
+
/** @type {number[]} */
|
|
125
|
+
const map = [];
|
|
126
|
+
for (let i = 0; i < lower.length; i++) {
|
|
127
|
+
if (/\s/.test(lower[i])) {
|
|
128
|
+
if (norm.length && norm[norm.length - 1] !== ' ') { norm += ' '; map.push(i); }
|
|
129
|
+
} else { norm += lower[i]; map.push(i); }
|
|
130
|
+
}
|
|
131
|
+
const sentences = splitSentences(promptText);
|
|
132
|
+
for (let at = norm.indexOf(q); at !== -1; at = norm.indexOf(q, at + 1)) {
|
|
133
|
+
const qs = map[at];
|
|
134
|
+
const qe = map[at + q.length - 1] + 1;
|
|
135
|
+
for (const s of sentences) {
|
|
136
|
+
const contains = s.start <= qs && qe <= s.end;
|
|
137
|
+
const covered = qs <= s.start && s.end <= qe;
|
|
138
|
+
if ((contains || covered) && sentenceNamesCap(s.body, s.term, cap)) return true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* True only when one sentence of the quote is exactly the SLOT_COMMAND form
|
|
146
|
+
* naming `cap` in digits. Sentences split on . ! ? ; and line breaks; a
|
|
147
|
+
* sentence ended by '?' never authorizes; a decimal ("14.5") is not split, so
|
|
148
|
+
* it never reads as 14. Refuses on doubt.
|
|
149
|
+
* @param {unknown} quote
|
|
150
|
+
* @param {number} cap
|
|
151
|
+
*/
|
|
152
|
+
function quoteNamesSlots(quote, cap) {
|
|
153
|
+
if (typeof quote !== 'string' || !Number.isInteger(cap) || cap < 0) return false;
|
|
154
|
+
return splitSentences(quote).some((x) => sentenceNamesCap(x.body, x.term, cap));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {{ registerRoute: Function }} adminHttp
|
|
159
|
+
* @param {{ findHumanPromptContaining?: Function, resolveProjectContext?: Function,
|
|
160
|
+
* sessionSlots?: any, appendAuditEvent?: Function, now?: () => number }} [deps]
|
|
161
|
+
*/
|
|
162
|
+
function registerSlotsRoute(adminHttp, deps = {}) {
|
|
163
|
+
const findPrompt = deps.findHumanPromptContaining
|
|
164
|
+
|| ((/** @type {string} */ s, /** @type {string} */ q, /** @type {number} */ n) => require('../feedback-remote/humanPromptLedger.cjs').findHumanPromptContaining(s, q, n));
|
|
165
|
+
const resolveContext = deps.resolveProjectContext
|
|
166
|
+
|| ((/** @type {any} */ o) => require('../projectRootResolve.cjs').resolveProjectContext(o));
|
|
167
|
+
const slots = () => deps.sessionSlots || require('./sessionSlots.cjs');
|
|
168
|
+
const audit = deps.appendAuditEvent
|
|
169
|
+
|| ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
|
|
170
|
+
const now = deps.now || Date.now;
|
|
171
|
+
|
|
172
|
+
adminHttp.registerRoute('GET', '/admin/scheduler/slots', (/** @type {any} */ _req, /** @type {any} */ res) => {
|
|
173
|
+
const s = slots();
|
|
174
|
+
sendJson(res, 200, {
|
|
175
|
+
ok: true,
|
|
176
|
+
cap: s.totalSlots(),
|
|
177
|
+
min: s.MIN_SLOTS,
|
|
178
|
+
max: s.MAX_SLOTS,
|
|
179
|
+
inUse: s.inUse(),
|
|
180
|
+
available: s.available(),
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
adminHttp.registerRoute('POST', '/admin/scheduler/slots', async (/** @type {any} */ req, /** @type {any} */ res) => {
|
|
185
|
+
const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
|
|
186
|
+
const refuse = (/** @type {number} */ status, /** @type {string} */ error, /** @type {string} */ reason) =>
|
|
187
|
+
sendJson(res, status, { ok: false, error, reason });
|
|
188
|
+
|
|
189
|
+
let raw;
|
|
190
|
+
try {
|
|
191
|
+
raw = await readBody(req, MAX_SLOTS_BODY_BYTES);
|
|
192
|
+
} catch (e) {
|
|
193
|
+
bad(e instanceof Error ? e.message : String(e));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
let json;
|
|
197
|
+
try { json = JSON.parse(raw || '{}'); } catch {
|
|
198
|
+
bad('body is not valid JSON');
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const parsed = slotsBodySchema.safeParse(json);
|
|
202
|
+
if (!parsed.success) {
|
|
203
|
+
bad(parsed.error.issues);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const { cap, quote, originClaudeSessionId, originProjectRoot, callerJobSlug } = parsed.data;
|
|
207
|
+
const s = slots();
|
|
208
|
+
if (typeof cap !== 'number' || !Number.isInteger(cap) || cap < s.MIN_SLOTS || cap > s.MAX_SLOTS) {
|
|
209
|
+
bad(`cap must be an integer in [${s.MIN_SLOTS}, ${s.MAX_SLOTS}]`);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (callerJobSlug) {
|
|
213
|
+
refuse(403, 'called_from_headless_job', `a headless scheduled job ('${callerJobSlug}') never changes the slot limit; say in your final result what the human should set`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const found = findPrompt(originClaudeSessionId, quote, now());
|
|
218
|
+
if (!found) {
|
|
219
|
+
refuse(403, 'human_request_unverified', 'quote was not found in a prompt the human typed in this chat session');
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (!quoteNamesSlots(quote, cap) || !promptSentenceNamesSlots(found.text, quote, cap)) {
|
|
223
|
+
refuse(403, 'quote_does_not_name_slots', `the human's quote does not ask to change the session limit to ${cap} in the accepted form; ${acceptedFormHint(cap)}`);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let epicId = null;
|
|
228
|
+
try {
|
|
229
|
+
const ctx = resolveContext({ originClaudeSessionId, originProjectRoot });
|
|
230
|
+
if (ctx && typeof ctx.epicId === 'string' && ctx.epicId) epicId = ctx.epicId;
|
|
231
|
+
} catch { epicId = null; }
|
|
232
|
+
|
|
233
|
+
const from = s.totalSlots();
|
|
234
|
+
let to;
|
|
235
|
+
try {
|
|
236
|
+
to = s.setCap(cap);
|
|
237
|
+
} catch (e) {
|
|
238
|
+
sendJson(res, 500, { ok: false, error: 'cap_write_failed', details: e instanceof Error ? e.message : String(e) });
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const promptMs = Number(found.at);
|
|
242
|
+
const promptAt = Number.isFinite(promptMs) ? new Date(promptMs).toISOString() : null;
|
|
243
|
+
try {
|
|
244
|
+
audit('slot_cap_changed', { from, to, epicId, quote, promptAt });
|
|
245
|
+
} catch { /* audit is best-effort, like taskSwitchRoute */ }
|
|
246
|
+
|
|
247
|
+
sendJson(res, 200, { ok: true, from, to });
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
module.exports = { registerSlotsRoute, quoteNamesSlots, promptSentenceNamesSlots, MAX_SLOTS_BODY_BYTES };
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* toolClearance.cjs — single-use clearances for tool-risk 'confirm' calls.
|
|
3
|
+
*
|
|
4
|
+
* Flow (see session-manager-operations/architecture/tool-risk.md):
|
|
5
|
+
* 1. The guard (scripts/hooks/lib/guard-tool-risk-policy.cjs) denies a
|
|
6
|
+
* confirm-marked call in a job and records a PENDING confirmation here
|
|
7
|
+
* (one record per tool + args digest, listing every job that asked).
|
|
8
|
+
* 2. The owner answers the Needs-you item. The scheduler takes the pending
|
|
9
|
+
* record and calls answerConfirmation: it emits human.tool_confirmation,
|
|
10
|
+
* and on approve grants one clearance bound to (job, tool, args digest,
|
|
11
|
+
* project) and resumes the SAME Claude session; on deny it parks the job
|
|
12
|
+
* with reason confirmation_denied.
|
|
13
|
+
* 3. In the resumed run the guard calls consumeClearance for the exact call.
|
|
14
|
+
* A matching live clearance lets exactly ONE call through: consumption is
|
|
15
|
+
* an atomic rename, so a second use (or a racing hook) finds nothing. A
|
|
16
|
+
* call with different args has a different digest, so it never matches.
|
|
17
|
+
*
|
|
18
|
+
* State lives machine-level under schedulerHome() (not the operations root):
|
|
19
|
+
* tool-clearances/<key>.json live grants
|
|
20
|
+
* tool-confirmations-pending/<key>.json pending confirmation records
|
|
21
|
+
* Plain Node (no Electron) so the guard hook can require it.
|
|
22
|
+
*/
|
|
23
|
+
'use strict';
|
|
24
|
+
|
|
25
|
+
const crypto = require('node:crypto');
|
|
26
|
+
const fs = require('node:fs');
|
|
27
|
+
const path = require('node:path');
|
|
28
|
+
const { writeJsonAtomicSync } = require('../util/atomicFs.cjs');
|
|
29
|
+
|
|
30
|
+
const CLEARANCES_DIR = 'tool-clearances';
|
|
31
|
+
const PENDING_DIR = 'tool-confirmations-pending';
|
|
32
|
+
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
const MAX_TTL_MS = 7 * DEFAULT_TTL_MS;
|
|
34
|
+
const DIGEST_RE = /^[0-9a-f]{64}$/;
|
|
35
|
+
const MAX_REQUESTS_PER_RECORD = 50;
|
|
36
|
+
const DENIED_REASON = 'confirmation_denied';
|
|
37
|
+
const NO_SESSION_REASON = 'confirmation_no_session';
|
|
38
|
+
const EVENT_KIND = 'human.tool_confirmation';
|
|
39
|
+
|
|
40
|
+
function home() {
|
|
41
|
+
return require('./schedulerPaths.cjs').schedulerHome();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function clearancesDir(dir) { return dir || path.join(home(), CLEARANCES_DIR); }
|
|
45
|
+
function pendingDir(dir) { return dir || path.join(home(), PENDING_DIR); }
|
|
46
|
+
|
|
47
|
+
function sha(parts) {
|
|
48
|
+
return crypto.createHash('sha256').update(parts.join('\u0000')).digest('hex');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** File key of a clearance: one per (job, tool, args digest). */
|
|
52
|
+
function clearanceKey(jobSlug, tool, argsDigest) {
|
|
53
|
+
return sha(['clearance', jobSlug, tool, argsDigest]).slice(0, 48);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** File key of a pending confirmation: one per (tool, args digest), like its Needs-you item. */
|
|
57
|
+
function confirmationKey(tool, argsDigest) {
|
|
58
|
+
return sha(['confirm', tool, argsDigest]).slice(0, 48);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function requireString(name, v) {
|
|
62
|
+
if (typeof v !== 'string' || !v) throw new Error(`toolClearance: ${name} must be a non-empty string`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function requireDigest(v) {
|
|
66
|
+
if (typeof v !== 'string' || !DIGEST_RE.test(v)) throw new Error('toolClearance: argsDigest must be a sha256 hex digest');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readJson(file) {
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Grant one single-use clearance. A new grant for the same key replaces the old one.
|
|
79
|
+
* @param {{ cwd?: string|null, jobSlug: string, tool: string, argsDigest: string, ttlMs?: number, now?: number, dir?: string }} args
|
|
80
|
+
* @returns {{ key: string, file: string, grantedAt: number, expiresAt: number }}
|
|
81
|
+
*/
|
|
82
|
+
function grantClearance({ cwd = null, jobSlug, tool, argsDigest, ttlMs = DEFAULT_TTL_MS, now = Date.now(), dir } = /** @type {any} */ ({})) {
|
|
83
|
+
requireString('jobSlug', jobSlug);
|
|
84
|
+
requireString('tool', tool);
|
|
85
|
+
requireDigest(argsDigest);
|
|
86
|
+
const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? Math.min(ttlMs, MAX_TTL_MS) : DEFAULT_TTL_MS;
|
|
87
|
+
const key = clearanceKey(jobSlug, tool, argsDigest);
|
|
88
|
+
const file = path.join(clearancesDir(dir), `${key}.json`);
|
|
89
|
+
const record = { key, cwd: typeof cwd === 'string' && cwd ? cwd : null, jobSlug, tool, argsDigest, grantedAt: now, expiresAt: now + ttl };
|
|
90
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
91
|
+
writeJsonAtomicSync(file, record);
|
|
92
|
+
return { key, file, grantedAt: record.grantedAt, expiresAt: record.expiresAt };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Consume the clearance for this exact call, at most once. Atomic: the grant
|
|
97
|
+
* is renamed aside before it is read, so only one caller can ever win it.
|
|
98
|
+
* A claimed grant is always deleted — expired or mismatched ones included.
|
|
99
|
+
* @param {{ cwd?: string|null, jobSlug: string, tool: string, argsDigest: string, now?: number, dir?: string }} args
|
|
100
|
+
* @returns {{ ok: true, clearance: object } | { ok: false, reason: 'none'|'expired'|'mismatch' }}
|
|
101
|
+
*/
|
|
102
|
+
function consumeClearance({ cwd = null, jobSlug, tool, argsDigest, now = Date.now(), dir } = /** @type {any} */ ({})) {
|
|
103
|
+
if (typeof jobSlug !== 'string' || !jobSlug || typeof tool !== 'string' || !tool
|
|
104
|
+
|| typeof argsDigest !== 'string' || !DIGEST_RE.test(argsDigest)) {
|
|
105
|
+
return { ok: false, reason: 'none' };
|
|
106
|
+
}
|
|
107
|
+
const file = path.join(clearancesDir(dir), `${clearanceKey(jobSlug, tool, argsDigest)}.json`);
|
|
108
|
+
const claimed = `${file}.consumed-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
|
|
109
|
+
try {
|
|
110
|
+
fs.renameSync(file, claimed);
|
|
111
|
+
} catch {
|
|
112
|
+
return { ok: false, reason: 'none' };
|
|
113
|
+
}
|
|
114
|
+
const record = readJson(claimed);
|
|
115
|
+
try { fs.rmSync(claimed, { force: true }); } catch { /* best effort */ }
|
|
116
|
+
if (!record || record.jobSlug !== jobSlug || record.tool !== tool || record.argsDigest !== argsDigest) {
|
|
117
|
+
return { ok: false, reason: 'mismatch' };
|
|
118
|
+
}
|
|
119
|
+
if (!(typeof record.expiresAt === 'number' && record.expiresAt > now)) return { ok: false, reason: 'expired' };
|
|
120
|
+
if (record.cwd && cwd && path.resolve(record.cwd) !== path.resolve(cwd)) return { ok: false, reason: 'mismatch' };
|
|
121
|
+
return { ok: true, clearance: record };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Delete every expired (or unreadable) grant. Never throws.
|
|
126
|
+
* @param {{ now?: number, dir?: string }} [opts]
|
|
127
|
+
* @returns {number} grants removed
|
|
128
|
+
*/
|
|
129
|
+
function pruneExpired({ now = Date.now(), dir } = {}) {
|
|
130
|
+
let removed = 0;
|
|
131
|
+
let names = [];
|
|
132
|
+
try { names = fs.readdirSync(clearancesDir(dir)); } catch { return 0; }
|
|
133
|
+
for (const name of names) {
|
|
134
|
+
if (!name.endsWith('.json')) continue;
|
|
135
|
+
const file = path.join(clearancesDir(dir), name);
|
|
136
|
+
const rec = readJson(file);
|
|
137
|
+
if (rec && typeof rec.expiresAt === 'number' && rec.expiresAt > now) continue;
|
|
138
|
+
try { fs.rmSync(file, { force: true }); removed++; } catch { /* next */ }
|
|
139
|
+
}
|
|
140
|
+
return removed;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ── pending confirmations ───────────────────────────────────────────────────
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Record (or extend) the pending confirmation for one guard refusal. One
|
|
147
|
+
* record per (tool, digest); each job asks at most once in it. Never throws.
|
|
148
|
+
* @param {{ tool: string, argsDigest: string, jobSlug: string, sessionId?: string|null, epicId?: string|null, cwd?: string|null, rule?: string, summary?: string }} req
|
|
149
|
+
* @param {{ dir?: string, now?: number }} [opts]
|
|
150
|
+
* @returns {boolean}
|
|
151
|
+
*/
|
|
152
|
+
function recordPendingConfirmation(req, { dir, now = Date.now() } = {}) {
|
|
153
|
+
try {
|
|
154
|
+
requireString('tool', req.tool);
|
|
155
|
+
requireDigest(req.argsDigest);
|
|
156
|
+
requireString('jobSlug', req.jobSlug);
|
|
157
|
+
const key = confirmationKey(req.tool, req.argsDigest);
|
|
158
|
+
const file = path.join(pendingDir(dir), `${key}.json`);
|
|
159
|
+
const existing = readJson(file);
|
|
160
|
+
const requests = existing && Array.isArray(existing.requests) ? existing.requests : [];
|
|
161
|
+
if (requests.some((r) => r && r.jobSlug === req.jobSlug)) return true;
|
|
162
|
+
if (requests.length >= MAX_REQUESTS_PER_RECORD) return false;
|
|
163
|
+
requests.push({
|
|
164
|
+
tool: req.tool,
|
|
165
|
+
argsDigest: req.argsDigest,
|
|
166
|
+
jobSlug: req.jobSlug,
|
|
167
|
+
sessionId: typeof req.sessionId === 'string' && req.sessionId ? req.sessionId : null,
|
|
168
|
+
epicId: typeof req.epicId === 'string' && req.epicId ? req.epicId : null,
|
|
169
|
+
cwd: typeof req.cwd === 'string' && req.cwd ? req.cwd : null,
|
|
170
|
+
...(typeof req.rule === 'string' ? { rule: req.rule } : {}),
|
|
171
|
+
...(typeof req.summary === 'string' ? { summary: req.summary } : {}),
|
|
172
|
+
requestedAt: now,
|
|
173
|
+
});
|
|
174
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
175
|
+
writeJsonAtomicSync(file, { key, tool: req.tool, argsDigest: req.argsDigest, requests });
|
|
176
|
+
return true;
|
|
177
|
+
} catch (e) {
|
|
178
|
+
console.error(`[toolClearance] pending confirmation not recorded: ${e && e.message}`);
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** @returns {{ key: string, tool: string, argsDigest: string, requests: object[] }[]} */
|
|
184
|
+
function listPendingConfirmations({ dir } = {}) {
|
|
185
|
+
let names = [];
|
|
186
|
+
try { names = fs.readdirSync(pendingDir(dir)); } catch { return []; }
|
|
187
|
+
const out = [];
|
|
188
|
+
for (const name of names.sort()) {
|
|
189
|
+
if (!name.endsWith('.json')) continue;
|
|
190
|
+
const rec = readJson(path.join(pendingDir(dir), name));
|
|
191
|
+
if (rec && typeof rec.key === 'string' && Array.isArray(rec.requests)) out.push(rec);
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Atomically take (remove and return) one pending record, or null when it is gone. */
|
|
197
|
+
function takePendingConfirmation(key, { dir } = {}) {
|
|
198
|
+
if (typeof key !== 'string' || !/^[0-9a-f]{1,64}$/.test(key)) return null;
|
|
199
|
+
const file = path.join(pendingDir(dir), `${key}.json`);
|
|
200
|
+
const claimed = `${file}.taken-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
|
|
201
|
+
try { fs.renameSync(file, claimed); } catch { return null; }
|
|
202
|
+
const rec = readJson(claimed);
|
|
203
|
+
try { fs.rmSync(claimed, { force: true }); } catch { /* best effort */ }
|
|
204
|
+
return rec && Array.isArray(rec.requests) ? rec : null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ── answering ───────────────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Apply the owner's answer to one job's confirmation request.
|
|
211
|
+
* approve → emit human.tool_confirmation { approved: true }, grant the
|
|
212
|
+
* clearance, resume({ jobSlug, sessionId, request }) — same session.
|
|
213
|
+
* deny → emit human.tool_confirmation { approved: false },
|
|
214
|
+
* park({ jobSlug, reason: 'confirmation_denied', request }).
|
|
215
|
+
* An approval with no session id to resume parks with 'confirmation_no_session'.
|
|
216
|
+
* @param {{ request: any, approved: boolean, ttlMs?: number, now?: number, dir?: string }} answer
|
|
217
|
+
* @param {{ emit: (e: object) => void, resume: (r: object) => void, park: (p: object) => void }} deps
|
|
218
|
+
* @returns {{ action: 'resume'|'park', clearance?: object }}
|
|
219
|
+
*/
|
|
220
|
+
function answerConfirmation({ request, approved, ttlMs, now = Date.now(), dir }, deps) {
|
|
221
|
+
requireString('jobSlug', request && request.jobSlug);
|
|
222
|
+
const event = {
|
|
223
|
+
kind: EVENT_KIND,
|
|
224
|
+
approved: approved === true,
|
|
225
|
+
tool: request.tool,
|
|
226
|
+
argsDigest: request.argsDigest,
|
|
227
|
+
jobSlug: request.jobSlug,
|
|
228
|
+
...(request.rule ? { rule: request.rule } : {}),
|
|
229
|
+
};
|
|
230
|
+
try { deps.emit(event); } catch (e) { console.error(`[toolClearance] event emit failed: ${e && e.message}`); }
|
|
231
|
+
if (approved === true && request.sessionId) {
|
|
232
|
+
const clearance = grantClearance({
|
|
233
|
+
cwd: request.cwd, jobSlug: request.jobSlug, tool: request.tool, argsDigest: request.argsDigest, ttlMs, now, dir,
|
|
234
|
+
});
|
|
235
|
+
deps.resume({ jobSlug: request.jobSlug, sessionId: request.sessionId, request });
|
|
236
|
+
return { action: 'resume', clearance };
|
|
237
|
+
}
|
|
238
|
+
deps.park({ jobSlug: request.jobSlug, reason: approved === true ? NO_SESSION_REASON : DENIED_REASON, request });
|
|
239
|
+
return { action: 'park' };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
module.exports = {
|
|
243
|
+
CLEARANCES_DIR,
|
|
244
|
+
PENDING_DIR,
|
|
245
|
+
DEFAULT_TTL_MS,
|
|
246
|
+
DENIED_REASON,
|
|
247
|
+
NO_SESSION_REASON,
|
|
248
|
+
EVENT_KIND,
|
|
249
|
+
clearanceKey,
|
|
250
|
+
confirmationKey,
|
|
251
|
+
grantClearance,
|
|
252
|
+
consumeClearance,
|
|
253
|
+
pruneExpired,
|
|
254
|
+
recordPendingConfirmation,
|
|
255
|
+
listPendingConfirmations,
|
|
256
|
+
takePendingConfirmation,
|
|
257
|
+
answerConfirmation,
|
|
258
|
+
};
|