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
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* webhookDelivery.cjs — delivers a project's event-log events
|
|
5
|
+
* (epic/epicEventLog.cjs) to each loopback webhook subscriber
|
|
6
|
+
* (webhookRegistry.cjs): HMAC-SHA256 signed, AT LEAST ONCE, in seq order.
|
|
7
|
+
*
|
|
8
|
+
* Request: POST <subscription url>, Content-Type application/json,
|
|
9
|
+
* body = JSON.stringify({ subscriptionId, event })
|
|
10
|
+
* X-SM-Signature = hex HMAC-SHA256(secret, body)
|
|
11
|
+
* 5 s timeout, redirects not followed (a 3xx is a failure).
|
|
12
|
+
*
|
|
13
|
+
* Cursor: per subscriber, per Epic, the seq of the last event the subscriber
|
|
14
|
+
* answered 2xx for (webhooks/delivery-state.json, written by the registry —
|
|
15
|
+
* the 'webhooks' namespace's only writer). The cursor moves ONLY on 2xx and is
|
|
16
|
+
* persisted after the subscriber's pass, so a crash before that write replays
|
|
17
|
+
* the already-sent events (duplicates possible, a skip is not). Receivers
|
|
18
|
+
* dedupe on (event.epicId, event.seq).
|
|
19
|
+
*
|
|
20
|
+
* Failure: the subscriber stops for this pass at its first failed attempt and
|
|
21
|
+
* backs off exponentially (BASE_BACKOFF_MS · 2^(failures-1), capped at
|
|
22
|
+
* MAX_BACKOFF_MS); a 2xx clears the backoff. A pass sends at most
|
|
23
|
+
* MAX_DELIVERIES_PER_PASS requests per subscriber, so one pass is bounded.
|
|
24
|
+
*
|
|
25
|
+
* Loopback only: every URL is re-checked with assertLoopbackUrl before a fetch,
|
|
26
|
+
* even though the registry already refused anything else on add.
|
|
27
|
+
*
|
|
28
|
+
* Driver: no timer of its own — main's existing 5-min intraday timer calls
|
|
29
|
+
* runDeliveryPass over the scheduler queue's project cwds (index.cjs). No
|
|
30
|
+
* subscriptions → no event-log reads, no state write, no fetch.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const crypto = require('node:crypto');
|
|
34
|
+
const fsp = require('node:fs/promises');
|
|
35
|
+
const { opsPath } = require('../opsOwnership.cjs');
|
|
36
|
+
const { readEpicEvents } = require('../epic/epicEventLog.cjs');
|
|
37
|
+
const registry = require('./webhookRegistry.cjs');
|
|
38
|
+
|
|
39
|
+
const REQUEST_TIMEOUT_MS = 5000;
|
|
40
|
+
const MAX_DELIVERIES_PER_PASS = 50;
|
|
41
|
+
const BASE_BACKOFF_MS = 30_000;
|
|
42
|
+
const MAX_BACKOFF_MS = 15 * 60_000;
|
|
43
|
+
const SIGNATURE_HEADER = 'X-SM-Signature';
|
|
44
|
+
const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
45
|
+
|
|
46
|
+
/** cwd → in-flight pass (overlapping passes for one cwd share the first). */
|
|
47
|
+
const inFlight = new Map();
|
|
48
|
+
|
|
49
|
+
/** @param {string} secret @param {string} body */
|
|
50
|
+
function sign(secret, body) {
|
|
51
|
+
return crypto.createHmac('sha256', secret).update(body).digest('hex');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param {number} failures */
|
|
55
|
+
function backoffMs(failures) {
|
|
56
|
+
return Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** Math.max(0, failures - 1));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Epic ids that have an event log under <cwd>/session-manager-operations/events/. @param {string} cwd */
|
|
60
|
+
async function listEpicIds(cwd) {
|
|
61
|
+
try {
|
|
62
|
+
const ents = await fsp.readdir(opsPath(cwd, 'events'), { withFileTypes: true });
|
|
63
|
+
return ents.filter((e) => e.isDirectory() && EPIC_ID_RE.test(e.name)).map((e) => e.name).sort();
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if (/** @type {NodeJS.ErrnoException} */ (err).code === 'ENOENT') return [];
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* POST one event; resolves true on 2xx, false otherwise (never throws).
|
|
72
|
+
* @param {(url: string, init: object) => Promise<{ status: number }>} fetchFn
|
|
73
|
+
* @param {{ id: string, url: string, secret: string }} sub
|
|
74
|
+
* @param {object} event
|
|
75
|
+
*/
|
|
76
|
+
async function postEvent(fetchFn, sub, event) {
|
|
77
|
+
const body = JSON.stringify({ subscriptionId: sub.id, event });
|
|
78
|
+
try {
|
|
79
|
+
const res = await fetchFn(sub.url, {
|
|
80
|
+
method: 'POST',
|
|
81
|
+
headers: { 'Content-Type': 'application/json', [SIGNATURE_HEADER]: sign(sub.secret, body) },
|
|
82
|
+
body,
|
|
83
|
+
redirect: 'manual',
|
|
84
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
85
|
+
});
|
|
86
|
+
return !!res && res.status >= 200 && res.status < 300;
|
|
87
|
+
} catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* @param {{ cwd: string, now?: () => number, fetch?: (url: string, init: object) => Promise<{ status: number }> }} opts
|
|
94
|
+
* @returns {Promise<{ delivered: number, failed: number, backedOff: number, refused: number }>}
|
|
95
|
+
*/
|
|
96
|
+
async function deliverOnce({ cwd, now = Date.now, fetch: fetchFn = /** @type {any} */ (globalThis.fetch) }) {
|
|
97
|
+
const result = { delivered: 0, failed: 0, backedOff: 0, refused: 0 };
|
|
98
|
+
const subs = await registry.listSubscriptions({ cwd, includeSecrets: true });
|
|
99
|
+
if (!subs.length) return result;
|
|
100
|
+
const state = await registry.readDeliveryState({ cwd });
|
|
101
|
+
const epicIds = await listEpicIds(cwd);
|
|
102
|
+
|
|
103
|
+
for (const sub of subs) {
|
|
104
|
+
try {
|
|
105
|
+
registry.assertLoopbackUrl(sub.url);
|
|
106
|
+
} catch {
|
|
107
|
+
result.refused++;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const b = state.backoff[sub.id];
|
|
111
|
+
if (b && b.nextAttemptAt > now()) {
|
|
112
|
+
result.backedOff++;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
/** @type {Record<string, number>} */
|
|
116
|
+
const advanced = {};
|
|
117
|
+
let budget = MAX_DELIVERIES_PER_PASS;
|
|
118
|
+
let failedAt = 0;
|
|
119
|
+
outer: for (const epicId of epicIds) {
|
|
120
|
+
let after = (state.cursors[sub.id] || {})[epicId] || 0;
|
|
121
|
+
while (budget > 0) {
|
|
122
|
+
const page = await readEpicEvents(cwd, epicId, { after, limit: budget, kinds: sub.kinds });
|
|
123
|
+
for (const event of page.events) {
|
|
124
|
+
budget--;
|
|
125
|
+
if (!(await postEvent(fetchFn, /** @type {{ id: string, url: string, secret: string }} */ (sub), event))) {
|
|
126
|
+
failedAt = now();
|
|
127
|
+
break outer;
|
|
128
|
+
}
|
|
129
|
+
result.delivered++;
|
|
130
|
+
after = event.seq;
|
|
131
|
+
advanced[epicId] = after;
|
|
132
|
+
}
|
|
133
|
+
if (!page.hasMore) break;
|
|
134
|
+
}
|
|
135
|
+
if (budget <= 0) break;
|
|
136
|
+
}
|
|
137
|
+
if (failedAt) result.failed++;
|
|
138
|
+
if (!failedAt && !Object.keys(advanced).length && !b) continue; // nothing to persist
|
|
139
|
+
await registry.updateDeliveryState({
|
|
140
|
+
cwd,
|
|
141
|
+
mutate: (s) => {
|
|
142
|
+
const cur = s.cursors[sub.id] || (s.cursors[sub.id] = {});
|
|
143
|
+
// Never move a cursor backwards (a concurrent writer may be ahead).
|
|
144
|
+
for (const [epicId, seq] of Object.entries(advanced)) cur[epicId] = Math.max(cur[epicId] || 0, seq);
|
|
145
|
+
if (failedAt) {
|
|
146
|
+
const failures = ((s.backoff[sub.id] && s.backoff[sub.id].failures) || 0) + 1;
|
|
147
|
+
s.backoff[sub.id] = { failures, nextAttemptAt: failedAt + backoffMs(failures) };
|
|
148
|
+
} else {
|
|
149
|
+
delete s.backoff[sub.id];
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* deliverPending({ cwd, now, fetch }) → Promise<{ delivered, failed, backedOff, refused }>.
|
|
159
|
+
* One bounded delivery pass for one project. `now` (ms clock) and `fetch` are
|
|
160
|
+
* injectable for tests; they default to Date.now and globalThis.fetch.
|
|
161
|
+
* @param {{ cwd: string, now?: () => number, fetch?: (url: string, init: object) => Promise<{ status: number }> }} opts
|
|
162
|
+
*/
|
|
163
|
+
function deliverPending(opts) {
|
|
164
|
+
const key = opts && opts.cwd;
|
|
165
|
+
if (typeof key !== 'string' || !key) return Promise.reject(new Error('deliverPending: cwd required'));
|
|
166
|
+
const running = inFlight.get(key);
|
|
167
|
+
if (running) return running;
|
|
168
|
+
const p = deliverOnce(opts).finally(() => { if (inFlight.get(key) === p) inFlight.delete(key); });
|
|
169
|
+
inFlight.set(key, p);
|
|
170
|
+
return p;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* runDeliveryPass({ cwds, logs }) — sequential deliverPending over cwds; each
|
|
175
|
+
* project's failure is logged and never stops the others. Never rejects.
|
|
176
|
+
* @param {{ cwds: Iterable<string>, logs?: { writeLine: (entry: object) => void } }} opts
|
|
177
|
+
*/
|
|
178
|
+
async function runDeliveryPass({ cwds, logs }) {
|
|
179
|
+
for (const cwd of new Set(cwds)) {
|
|
180
|
+
try {
|
|
181
|
+
const r = await deliverPending({ cwd });
|
|
182
|
+
if (r.failed && logs) {
|
|
183
|
+
logs.writeLine({ scope: 'webhooks', level: 'warn', message: 'webhook delivery failed', meta: { cwd, ...r } });
|
|
184
|
+
}
|
|
185
|
+
} catch (e) {
|
|
186
|
+
if (logs) logs.writeLine({ scope: 'webhooks', level: 'error', message: 'webhook delivery pass failed', meta: { cwd, error: /** @type {Error} */ (e)?.message } });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function _resetForTests() {
|
|
192
|
+
inFlight.clear();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
module.exports = {
|
|
196
|
+
deliverPending,
|
|
197
|
+
runDeliveryPass,
|
|
198
|
+
sign,
|
|
199
|
+
REQUEST_TIMEOUT_MS,
|
|
200
|
+
MAX_DELIVERIES_PER_PASS,
|
|
201
|
+
BASE_BACKOFF_MS,
|
|
202
|
+
MAX_BACKOFF_MS,
|
|
203
|
+
SIGNATURE_HEADER,
|
|
204
|
+
_resetForTests,
|
|
205
|
+
};
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* webhookRegistry.cjs — the local webhook subscription registry (one primitive:
|
|
5
|
+
* URL + kinds filter + HMAC secret), per project.
|
|
6
|
+
*
|
|
7
|
+
* Store: session-manager-operations/webhooks/subscriptions.json, mode 0600,
|
|
8
|
+
* written only here as writer 'webhooks' (opsOwnership.cjs). Runtime state,
|
|
9
|
+
* self-ignored — it holds secrets and must never be committed.
|
|
10
|
+
*
|
|
11
|
+
* { version: 1, subscriptions: [{ id, url, kinds, secret, createdAt }] }
|
|
12
|
+
*
|
|
13
|
+
* LOOPBACK ONLY: a subscription URL must be plain http to exactly 127.0.0.1,
|
|
14
|
+
* [::1] or localhost (optional port, optional path). Anything else — https,
|
|
15
|
+
* another host, a lookalike such as 127.0.0.1.nip.io or localhost.evil.com
|
|
16
|
+
* (DNS-rebinding style), userinfo, a numeric alias like 0x7f000001 — is refused
|
|
17
|
+
* with a WebhookUrlRefusedError (code 'webhook_url_refused'). The check is on
|
|
18
|
+
* the literal text the caller sent AND on the WHATWG-parsed hostname, so no
|
|
19
|
+
* normalization trick can turn an accepted string into another host.
|
|
20
|
+
*
|
|
21
|
+
* kinds must be a non-empty list of epicEventLog.cjs EVENT_KINDS; otherwise a
|
|
22
|
+
* WebhookKindsInvalidError (code 'webhook_kinds_invalid').
|
|
23
|
+
*
|
|
24
|
+
* The secret (32 random bytes, hex) is returned once by addSubscription;
|
|
25
|
+
* listSubscriptions omits it unless { includeSecrets: true } (for an in-process
|
|
26
|
+
* deliverer). Delivery lives in webhookDelivery.cjs; its per-subscriber
|
|
27
|
+
* cursors + backoff persist in webhooks/delivery-state.json (mode 0600), also
|
|
28
|
+
* written only here (readDeliveryState / updateDeliveryState):
|
|
29
|
+
*
|
|
30
|
+
* { version: 1, cursors: { <subId>: { <epicId>: seq } },
|
|
31
|
+
* backoff: { <subId>: { failures, nextAttemptAt } } }
|
|
32
|
+
*
|
|
33
|
+
* The bilko.run relay (webRemote.cjs) is unrelated and untouched.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const crypto = require('node:crypto');
|
|
37
|
+
const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
|
|
38
|
+
const { writeJsonAtomic, readJsonOr } = require('../util/atomicFs.cjs');
|
|
39
|
+
|
|
40
|
+
const WRITER = 'webhooks';
|
|
41
|
+
const NS = 'webhooks';
|
|
42
|
+
const FILE_NAME = 'subscriptions.json';
|
|
43
|
+
const STATE_FILE_NAME = 'delivery-state.json';
|
|
44
|
+
const MAX_SUBSCRIPTIONS = 100;
|
|
45
|
+
const MAX_URL_CHARS = 2048;
|
|
46
|
+
const ID_RE = /^wh_[0-9a-f]{16}$/;
|
|
47
|
+
const LOOPBACK_HOSTS = Object.freeze(['127.0.0.1', '[::1]', 'localhost']);
|
|
48
|
+
// Literal form: http://<loopback host>[:port][/path][?query]. No userinfo,
|
|
49
|
+
// no fragment, no whitespace, no trailing-dot hosts.
|
|
50
|
+
const LOOPBACK_URL_RE = /^http:\/\/(127\.0\.0\.1|\[::1\]|localhost)(?::(\d{1,5}))?(?:[/?][^\s#]*)?$/;
|
|
51
|
+
|
|
52
|
+
class WebhookUrlRefusedError extends Error {
|
|
53
|
+
constructor(message) {
|
|
54
|
+
super(message);
|
|
55
|
+
this.name = 'WebhookUrlRefusedError';
|
|
56
|
+
this.code = 'webhook_url_refused';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
class WebhookKindsInvalidError extends Error {
|
|
61
|
+
constructor(message) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = 'WebhookKindsInvalidError';
|
|
64
|
+
this.code = 'webhook_kinds_invalid';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
class WebhookNotFoundError extends Error {
|
|
69
|
+
constructor(message) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.name = 'WebhookNotFoundError';
|
|
72
|
+
this.code = 'webhook_not_found';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Validate a subscription URL; returns the accepted string unchanged or throws
|
|
78
|
+
* WebhookUrlRefusedError.
|
|
79
|
+
* @param {unknown} url
|
|
80
|
+
*/
|
|
81
|
+
function assertLoopbackUrl(url) {
|
|
82
|
+
if (typeof url !== 'string' || !url || url.length > MAX_URL_CHARS) {
|
|
83
|
+
throw new WebhookUrlRefusedError('webhook url must be a non-empty string');
|
|
84
|
+
}
|
|
85
|
+
const m = LOOPBACK_URL_RE.exec(url);
|
|
86
|
+
if (!m) {
|
|
87
|
+
throw new WebhookUrlRefusedError(
|
|
88
|
+
`webhook url refused: only http://127.0.0.1, http://[::1] and http://localhost are allowed, got ${JSON.stringify(url)}`,
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
if (m[2] !== undefined) {
|
|
92
|
+
const port = Number(m[2]);
|
|
93
|
+
if (port < 1 || port > 65535) throw new WebhookUrlRefusedError(`webhook url refused: port ${m[2]} out of range`);
|
|
94
|
+
}
|
|
95
|
+
let parsed;
|
|
96
|
+
try {
|
|
97
|
+
parsed = new URL(url);
|
|
98
|
+
} catch {
|
|
99
|
+
throw new WebhookUrlRefusedError(`webhook url refused: unparsable ${JSON.stringify(url)}`);
|
|
100
|
+
}
|
|
101
|
+
if (parsed.protocol !== 'http:' || parsed.username || parsed.password || !LOOPBACK_HOSTS.includes(parsed.hostname)) {
|
|
102
|
+
throw new WebhookUrlRefusedError(`webhook url refused: parsed host ${JSON.stringify(parsed.hostname)} is not loopback`);
|
|
103
|
+
}
|
|
104
|
+
return url;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Validate kinds against epicEventLog.cjs EVENT_KINDS; returns a de-duplicated copy.
|
|
109
|
+
* @param {unknown} kinds
|
|
110
|
+
* @returns {string[]}
|
|
111
|
+
*/
|
|
112
|
+
function assertKinds(kinds) {
|
|
113
|
+
const { EVENT_KINDS } = require('../epic/epicEventLog.cjs');
|
|
114
|
+
if (!Array.isArray(kinds) || kinds.length === 0) {
|
|
115
|
+
throw new WebhookKindsInvalidError('webhook kinds must be a non-empty array of event kinds');
|
|
116
|
+
}
|
|
117
|
+
const known = new Set(EVENT_KINDS);
|
|
118
|
+
const bad = kinds.filter((k) => typeof k !== 'string' || !known.has(k));
|
|
119
|
+
if (bad.length) {
|
|
120
|
+
throw new WebhookKindsInvalidError(`unknown event kind(s): ${bad.map((k) => JSON.stringify(k)).join(', ')}`);
|
|
121
|
+
}
|
|
122
|
+
return [...new Set(kinds)];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function storeFile(cwd) {
|
|
126
|
+
return opsPath(cwd, NS, FILE_NAME);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** @param {string} file */
|
|
130
|
+
async function readStore(file) {
|
|
131
|
+
const raw = await readJsonOr(file, null);
|
|
132
|
+
const subs = raw && Array.isArray(raw.subscriptions) ? raw.subscriptions : [];
|
|
133
|
+
return subs.filter((s) => s && typeof s === 'object' && typeof s.id === 'string' && typeof s.url === 'string');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** @param {string} file @param {object[]} subscriptions */
|
|
137
|
+
async function writeStore(file, subscriptions) {
|
|
138
|
+
assertOpsWrite(file, WRITER);
|
|
139
|
+
await writeJsonAtomic(file, { version: 1, subscriptions }, { mode: 0o600 });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** file path → tail of its mutation chain (serializes read-modify-write). */
|
|
143
|
+
const chains = new Map();
|
|
144
|
+
/**
|
|
145
|
+
* @template T
|
|
146
|
+
* @param {string} file @param {() => Promise<T>} fn
|
|
147
|
+
* @returns {Promise<T>}
|
|
148
|
+
*/
|
|
149
|
+
function serialized(file, fn) {
|
|
150
|
+
const prev = chains.get(file) || Promise.resolve();
|
|
151
|
+
const next = prev.then(fn, fn);
|
|
152
|
+
const tail = next.then(() => undefined, () => undefined);
|
|
153
|
+
chains.set(file, tail);
|
|
154
|
+
tail.then(() => { if (chains.get(file) === tail) chains.delete(file); });
|
|
155
|
+
return next;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** @param {{ id: string, url: string, kinds: string[], createdAt: string, secret?: string }} s */
|
|
159
|
+
function publicView(s) {
|
|
160
|
+
return { id: s.id, url: s.url, kinds: [...s.kinds], createdAt: s.createdAt };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* addSubscription({ cwd, url, kinds }) → Promise<{ id, secret }>.
|
|
165
|
+
* Validates before touching disk.
|
|
166
|
+
* @param {{ cwd: string, url: unknown, kinds: unknown }} opts
|
|
167
|
+
*/
|
|
168
|
+
async function addSubscription({ cwd, url, kinds } = /** @type {any} */ ({})) {
|
|
169
|
+
const acceptedUrl = assertLoopbackUrl(url);
|
|
170
|
+
const acceptedKinds = assertKinds(kinds);
|
|
171
|
+
const file = storeFile(cwd);
|
|
172
|
+
return serialized(file, async () => {
|
|
173
|
+
const subs = await readStore(file);
|
|
174
|
+
if (subs.length >= MAX_SUBSCRIPTIONS) throw new Error(`webhook registry full (${MAX_SUBSCRIPTIONS} subscriptions)`);
|
|
175
|
+
const id = `wh_${crypto.randomBytes(8).toString('hex')}`;
|
|
176
|
+
const secret = crypto.randomBytes(32).toString('hex');
|
|
177
|
+
subs.push({ id, url: acceptedUrl, kinds: acceptedKinds, secret, createdAt: new Date().toISOString() });
|
|
178
|
+
await writeStore(file, subs);
|
|
179
|
+
return { id, secret };
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* listSubscriptions({ cwd, includeSecrets }) → Promise<subscription[]>.
|
|
185
|
+
* Secrets are omitted unless includeSecrets is true.
|
|
186
|
+
* @param {{ cwd: string, includeSecrets?: boolean }} opts
|
|
187
|
+
*/
|
|
188
|
+
async function listSubscriptions({ cwd, includeSecrets = false } = /** @type {any} */ ({})) {
|
|
189
|
+
const subs = await readStore(storeFile(cwd));
|
|
190
|
+
return subs.map((s) => (includeSecrets ? { ...publicView(s), secret: s.secret } : publicView(s)));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* removeSubscription({ cwd, id }) → Promise<{ removed: true }>; throws
|
|
195
|
+
* WebhookNotFoundError for an unknown id.
|
|
196
|
+
* @param {{ cwd: string, id: unknown }} opts
|
|
197
|
+
*/
|
|
198
|
+
async function removeSubscription({ cwd, id } = /** @type {any} */ ({})) {
|
|
199
|
+
if (typeof id !== 'string' || !ID_RE.test(id)) throw new WebhookNotFoundError(`no webhook subscription ${JSON.stringify(id)}`);
|
|
200
|
+
const file = storeFile(cwd);
|
|
201
|
+
return serialized(file, async () => {
|
|
202
|
+
const subs = await readStore(file);
|
|
203
|
+
const kept = subs.filter((s) => s.id !== id);
|
|
204
|
+
if (kept.length === subs.length) throw new WebhookNotFoundError(`no webhook subscription ${JSON.stringify(id)}`);
|
|
205
|
+
await writeStore(file, kept);
|
|
206
|
+
return { removed: true };
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function stateFile(cwd) {
|
|
211
|
+
return opsPath(cwd, NS, STATE_FILE_NAME);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** @param {any} raw */
|
|
215
|
+
function normalizeState(raw) {
|
|
216
|
+
const isObj = (/** @type {unknown} */ v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
217
|
+
/** @type {{ cursors: Record<string, Record<string, number>>, backoff: Record<string, { failures: number, nextAttemptAt: number }> }} */
|
|
218
|
+
const out = { cursors: {}, backoff: {} };
|
|
219
|
+
if (!isObj(raw)) return out;
|
|
220
|
+
if (isObj(raw.cursors)) {
|
|
221
|
+
for (const [subId, perEpic] of Object.entries(raw.cursors)) {
|
|
222
|
+
if (!isObj(perEpic)) continue;
|
|
223
|
+
/** @type {Record<string, number>} */
|
|
224
|
+
const m = {};
|
|
225
|
+
for (const [epicId, seq] of Object.entries(perEpic)) if (Number.isInteger(seq) && seq > 0) m[epicId] = seq;
|
|
226
|
+
out.cursors[subId] = m;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (isObj(raw.backoff)) {
|
|
230
|
+
for (const [subId, b] of Object.entries(raw.backoff)) {
|
|
231
|
+
if (isObj(b) && Number.isInteger(b.failures) && b.failures > 0 && Number.isFinite(b.nextAttemptAt)) {
|
|
232
|
+
out.backoff[subId] = { failures: b.failures, nextAttemptAt: b.nextAttemptAt };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* readDeliveryState({ cwd }) → Promise<{ cursors, backoff }> (empty when absent).
|
|
241
|
+
* @param {{ cwd: string }} opts
|
|
242
|
+
*/
|
|
243
|
+
async function readDeliveryState({ cwd } = /** @type {any} */ ({})) {
|
|
244
|
+
return normalizeState(await readJsonOr(stateFile(cwd), null));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* updateDeliveryState({ cwd, mutate }) — serialized read-modify-write of the
|
|
249
|
+
* delivery state; `mutate(state)` edits in place. Entries for subscriptions
|
|
250
|
+
* that no longer exist are pruned on every write.
|
|
251
|
+
* @param {{ cwd: string, mutate: (state: { cursors: Record<string, Record<string, number>>, backoff: Record<string, { failures: number, nextAttemptAt: number }> }) => void }} opts
|
|
252
|
+
*/
|
|
253
|
+
async function updateDeliveryState({ cwd, mutate } = /** @type {any} */ ({})) {
|
|
254
|
+
const file = stateFile(cwd);
|
|
255
|
+
return serialized(file, async () => {
|
|
256
|
+
const state = normalizeState(await readJsonOr(file, null));
|
|
257
|
+
mutate(state);
|
|
258
|
+
const live = new Set((await readStore(storeFile(cwd))).map((s) => s.id));
|
|
259
|
+
for (const key of ['cursors', 'backoff']) {
|
|
260
|
+
const m = /** @type {Record<string, unknown>} */ (state[/** @type {'cursors'|'backoff'} */ (key)]);
|
|
261
|
+
for (const id of Object.keys(m)) if (!live.has(id)) delete m[id];
|
|
262
|
+
}
|
|
263
|
+
assertOpsWrite(file, WRITER);
|
|
264
|
+
await writeJsonAtomic(file, { version: 1, ...state }, { mode: 0o600 });
|
|
265
|
+
return state;
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
module.exports = {
|
|
270
|
+
addSubscription,
|
|
271
|
+
readDeliveryState,
|
|
272
|
+
updateDeliveryState,
|
|
273
|
+
listSubscriptions,
|
|
274
|
+
removeSubscription,
|
|
275
|
+
assertLoopbackUrl,
|
|
276
|
+
assertKinds,
|
|
277
|
+
WebhookUrlRefusedError,
|
|
278
|
+
WebhookKindsInvalidError,
|
|
279
|
+
WebhookNotFoundError,
|
|
280
|
+
LOOPBACK_HOSTS,
|
|
281
|
+
};
|
|
@@ -54,3 +54,184 @@ function classifyToolUse(block) {
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
module.exports = { classifyToolUse, extractDiff, MAX_DIFF_STR };
|
|
57
|
+
|
|
58
|
+
// ─── Epic event log summaries (job.tool_use / human.message) ────────────────
|
|
59
|
+
// Events carry summaries only — never a tool's full input or output.
|
|
60
|
+
const EVENT_SUMMARY_MAX = 200;
|
|
61
|
+
|
|
62
|
+
// Secret-shaped values: KEY=value / "key": "value" pairs whose key names a
|
|
63
|
+
// secret, bearer tokens, and well-known token prefixes.
|
|
64
|
+
const SECRET_ASSIGN_RE = /\b([A-Za-z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL|AUTH)[A-Za-z0-9_]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi;
|
|
65
|
+
const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
|
|
66
|
+
const TOKEN_PREFIX_RE = /\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|xox[abposr]-[A-Za-z0-9-]{8,}|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+)/g;
|
|
67
|
+
|
|
68
|
+
/** Replace secret-shaped values with [redacted]. */
|
|
69
|
+
function redactSecrets(s) {
|
|
70
|
+
if (typeof s !== 'string') return '';
|
|
71
|
+
// Bearer first: "Authorization: Bearer <t>" would otherwise redact only "Bearer".
|
|
72
|
+
return s
|
|
73
|
+
.replace(BEARER_RE, (_m, scheme) => `${scheme} [redacted]`)
|
|
74
|
+
.replace(SECRET_ASSIGN_RE, (m, k, sep, v) => (/^\[redacted\]$|^(?:Bearer|Basic)$/i.test(v) ? m : `${k}${sep}[redacted]`))
|
|
75
|
+
.replace(TOKEN_PREFIX_RE, '[redacted]');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Collapse whitespace and cap at max chars (ellipsis counted inside the cap). */
|
|
79
|
+
function capSummary(s, max = EVENT_SUMMARY_MAX) {
|
|
80
|
+
const flat = String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
81
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The one input field that best describes each common tool call.
|
|
85
|
+
const SUMMARY_FIELDS = ['file_path', 'command', 'pattern', 'path', 'url', 'query', 'skill', 'description', 'prompt', 'notebook_path'];
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A ≤200-char, secret-redacted one-line summary of a tool_use block:
|
|
89
|
+
* the classified label plus its most descriptive input field. Never the
|
|
90
|
+
* full input (Edit/Write bodies are never included).
|
|
91
|
+
* @param {{name: string, input?: Record<string, unknown>}} block
|
|
92
|
+
* @returns {string}
|
|
93
|
+
*/
|
|
94
|
+
function summarizeToolUse(block) {
|
|
95
|
+
const name = typeof block?.name === 'string' ? block.name : 'tool';
|
|
96
|
+
let label = name;
|
|
97
|
+
try { label = classifyToolUse({ name, input: block?.input }).label || name; } catch { /* keep name */ }
|
|
98
|
+
const input = block?.input && typeof block.input === 'object' ? block.input : {};
|
|
99
|
+
let detail = '';
|
|
100
|
+
for (const f of SUMMARY_FIELDS) {
|
|
101
|
+
if (typeof input[f] === 'string' && input[f]) { detail = input[f]; break; }
|
|
102
|
+
}
|
|
103
|
+
// Redact before capping so a cut can never expose a partial secret.
|
|
104
|
+
const redacted = redactSecrets(capSummary(detail, 4 * EVENT_SUMMARY_MAX));
|
|
105
|
+
return capSummary(detail ? `${label}: ${redacted}` : String(label));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The human.message payload for one human prompt: char count + ≤200-char
|
|
110
|
+
* redacted excerpt.
|
|
111
|
+
* @param {string} prompt
|
|
112
|
+
* @returns {{ chars: number, excerpt: string }}
|
|
113
|
+
*/
|
|
114
|
+
function humanMessageSummary(prompt) {
|
|
115
|
+
const text = typeof prompt === 'string' ? prompt : '';
|
|
116
|
+
return { chars: text.length, excerpt: capSummary(redactSecrets(capSummary(text, 4 * EVENT_SUMMARY_MAX))) };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Parse complete stream-json lines from `text` (which starts at byte
|
|
121
|
+
* `baseOffset` of the job log) into tool_use descriptors. Unparsable lines
|
|
122
|
+
* (scheduler banner lines, torn writes) are skipped.
|
|
123
|
+
* @param {string} text
|
|
124
|
+
* @param {number} baseOffset
|
|
125
|
+
* @returns {Array<{ tool: string, summary: string, transcriptOffset: number }>}
|
|
126
|
+
*/
|
|
127
|
+
function extractToolUses(text, baseOffset = 0) {
|
|
128
|
+
const out = [];
|
|
129
|
+
let offset = baseOffset;
|
|
130
|
+
for (const line of String(text).split('\n')) {
|
|
131
|
+
const lineOffset = offset;
|
|
132
|
+
offset += Buffer.byteLength(line, 'utf8') + 1;
|
|
133
|
+
if (!line.includes('"tool_use"')) continue;
|
|
134
|
+
let obj;
|
|
135
|
+
try { obj = JSON.parse(line); } catch { continue; }
|
|
136
|
+
const content = obj?.type === 'assistant' ? obj?.message?.content : null;
|
|
137
|
+
if (!Array.isArray(content)) continue;
|
|
138
|
+
for (const block of content) {
|
|
139
|
+
if (!block || block.type !== 'tool_use' || typeof block.name !== 'string') continue;
|
|
140
|
+
out.push({ tool: block.name, summary: summarizeToolUse(block), transcriptOffset: lineOffset });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Incremental tail of a job's stream-json log. poll() reads the bytes
|
|
148
|
+
* written since the last poll, hands each complete line's tool_use blocks
|
|
149
|
+
* to onToolUse, and keeps a partial trailing line for the next poll.
|
|
150
|
+
* flush() also parses the final unterminated line. Never throws.
|
|
151
|
+
* @param {{ logPath: string, onToolUse: (e: { tool: string, summary: string, transcriptOffset: number }) => void, fsImpl?: typeof import('node:fs') }} opts
|
|
152
|
+
*/
|
|
153
|
+
function createToolUseLogTailer({ logPath, onToolUse, fsImpl }) {
|
|
154
|
+
const fsMod = fsImpl || require('node:fs');
|
|
155
|
+
let readOffset = 0; // bytes consumed from the file
|
|
156
|
+
let pending = Buffer.alloc(0); // bytes of an unterminated trailing line
|
|
157
|
+
let pendingOffset = 0; // file offset where `pending` starts
|
|
158
|
+
|
|
159
|
+
const emit = (text, base) => {
|
|
160
|
+
for (const e of extractToolUses(text, base)) {
|
|
161
|
+
try { onToolUse(e); } catch (err) { console.error('[toolUseTailer] onToolUse failed', err?.message ?? err); }
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
function poll() {
|
|
166
|
+
try {
|
|
167
|
+
const size = fsMod.statSync(logPath).size;
|
|
168
|
+
if (size <= readOffset) return;
|
|
169
|
+
const len = size - readOffset;
|
|
170
|
+
const buf = Buffer.alloc(len);
|
|
171
|
+
const fd = fsMod.openSync(logPath, 'r');
|
|
172
|
+
let n = 0;
|
|
173
|
+
try { n = fsMod.readSync(fd, buf, 0, len, readOffset); } finally { fsMod.closeSync(fd); }
|
|
174
|
+
readOffset += n;
|
|
175
|
+
const all = pending.length ? Buffer.concat([pending, buf.subarray(0, n)]) : buf.subarray(0, n);
|
|
176
|
+
const lastNl = all.lastIndexOf(0x0a);
|
|
177
|
+
if (lastNl === -1) { pending = Buffer.from(all); return; }
|
|
178
|
+
const complete = all.subarray(0, lastNl);
|
|
179
|
+
const base = pendingOffset;
|
|
180
|
+
pending = Buffer.from(all.subarray(lastNl + 1));
|
|
181
|
+
pendingOffset = base + lastNl + 1;
|
|
182
|
+
emit(complete.toString('utf8'), base);
|
|
183
|
+
} catch { /* missing/unreadable log: try again next poll */ }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function flush() {
|
|
187
|
+
poll();
|
|
188
|
+
if (pending.length) {
|
|
189
|
+
const text = pending.toString('utf8');
|
|
190
|
+
const base = pendingOffset;
|
|
191
|
+
pendingOffset += pending.length;
|
|
192
|
+
pending = Buffer.alloc(0);
|
|
193
|
+
emit(text, base);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return { poll, flush };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
module.exports.EVENT_SUMMARY_MAX = EVENT_SUMMARY_MAX;
|
|
201
|
+
module.exports.redactSecrets = redactSecrets;
|
|
202
|
+
module.exports.summarizeToolUse = summarizeToolUse;
|
|
203
|
+
module.exports.humanMessageSummary = humanMessageSummary;
|
|
204
|
+
module.exports.extractToolUses = extractToolUses;
|
|
205
|
+
module.exports.createToolUseLogTailer = createToolUseLogTailer;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Wire a job's log tailer to the Epic event log: each tool_use block of a job
|
|
209
|
+
* with an epicId appends job.tool_use { slug, tool, summary, transcriptOffset }
|
|
210
|
+
* through `appendEvent` (epicEventLog.appendEpicEvent). An append failure
|
|
211
|
+
* (sync throw or rejection) is logged via `logError`, never thrown. Returns
|
|
212
|
+
* null when the job has no epicId/cwd (nothing to emit).
|
|
213
|
+
* @param {{ job: { slug?: string, epicId?: string, cwd?: string }, logPath: string, appendEvent: (cwd: string, epicId: string, event: Record<string, unknown>) => unknown, logError?: (msg: string) => void, fsImpl?: typeof import('node:fs') }} opts
|
|
214
|
+
*/
|
|
215
|
+
function createJobToolUseEmitter({ job, logPath, appendEvent, logError, fsImpl }) {
|
|
216
|
+
const epicId = job && job.epicId;
|
|
217
|
+
const cwd = job && job.cwd;
|
|
218
|
+
if (typeof epicId !== 'string' || !epicId || typeof cwd !== 'string' || !cwd || typeof appendEvent !== 'function') return null;
|
|
219
|
+
const report = (err) => {
|
|
220
|
+
const msg = `[scheduler] job.tool_use append failed for ${job.slug ?? '(unknown)'}: ${err?.message ?? String(err)}`;
|
|
221
|
+
try { (logError || console.error)(msg); } catch { /* logging must never be the thing that fails */ }
|
|
222
|
+
};
|
|
223
|
+
return createToolUseLogTailer({
|
|
224
|
+
logPath,
|
|
225
|
+
fsImpl,
|
|
226
|
+
onToolUse: ({ tool, summary, transcriptOffset }) => {
|
|
227
|
+
try {
|
|
228
|
+
const p = appendEvent(cwd, epicId, { kind: 'job.tool_use', slug: job.slug ?? null, tool, summary, transcriptOffset });
|
|
229
|
+
if (p && typeof (/** @type {any} */ (p)).catch === 'function') (/** @type {any} */ (p)).catch(report);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
report(err);
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
module.exports.createJobToolUseEmitter = createJobToolUseEmitter;
|
|
@@ -95,9 +95,9 @@ async function readJsonOr(file, fallback) {
|
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
-
function readJsonOrSync(file, fallback) {
|
|
98
|
+
function readJsonOrSync(file, fallback, fsImpl = fs) {
|
|
99
99
|
try {
|
|
100
|
-
const raw =
|
|
100
|
+
const raw = fsImpl.readFileSync(file, 'utf8');
|
|
101
101
|
if (raw.trim() === '') return fallback;
|
|
102
102
|
return JSON.parse(raw);
|
|
103
103
|
} catch {
|