codehere 0.6.2 → 0.7.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.
Files changed (70) hide show
  1. package/README.md +5 -3
  2. package/dist/application/use-cases/domain-trust.js +110 -0
  3. package/dist/application/use-cases/generate-final-report.js +28 -4
  4. package/dist/application/use-cases/generate-narration.js +11 -0
  5. package/dist/application/use-cases/generate-thread-title.js +4 -0
  6. package/dist/application/use-cases/thread-export.js +155 -0
  7. package/dist/application/use-cases/verify-claim.js +274 -0
  8. package/dist/application/use-cases/write-pass.js +277 -0
  9. package/dist/index.js +211 -16
  10. package/dist/infrastructure/completion/bash-completion.js +2 -2
  11. package/dist/infrastructure/config/config-manager.js +1 -1
  12. package/dist/infrastructure/context/adapters/drawio-source.js +157 -0
  13. package/dist/infrastructure/context/adapters/figma-source.js +163 -0
  14. package/dist/infrastructure/context/adapters/github-issue-source.js +159 -0
  15. package/dist/infrastructure/context/adapters/linear-source.js +190 -0
  16. package/dist/infrastructure/context/context-resolver.js +144 -0
  17. package/dist/infrastructure/context/context-source.js +114 -0
  18. package/dist/infrastructure/context/oauth-flow.js +207 -0
  19. package/dist/infrastructure/context/oauth-store.js +119 -0
  20. package/dist/infrastructure/context/registry-bootstrap.js +99 -0
  21. package/dist/infrastructure/context/write-pass-resolver.js +106 -0
  22. package/dist/infrastructure/hooks/claude-sdk-hook.js +73 -57
  23. package/dist/infrastructure/hooks/session-analyzer.js +65 -8
  24. package/dist/infrastructure/observability/execution-tracer.js +0 -5
  25. package/dist/infrastructure/orchestration/aider-adapter.js +45 -17
  26. package/dist/infrastructure/orchestration/artifacts-extractor.js +39 -5
  27. package/dist/infrastructure/orchestration/cassette-recorder.js +120 -0
  28. package/dist/infrastructure/orchestration/claude-code-adapter.js +33 -4
  29. package/dist/infrastructure/orchestration/codex-adapter.js +146 -13
  30. package/dist/infrastructure/orchestration/context-handoff.js +3 -2
  31. package/dist/infrastructure/orchestration/control/codex-control-surface.js +99 -0
  32. package/dist/infrastructure/orchestration/control/control-surface.js +15 -0
  33. package/dist/infrastructure/orchestration/gemini-adapter.js +12 -2
  34. package/dist/infrastructure/orchestration/mocks/mock-agent-repl.js +233 -0
  35. package/dist/infrastructure/orchestration/mocks/mock-codex-app-server.js +73 -0
  36. package/dist/infrastructure/orchestration/mocks/mock-synthesis.js +83 -0
  37. package/dist/infrastructure/orchestration/mocks/resolve-agent-spawn.js +37 -0
  38. package/dist/infrastructure/orchestration/opencode-adapter.js +22 -2
  39. package/dist/infrastructure/orchestration/progress-aggregator.js +177 -3
  40. package/dist/infrastructure/orchestration/session-manager.js +94 -6
  41. package/dist/infrastructure/orchestration/session-persistence.js +139 -30
  42. package/dist/infrastructure/orchestration/thread-key-store.js +127 -0
  43. package/dist/infrastructure/orchestration/write-pass-store.js +46 -0
  44. package/dist/infrastructure/protocols/cloud-sync.js +1 -6
  45. package/dist/infrastructure/protocols/mcp-server-impl.js +1280 -12
  46. package/dist/infrastructure/protocols/thread-phase.js +105 -0
  47. package/dist/infrastructure/protocols/ui-page-v2.js +3768 -75
  48. package/dist/infrastructure/protocols/ui-page.js +12 -3299
  49. package/dist/infrastructure/protocols/verify-page.js +941 -0
  50. package/dist/infrastructure/security/trust-scorer.js +76 -1
  51. package/dist/infrastructure/storage/cross-tool-agents.js +1 -1
  52. package/dist/infrastructure/storage/project-thread-migration.js +2 -2
  53. package/dist/infrastructure/storage/project-thread-title-backfill.js +1 -1
  54. package/dist/monitoring.js +1 -1
  55. package/dist/presentation/cli/commands/audit-command.js +126 -0
  56. package/dist/presentation/cli/commands/config-command.js +2 -2
  57. package/dist/presentation/cli/commands/context-source-command.js +198 -0
  58. package/dist/presentation/cli/commands/help-command.js +51 -1
  59. package/dist/presentation/cli/commands/report-command.js +6 -4
  60. package/dist/presentation/cli/commands/setup-command.js +71 -18
  61. package/dist/presentation/cli/commands/status-command.js +0 -4
  62. package/dist/presentation/cli/commands/thread-command.js +288 -0
  63. package/dist/presentation/cli/commands/verify-command.js +233 -0
  64. package/dist/presentation/cli/error-display.js +1 -1
  65. package/dist/presentation/cli/repl.js +32 -1
  66. package/dist/presentation/cli/task-deliverable.js +127 -0
  67. package/dist/testing/cassette.js +125 -0
  68. package/dist/testing/replay-adapter.js +166 -0
  69. package/dist/ui.js +18 -1
  70. package/package.json +4 -2
@@ -23,10 +23,27 @@ import { readFileSync, existsSync, statSync, watchFile, unwatchFile } from 'fs';
23
23
  import { join, relative, dirname } from 'path';
24
24
  import { fileURLToPath } from 'url';
25
25
  import { collectFilesForMCP, scoreFileForMCP } from './mcp-helpers.js';
26
- import { scanPayload, calculateRiskScore, AUDIT_FILE, verifyAuditChain, } from '../hooks/claude-sdk-hook.js';
26
+ import { scanPayload, calculateRiskScore, AUDIT_FILE, verifyAuditChain } from '../hooks/claude-sdk-hook.js';
27
+ import { analyzeSessions, isRealHostSession, previewFromToolInput } from '../hooks/session-analyzer.js';
28
+ import { CodexControlSurface } from '../orchestration/control/codex-control-surface.js';
27
29
  import { getVersion } from '../../utils/version.js';
28
- import { TASK_HTML, HISTORY_HTML, THREAD_HTML } from './ui-page.js';
30
+ import { HISTORY_HTML, THREAD_HTML } from './ui-page.js';
29
31
  import { TASK_HTML_V2 } from './ui-page-v2.js';
32
+ import { VERIFY_HTML } from './verify-page.js';
33
+ import { verifyClaim } from '../../application/use-cases/verify-claim.js';
34
+ import { signBundle, verifyBundle, shortFingerprint, } from '../../application/use-cases/thread-export.js';
35
+ import { loadOrCreateKeypair, trustedKeySet, trustKey } from '../orchestration/thread-key-store.js';
36
+ import { loadSessionById } from '../orchestration/session-persistence.js';
37
+ import { validateIntent as validateWritePassIntent, validateDecision as validateWritePassDecision, applyDecision as applyWritePassDecision, applyResponse as applyWritePassResponse, statusToAuditLine as writePassStatusToAuditLine, newPassId, WritePassError, } from '../../application/use-cases/write-pass.js';
38
+ import { putPending as wpPutPending, getById as wpGetById, setStatus as wpSetStatus, listForSession as wpListForSession, listPending as wpListPending, } from '../orchestration/write-pass-store.js';
39
+ import { resolveWriteRequest, WritePassResolveError } from '../context/write-pass-resolver.js';
40
+ import { trustDomain as trustDomainStore } from '../../application/use-cases/domain-trust.js';
41
+ import { appendAuditLog, appendOverrideAudit } from '../hooks/claude-sdk-hook.js';
42
+ import { readFileSync as fsReadFileSync, existsSync as fsExistsSync } from 'fs';
43
+ import { resolveContextSourceUrls } from '../context/context-resolver.js';
44
+ import { getDefaultRegistry, createDefaultFetchContextWithPost } from '../context/registry-bootstrap.js';
45
+ import { begin as oauthBegin, complete as oauthComplete, getProvider as getOAuthProvider, listProviders as listOAuthProviders, } from '../context/oauth-flow.js';
46
+ import { saveToken, clearToken, connectionStatus } from '../context/oauth-store.js';
30
47
  import { SessionManager, availableAgents, readinessForAllAgents, getAdapter, allAdapters, } from '../orchestration/session-manager.js';
31
48
  import { isAbsolute } from 'path';
32
49
  import { readCrossToolAgents } from '../storage/cross-tool-agents.js';
@@ -97,7 +114,8 @@ const TOOLS = [
97
114
  ];
98
115
  // ── Tool handlers ────────────────────────────────────────────────────────────
99
116
  import { homedir } from 'os';
100
- const AUDIT_FILE_PATH = join(homedir(), '.codehere', 'audit', 'hook-events.jsonl');
117
+ const controlSessions = new Map();
118
+ let controlSeq = 0;
101
119
  /**
102
120
  * Dev-only behavior-observer injection (v0.6.0 — elu joined the team roster
103
121
  * 2026-05-03 as behavior reviewer). Activated only when CODEHERE_DEV_ELU=1
@@ -175,9 +193,26 @@ function handleScan(params) {
175
193
  findings: findings.slice(0, 10), // cap at 10 to keep response small
176
194
  });
177
195
  }
196
+ /**
197
+ * Coerce a client-supplied numeric param to a bounded integer. Daemon
198
+ * endpoints take topN/limit straight from request bodies; a negative or NaN
199
+ * value silently corrupts slice() math (limit=-1 → slice keeps all-but-last,
200
+ * NaN → slice returns everything). Clamp to a sane range instead of trusting
201
+ * the wire.
202
+ */
203
+ export function clampInt(v, def, min, max) {
204
+ // null/undefined = absent → default. Number(null) is 0 (finite), so without
205
+ // this guard a literal null would coerce to the min instead of the default.
206
+ if (v === null || v === undefined)
207
+ return def;
208
+ const n = Math.floor(Number(v));
209
+ if (!Number.isFinite(n))
210
+ return def;
211
+ return Math.max(min, Math.min(n, max));
212
+ }
178
213
  function handleReview(params) {
179
214
  const targetPath = String(params.path ?? process.cwd());
180
- const topN = Number(params.topN ?? 10);
215
+ const topN = clampInt(params.topN, 10, 1, 100);
181
216
  try {
182
217
  const files = collectFilesForMCP(targetPath);
183
218
  if (files.length === 0) {
@@ -206,23 +241,23 @@ function handleReview(params) {
206
241
  }
207
242
  }
208
243
  function handleAudit(params) {
209
- const limit = Number(params.limit ?? 20);
244
+ const limit = clampInt(params.limit, 20, 1, 500);
210
245
  const blockedOnly = Boolean(params.blockedOnly);
211
246
  const overrideOnly = Boolean(params.overrideOnly);
212
247
  const verify = Boolean(params.verify);
213
248
  if (verify) {
214
249
  // Tamper-evidence verification — walks the file, recomputes every hash,
215
250
  // checks the chain. Returns full report including ALL break points.
216
- const result = verifyAuditChain(AUDIT_FILE_PATH);
251
+ const result = verifyAuditChain(AUDIT_FILE);
217
252
  return JSON.stringify(result, null, 2);
218
253
  }
219
- if (!existsSync(AUDIT_FILE_PATH)) {
254
+ if (!existsSync(AUDIT_FILE)) {
220
255
  return JSON.stringify({
221
256
  message: 'No audit log yet — install hooks first with: codehere hook install',
222
257
  entries: [],
223
258
  });
224
259
  }
225
- const lines = readFileSync(AUDIT_FILE_PATH, 'utf-8')
260
+ const lines = readFileSync(AUDIT_FILE, 'utf-8')
226
261
  .split('\n')
227
262
  .filter(Boolean)
228
263
  .slice(-Math.min(limit * 3, 500)); // read more than needed to account for filter
@@ -301,6 +336,11 @@ function dispatch(req) {
301
336
  }
302
337
  }
303
338
  const MAX_BODY_SIZE = 2_097_152; // 2 MiB — covers 1MB code-scan payloads + framing
339
+ // v0.8 S2.5 · in-memory map of pending OAuth flows keyed by `state` value.
340
+ // Lifecycle: begin() inserts; callback resolves and removes; entries also
341
+ // expire on a 10-min wall clock (the oauth-flow.ts complete() does the
342
+ // check). Daemon restart wipes this · users just click Connect again.
343
+ const PENDING_OAUTH_FLOWS = new Map();
304
344
  function readBody(req, res) {
305
345
  return new Promise((resolve, reject) => {
306
346
  let body = '';
@@ -317,11 +357,52 @@ function readBody(req, res) {
317
357
  req.on('error', () => reject(new Error('request aborted')));
318
358
  });
319
359
  }
360
+ /** v0.9 S6 · Load context-sources.json into the shape resolveWriteRequest
361
+ * expects. Same on-disk file as the READ adapters · symmetric storage. */
362
+ function loadContextSourcesConfigForWritePass() {
363
+ const path = join(process.env.CODEHERE_HOME || homedir(), '.codehere', 'context-sources.json');
364
+ if (!fsExistsSync(path))
365
+ return {};
366
+ try {
367
+ const raw = JSON.parse(fsReadFileSync(path, 'utf-8'));
368
+ return raw;
369
+ }
370
+ catch {
371
+ return {};
372
+ }
373
+ }
320
374
  export function startMCPServer(options = {}) {
321
375
  const port = options.port ?? 3773;
322
376
  const host = options.host ?? '127.0.0.1'; // localhost only by default
323
377
  const token = options.token;
324
378
  const server = http.createServer((req, res) => {
379
+ // v0.7 Week-2.2 · CORS for read-only public endpoints.
380
+ // The landing-page daemon-status pill (codehere.uk → 127.0.0.1:3773)
381
+ // fetches /health · /api/version · /api/tasks across origins to render
382
+ // "running locally · vX.Y.Z · N tasks." Without these headers the
383
+ // browser blocks the cross-origin fetch. Safe to allow * on these
384
+ // because the endpoints expose only version + task COUNTS (no PII ·
385
+ // no auth-state · no payload). Mutation endpoints (POST /api/task,
386
+ // /api/writepass/:id/:decision, etc.) are NOT covered by this · they
387
+ // remain same-origin-only.
388
+ const url = req.url ?? '';
389
+ const isReadOnlyPublic = url === '/health' ||
390
+ url === '/api/version' ||
391
+ url === '/api/tasks' ||
392
+ url === '/api/host-sessions' ||
393
+ url.startsWith('/api/host-sessions/') ||
394
+ url.startsWith('/api/audit/stats') ||
395
+ url.startsWith('/api/readiness/agents');
396
+ if (isReadOnlyPublic) {
397
+ res.setHeader('Access-Control-Allow-Origin', '*');
398
+ res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
399
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
400
+ if (req.method === 'OPTIONS') {
401
+ res.writeHead(204);
402
+ res.end();
403
+ return;
404
+ }
405
+ }
325
406
  // Auth check — timing-safe comparison
326
407
  if (token) {
327
408
  const authHeader = req.headers.authorization ?? '';
@@ -338,6 +419,28 @@ export function startMCPServer(options = {}) {
338
419
  return;
339
420
  }
340
421
  }
422
+ // CSRF / DNS-rebind defense for state-changing requests. The daemon binds
423
+ // localhost, but the user's own browser can reach it — so a page on a
424
+ // malicious site could fire a cross-origin POST (a text/plain "simple
425
+ // request" sidesteps the CORS preflight) to spawn an agent or mutate state.
426
+ // `codehere start` runs without a bearer token, so that gate is off by
427
+ // default; this enforces the same-origin-only intent noted above. Browsers
428
+ // attach Origin / Sec-Fetch-Site on these requests; native clients (the
429
+ // CLI, curl, MCP stdio) do not — so we reject only requests a browser
430
+ // marks as cross-origin, and leave header-less non-browser clients alone.
431
+ const method = req.method ?? 'GET';
432
+ if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {
433
+ const sfs = req.headers['sec-fetch-site'];
434
+ const origin = req.headers.origin;
435
+ const selfOrigins = new Set([`http://${host}:${port}`, `http://127.0.0.1:${port}`, `http://localhost:${port}`]);
436
+ const browserCrossOrigin = (typeof sfs === 'string' && sfs !== 'same-origin' && sfs !== 'none') ||
437
+ (typeof origin === 'string' && origin !== 'null' && !selfOrigins.has(origin));
438
+ if (browserCrossOrigin) {
439
+ res.writeHead(403, { 'Content-Type': 'application/json' });
440
+ res.end(JSON.stringify({ error: 'cross-origin request rejected' }));
441
+ return;
442
+ }
443
+ }
341
444
  // Health check
342
445
  if (req.method === 'GET' && req.url === '/health') {
343
446
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -350,10 +453,21 @@ export function startMCPServer(options = {}) {
350
453
  res.end(withDevElu(TASK_HTML_V2));
351
454
  return;
352
455
  }
353
- // v1 dashboard (legacy — at /v1)
456
+ // /v1 deleted 2026-05-23 · failover UI ported to v2 (see ui-page-v2.ts
457
+ // .failover-banner). The route now redirects to / so old bookmarks land
458
+ // on the real product instead of 404.
354
459
  if (req.method === 'GET' && (req.url === '/v1' || req.url === '/v1/')) {
460
+ res.writeHead(301, { Location: '/' });
461
+ res.end();
462
+ return;
463
+ }
464
+ // verify-at-the-surface dashboard · /verify (+ /verify/replay, query params).
465
+ // Serves the SAME HTML for both — the page reads ?mode=replay itself. It
466
+ // embeds `/` in an iframe as the real observation surface. Not dev-elu
467
+ // wrapped: it IS the verification view, the elu overlay would be noise.
468
+ if (req.method === 'GET' && req.url && /^\/verify(\/replay)?(\?.*)?$/.test(req.url)) {
355
469
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
356
- res.end(withDevElu(TASK_HTML));
470
+ res.end(VERIFY_HTML);
357
471
  return;
358
472
  }
359
473
  // History / audit feed (what we built Day 0; now secondary)
@@ -667,6 +781,310 @@ export function startMCPServer(options = {}) {
667
781
  }));
668
782
  return;
669
783
  }
784
+ // ── Host sessions — the coding-agent CLIs codehere observes via the hook ──
785
+ // These are NOT spawned-by-codehere agents (those live in /api/tasks). These
786
+ // are the Claude Code / Codex / etc. sessions running in the user's own
787
+ // terminal, captured by the PreToolUse hook. This is the surface that proves
788
+ // the INWARD axis: every coding agent — including the one the user is talking
789
+ // to right now — is a first-class workspace member, not a black box.
790
+ if (req.method === 'GET' && req.url === '/api/host-sessions') {
791
+ const entries = [];
792
+ try {
793
+ if (existsSync(AUDIT_FILE)) {
794
+ const lines = readFileSync(AUDIT_FILE, 'utf-8').split('\n');
795
+ for (const line of lines) {
796
+ const t = line.trim();
797
+ if (!t)
798
+ continue;
799
+ try {
800
+ const e = JSON.parse(t);
801
+ if (e && typeof e.sessionId === 'string')
802
+ entries.push(e);
803
+ }
804
+ catch {
805
+ /* skip malformed line */
806
+ }
807
+ }
808
+ }
809
+ }
810
+ catch {
811
+ /* empty audit — empty list is fine */
812
+ }
813
+ // Only surface genuine host coding sessions — not seed fixtures or the
814
+ // synthetic WritePass/pre_prompt audit rows. isRealHostSession() requires
815
+ // a real coding tool + 48h recency. Without it the strip would claim
816
+ // "10 sessions running" when 9 are stale demo artifacts — the screen-lie
817
+ // the no-screen-lies rule bans.
818
+ const now = Date.now();
819
+ const sessions = analyzeSessions(entries)
820
+ .filter((s) => s.sessionId !== 'unknown')
821
+ .filter((s) => isRealHostSession(s, now))
822
+ .sort((a, b) => new Date(b.lastSeen).getTime() - new Date(a.lastSeen).getTime())
823
+ .slice(0, 10)
824
+ .map((s) => ({
825
+ sessionId: s.sessionId,
826
+ shortId: s.sessionId.substring(0, 8),
827
+ totalCalls: s.totalCalls,
828
+ blockedCalls: s.blockedCalls,
829
+ criticalCalls: s.criticalCalls,
830
+ durationMs: s.durationMs,
831
+ lastSeen: s.lastSeen,
832
+ risk: s.amplificationRisk,
833
+ toolMix: s.toolMix,
834
+ }));
835
+ res.writeHead(200, { 'Content-Type': 'application/json' });
836
+ res.end(JSON.stringify({ sessions, total: sessions.length }));
837
+ return;
838
+ }
839
+ // ── Host session as a THREAD — full tool-call timeline for one observed ──
840
+ // session. This is the meta-dogfood payoff: open the coding-agent session
841
+ // running in your terminal and see every call codehere scanned, in order,
842
+ // hash-chained. GET /api/host-sessions/:id
843
+ const hostDetailMatch = req.url?.match(/^\/api\/host-sessions\/([^/?]+)$/);
844
+ if (req.method === 'GET' && hostDetailMatch) {
845
+ const wantId = decodeURIComponent(hostDetailMatch[1]);
846
+ // Group matching entries by their FULL session id, then resolve to ONE
847
+ // session. The strip links with an 8-char short id; if two sessions share
848
+ // that prefix, a naive startsWith() would merge their timelines into a
849
+ // single bogus session. Grouping + resolving keeps each session distinct.
850
+ const bySession = new Map();
851
+ const lastTs = new Map();
852
+ try {
853
+ if (existsSync(AUDIT_FILE)) {
854
+ const lines = readFileSync(AUDIT_FILE, 'utf-8').split('\n');
855
+ for (const line of lines) {
856
+ const t = line.trim();
857
+ if (!t)
858
+ continue;
859
+ let e;
860
+ try {
861
+ e = JSON.parse(t);
862
+ }
863
+ catch {
864
+ continue;
865
+ }
866
+ const sid = e.sessionId;
867
+ if (!sid || (sid !== wantId && !sid.startsWith(wantId)))
868
+ continue;
869
+ // Plain-English preview: the bash command or the file path, never
870
+ // the full JSON blob. Persona-facing surface, not a log dump.
871
+ const preview = previewFromToolInput(e.toolInput);
872
+ const call = {
873
+ timestamp: e.timestamp,
874
+ toolName: e.toolName,
875
+ riskScore: e.riskScore ?? 0,
876
+ blocked: !!e.blocked,
877
+ findings: e.findings ?? 0,
878
+ criticalFindings: e.criticalFindings ?? 0,
879
+ seq: e.seq,
880
+ chained: typeof e.entryHash === 'string' && e.entryHash.length > 0,
881
+ preview,
882
+ };
883
+ if (!bySession.has(sid))
884
+ bySession.set(sid, []);
885
+ bySession.get(sid).push(call);
886
+ const ts = e.timestamp ? Date.parse(e.timestamp) : 0;
887
+ if (Number.isFinite(ts) && ts > (lastTs.get(sid) ?? 0))
888
+ lastTs.set(sid, ts);
889
+ }
890
+ }
891
+ }
892
+ catch {
893
+ /* empty / unreadable audit — empty timeline is honest */
894
+ }
895
+ // Resolve to one session: an exact full-id match wins; otherwise the most
896
+ // recently active session carrying the prefix. We never merge two.
897
+ let resolvedId;
898
+ if (bySession.has(wantId)) {
899
+ resolvedId = wantId;
900
+ }
901
+ else if (bySession.size >= 1) {
902
+ resolvedId = [...bySession.keys()].sort((a, b) => (lastTs.get(b) ?? 0) - (lastTs.get(a) ?? 0))[0];
903
+ }
904
+ const calls = resolvedId ? bySession.get(resolvedId) : [];
905
+ if (calls.length === 0) {
906
+ res.writeHead(404, { 'Content-Type': 'application/json' });
907
+ res.end(JSON.stringify({ error: 'No observed session matching ' + wantId }));
908
+ return;
909
+ }
910
+ calls.sort((a, b) => new Date(String(a.timestamp)).getTime() - new Date(String(b.timestamp)).getTime());
911
+ const chain = verifyAuditChain(AUDIT_FILE);
912
+ res.writeHead(200, { 'Content-Type': 'application/json' });
913
+ res.end(JSON.stringify({
914
+ sessionId: resolvedId ?? wantId,
915
+ calls,
916
+ totalCalls: calls.length,
917
+ blockedCalls: calls.filter((c) => c.blocked).length,
918
+ criticalCalls: calls.filter((c) => c.criticalFindings > 0).length,
919
+ chainValid: chain.valid,
920
+ chainEntries: chain.chainedEntries,
921
+ }));
922
+ return;
923
+ }
924
+ // ── Remote control · drive a running agent from the web ───────────────
925
+ // POST /api/control/open { agent, prompt } → opens a ControlSurface, starts
926
+ // a thread + initial turn, returns { controlId, threadId }.
927
+ // POST /api/control/:id/inject { message } → turn/steer into the running
928
+ // turn (the remote-control primitive).
929
+ // GET /api/control/:id/events → what the driven agent emitted.
930
+ // Same-origin only (mutating). Under CODEHERE_MOCK=1 the surface drives the
931
+ // mock app-server — zero API, no rate-limit.
932
+ if (req.method === 'POST' && req.url === '/api/control/open') {
933
+ (async () => {
934
+ try {
935
+ const raw = JSON.parse((await readBody(req, res)) || '{}');
936
+ const agent = String(raw.agent ?? 'codex');
937
+ const prompt = String(raw.prompt ?? '').trim();
938
+ if (!prompt) {
939
+ res.writeHead(400, { 'Content-Type': 'application/json' });
940
+ res.end(JSON.stringify({ error: 'prompt required' }));
941
+ return;
942
+ }
943
+ if (agent !== 'codex') {
944
+ res.writeHead(400, { 'Content-Type': 'application/json' });
945
+ res.end(JSON.stringify({ error: 'only codex control surface is wired today' }));
946
+ return;
947
+ }
948
+ const surface = new CodexControlSurface();
949
+ const controlId = 'ctrl-' + ++controlSeq;
950
+ const entry = { surface, agent, threadId: '', events: [], openedAt: Date.now() };
951
+ surface.onEvent((e) => entry.events.push(e));
952
+ controlSessions.set(controlId, entry);
953
+ const { threadId } = await surface.open(prompt);
954
+ entry.threadId = threadId;
955
+ res.writeHead(200, { 'Content-Type': 'application/json' });
956
+ res.end(JSON.stringify({ controlId, threadId, agent }));
957
+ }
958
+ catch (e) {
959
+ res.writeHead(500, { 'Content-Type': 'application/json' });
960
+ res.end(JSON.stringify({ error: 'control open failed: ' + e.message }));
961
+ }
962
+ })();
963
+ return;
964
+ }
965
+ const ctlInject = req.url?.match(/^\/api\/control\/([^/]+)\/inject$/);
966
+ if (req.method === 'POST' && ctlInject) {
967
+ (async () => {
968
+ const entry = controlSessions.get(decodeURIComponent(ctlInject[1]));
969
+ if (!entry) {
970
+ res.writeHead(404, { 'Content-Type': 'application/json' });
971
+ res.end(JSON.stringify({ error: 'no such control session' }));
972
+ return;
973
+ }
974
+ try {
975
+ const raw = JSON.parse((await readBody(req, res)) || '{}');
976
+ const message = String(raw.message ?? '').trim();
977
+ if (!message) {
978
+ res.writeHead(400, { 'Content-Type': 'application/json' });
979
+ res.end(JSON.stringify({ error: 'message required' }));
980
+ return;
981
+ }
982
+ const r = await entry.surface.inject(message);
983
+ res.writeHead(200, { 'Content-Type': 'application/json' });
984
+ res.end(JSON.stringify({ accepted: r.accepted }));
985
+ }
986
+ catch (e) {
987
+ res.writeHead(500, { 'Content-Type': 'application/json' });
988
+ res.end(JSON.stringify({ error: 'inject failed: ' + e.message }));
989
+ }
990
+ })();
991
+ return;
992
+ }
993
+ const ctlEvents = req.url?.match(/^\/api\/control\/([^/]+)\/events$/);
994
+ if (req.method === 'GET' && ctlEvents) {
995
+ const entry = controlSessions.get(decodeURIComponent(ctlEvents[1]));
996
+ if (!entry) {
997
+ res.writeHead(404, { 'Content-Type': 'application/json' });
998
+ res.end(JSON.stringify({ error: 'no such control session' }));
999
+ return;
1000
+ }
1001
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1002
+ res.end(JSON.stringify({ threadId: entry.threadId, agent: entry.agent, events: entry.events }));
1003
+ return;
1004
+ }
1005
+ // ── User override · a human reviewed a block and chose to proceed ──────
1006
+ // POST /api/audit/override · body { sessionId, toolName, reason }. Appends
1007
+ // a 'user_override' entry with the free-text reason to the hash chain and
1008
+ // returns the new entry's seq + short hash, so the UI can show "logged ·
1009
+ // chain continues <hash>" with the REAL hash, not a mockup. Same-origin
1010
+ // only (mutating · not in the CORS read-only list).
1011
+ if (req.method === 'POST' && req.url === '/api/audit/override') {
1012
+ (async () => {
1013
+ try {
1014
+ const text = await readBody(req, res);
1015
+ let raw;
1016
+ try {
1017
+ raw = JSON.parse(text || '{}');
1018
+ }
1019
+ catch {
1020
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1021
+ res.end(JSON.stringify({ error: 'invalid JSON' }));
1022
+ return;
1023
+ }
1024
+ const reason = String(raw.reason ?? '').trim();
1025
+ if (!reason) {
1026
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1027
+ res.end(JSON.stringify({ error: 'a reason is required to log an override' }));
1028
+ return;
1029
+ }
1030
+ appendOverrideAudit('user_override', {
1031
+ sessionId: typeof raw.sessionId === 'string' ? raw.sessionId : 'unknown',
1032
+ toolName: typeof raw.toolName === 'string' ? raw.toolName : 'unknown',
1033
+ note: reason,
1034
+ });
1035
+ // appendOverrideAudit → appendAuditLog is fail-open: it swallows
1036
+ // write errors so a logging failure never blocks a tool call. That's
1037
+ // right for the hook, but here the UI shows "✓ override logged", so
1038
+ // we must CONFIRM our entry actually landed before claiming success
1039
+ // (no screen-lies). Scan the tail backward for our exact entry — a
1040
+ // concurrent hook process may have appended after ours, so it isn't
1041
+ // guaranteed to be the very last line.
1042
+ const wantSid = typeof raw.sessionId === 'string' ? raw.sessionId : 'unknown';
1043
+ const wantNote = reason.slice(0, 500);
1044
+ let seq = null;
1045
+ let entryHash = '';
1046
+ let confirmed = false;
1047
+ try {
1048
+ const lines = readFileSync(AUDIT_FILE, 'utf-8').trim().split('\n');
1049
+ for (let i = lines.length - 1; i >= 0 && i >= lines.length - 10; i--) {
1050
+ let e;
1051
+ try {
1052
+ e = JSON.parse(lines[i]);
1053
+ }
1054
+ catch {
1055
+ continue;
1056
+ }
1057
+ if (e.overrideReason === 'user_override' && e.sessionId === wantSid && e.overrideNote === wantNote) {
1058
+ seq = typeof e.seq === 'number' ? e.seq : null;
1059
+ entryHash = typeof e.entryHash === 'string' ? e.entryHash : '';
1060
+ confirmed = true;
1061
+ break;
1062
+ }
1063
+ }
1064
+ }
1065
+ catch {
1066
+ /* readback failed — cannot confirm the write landed */
1067
+ }
1068
+ if (!confirmed) {
1069
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1070
+ res.end(JSON.stringify({ ok: false, error: 'override could not be confirmed in the audit log' }));
1071
+ return;
1072
+ }
1073
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1074
+ res.end(JSON.stringify({
1075
+ ok: true,
1076
+ seq,
1077
+ entryHash,
1078
+ shortHash: entryHash ? entryHash.slice(0, 4) + '...' + entryHash.slice(-4) : '',
1079
+ }));
1080
+ }
1081
+ catch {
1082
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1083
+ res.end(JSON.stringify({ error: 'override failed' }));
1084
+ }
1085
+ })();
1086
+ return;
1087
+ }
670
1088
  // ── F1 · Agent install (zero-terminal setup — principle #10) ──────────────
671
1089
  // POST /api/agents/:id/install → SSE stream of install output.
672
1090
  // The command comes from the adapter's checkReadiness().installHint — never
@@ -938,6 +1356,10 @@ export function startMCPServer(options = {}) {
938
1356
  results.push({ error: 'prompt (string) required', agent: t.agent ?? null });
939
1357
  continue;
940
1358
  }
1359
+ if (prompt.trim().length === 0) {
1360
+ results.push({ error: 'prompt is empty — describe what you want done', agent: t.agent ?? null });
1361
+ continue;
1362
+ }
941
1363
  const agentId = typeof t.agent === 'string' && t.agent.length > 0 ? t.agent : 'conductor';
942
1364
  if (!validAgentIds.has(agentId)) {
943
1365
  results.push({ error: `Unknown agent: ${agentId}`, agent: agentId });
@@ -1011,6 +1433,14 @@ export function startMCPServer(options = {}) {
1011
1433
  res.end(JSON.stringify({ error: 'prompt (string) required' }));
1012
1434
  return;
1013
1435
  }
1436
+ // Whitespace-only prompts are a real spawn with nothing to do —
1437
+ // they burn an agent run for no work (dogfood 2026-05-27 Phase D).
1438
+ // Reject before spawn; require something to act on.
1439
+ if (prompt.trim().length === 0) {
1440
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1441
+ res.end(JSON.stringify({ error: 'prompt is empty — describe what you want done' }));
1442
+ return;
1443
+ }
1014
1444
  // CRIT-5 fix · whitelist agent ID against the registry BEFORE any
1015
1445
  // log/spawn. Stops log injection (`agent: "claude-code\n[FAKE]"`),
1016
1446
  // future-proofs against partial-match exploits, and fails fast
@@ -1065,7 +1495,36 @@ export function startMCPServer(options = {}) {
1065
1495
  }
1066
1496
  }
1067
1497
  }
1068
- const session = manager.spawn(prompt, agentId, { cwd });
1498
+ // v0.8 S2 · resolve any context-source URLs in the prompt
1499
+ // (linear://INFRA-247, figma://file/<key>/...) before spawn.
1500
+ // Best-effort · resolver failures get logged inline in the
1501
+ // prompt + emit audit lines, never block the spawn.
1502
+ const reg = getDefaultRegistry();
1503
+ const fetchCtx = createDefaultFetchContextWithPost({
1504
+ emitAuditLine: (line) => {
1505
+ // Future · feed into the hook audit chain (F-05/F-06).
1506
+ // For now console-debug only · the spawn audit line below
1507
+ // captures the user-facing outcome.
1508
+ if (process.env.CODEHERE_DEBUG === '1') {
1509
+ console.error('[context-source]', line.status, line.source, line.url, line.detail ?? '');
1510
+ }
1511
+ },
1512
+ });
1513
+ let promptForSpawn = prompt;
1514
+ try {
1515
+ const r = await resolveContextSourceUrls(prompt, reg, fetchCtx);
1516
+ promptForSpawn = r.enrichedPrompt;
1517
+ if (r.outcomes.length && process.env.CODEHERE_DEBUG === '1') {
1518
+ console.error('[context-source] resolved', r.outcomes.length, 'URL(s) ·', r.totalEstimatedTokens, 'tokens');
1519
+ }
1520
+ }
1521
+ catch (e) {
1522
+ // Resolver-level failure (registry corrupt, etc) · log and
1523
+ // fall back to the raw prompt. The agent runs without
1524
+ // enrichment instead of failing outright.
1525
+ console.error('[context-source] resolver failed:', e instanceof Error ? e.message : String(e));
1526
+ }
1527
+ const session = manager.spawn(promptForSpawn, agentId, { cwd });
1069
1528
  res.writeHead(200, { 'Content-Type': 'application/json' });
1070
1529
  res.end(JSON.stringify({
1071
1530
  sessionId: session.sessionId,
@@ -1101,6 +1560,15 @@ export function startMCPServer(options = {}) {
1101
1560
  const continuedFrom = manager.getContinuedFrom(s.sessionId);
1102
1561
  const continuedAs = manager.getContinuedAs(s.sessionId);
1103
1562
  const failedReport = manager.hasFailedReport(s.sessionId);
1563
+ const stalledReason = manager.getStallReason(s.sessionId);
1564
+ // F-07 · verifier-agent block · run claim vs reality on every task.
1565
+ // Pure function, no I/O, runs sync · cheap to do per request.
1566
+ // The UI renders the verdict + findings inline below the Summary.
1567
+ const verifyResult = verifyClaim({
1568
+ summary: finalReport?.summary,
1569
+ artifacts: s.artifacts,
1570
+ steps: s.steps,
1571
+ });
1104
1572
  return {
1105
1573
  sessionId: s.sessionId,
1106
1574
  prompt: s.prompt,
@@ -1112,6 +1580,8 @@ export function startMCPServer(options = {}) {
1112
1580
  ...(completedAt !== undefined ? { completedAt, durationMs: completedAt - s.startedAt } : {}),
1113
1581
  ...(finalReport !== undefined ? { finalReport } : {}),
1114
1582
  ...(failedReport ? { failedReport: true } : {}),
1583
+ ...(stalledReason ? { stalledReason } : {}),
1584
+ verifyResult,
1115
1585
  canAppendMessage: s.canAppendMessage === true,
1116
1586
  ...(cwd !== undefined ? { cwd } : {}),
1117
1587
  ...(continuedFrom !== undefined ? { continuedFrom } : {}),
@@ -1120,7 +1590,15 @@ export function startMCPServer(options = {}) {
1120
1590
  };
1121
1591
  });
1122
1592
  const activeAgents = manager.listActiveAgents();
1123
- const persisted = manager.listPersisted();
1593
+ // F-07 · attach verifyResult to persisted records too · same logic.
1594
+ const persisted = manager.listPersisted().map((p) => ({
1595
+ ...p,
1596
+ verifyResult: verifyClaim({
1597
+ summary: p.finalReport?.summary,
1598
+ artifacts: p.artifacts,
1599
+ steps: p.steps,
1600
+ }),
1601
+ }));
1124
1602
  // Layer 7: timestamp of most recent hook-audit line (= "last edit on this machine")
1125
1603
  let lastEditAt = null;
1126
1604
  try {
@@ -1382,6 +1860,766 @@ export function startMCPServer(options = {}) {
1382
1860
  })();
1383
1861
  return;
1384
1862
  }
1863
+ // F-05 / F-06 · public endpoint for the audit chain verifier · powers
1864
+ // the web UI's "Verify chain" button + can be hit directly by CI.
1865
+ // v0.8 S2.5 · context-source OAuth routes
1866
+ // GET /api/context-sources · list all providers + status
1867
+ // POST /api/context-sources/:id/connect · returns authorize URL + opens browser
1868
+ // POST /api/context-sources/:id/disconnect · clears stored token
1869
+ // GET /oauth/callback?code=...&state=... · provider redirect target
1870
+ if (req.url === '/api/context-sources' && req.method === 'GET') {
1871
+ try {
1872
+ const oauthItems = listOAuthProviders().map((p) => {
1873
+ const status = connectionStatus(p.id);
1874
+ return {
1875
+ id: p.id,
1876
+ label: p.label,
1877
+ scheme: p.id,
1878
+ authType: 'oauth',
1879
+ status: status.status,
1880
+ userLabel: status.userLabel ?? null,
1881
+ connectedAt: status.connectedAt ?? null,
1882
+ expiresAt: status.expiresAt ?? null,
1883
+ clientIdConfigured: !!process.env[p.clientIdEnv],
1884
+ };
1885
+ });
1886
+ // v0.8 S5 · public-by-URL adapters appear with status='available'
1887
+ // (no Connect button needed · they work out of the box).
1888
+ const oauthIds = new Set(oauthItems.map((i) => i.id));
1889
+ const reg = getDefaultRegistry();
1890
+ const noAuthItems = [...reg.bySchemeOnly.values()]
1891
+ .filter((s) => !oauthIds.has(s.id))
1892
+ .map((s) => ({
1893
+ id: s.id,
1894
+ label: s.label,
1895
+ scheme: s.scheme,
1896
+ authType: 'public',
1897
+ status: 'available',
1898
+ userLabel: null,
1899
+ connectedAt: null,
1900
+ expiresAt: null,
1901
+ clientIdConfigured: true,
1902
+ description: s.description,
1903
+ }));
1904
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1905
+ res.end(JSON.stringify({ providers: [...oauthItems, ...noAuthItems] }));
1906
+ }
1907
+ catch (e) {
1908
+ console.error('[/api/context-sources] failed:', e);
1909
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1910
+ res.end(JSON.stringify({ error: 'Failed to list context sources' }));
1911
+ }
1912
+ return;
1913
+ }
1914
+ const connectMatch = req.url?.match(/^\/api\/context-sources\/([^/]+)\/connect$/);
1915
+ if (connectMatch && req.method === 'POST') {
1916
+ const providerId = connectMatch[1];
1917
+ const provider = getOAuthProvider(providerId);
1918
+ if (!provider) {
1919
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1920
+ res.end(JSON.stringify({ error: `unknown provider: ${providerId}` }));
1921
+ return;
1922
+ }
1923
+ const clientId = process.env[provider.clientIdEnv] || null;
1924
+ const r = oauthBegin(provider, { clientId });
1925
+ if ('kind' in r && r.kind === 'not_registered') {
1926
+ res.writeHead(409, { 'Content-Type': 'application/json' });
1927
+ res.end(JSON.stringify({
1928
+ error: 'provider_not_registered',
1929
+ provider: providerId,
1930
+ envVar: provider.clientIdEnv,
1931
+ message: `Set ${provider.clientIdEnv} to the OAuth client id from ${provider.label}. Until then, paste a manual key into ~/.codehere/context-sources.json under '${providerId}.apiKey'.`,
1932
+ }));
1933
+ return;
1934
+ }
1935
+ const result = r;
1936
+ PENDING_OAUTH_FLOWS.set(result.pending.state, result.pending);
1937
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1938
+ res.end(JSON.stringify({ authorizeUrl: result.authorizeUrl, state: result.pending.state }));
1939
+ return;
1940
+ }
1941
+ // S2.6 · /test endpoint · proves the stored token actually works against
1942
+ // the provider with a minimal read. Returns ok or detail.
1943
+ const testMatch = req.url?.match(/^\/api\/context-sources\/([^/]+)\/test$/);
1944
+ if (testMatch && req.method === 'POST') {
1945
+ const providerId = testMatch[1];
1946
+ const provider = getOAuthProvider(providerId);
1947
+ if (!provider) {
1948
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1949
+ res.end(JSON.stringify({ ok: false, error: 'unknown_provider' }));
1950
+ return;
1951
+ }
1952
+ (async () => {
1953
+ try {
1954
+ const status = connectionStatus(providerId);
1955
+ if (status.status === 'disconnected') {
1956
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1957
+ res.end(JSON.stringify({ ok: false, error: 'not_connected' }));
1958
+ return;
1959
+ }
1960
+ // Minimal probe per provider · the user-info endpoint is the
1961
+ // cheapest "does this token read at all" call.
1962
+ const userInfoUrl = provider.userInfoUrl;
1963
+ if (!userInfoUrl) {
1964
+ res.writeHead(501, { 'Content-Type': 'application/json' });
1965
+ res.end(JSON.stringify({ ok: false, error: 'no_test_endpoint' }));
1966
+ return;
1967
+ }
1968
+ const cfg = JSON.parse(readFileSync(join(process.env.CODEHERE_HOME || homedir(), '.codehere', 'context-sources.json'), 'utf-8'));
1969
+ const entry = cfg[providerId] ?? {};
1970
+ let probeRes;
1971
+ if (providerId === 'linear') {
1972
+ const auth = entry.oauth?.accessToken ? `Bearer ${entry.oauth.accessToken}` : (entry.apiKey ?? '');
1973
+ probeRes = await fetch(userInfoUrl, {
1974
+ method: 'POST',
1975
+ headers: { Authorization: auth, 'Content-Type': 'application/json' },
1976
+ body: JSON.stringify({ query: '{ viewer { name email } }' }),
1977
+ });
1978
+ }
1979
+ else {
1980
+ // figma · GET with X-Figma-Token OR Bearer
1981
+ const headers = entry.oauth?.accessToken
1982
+ ? { Authorization: `Bearer ${entry.oauth.accessToken}` }
1983
+ : { 'X-Figma-Token': entry.token ?? '' };
1984
+ probeRes = await fetch(userInfoUrl, { headers });
1985
+ }
1986
+ if (!probeRes.ok) {
1987
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1988
+ res.end(JSON.stringify({ ok: false, error: 'provider_returned_' + probeRes.status }));
1989
+ return;
1990
+ }
1991
+ const body = (await probeRes.json());
1992
+ const who = body.data?.viewer?.email || body.data?.viewer?.name || body.email || body.handle || null;
1993
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1994
+ res.end(JSON.stringify({ ok: true, who }));
1995
+ }
1996
+ catch (e) {
1997
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1998
+ res.end(JSON.stringify({ ok: false, error: e instanceof Error ? e.message : String(e) }));
1999
+ }
2000
+ })();
2001
+ return;
2002
+ }
2003
+ const disconnectMatch = req.url?.match(/^\/api\/context-sources\/([^/]+)\/disconnect$/);
2004
+ if (disconnectMatch && req.method === 'POST') {
2005
+ const providerId = disconnectMatch[1];
2006
+ const ok = clearToken(providerId);
2007
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2008
+ res.end(JSON.stringify({ ok, provider: providerId }));
2009
+ return;
2010
+ }
2011
+ if (req.url?.startsWith('/oauth/callback') && req.method === 'GET') {
2012
+ (async () => {
2013
+ try {
2014
+ const u = new URL(req.url, 'http://127.0.0.1');
2015
+ const code = u.searchParams.get('code');
2016
+ const state = u.searchParams.get('state');
2017
+ const error = u.searchParams.get('error');
2018
+ if (error || !code || !state) {
2019
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
2020
+ res.end(callbackHtml('error', error || 'missing code/state', null));
2021
+ return;
2022
+ }
2023
+ const pending = PENDING_OAUTH_FLOWS.get(state);
2024
+ if (!pending) {
2025
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
2026
+ res.end(callbackHtml('error', 'unknown state · this flow was not started by this daemon or has expired', null));
2027
+ return;
2028
+ }
2029
+ const provider = getOAuthProvider(pending.provider);
2030
+ if (!provider) {
2031
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
2032
+ res.end(callbackHtml('error', `unknown provider: ${pending.provider}`, null));
2033
+ return;
2034
+ }
2035
+ const clientId = process.env[provider.clientIdEnv] || null;
2036
+ const out = await oauthComplete(code, state, {
2037
+ clientId,
2038
+ pending: PENDING_OAUTH_FLOWS,
2039
+ async httpPost(target, body, headers) {
2040
+ const r = await fetch(target, { method: 'POST', headers: headers ?? {}, body });
2041
+ const text = await r.text();
2042
+ const h = {};
2043
+ r.headers.forEach((v, k) => {
2044
+ h[k.toLowerCase()] = v;
2045
+ });
2046
+ return { status: r.status, body: text, headers: h };
2047
+ },
2048
+ async fetchUserInfo(token, userInfoUrl) {
2049
+ try {
2050
+ if (provider.id === 'linear') {
2051
+ const r = await fetch(userInfoUrl, {
2052
+ method: 'POST',
2053
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
2054
+ body: JSON.stringify({ query: '{ viewer { name email } }' }),
2055
+ });
2056
+ if (!r.ok)
2057
+ return null;
2058
+ const j = (await r.json());
2059
+ return j.data?.viewer ?? null;
2060
+ }
2061
+ if (provider.id === 'figma') {
2062
+ const r = await fetch(userInfoUrl, {
2063
+ headers: { Authorization: `Bearer ${token}` },
2064
+ });
2065
+ if (!r.ok)
2066
+ return null;
2067
+ const j = (await r.json());
2068
+ return { name: j.handle, email: j.email };
2069
+ }
2070
+ return null;
2071
+ }
2072
+ catch {
2073
+ return null;
2074
+ }
2075
+ },
2076
+ });
2077
+ if ('kind' in out) {
2078
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
2079
+ res.end(callbackHtml('error', `${out.kind}: ${out.detail}`, provider.label));
2080
+ return;
2081
+ }
2082
+ saveToken(out);
2083
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
2084
+ res.end(callbackHtml('ok', `Connected as ${out.userLabel ?? '(unknown user)'}`, provider.label));
2085
+ }
2086
+ catch (e) {
2087
+ console.error('[/oauth/callback] failed:', e);
2088
+ res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
2089
+ res.end(callbackHtml('error', e instanceof Error ? e.message : String(e), null));
2090
+ }
2091
+ })();
2092
+ return;
2093
+ }
2094
+ if (req.url === '/api/audit/verify' && req.method === 'GET') {
2095
+ try {
2096
+ const r = verifyAuditChain(AUDIT_FILE);
2097
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2098
+ res.end(JSON.stringify({
2099
+ path: AUDIT_FILE,
2100
+ valid: r.valid,
2101
+ totalEntries: r.totalEntries,
2102
+ chainedEntries: r.chainedEntries,
2103
+ legacyEntries: r.legacyEntries,
2104
+ errors: r.errors,
2105
+ }));
2106
+ }
2107
+ catch (e) {
2108
+ console.error('[/api/audit/verify] failed:', e);
2109
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2110
+ res.end(JSON.stringify({ error: 'Failed to verify audit chain' }));
2111
+ }
2112
+ return;
2113
+ }
2114
+ // v0.8 S4 · share-thread · POST /api/thread/:id/export returns a signed
2115
+ // bundle of one session that the recipient can replay locally. No relay
2116
+ // through codehere's infrastructure · the response stays on-machine.
2117
+ if (req.method === 'POST' && req.url && /^\/api\/thread\/[^/]+\/export$/.test(req.url)) {
2118
+ try {
2119
+ const m = req.url.match(/^\/api\/thread\/([^/]+)\/export$/);
2120
+ const sessionId = m ? decodeURIComponent(m[1]) : '';
2121
+ const session = sessionId ? loadSessionById(sessionId) : undefined;
2122
+ if (!session) {
2123
+ res.writeHead(404, { 'Content-Type': 'application/json' });
2124
+ res.end(JSON.stringify({ error: 'session not found', sessionId }));
2125
+ return;
2126
+ }
2127
+ const keys = loadOrCreateKeypair();
2128
+ const body = {
2129
+ schema: 1,
2130
+ kind: 'thread',
2131
+ sessionId: session.sessionId,
2132
+ session,
2133
+ exporter: { codehereVersion: '0.7.0' },
2134
+ exportedAt: new Date().toISOString(),
2135
+ };
2136
+ const bundle = signBundle(body, keys);
2137
+ const fp = shortFingerprint(bundle.publicKey);
2138
+ const link = `codehere://thread/${session.sessionId}?signed=ed25519:${bundle.signature.slice(0, 24)}`;
2139
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2140
+ res.end(JSON.stringify({ bundle, link, fingerprint: fp }));
2141
+ }
2142
+ catch (e) {
2143
+ console.error('[/api/thread/.../export] failed:', e);
2144
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2145
+ res.end(JSON.stringify({ error: 'export failed' }));
2146
+ }
2147
+ return;
2148
+ }
2149
+ // v0.8 S4 · share-thread · POST /api/thread/import · accepts a bundle in
2150
+ // the body, verifies it, optionally trusts the signer if the caller sets
2151
+ // { trust: true }, persists the session record on success.
2152
+ if (req.method === 'POST' && req.url === '/api/thread/import') {
2153
+ (async () => {
2154
+ try {
2155
+ const text = await readBody(req, res);
2156
+ let payload = {};
2157
+ try {
2158
+ payload = JSON.parse(text || '{}');
2159
+ }
2160
+ catch {
2161
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2162
+ res.end(JSON.stringify({ error: 'invalid JSON' }));
2163
+ return;
2164
+ }
2165
+ const verdict = verifyBundle(payload.bundle, trustedKeySet());
2166
+ if (verdict.status === 'malformed' || verdict.status === 'tampered') {
2167
+ res.writeHead(verdict.status === 'malformed' ? 400 : 409, { 'Content-Type': 'application/json' });
2168
+ res.end(JSON.stringify({ status: verdict.status, reason: verdict.reason }));
2169
+ return;
2170
+ }
2171
+ if (verdict.status === 'unknown_key') {
2172
+ if (!payload.trust) {
2173
+ res.writeHead(202, { 'Content-Type': 'application/json' });
2174
+ res.end(JSON.stringify({
2175
+ status: 'unknown_key',
2176
+ publicKey: verdict.publicKey,
2177
+ fingerprint: shortFingerprint(verdict.publicKey),
2178
+ hint: 'Re-POST with { "trust": true } to trust this key and import.',
2179
+ }));
2180
+ return;
2181
+ }
2182
+ trustKey(verdict.publicKey);
2183
+ }
2184
+ const finalBundle = verdict.bundle;
2185
+ const ses = finalBundle.body.session;
2186
+ const home = process.env.CODEHERE_HOME || homedir();
2187
+ const sessionsPath = join(home, '.codehere', 'sessions.jsonl');
2188
+ const fs = await import('fs');
2189
+ fs.mkdirSync(dirname(sessionsPath), { recursive: true });
2190
+ const lines = [];
2191
+ lines.push(JSON.stringify({
2192
+ t: 'spawned',
2193
+ id: ses.sessionId,
2194
+ agent: ses.agent,
2195
+ prompt: ses.prompt,
2196
+ cwd: ses.cwd,
2197
+ startedAt: ses.startedAt,
2198
+ }));
2199
+ lines.push(JSON.stringify({
2200
+ t: 'completed',
2201
+ id: ses.sessionId,
2202
+ status: ses.status,
2203
+ durationMs: ses.durationMs,
2204
+ completedAt: ses.completedAt,
2205
+ steps: ses.steps,
2206
+ artifacts: ses.artifacts,
2207
+ }));
2208
+ if (ses.finalReport) {
2209
+ lines.push(JSON.stringify({
2210
+ t: 'finalReport',
2211
+ id: ses.sessionId,
2212
+ summary: ses.finalReport.summary,
2213
+ generatedAt: ses.finalReport.generatedAt,
2214
+ durationMs: ses.finalReport.durationMs,
2215
+ }));
2216
+ }
2217
+ fs.appendFileSync(sessionsPath, lines.join('\n') + '\n', 'utf-8');
2218
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2219
+ res.end(JSON.stringify({
2220
+ status: 'imported',
2221
+ sessionId: ses.sessionId,
2222
+ fingerprint: shortFingerprint(finalBundle.publicKey),
2223
+ }));
2224
+ }
2225
+ catch (e) {
2226
+ console.error('[/api/thread/import] failed:', e);
2227
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2228
+ res.end(JSON.stringify({ error: 'import failed' }));
2229
+ }
2230
+ })();
2231
+ return;
2232
+ }
2233
+ /* v0.9 S7 · overlay-renderer · preview a 3rd-party URL via context-source */
2234
+ // GET /api/context-source/preview?url=<urlencoded scheme://...>
2235
+ if (req.method === 'GET' && req.url && req.url.startsWith('/api/context-source/preview')) {
2236
+ (async () => {
2237
+ try {
2238
+ const u = new URL(req.url, 'http://localhost');
2239
+ const target = u.searchParams.get('url');
2240
+ if (!target) {
2241
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2242
+ res.end(JSON.stringify({ error: 'url required' }));
2243
+ return;
2244
+ }
2245
+ const reg = getDefaultRegistry();
2246
+ const fetchCtx = createDefaultFetchContextWithPost({
2247
+ emitAuditLine: (line) => {
2248
+ if (process.env.CODEHERE_DEBUG === '1') {
2249
+ console.error('[overlay-renderer]', line.status, line.source, line.url, line.detail ?? '');
2250
+ }
2251
+ },
2252
+ });
2253
+ const { fetchViaRegistry } = await import('../context/context-source.js');
2254
+ try {
2255
+ const payload = await fetchViaRegistry(reg, target, fetchCtx);
2256
+ if (!payload) {
2257
+ // No adapter registered for that scheme · honest 400 instead of
2258
+ // silent ok:true with payload:null.
2259
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2260
+ res.end(JSON.stringify({
2261
+ ok: false,
2262
+ kind: 'invalid_url',
2263
+ error: `No adapter registered for "${target}" · supported: linear://, github://, figma://, drawio://`,
2264
+ }));
2265
+ return;
2266
+ }
2267
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2268
+ res.end(JSON.stringify({ ok: true, payload }));
2269
+ }
2270
+ catch (err) {
2271
+ const code = err.kind ?? 'unknown';
2272
+ const message = err instanceof Error ? err.message : String(err);
2273
+ // Map adapter errors to honest HTTP codes so the UI can render
2274
+ // a useful empty/error state instead of swallowing everything.
2275
+ const httpStatus = code === 'not_found'
2276
+ ? 404
2277
+ : code === 'auth'
2278
+ ? 401
2279
+ : code === 'rate_limit'
2280
+ ? 429
2281
+ : code === 'invalid_url'
2282
+ ? 400
2283
+ : 502;
2284
+ res.writeHead(httpStatus, { 'Content-Type': 'application/json' });
2285
+ res.end(JSON.stringify({ ok: false, kind: code, error: message }));
2286
+ }
2287
+ }
2288
+ catch (e) {
2289
+ console.error('[/api/context-source/preview] failed:', e);
2290
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2291
+ res.end(JSON.stringify({ ok: false, error: 'preview failed' }));
2292
+ }
2293
+ })();
2294
+ return;
2295
+ }
2296
+ /* v0.9 S6 part B · W-PASS write-pass routes ────────────────────────── */
2297
+ // POST /api/writepass/intent · agent emits an intent.
2298
+ // Body: { sessionId, target, method, payload, reason, emittedBy? }
2299
+ // Response: 201 { status: 'pending', intent: WritePassIntent }
2300
+ if (req.method === 'POST' && req.url === '/api/writepass/intent') {
2301
+ (async () => {
2302
+ try {
2303
+ const text = await readBody(req, res);
2304
+ let raw;
2305
+ try {
2306
+ raw = JSON.parse(text || '{}');
2307
+ }
2308
+ catch {
2309
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2310
+ res.end(JSON.stringify({ error: 'invalid JSON' }));
2311
+ return;
2312
+ }
2313
+ // Server assigns the id · agents shouldn't pick collisions.
2314
+ raw.id = typeof raw.id === 'string' && raw.id ? raw.id : newPassId();
2315
+ raw.emittedAt =
2316
+ typeof raw.emittedAt === 'number' && Number.isFinite(raw.emittedAt) ? raw.emittedAt : Date.now();
2317
+ let intent;
2318
+ try {
2319
+ intent = validateWritePassIntent(raw);
2320
+ }
2321
+ catch (err) {
2322
+ if (err instanceof WritePassError) {
2323
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2324
+ res.end(JSON.stringify({ error: err.code, detail: err.message }));
2325
+ return;
2326
+ }
2327
+ throw err;
2328
+ }
2329
+ const status = wpPutPending(intent);
2330
+ // Audit the intent immediately · the chain captures the agent's
2331
+ // request even if the user never decides (i.e. session ends).
2332
+ try {
2333
+ const line = writePassStatusToAuditLine(status);
2334
+ appendAuditLog({
2335
+ timestamp: line.timestamp,
2336
+ sessionId: line.sessionId,
2337
+ toolName: line.toolName,
2338
+ toolInput: line.toolInput,
2339
+ riskScore: line.riskScore,
2340
+ blocked: line.blocked,
2341
+ findings: line.findings,
2342
+ criticalFindings: line.criticalFindings,
2343
+ });
2344
+ }
2345
+ catch (e) {
2346
+ // Audit failure must not block the API (matches claude-sdk-hook discipline).
2347
+ console.error('[w-pass] audit append failed for intent:', e);
2348
+ }
2349
+ res.writeHead(201, { 'Content-Type': 'application/json' });
2350
+ res.end(JSON.stringify(status));
2351
+ }
2352
+ catch (e) {
2353
+ console.error('[/api/writepass/intent] failed:', e);
2354
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2355
+ res.end(JSON.stringify({ error: 'intent failed' }));
2356
+ }
2357
+ })();
2358
+ return;
2359
+ }
2360
+ // GET /api/writepass/pending · list all pending intents (UI poll target).
2361
+ if (req.method === 'GET' && req.url === '/api/writepass/pending') {
2362
+ try {
2363
+ const pending = wpListPending();
2364
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2365
+ res.end(JSON.stringify({ passes: pending }));
2366
+ }
2367
+ catch (e) {
2368
+ console.error('[/api/writepass/pending] failed:', e);
2369
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2370
+ res.end(JSON.stringify({ error: 'list failed' }));
2371
+ }
2372
+ return;
2373
+ }
2374
+ // GET /api/writepass/session/:id · list all passes for a session.
2375
+ if (req.method === 'GET' && req.url && /^\/api\/writepass\/session\/[^/]+$/.test(req.url)) {
2376
+ try {
2377
+ const m = req.url.match(/^\/api\/writepass\/session\/([^/]+)$/);
2378
+ const sessionId = m ? decodeURIComponent(m[1]) : '';
2379
+ const passes = wpListForSession(sessionId);
2380
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2381
+ res.end(JSON.stringify({ sessionId, passes }));
2382
+ }
2383
+ catch (e) {
2384
+ console.error('[/api/writepass/session] failed:', e);
2385
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2386
+ res.end(JSON.stringify({ error: 'list failed' }));
2387
+ }
2388
+ return;
2389
+ }
2390
+ // GET /api/writepass/:id/trust · returns the domain trust grade the
2391
+ // pending pass would resolve to. UI uses this to render the trust chip
2392
+ // BEFORE the user clicks approve.
2393
+ if (req.method === 'GET' && req.url && /^\/api\/writepass\/[^/]+\/trust$/.test(req.url)) {
2394
+ try {
2395
+ const m = req.url.match(/^\/api\/writepass\/([^/]+)\/trust$/);
2396
+ const passId = m ? decodeURIComponent(m[1]) : '';
2397
+ const current = wpGetById(passId);
2398
+ if (!current) {
2399
+ res.writeHead(404, { 'Content-Type': 'application/json' });
2400
+ res.end(JSON.stringify({ error: 'pass not found' }));
2401
+ return;
2402
+ }
2403
+ const payload = current.kind === 'edited' ? current.effectivePayload : current.intent.payload;
2404
+ try {
2405
+ const resolved = resolveWriteRequest(current.intent, payload, loadContextSourcesConfigForWritePass());
2406
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2407
+ res.end(JSON.stringify(resolved.trust));
2408
+ }
2409
+ catch (err) {
2410
+ // Resolver failed (auth missing, unsupported scheme) · return null
2411
+ // trust so the UI knows there's no domain to grade yet.
2412
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2413
+ res.end(JSON.stringify({
2414
+ host: '',
2415
+ grade: 'F',
2416
+ reason: err instanceof Error ? err.message : 'resolve failed',
2417
+ userTrusted: false,
2418
+ requiresFirstWriteConfirmation: false,
2419
+ }));
2420
+ }
2421
+ }
2422
+ catch (e) {
2423
+ console.error('[/api/writepass/.../trust] failed:', e);
2424
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2425
+ res.end(JSON.stringify({ error: 'trust lookup failed' }));
2426
+ }
2427
+ return;
2428
+ }
2429
+ // POST /api/writepass/:id/decide · user approves / edits / cancels.
2430
+ // Body: { kind: 'approve'|'edit'|'cancel', editedPayload?, note? }
2431
+ // On approve/edit · the daemon resolves + sends, audits the outcome.
2432
+ if (req.method === 'POST' && req.url && /^\/api\/writepass\/[^/]+\/decide$/.test(req.url)) {
2433
+ (async () => {
2434
+ try {
2435
+ const m = req.url.match(/^\/api\/writepass\/([^/]+)\/decide$/);
2436
+ const passId = m ? decodeURIComponent(m[1]) : '';
2437
+ const current = wpGetById(passId);
2438
+ if (!current) {
2439
+ res.writeHead(404, { 'Content-Type': 'application/json' });
2440
+ res.end(JSON.stringify({ error: 'pass not found', passId }));
2441
+ return;
2442
+ }
2443
+ if (current.kind !== 'pending') {
2444
+ res.writeHead(409, { 'Content-Type': 'application/json' });
2445
+ res.end(JSON.stringify({ error: 'already decided', current }));
2446
+ return;
2447
+ }
2448
+ const bodyText = await readBody(req, res);
2449
+ let raw;
2450
+ try {
2451
+ raw = JSON.parse(bodyText || '{}');
2452
+ }
2453
+ catch {
2454
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2455
+ res.end(JSON.stringify({ error: 'invalid JSON' }));
2456
+ return;
2457
+ }
2458
+ // Default decidedAt to now if the client didn't set one.
2459
+ raw.passId = passId;
2460
+ raw.decidedAt =
2461
+ typeof raw.decidedAt === 'number' && Number.isFinite(raw.decidedAt) ? raw.decidedAt : Date.now();
2462
+ let decision;
2463
+ try {
2464
+ decision = validateWritePassDecision(raw, current.intent);
2465
+ }
2466
+ catch (err) {
2467
+ if (err instanceof WritePassError) {
2468
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2469
+ res.end(JSON.stringify({ error: err.code, detail: err.message }));
2470
+ return;
2471
+ }
2472
+ throw err;
2473
+ }
2474
+ const next = applyWritePassDecision(current.intent, decision);
2475
+ wpSetStatus(next);
2476
+ // Audit the decision.
2477
+ try {
2478
+ const line = writePassStatusToAuditLine(next);
2479
+ appendAuditLog({
2480
+ timestamp: line.timestamp,
2481
+ sessionId: line.sessionId,
2482
+ toolName: line.toolName,
2483
+ toolInput: line.toolInput,
2484
+ riskScore: line.riskScore,
2485
+ blocked: line.blocked,
2486
+ findings: line.findings,
2487
+ criticalFindings: line.criticalFindings,
2488
+ });
2489
+ }
2490
+ catch (e) {
2491
+ console.error('[w-pass] audit append failed for decision:', e);
2492
+ }
2493
+ // Cancelled · we stop here.
2494
+ if (next.kind === 'cancelled') {
2495
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2496
+ res.end(JSON.stringify(next));
2497
+ return;
2498
+ }
2499
+ // Approved or edited · do the mediated send.
2500
+ if (next.kind !== 'approved' && next.kind !== 'edited') {
2501
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2502
+ res.end(JSON.stringify({ error: 'unexpected status after decision', next }));
2503
+ return;
2504
+ }
2505
+ const effectivePayload = next.kind === 'edited' ? next.effectivePayload : current.intent.payload;
2506
+ // Load auth config from the same context-sources.json the read
2507
+ // adapters use · symmetric storage.
2508
+ const writePassConfig = loadContextSourcesConfigForWritePass();
2509
+ let resolved;
2510
+ try {
2511
+ resolved = resolveWriteRequest(current.intent, effectivePayload, writePassConfig);
2512
+ }
2513
+ catch (err) {
2514
+ if (err instanceof WritePassResolveError) {
2515
+ const failResponse = {
2516
+ passId,
2517
+ status: 0,
2518
+ bodySnippet: '',
2519
+ receivedAt: Date.now(),
2520
+ error: err.message,
2521
+ };
2522
+ const failed = applyWritePassResponse(next, failResponse);
2523
+ wpSetStatus(failed);
2524
+ try {
2525
+ const line = writePassStatusToAuditLine(failed);
2526
+ appendAuditLog({
2527
+ timestamp: line.timestamp,
2528
+ sessionId: line.sessionId,
2529
+ toolName: line.toolName,
2530
+ toolInput: line.toolInput,
2531
+ riskScore: line.riskScore,
2532
+ blocked: line.blocked,
2533
+ findings: line.findings,
2534
+ criticalFindings: line.criticalFindings,
2535
+ });
2536
+ }
2537
+ catch { }
2538
+ res.writeHead(424, { 'Content-Type': 'application/json' });
2539
+ res.end(JSON.stringify({ error: err.code, detail: err.message, status: failed }));
2540
+ return;
2541
+ }
2542
+ throw err;
2543
+ }
2544
+ // v0.9 · per-domain mediated-write trust gate. If the resolved
2545
+ // target's host is graded F (unknown), require the decision to
2546
+ // explicitly include trustThisDomain:true before sending. Once
2547
+ // set, persist the host to trusted-domains.json so subsequent
2548
+ // writes auto-allow at grade B.
2549
+ if (resolved.trust.requiresFirstWriteConfirmation) {
2550
+ const decisionRaw = raw;
2551
+ if (!decisionRaw.trustThisDomain) {
2552
+ res.writeHead(202, { 'Content-Type': 'application/json' });
2553
+ res.end(JSON.stringify({
2554
+ status: 'requires_domain_trust',
2555
+ host: resolved.trust.host,
2556
+ grade: resolved.trust.grade,
2557
+ reason: resolved.trust.reason,
2558
+ hint: 'Re-POST with { "kind": "approve", "trustThisDomain": true } to trust this host once + send.',
2559
+ }));
2560
+ return;
2561
+ }
2562
+ try {
2563
+ trustDomainStore(resolved.trust.host, 'trusted during first W-PASS approval');
2564
+ }
2565
+ catch (e) {
2566
+ console.error('[w-pass] trustDomain store failed:', e);
2567
+ }
2568
+ }
2569
+ // Mediated send.
2570
+ let response;
2571
+ try {
2572
+ const f = await fetch(resolved.url, {
2573
+ method: resolved.method,
2574
+ headers: resolved.headers,
2575
+ body: resolved.body,
2576
+ });
2577
+ const text = await f.text();
2578
+ response = {
2579
+ passId,
2580
+ status: f.status,
2581
+ bodySnippet: text.slice(0, 2048),
2582
+ receivedAt: Date.now(),
2583
+ };
2584
+ }
2585
+ catch (err) {
2586
+ response = {
2587
+ passId,
2588
+ status: 0,
2589
+ bodySnippet: '',
2590
+ receivedAt: Date.now(),
2591
+ error: err instanceof Error ? err.message : String(err),
2592
+ };
2593
+ }
2594
+ const final = applyWritePassResponse(next, response);
2595
+ wpSetStatus(final);
2596
+ try {
2597
+ const line = writePassStatusToAuditLine(final);
2598
+ appendAuditLog({
2599
+ timestamp: line.timestamp,
2600
+ sessionId: line.sessionId,
2601
+ toolName: line.toolName,
2602
+ toolInput: line.toolInput,
2603
+ riskScore: line.riskScore,
2604
+ blocked: line.blocked,
2605
+ findings: line.findings,
2606
+ criticalFindings: line.criticalFindings,
2607
+ });
2608
+ }
2609
+ catch (e) {
2610
+ console.error('[w-pass] audit append failed for response:', e);
2611
+ }
2612
+ res.writeHead(final.kind === 'sent' ? 200 : 502, { 'Content-Type': 'application/json' });
2613
+ res.end(JSON.stringify(final));
2614
+ }
2615
+ catch (e) {
2616
+ console.error('[/api/writepass/decide] failed:', e);
2617
+ res.writeHead(500, { 'Content-Type': 'application/json' });
2618
+ res.end(JSON.stringify({ error: 'decide failed' }));
2619
+ }
2620
+ })();
2621
+ return;
2622
+ }
1385
2623
  // /api/version — small completeness item for ops monitoring (rc.17).
1386
2624
  // ESM-friendly: resolve package.json relative to the compiled module's
1387
2625
  // own URL via fileURLToPath. Works in both src/ (during dev) and dist/
@@ -1518,4 +2756,34 @@ export function startMCPServer(options = {}) {
1518
2756
  });
1519
2757
  return server;
1520
2758
  }
2759
+ /**
2760
+ * v0.8 S2.5 · response page rendered to the user's browser after the OAuth
2761
+ * provider redirects to /oauth/callback. Tiny styled card with status +
2762
+ * "you can close this tab now" affordance. Auto-closes after 3s if window
2763
+ * was opened via window.open() from our UI.
2764
+ */
2765
+ function callbackHtml(status, message, providerLabel) {
2766
+ const safe = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
2767
+ const tone = status === 'ok' ? '#28c840' : '#ff5f57';
2768
+ const icon = status === 'ok' ? '✓' : '✗';
2769
+ const title = status === 'ok' ? `${providerLabel ?? 'Provider'} connected` : 'Connection failed';
2770
+ return `<!doctype html><html lang="en"><head>
2771
+ <meta charset="utf-8"><title>${safe(title)}</title>
2772
+ <style>
2773
+ body { margin:0; background:#0a0a0a; color:#fff; font-family:ui-sans-serif,system-ui,-apple-system,sans-serif; display:flex; align-items:center; justify-content:center; min-height:100vh; }
2774
+ .card { max-width:480px; padding:32px 36px; border:1px solid rgba(255,255,255,0.08); border-radius:12px; background:#111; }
2775
+ .icon { width:48px; height:48px; border-radius:50%; background:${tone}; display:flex; align-items:center; justify-content:center; font-size:28px; font-weight:600; color:#000; margin-bottom:16px; }
2776
+ h1 { font-size:18px; font-weight:600; margin:0 0 8px; }
2777
+ p { color:rgba(255,255,255,0.65); font-size:14px; line-height:1.5; margin:0 0 16px; }
2778
+ .hint { color:rgba(255,255,255,0.4); font-size:12px; font-family:ui-monospace,Menlo,monospace; }
2779
+ </style></head><body>
2780
+ <div class="card">
2781
+ <div class="icon">${icon}</div>
2782
+ <h1>${safe(title)}</h1>
2783
+ <p>${safe(message)}</p>
2784
+ <p class="hint">You can close this tab. Codehere has stored the connection locally.</p>
2785
+ </div>
2786
+ <script>setTimeout(function(){ try{ window.close(); }catch(_){} }, 3000);</script>
2787
+ </body></html>`;
2788
+ }
1521
2789
  //# sourceMappingURL=mcp-server-impl.js.map