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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- PRD_AUTHORING.md
|
|
1
|
+
<!-- PRD_AUTHORING.md v30 -->
|
|
2
2
|
# PRD Authoring Guide — Scheduler Safety Rules
|
|
3
3
|
|
|
4
4
|
Rule: every PRD you queue follows the rules below.
|
|
@@ -33,7 +33,7 @@ Recommended cap: 20 × 15s = 5 min for HTTP polls. Never use an uptime/restart s
|
|
|
33
33
|
Rule: once every acceptance-criteria line is checked, follow the finish protocol (§11) and stop. Do not add polish, fixtures, or "while we're here" work that isn't an AC line.
|
|
34
34
|
Why: `112-etch-engine` declared success at 17:44 UTC, then ran an unbounded fixture search until a user killed it at 20:28 — 2h44m of token burn on work no AC line asked for.
|
|
35
35
|
|
|
36
|
-
Executor: if more work seems valuable,
|
|
36
|
+
Executor: if more work seems valuable, add one `Follow-up: <one line>` trailer per item to the commit message. Do not do it, and do not queue it. Why: only the planner queues work.
|
|
37
37
|
|
|
38
38
|
---
|
|
39
39
|
|
|
@@ -121,6 +121,8 @@ Both fields are required in every `scheduler_create_prd` call.
|
|
|
121
121
|
Optional. One read-only command in gate syntax (every §6 gate rule applies; one line, at most 500 chars, never `none`), run without a shell for at most 60 s. Exit 0 = the precondition holds.
|
|
122
122
|
Rule: declare it on a PRD whose work needs an external state a person controls — a store agreement, billing, DNS, OAuth consent, a device. While it exits non-zero the scheduler holds the PRD `pending` and re-checks on its own; the hold is described in Session Manager's `session-manager-operations/architecture/scheduler-operations.md` §4b.
|
|
123
123
|
Rule: the executor still ends `SCHEDULER_VERDICT: FAIL` naming what is missing when it meets the missing state; a red preflight at that point reroutes the run to the hold instead of a park.
|
|
124
|
+
Rule: no shell runs it, so it cannot `source` a file, and Node's `--env-file` expands no variables (`$HOME` stays literal). Write absolute paths, or put `NAME=value` words before `timeout`; an environment variable wins over the file's value. The scheduler sets `TMPDIR` itself and drops a `TMPDIR=` word.
|
|
125
|
+
Rule: a blocker no API can read (an agreement accepted only in a web console) can still be held: check a marker file whose path names the step, e.g. `test -f /abs/path/apple-paid-apps-agreement-accepted`. The PRECONDITION HOLD notice prints the command, so that path is what tells the person what to do.
|
|
124
126
|
Why: a human-only blocker used to park `needs_review` and spend the recovery ladder on work no model can do.
|
|
125
127
|
|
|
126
128
|
### What the API writes
|
|
@@ -141,9 +143,12 @@ A short Epic-context digest is prepended automatically for orientation only —
|
|
|
141
143
|
|
|
142
144
|
The executor can't ask you anything: no `ScheduleWakeup`, Cron, Monitor, `AskUserQuestion`, plan mode, or worktree tools; background tasks are off (a `timeout` command is always on PATH — the app installs a shim on macOS). It must never stop to ask a question — it makes the safest reasonable call and reports it, so write the PRD so that call is obvious.
|
|
143
145
|
|
|
144
|
-
Worktree reach: every PRD runs in an isolated git worktree holding tracked files plus `node_modules` and non-uv `.venv`/`venv` symlinked
|
|
146
|
+
Worktree reach: every PRD runs in an isolated git worktree holding tracked files plus linked dependencies: `node_modules` (the root and each nested npm package's) is a worktree-local folder whose entries link to the main checkout's, and non-uv `.venv`/`venv` is symlinked whole; pnpm projects (pnpm-lock.yaml) get a worktree-local `node_modules` installed offline from the store, and uv projects (uv.lock) get a worktree-local env built by an offline frozen `uv sync`, not a symlink. Why: a pnpm install through the symlink purged the main checkout's node_modules (Bilko-Game-Academy 2026-10-18). A step that needs gitignored runtime state (databases, downloads/, browser profiles, logs) or a live side effect must address the main checkout by absolute path (e.g. `$HOME/Projects/<repo>/...`), be artifact-only (a deliverable artifact + `artifactPaths`, no tracked edits), and `dependsOn` the PRD that lands its tracked edits. A project may declare `worktreeSetup` gate-syntax commands in a tracked `.session-manager.json` at the repo root; they run once per fresh job worktree and baseline scratch worktree, before the executor starts, with cwd = the worktree root (a project in a subfolder names it, e.g. `timeout 600 godot --headless --path game --import`). Setups run one at a time per project and are never skipped; they must write only inside the worktree (node_modules entries and non-uv venvs link into the main checkout). The outcome is the `[scheduler] worktree setup:` lines at the top of the run log plus `worktreeSetup` in the run's meta.json. Host crontab installs stay human-only (see §14).
|
|
145
147
|
Why: burrow PRD 1516 halted because its relative `.venv` python against downloads/fb-tracker.db, scripts/install-cron.sh and `pipeline-cron.sh --now` resolved inside the worktree (no runtime state; install-cron would bake a temporary worktree path into crontab), while sibling 1494 succeeded the same day using an absolute main-checkout path and artifact-only output. `scheduler_create_prd` warns on relative gitignored paths.
|
|
146
148
|
|
|
149
|
+
Rule: gates never run `npm ci` or `npm install` — dependencies are already linked, so an install only slows the run.
|
|
150
|
+
Why: `npm --prefix web/feedback-widget ci` through the old whole-folder link emptied the main checkout's web/feedback-widget/node_modules (session-manager, 2026-11-24).
|
|
151
|
+
|
|
147
152
|
Rule: a job's processes never outlive it — the group sweep at exit, the job scope stop (systemd) and the 5-minute leftover sweep (Linux) stop anything it started, so `nohup` or `&` does not daemonize. Anything that must keep running goes to a service manager (systemd unit, cron), never `nohup` or `&`.
|
|
148
153
|
Why: finished jobs left dev servers running for days, holding memory and ports.
|
|
149
154
|
|
|
@@ -241,6 +246,7 @@ Before queueing a new PRD, verify each of these:
|
|
|
241
246
|
- [ ] **§6 Gate and files:** `gate` follows every rule in §6 (or is `["none"]` alone); `files` is 1–50 repo-relative paths, no overlap with a concurrent PRD.
|
|
242
247
|
- [ ] **§7 Self-contained:** no reference to "the conversation" or outside context; paths/identifiers inline; clean UTF-8, no NUL bytes (`grep -qP '\x00' file && echo BAD`).
|
|
243
248
|
- [ ] **§7 Worktree reach:** no relative path to a gitignored file; live-run steps use absolute main-checkout paths in an artifact-only PRD. Why: the job worktree has no gitignored runtime state, so relative paths fail or bake a temporary path into host config (burrow 1516).
|
|
249
|
+
- [ ] **§7 No installs:** no gate runs `npm ci` or `npm install`. Why: dependencies are linked; an install through a link emptied the main checkout's web/feedback-widget/node_modules (2026-11-24).
|
|
244
250
|
- [ ] **§8 Scope:** targets ≤10 min, ceiling 15; e2e/publish sharded to one spec per PRD.
|
|
245
251
|
- [ ] **§9 Failure surfacing:** errors exit 1 with a diagnostic line; no silent `|| true`.
|
|
246
252
|
- [ ] **§10 Negative assertions:** every "should find nothing" check is inverted to exit 0 on the clean case.
|
|
@@ -250,4 +256,6 @@ Before queueing a new PRD, verify each of these:
|
|
|
250
256
|
- [ ] **§6 Preflight:** a PRD whose work needs an external state a person controls declares a read-only `preflight` (exit 0 = precondition holds); every other PRD omits it.
|
|
251
257
|
- [ ] **No interactive AC:** no criterion asks to launch the app, click through, capture a screenshot, run under xvfb or open a browser. Why: a headless run stalls on a rendered frame and is SIGTERM'd uncommitted; recommend manual visual confirmation in the report instead.
|
|
252
258
|
- [ ] **Contract consumers gated:** a PRD that changes a return shape, IPC payload or remote contract greps `tests/` (and `src/**/__tests__`) for every spec using it and puts each in its gate and files. Why: scoped gates let other specs go red unseen until the release gate.
|
|
259
|
+
- [ ] **Doc links gated:** a PRD that adds, moves or renames a markdown file runs the project's doc-link check in its gate when the project has one (in session-manager: `timeout 120 npm run lint:docs`). Why: PRD kit-cast-playbook added `src/main/lib/demo-video-kit/cast.md` with only the kit tests in its gate, so the orphan doc landed on 2026-11-23 and turned lint:docs red for the next PRD.
|
|
260
|
+
- [ ] **Size budgets gated:** a PRD that edits a file the project caps by size runs that cap's check in its gate when the project has one (in session-manager: README.md gates `timeout 120 npm run lint:readme`). Why: PRD 4105-web-remote-label-leftovers edited README.md with only lint:docs and typecheck in its gate, so README.md reached 24,026 bytes on 2026-11-24, over its cap, and npm run lint turned red for every later PRD.
|
|
253
261
|
- [ ] **Gate purity:** a gate command must not create or modify tracked files; outputs go to the per-gate TMPDIR or a gitignored path. Why: a dirtied tree fails the clean-tree check.
|
package/src/main/webRemote.cjs
CHANGED
|
@@ -178,6 +178,17 @@ async function loadConfig() {
|
|
|
178
178
|
return _configCache;
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
// Device token of the first paired device in web-remote.json, or null. Read regardless of
|
|
182
|
+
// remoteEnabled: website feedback (feedbackRelayClient) is a capability separate from remote
|
|
183
|
+
// control. Never log or return the token anywhere else.
|
|
184
|
+
function getLinkedDeviceToken() {
|
|
185
|
+
const cfg = loadConfigSync();
|
|
186
|
+
const device = (Array.isArray(cfg.devices) ? cfg.devices : []).find(
|
|
187
|
+
(d) => d && typeof d.deviceToken === 'string' && d.deviceToken.length > 0,
|
|
188
|
+
);
|
|
189
|
+
return device ? device.deviceToken : null;
|
|
190
|
+
}
|
|
191
|
+
|
|
181
192
|
function invalidateConfigCache() {
|
|
182
193
|
_configCacheAt = 0;
|
|
183
194
|
_configCache = null;
|
|
@@ -265,6 +276,62 @@ async function getDeviceTicket(deviceToken) {
|
|
|
265
276
|
return result.ticket;
|
|
266
277
|
}
|
|
267
278
|
|
|
279
|
+
/**
|
|
280
|
+
* One relay REST call that never throws on an HTTP status: resolves
|
|
281
|
+
* { status, json } (json = parsed body or {}), or { status: 0, error } on a
|
|
282
|
+
* network failure. Never logs the request (it carries the device token).
|
|
283
|
+
*/
|
|
284
|
+
function relayRequest(method, url, { body, token } = {}) {
|
|
285
|
+
return new Promise((resolve) => {
|
|
286
|
+
const parsed = new URL(url);
|
|
287
|
+
if (parsed.protocol !== 'https:') {
|
|
288
|
+
resolve({ status: 0, json: {}, error: 'Only https:// allowed for relay API calls' });
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const payload = body === undefined ? null : JSON.stringify(body);
|
|
292
|
+
/** @type {Record<string, string | number>} */
|
|
293
|
+
const headers = {};
|
|
294
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
295
|
+
if (payload !== null) {
|
|
296
|
+
headers['Content-Type'] = 'application/json';
|
|
297
|
+
headers['Content-Length'] = Buffer.byteLength(payload);
|
|
298
|
+
}
|
|
299
|
+
let settled = false;
|
|
300
|
+
const done = (v) => { if (!settled) { settled = true; resolve(v); } };
|
|
301
|
+
const req = https.request({
|
|
302
|
+
hostname: parsed.hostname,
|
|
303
|
+
port: parsed.port || 443,
|
|
304
|
+
path: parsed.pathname + (parsed.search || ''),
|
|
305
|
+
method,
|
|
306
|
+
headers,
|
|
307
|
+
rejectUnauthorized: true,
|
|
308
|
+
}, (res) => {
|
|
309
|
+
let data = '';
|
|
310
|
+
res.on('data', (c) => { data += c; });
|
|
311
|
+
res.on('end', () => {
|
|
312
|
+
let json = {};
|
|
313
|
+
try { json = JSON.parse(data); } catch { /* non-JSON body */ }
|
|
314
|
+
done({ status: res.statusCode || 0, json: json && typeof json === 'object' ? json : {} });
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
req.on('error', (e) => done({ status: 0, json: {}, error: e?.message || 'relay request failed' }));
|
|
318
|
+
req.setTimeout(15_000, () => { req.destroy(new Error('timeout')); });
|
|
319
|
+
if (payload !== null) req.write(payload);
|
|
320
|
+
req.end();
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Map a non-2xx relay reply to the renderer-facing error string. */
|
|
325
|
+
function relayErrorOf(r) {
|
|
326
|
+
if (r.status === 404 || r.status === 405) return 'relay_unsupported';
|
|
327
|
+
if (r.status === 401) return 'device_token_invalid';
|
|
328
|
+
if (r.status === 429) return 'rate_limited';
|
|
329
|
+
if (r.status === 0) return r.error || 'relay request failed';
|
|
330
|
+
return typeof r.json?.error === 'string' && r.json.error ? r.json.error.slice(0, 200) : `HTTP ${r.status}`;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const isOk = (r) => r.status >= 200 && r.status < 300;
|
|
334
|
+
|
|
268
335
|
// Per-client-key time of the last e2e:rekey sent, so a burst of stale boxes yields one rekey.
|
|
269
336
|
const REKEY_THROTTLE_MS = 5000;
|
|
270
337
|
const _lastRekeyMs = new Map();
|
|
@@ -294,8 +361,9 @@ function anyAuthenticated() {
|
|
|
294
361
|
}
|
|
295
362
|
|
|
296
363
|
// Every client currently awaiting SAS confirmation.
|
|
364
|
+
// Service clients confirm through confirmServiceSas only (their key never becomes a device pin).
|
|
297
365
|
function pendingClients() {
|
|
298
|
-
return _clients.values().filter((r) => r.e2e.state === 'pending_sas');
|
|
366
|
+
return _clients.values().filter((r) => r.e2e.state === 'pending_sas' && r.role !== 'service');
|
|
299
367
|
}
|
|
300
368
|
|
|
301
369
|
const MAX_PINNED_PEER_KEYS = 20;
|
|
@@ -323,7 +391,8 @@ function addPinnedPeerKey(device, pubKey) {
|
|
|
323
391
|
function computeStatus(cfg) {
|
|
324
392
|
const connected = _ws !== null && _ws.readyState === WebSocket.OPEN;
|
|
325
393
|
const authed = _clients.authenticated()[0] || null;
|
|
326
|
-
|
|
394
|
+
// The phone SAS prompt never shows a paired service's code (confirmServiceSas owns that).
|
|
395
|
+
const pending = _clients.values().find((r) => r.e2e.state === 'pending_sas' && r.role !== 'service') || null;
|
|
327
396
|
const shown = authed || pending || _clients.values()[0] || null;
|
|
328
397
|
const e2eState = shown ? shown.e2e.state : 'idle';
|
|
329
398
|
return {
|
|
@@ -339,6 +408,7 @@ function computeStatus(cfg) {
|
|
|
339
408
|
key: r.key,
|
|
340
409
|
state: r.e2e.state,
|
|
341
410
|
pendingSas: r.e2e.state === 'pending_sas' ? r.e2e.pendingSas : null,
|
|
411
|
+
...(r.role === 'service' ? { role: 'service', pairingId: r.pendingPairingId ?? null } : {}),
|
|
342
412
|
})),
|
|
343
413
|
devices: (cfg.devices || []).map(({ deviceId, deviceName, issuedAt, lastConnectedAt }) => ({
|
|
344
414
|
deviceId, deviceName, issuedAt, lastConnectedAt,
|
|
@@ -856,6 +926,12 @@ async function handleMessage(raw, device) {
|
|
|
856
926
|
broadcastStatus();
|
|
857
927
|
return;
|
|
858
928
|
}
|
|
929
|
+
// Paired service (e.g. Kiln): handled before the phone TOFU branch so a
|
|
930
|
+
// service key never lands in a device's verifiedPeerPubKeys.
|
|
931
|
+
if (payload?.role === 'service') {
|
|
932
|
+
await handleServiceHello(envelope, device, client, browserPubKey);
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
859
935
|
try {
|
|
860
936
|
const sessionKey = deriveSessionKey(device.e2ePrivateKey, browserPubKey, device.deviceId);
|
|
861
937
|
let pendingSas;
|
|
@@ -871,6 +947,9 @@ async function handleMessage(raw, device) {
|
|
|
871
947
|
}
|
|
872
948
|
client.peerPubKey = browserPubKey;
|
|
873
949
|
client.deviceId = device.deviceId;
|
|
950
|
+
client.role = null; // a phone hello on this connection drops any service identity
|
|
951
|
+
client.service = null;
|
|
952
|
+
client.pendingPairingId = null;
|
|
874
953
|
// TOFU pinning: if this exact (deviceId, browserPubKey) pair was already
|
|
875
954
|
// manually SAS-confirmed once, skip pending_sas and auto-authenticate — the
|
|
876
955
|
// user already verified this browser. A different/first-seen pubKey always
|
|
@@ -1119,8 +1198,354 @@ function fanoutIpcEvent(channel, payload) {
|
|
|
1119
1198
|
}
|
|
1120
1199
|
}
|
|
1121
1200
|
|
|
1201
|
+
// ─── Paired services (servicePairings.cjs + serviceMcpSession.cjs) ───────────
|
|
1202
|
+
// A service connects through the relay like the phone, says role:'service' in
|
|
1203
|
+
// its e2e:hello, and may only send boxed cmd:mcp (MCP JSON-RPC 2.0), answered
|
|
1204
|
+
// over adminHttp.invoke. It never gets phone commands, ipc:*, asset:* or pins.
|
|
1205
|
+
|
|
1206
|
+
let _serviceInvoker = null;
|
|
1207
|
+
let _serviceStore = null;
|
|
1208
|
+
|
|
1209
|
+
/** Install the in-process admin route caller (localAdminHttp invoke), bound in index.cjs. */
|
|
1210
|
+
function setServiceInvoker(fn) {
|
|
1211
|
+
_serviceInvoker = typeof fn === 'function' ? fn : null;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/** The paired-services store (one per process; remote-services.json under claudeHome). */
|
|
1215
|
+
function getServiceStore() {
|
|
1216
|
+
if (!_serviceStore) {
|
|
1217
|
+
const { createServicePairings } = require('./lib/feedback-remote/servicePairings.cjs');
|
|
1218
|
+
_serviceStore = createServicePairings();
|
|
1219
|
+
}
|
|
1220
|
+
return _serviceStore;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/** Relay client ids are UUIDs only; anything else is dropped. */
|
|
1224
|
+
function relayClientIdOf(v) {
|
|
1225
|
+
return typeof v === 'string' && UUID_RE.test(v) ? v.toLowerCase() : null;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
/** Audit-safe token (tool or method names come from the caller). */
|
|
1229
|
+
function auditToken(v) {
|
|
1230
|
+
return String(v ?? '-').replace(/[^\w:.-]/g, '_').slice(0, 64) || '-';
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/** Drop a client's service identity + key and mark it failed. */
|
|
1234
|
+
function failServiceClient(client) {
|
|
1235
|
+
failClient(client);
|
|
1236
|
+
client.role = null;
|
|
1237
|
+
client.service = null;
|
|
1238
|
+
client.pendingPairingId = null;
|
|
1239
|
+
client.relayClientId = null;
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
async function handleServiceHello(envelope, device, client, peerPubKey) {
|
|
1243
|
+
const { id, payload } = envelope;
|
|
1244
|
+
const ts = new Date().toISOString();
|
|
1245
|
+
if (client.key === LEGACY_CLIENT_KEY) {
|
|
1246
|
+
// A service must be relay-stamped: replies are unicast to its connection.
|
|
1247
|
+
await auditLog(ts, 'service:unpaired', device.deviceId, id, 'refused:no_conn', client);
|
|
1248
|
+
failServiceClient(client);
|
|
1249
|
+
broadcastStatus();
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
const store = getServiceStore();
|
|
1253
|
+
let sessionKey;
|
|
1254
|
+
let sas;
|
|
1255
|
+
try {
|
|
1256
|
+
sessionKey = deriveSessionKey(device.e2ePrivateKey, peerPubKey, device.deviceId);
|
|
1257
|
+
sas = deriveSas(device.e2ePrivateKey, peerPubKey, device.deviceId);
|
|
1258
|
+
} catch (e) {
|
|
1259
|
+
logs.writeLine({ scope: 'webRemote', level: 'warn', message: 'service E2E key derivation failed', meta: { error: e?.message } });
|
|
1260
|
+
await auditLog(ts, 'service:hello', device.deviceId, id, 'error:key_derivation', client);
|
|
1261
|
+
failServiceClient(client);
|
|
1262
|
+
broadcastStatus();
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
const relayClientId = relayClientIdOf(payload?.clientId);
|
|
1266
|
+
|
|
1267
|
+
const pinned = store.findByPubKey(peerPubKey);
|
|
1268
|
+
if (pinned) {
|
|
1269
|
+
client.role = 'service';
|
|
1270
|
+
client.service = pinned;
|
|
1271
|
+
client.pendingPairingId = null;
|
|
1272
|
+
client.relayClientId = relayClientId;
|
|
1273
|
+
client.peerPubKey = peerPubKey;
|
|
1274
|
+
client.deviceId = device.deviceId;
|
|
1275
|
+
client.e2e = makeState('authenticated', sessionKey, null);
|
|
1276
|
+
store.touchLastSeen(pinned.serviceId).catch(() => {});
|
|
1277
|
+
await auditLog(ts, 'service:hello', device.deviceId, id, `ok:service=${auditToken(pinned.serviceId)}`, client);
|
|
1278
|
+
finalizeE2eAuthenticated('paired service authenticated — pinned key matched', client);
|
|
1279
|
+
respond(id, undefined, 'e2e:ready', client);
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
const pending = store.listPending();
|
|
1284
|
+
const wanted = typeof payload?.pairingId === 'string' ? payload.pairingId : null;
|
|
1285
|
+
const pairing = wanted
|
|
1286
|
+
? pending.find((p) => p.pairingId === wanted) || null
|
|
1287
|
+
: pending.slice().sort((a, b) => b.createdAt - a.createdAt)[0] || null;
|
|
1288
|
+
if (!pairing) {
|
|
1289
|
+
await auditLog(ts, 'service:unpaired', device.deviceId, id, 'refused', client);
|
|
1290
|
+
failServiceClient(client);
|
|
1291
|
+
broadcastStatus();
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
client.role = 'service';
|
|
1295
|
+
client.service = null;
|
|
1296
|
+
client.pendingPairingId = pairing.pairingId;
|
|
1297
|
+
client.relayClientId = relayClientId;
|
|
1298
|
+
client.peerPubKey = peerPubKey;
|
|
1299
|
+
client.deviceId = device.deviceId;
|
|
1300
|
+
client.e2e = makeState('pending_sas', sessionKey, sas);
|
|
1301
|
+
await auditLog(ts, 'service:hello', device.deviceId, id, 'pending_sas', client);
|
|
1302
|
+
logs.writeLine({ scope: 'webRemote', level: 'info', message: 'paired service key established — SAS pending confirmation' });
|
|
1303
|
+
broadcastStatus();
|
|
1304
|
+
respond(id, undefined, 'e2e:ready', client);
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/**
|
|
1308
|
+
* Owner confirmed a pending service's SAS: check it against that client's own
|
|
1309
|
+
* SAS, then pin the key via store.confirmPending. Returns { ok, service } or { ok:false, error }.
|
|
1310
|
+
*/
|
|
1311
|
+
async function confirmServiceSas(pairingId, sas) {
|
|
1312
|
+
const target = _clients.values().find((c) => c.role === 'service' && c.pendingPairingId === pairingId) || null;
|
|
1313
|
+
if (!target) return { ok: false, error: 'no_pending_service' };
|
|
1314
|
+
if (target.e2e.state !== 'pending_sas' || typeof target.e2e.pendingSas !== 'string') return { ok: false, error: 'wrong_state' };
|
|
1315
|
+
const expected = Buffer.from(target.e2e.pendingSas, 'utf8');
|
|
1316
|
+
const given = Buffer.from(String(sas ?? ''), 'utf8');
|
|
1317
|
+
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {
|
|
1318
|
+
await auditLog(new Date().toISOString(), 'service:confirm-sas', target.deviceId, undefined, 'refused:sas_mismatch', target);
|
|
1319
|
+
return { ok: false, error: 'sas_mismatch' };
|
|
1320
|
+
}
|
|
1321
|
+
let service;
|
|
1322
|
+
try {
|
|
1323
|
+
service = await getServiceStore().confirmPending(pairingId, target.peerPubKey, { relayClientId: target.relayClientId });
|
|
1324
|
+
} catch (e) {
|
|
1325
|
+
await auditLog(new Date().toISOString(), 'service:confirm-sas', target.deviceId, undefined, 'error:confirm_failed', target);
|
|
1326
|
+
return { ok: false, error: e?.message ?? 'confirm_failed' };
|
|
1327
|
+
}
|
|
1328
|
+
// The client may have disconnected while the store write ran.
|
|
1329
|
+
if (_clients.get(target.key) !== target || target.e2e.state !== 'pending_sas') return { ok: false, error: 'client_gone' };
|
|
1330
|
+
target.e2e = confirmSasLogic(target.e2e).next;
|
|
1331
|
+
target.service = service;
|
|
1332
|
+
target.pendingPairingId = null;
|
|
1333
|
+
await auditLog(new Date().toISOString(), 'service:confirm-sas', target.deviceId, undefined, `ok:service=${auditToken(service.serviceId)}`, target);
|
|
1334
|
+
finalizeE2eAuthenticated('paired service authenticated — SAS confirmed by owner', target);
|
|
1335
|
+
return { ok: true, service };
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
// ─── Paired services: renderer IPC (pair start / list / revoke) ─────────────
|
|
1339
|
+
|
|
1340
|
+
const CLIENT_OTP_TTL_MS = 5 * 60 * 1000;
|
|
1341
|
+
const CLIENT_OTP_RE = /^[A-Z0-9]{8}$/i;
|
|
1342
|
+
|
|
1343
|
+
/** The paired device (first with a token) whose token authorizes relay client calls, or null. */
|
|
1344
|
+
async function pairedDevice() {
|
|
1345
|
+
const cfg = await loadConfig();
|
|
1346
|
+
return (Array.isArray(cfg.devices) ? cfg.devices : []).find(
|
|
1347
|
+
(d) => d && typeof d.deviceToken === 'string' && d.deviceToken.length > 0,
|
|
1348
|
+
) || null;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
/** A service as the renderer may see it: no pinned key. */
|
|
1352
|
+
function redactService(s) {
|
|
1353
|
+
if (!s) return s;
|
|
1354
|
+
const { pubKey: _omit, ...rest } = s;
|
|
1355
|
+
return rest;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
function logRelayFailure(op, r) {
|
|
1359
|
+
logs.writeLine({
|
|
1360
|
+
scope: 'webRemote', level: 'warn', message: `relay ${op} failed`,
|
|
1361
|
+
meta: { status: r.status, error: relayErrorOf(r) },
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
async function servicePairStart({ name, homeCwd, scope }) {
|
|
1366
|
+
const device = await pairedDevice();
|
|
1367
|
+
if (!device) return { ok: false, error: 'no_paired_device' };
|
|
1368
|
+
const { SERVICE_TOOL_NAMES } = require('./lib/feedback-remote/servicePairings.cjs');
|
|
1369
|
+
// Refuse bad input before spending one of the account's hourly relay codes.
|
|
1370
|
+
if (!path.isAbsolute(homeCwd)) return { ok: false, error: 'homeCwd must be an absolute path' };
|
|
1371
|
+
const unknown = scope.find((t) => !SERVICE_TOOL_NAMES.includes(t));
|
|
1372
|
+
if (unknown) return { ok: false, error: `scope names an unknown tool: ${unknown}` };
|
|
1373
|
+
|
|
1374
|
+
const r = await relayRequest('POST', `${RELAY_API_BASE}/client-otp`, { body: {}, token: device.deviceToken });
|
|
1375
|
+
if (!isOk(r)) {
|
|
1376
|
+
logRelayFailure('client-otp', r);
|
|
1377
|
+
return { ok: false, error: relayErrorOf(r) };
|
|
1378
|
+
}
|
|
1379
|
+
const code = r.json?.code;
|
|
1380
|
+
if (typeof code !== 'string' || !CLIENT_OTP_RE.test(code)) return { ok: false, error: 'relay returned no code' };
|
|
1381
|
+
const codeExpiresAt = Date.now() + CLIENT_OTP_TTL_MS;
|
|
1382
|
+
let pairingId;
|
|
1383
|
+
try {
|
|
1384
|
+
({ pairingId } = await getServiceStore().createPending({ name, homeCwd, scope }));
|
|
1385
|
+
} catch (e) {
|
|
1386
|
+
return { ok: false, error: e?.message || 'pending pairing failed' };
|
|
1387
|
+
}
|
|
1388
|
+
await auditLog(new Date().toISOString(), 'service:pair-start', device.deviceId, undefined, 'ok', null);
|
|
1389
|
+
return { ok: true, code, pairingId, codeExpiresAt, deviceId: device.deviceId };
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
async function servicesList() {
|
|
1393
|
+
const store = getServiceStore();
|
|
1394
|
+
const services = store.list().map(redactService);
|
|
1395
|
+
const pending = store.listPending();
|
|
1396
|
+
const known = new Set(services.map((s) => s.relayClientId).filter(Boolean));
|
|
1397
|
+
const device = await pairedDevice();
|
|
1398
|
+
if (!device) return { ok: true, services, pending, relayOrphans: [], relayError: 'no_paired_device' };
|
|
1399
|
+
const r = await relayRequest('GET', `${RELAY_API_BASE}/clients`, { token: device.deviceToken });
|
|
1400
|
+
if (!isOk(r)) {
|
|
1401
|
+
logRelayFailure('clients list', r);
|
|
1402
|
+
return { ok: true, services, pending, relayOrphans: [], relayError: relayErrorOf(r) };
|
|
1403
|
+
}
|
|
1404
|
+
const raw = Array.isArray(r.json) ? r.json : Array.isArray(r.json?.clients) ? r.json.clients : [];
|
|
1405
|
+
const relayOrphans = raw
|
|
1406
|
+
.filter((c) => c && typeof c.clientId === 'string' && !known.has(c.clientId.toLowerCase()))
|
|
1407
|
+
.map((c) => ({
|
|
1408
|
+
clientId: c.clientId,
|
|
1409
|
+
clientName: typeof c.clientName === 'string' ? c.clientName : '',
|
|
1410
|
+
issuedAt: typeof c.issuedAt === 'string' || typeof c.issuedAt === 'number' ? c.issuedAt : null,
|
|
1411
|
+
}));
|
|
1412
|
+
return { ok: true, services, pending, relayOrphans };
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
/** DELETE one relay client. 404 client_not_found counts as gone. */
|
|
1416
|
+
async function deleteRelayClient(clientId, token) {
|
|
1417
|
+
const r = await relayRequest('DELETE', `${RELAY_API_BASE}/clients/${encodeURIComponent(clientId)}`, { token });
|
|
1418
|
+
if (isOk(r) || (r.status === 404 && r.json?.error === 'client_not_found')) return { ok: true };
|
|
1419
|
+
logRelayFailure('client delete', r);
|
|
1420
|
+
return { ok: false, error: relayErrorOf(r) };
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
async function serviceRevoke(serviceId) {
|
|
1424
|
+
const store = getServiceStore();
|
|
1425
|
+
const svc = store.list().find((s) => s.serviceId === serviceId);
|
|
1426
|
+
if (!svc) return { ok: false, error: 'no_such_service' };
|
|
1427
|
+
await store.revoke(serviceId);
|
|
1428
|
+
for (const c of _clients.values()) {
|
|
1429
|
+
if (c.role === 'service' && (c.service?.serviceId === serviceId || (c.peerPubKey && c.peerPubKey === svc.pubKey))) {
|
|
1430
|
+
teardownClient(c.key);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
broadcastStatus();
|
|
1434
|
+
let relayRevoked = false;
|
|
1435
|
+
const device = svc.relayClientId ? await pairedDevice() : null;
|
|
1436
|
+
if (svc.relayClientId && device) {
|
|
1437
|
+
relayRevoked = (await deleteRelayClient(svc.relayClientId, device.deviceToken)).ok;
|
|
1438
|
+
}
|
|
1439
|
+
await auditLog(new Date().toISOString(), 'service:revoke', device?.deviceId, undefined, `ok:service=${auditToken(serviceId)}`, null);
|
|
1440
|
+
return { ok: true, relayRevoked };
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
/**
|
|
1444
|
+
* Owner denied a pending pairing: drop it from the store and fail + tear down
|
|
1445
|
+
* any service client waiting on it, so a later hello for it is refused.
|
|
1446
|
+
*/
|
|
1447
|
+
async function servicePairCancel(pairingId) {
|
|
1448
|
+
const cancelled = await getServiceStore().cancelPending(pairingId);
|
|
1449
|
+
let dropped = 0;
|
|
1450
|
+
for (const c of _clients.values()) {
|
|
1451
|
+
if (c.role === 'service' && c.pendingPairingId === pairingId) {
|
|
1452
|
+
failServiceClient(c);
|
|
1453
|
+
teardownClient(c.key);
|
|
1454
|
+
dropped += 1;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
if (dropped > 0) broadcastStatus();
|
|
1458
|
+
const device = await pairedDevice();
|
|
1459
|
+
await auditLog(new Date().toISOString(), 'service:pair-cancelled', device?.deviceId || '-', undefined,
|
|
1460
|
+
cancelled ? `ok:dropped=${dropped}` : `noop:dropped=${dropped}`, null);
|
|
1461
|
+
return { ok: true, cancelled, dropped };
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
async function relayClientRevoke(clientId) {
|
|
1465
|
+
const device = await pairedDevice();
|
|
1466
|
+
if (!device) return { ok: false, error: 'no_paired_device' };
|
|
1467
|
+
return deleteRelayClient(clientId, device.deviceToken);
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/** Drop every locally paired service (revoke-all). Logs, never throws. */
|
|
1471
|
+
async function clearLocalServices() {
|
|
1472
|
+
try {
|
|
1473
|
+
const store = getServiceStore();
|
|
1474
|
+
for (const s of store.list()) await store.revoke(s.serviceId);
|
|
1475
|
+
} catch (e) {
|
|
1476
|
+
logs.writeLine({ scope: 'webRemote', level: 'warn', message: 'failed to clear paired services', meta: { error: e?.message } });
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
/** Encrypt + unicast one boxed mcp:result to a service client (never plaintext). */
|
|
1481
|
+
function sendMcpResult(client, msgId, response) {
|
|
1482
|
+
if (!_ws || _ws.readyState !== WebSocket.OPEN) return;
|
|
1483
|
+
if (!client.e2e.sessionKey) return;
|
|
1484
|
+
try {
|
|
1485
|
+
const inner = { type: 'mcp:result', id: msgId, payload: response, ts: Date.now() };
|
|
1486
|
+
const { nonce, ciphertext } = encryptBox(JSON.stringify(inner), client.e2e.sessionKey);
|
|
1487
|
+
const out = { type: 'e2e:box', id: crypto.randomUUID(), payload: { nonce, ciphertext }, ts: Date.now() };
|
|
1488
|
+
if (client.key !== LEGACY_CLIENT_KEY) out.toConn = client.key;
|
|
1489
|
+
_ws.send(JSON.stringify(out));
|
|
1490
|
+
} catch (e) {
|
|
1491
|
+
logs.writeLine({ scope: 'webRemote', level: 'warn', message: 'mcp:result send failed', meta: { error: e?.message } });
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// Leave room for the box envelope (base64 + nonce) under the relay's message cap.
|
|
1496
|
+
const MCP_RESULT_MAX_BYTES = Math.floor(MSG_MAX_BYTES * 0.7);
|
|
1497
|
+
|
|
1498
|
+
async function dispatchServiceEnvelope(envelope, device, client) {
|
|
1499
|
+
const { type, id, payload } = envelope;
|
|
1500
|
+
const ts = new Date().toISOString();
|
|
1501
|
+
const auditType = typeof type === 'string' ? type : 'service:unknown';
|
|
1502
|
+
const reject = async (result) => {
|
|
1503
|
+
await auditLog(ts, auditType, device.deviceId, id, result, client);
|
|
1504
|
+
respond(id, { error: 'rejected' }, undefined, client); // opaque — reason stays in audit log only
|
|
1505
|
+
};
|
|
1506
|
+
if (client.role !== 'service') return reject('error:not_service');
|
|
1507
|
+
if (type !== 'cmd:mcp') return reject('refused:service_not_allowed');
|
|
1508
|
+
if (!(await loadConfig()).remoteEnabled) return reject('error:disabled');
|
|
1509
|
+
if (client.e2e.state !== 'authenticated' || !client.e2e.sessionKey) return reject('error:e2e_not_authenticated');
|
|
1510
|
+
// Re-read the pin each call so a revoke takes effect at once.
|
|
1511
|
+
const store = getServiceStore();
|
|
1512
|
+
const service = client.peerPubKey ? store.findByPubKey(client.peerPubKey) : null;
|
|
1513
|
+
if (!service) {
|
|
1514
|
+
await reject('refused:service_revoked');
|
|
1515
|
+
teardownClient(client.key);
|
|
1516
|
+
broadcastStatus();
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
client.service = service;
|
|
1520
|
+
const invoke = _serviceInvoker || (async () => { throw new Error('service invoker not installed'); });
|
|
1521
|
+
let outcome;
|
|
1522
|
+
try {
|
|
1523
|
+
outcome = await handleServiceMcp(payload, { service, invoke, store });
|
|
1524
|
+
} catch (e) {
|
|
1525
|
+
return reject('error:dispatch_error');
|
|
1526
|
+
}
|
|
1527
|
+
let response = outcome.response;
|
|
1528
|
+
let audit = outcome.audit;
|
|
1529
|
+
if (response && Buffer.byteLength(JSON.stringify(response), 'utf8') > MCP_RESULT_MAX_BYTES) {
|
|
1530
|
+
response = { jsonrpc: '2.0', id: response.id ?? null, error: { code: -32603, message: 'response too large for the relay' } };
|
|
1531
|
+
if (audit) audit = { ...audit, result: 'error:too_large' };
|
|
1532
|
+
}
|
|
1533
|
+
// One audit line per tool call: tool + result, never argument values.
|
|
1534
|
+
if (audit) await auditLog(ts, `mcp:${auditToken(audit.tool)}`, device.deviceId, id, auditToken(audit.result), client);
|
|
1535
|
+
if (response) sendMcpResult(client, id, response);
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
function handleServiceMcp(msg, deps) {
|
|
1539
|
+
return require('./lib/feedback-remote/serviceMcpSession.cjs').handleServiceMcp(msg, deps);
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1122
1542
|
async function dispatchEnvelope(envelope, device, client) {
|
|
1123
1543
|
const { type, id, payload } = envelope;
|
|
1544
|
+
// A paired service may send only cmd:mcp; a non-service client may never send it.
|
|
1545
|
+
if (client.role === 'service' || type === 'cmd:mcp') {
|
|
1546
|
+
await dispatchServiceEnvelope(envelope, device, client);
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1124
1549
|
if (type === 'ipc:subscribe' || type === 'ipc:unsubscribe') {
|
|
1125
1550
|
if (client.e2e.state === 'authenticated') handleIpcSubscribe(envelope, client, type === 'ipc:subscribe');
|
|
1126
1551
|
return;
|
|
@@ -1300,7 +1725,7 @@ function getDispatchMap() {
|
|
|
1300
1725
|
const all = await require('./scheduler.cjs').listPrdsInternal();
|
|
1301
1726
|
const prds = all
|
|
1302
1727
|
.filter((e) => e && e.epicId === parsed.epicId)
|
|
1303
|
-
.map((e) => ({ slug: e.slug, title: e.title, status: e.status ?? null, archived: !!e.archived }))
|
|
1728
|
+
.map((e) => ({ slug: e.slug, title: e.title, status: e.status ?? null, archived: !!e.archived, ...(e.cancelled === true ? { cancelled: true } : {}) }))
|
|
1304
1729
|
.sort((a, b) => Number(a.archived) - Number(b.archived) || String(a.slug).localeCompare(String(b.slug)))
|
|
1305
1730
|
.slice(0, 50);
|
|
1306
1731
|
return { prds };
|
|
@@ -1378,8 +1803,8 @@ function getDispatchMap() {
|
|
|
1378
1803
|
if (!target) return { ok: false, disposition: 'refused', reason: 'unknown-target' };
|
|
1379
1804
|
|
|
1380
1805
|
const enqueue = (prompt) => (target.extra
|
|
1381
|
-
? chatRunner.enqueueExternalPrompt(target.id, prompt, target.extra)
|
|
1382
|
-
: chatRunner.enqueueExternalPrompt(target.id, prompt));
|
|
1806
|
+
? chatRunner.enqueueExternalPrompt(target.id, prompt, { ...target.extra, relay: 'web-remote' })
|
|
1807
|
+
: chatRunner.enqueueExternalPrompt(target.id, prompt, { relay: 'web-remote' }));
|
|
1383
1808
|
|
|
1384
1809
|
const images = parsed.images ?? [];
|
|
1385
1810
|
if (images.length === 0) return outcome(await enqueue(parsed.prompt));
|
|
@@ -1566,6 +1991,7 @@ async function revokeAllDevices() {
|
|
|
1566
1991
|
const cfg = await loadConfig();
|
|
1567
1992
|
const revokedCount = (cfg.devices || []).length;
|
|
1568
1993
|
await saveConfig({ ...cfg, remoteEnabled: false, devices: [] });
|
|
1994
|
+
await clearLocalServices(); // a paired service rides the device; it goes too
|
|
1569
1995
|
await disconnect(); // tears down WS + clears session key
|
|
1570
1996
|
broadcastStatus();
|
|
1571
1997
|
sendIfAlive(_window, 'webRemote:revoked-all', { revokedCount });
|
|
@@ -1592,7 +2018,8 @@ function registerRemoteHandlers() {
|
|
|
1592
2018
|
const clientKey = arg?.clientKey;
|
|
1593
2019
|
let target;
|
|
1594
2020
|
if (clientKey !== undefined) {
|
|
1595
|
-
|
|
2021
|
+
const found = _clients.get(clientKey);
|
|
2022
|
+
target = found && found.role !== 'service' ? found : makeClientlessState();
|
|
1596
2023
|
} else {
|
|
1597
2024
|
const pending = pendingClients();
|
|
1598
2025
|
if (pending.length > 1) {
|
|
@@ -1670,6 +2097,30 @@ function registerRemoteHandlers() {
|
|
|
1670
2097
|
return revokeAllDevices();
|
|
1671
2098
|
});
|
|
1672
2099
|
|
|
2100
|
+
// Paired services: list (no keys/tokens) + relay orphans, start, confirm, revoke.
|
|
2101
|
+
ipcMain.handle('webRemote:services-list', async () => servicesList());
|
|
2102
|
+
|
|
2103
|
+
ipcMain.handle('webRemote:service-pair-start', validated(schemas.webRemoteServicePairStart, async (arg) => {
|
|
2104
|
+
return servicePairStart(arg);
|
|
2105
|
+
}));
|
|
2106
|
+
|
|
2107
|
+
ipcMain.handle('webRemote:service-confirm-sas', validated(schemas.webRemoteServiceConfirmSas, async ({ pairingId, sas }) => {
|
|
2108
|
+
const r = await confirmServiceSas(pairingId, sas);
|
|
2109
|
+
return r.ok ? { ok: true, service: redactService(r.service) } : r;
|
|
2110
|
+
}));
|
|
2111
|
+
|
|
2112
|
+
ipcMain.handle('webRemote:service-pair-cancel', validated(schemas.webRemoteServicePairCancel, async ({ pairingId }) => {
|
|
2113
|
+
return servicePairCancel(pairingId);
|
|
2114
|
+
}));
|
|
2115
|
+
|
|
2116
|
+
ipcMain.handle('webRemote:service-revoke', validated(schemas.webRemoteServiceRevoke, async ({ serviceId }) => {
|
|
2117
|
+
return serviceRevoke(serviceId);
|
|
2118
|
+
}));
|
|
2119
|
+
|
|
2120
|
+
ipcMain.handle('webRemote:relay-client-revoke', validated(schemas.webRemoteRelayClientRevoke, async ({ clientId }) => {
|
|
2121
|
+
return relayClientRevoke(clientId);
|
|
2122
|
+
}));
|
|
2123
|
+
|
|
1673
2124
|
ipcMain.handle('webRemote:audit-tail', validated(schemas.webRemoteAuditTail, async ({ lines }) => {
|
|
1674
2125
|
const lineCount = lines || 50;
|
|
1675
2126
|
const ymd = new Date().toISOString().slice(0, 10);
|
|
@@ -1716,7 +2167,12 @@ function destroy() {
|
|
|
1716
2167
|
module.exports = {
|
|
1717
2168
|
REMOTE_CAPABILITIES,
|
|
1718
2169
|
loadConfig,
|
|
2170
|
+
getLinkedDeviceToken,
|
|
1719
2171
|
setIpcDispatcher,
|
|
2172
|
+
setServiceInvoker,
|
|
2173
|
+
getServiceStore,
|
|
2174
|
+
confirmServiceSas,
|
|
2175
|
+
servicePairCancel,
|
|
1720
2176
|
attachWindow,
|
|
1721
2177
|
registerRemoteHandlers,
|
|
1722
2178
|
init,
|
|
@@ -1751,5 +2207,6 @@ module.exports = {
|
|
|
1751
2207
|
getClient: (clientKey = LEGACY_CLIENT_KEY) => _clients.getOrCreate(clientKey),
|
|
1752
2208
|
revokeAllDevices,
|
|
1753
2209
|
pair,
|
|
2210
|
+
setServiceStore: (store) => { _serviceStore = store; },
|
|
1754
2211
|
},
|
|
1755
2212
|
};
|