@dailephd/my-centcom 0.2.0 → 0.3.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 (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,1595 @@
1
+ import {
2
+ ActivityResponseSchema, WorkflowWatchResponseSchema, describeObservedProcess, type ActivityResponse,
3
+ PairCompleteResponseV1Schema,
4
+ TrustedCliConsentRequestSchema,
5
+ ReviewedPatchRequestV1Schema,
6
+ ReviewedCommitRequestSchema,
7
+ PrepareIntentResponseV1Schema,
8
+ RunStatusResponseV1Schema,
9
+ RunDecisionResponseV1Schema,
10
+ RunCancelAcceptedResponseV1Schema,
11
+ PROMPT_MAX_UTF8_BYTES_STDIN_V1,
12
+ ReturnSnapshotResponseV1Schema,
13
+ ReturnCargoV1Schema,
14
+ ComposerInsertionV1Schema,
15
+ SCHEMA_VERSION_V1,
16
+ NATIVE_HOST_NAME,
17
+ NATIVE_HOST_ERROR_CODES,
18
+ NativeResponseV1Schema,
19
+ CaptureStoreResponseV1Schema,
20
+ CaptureRunResponseV1Schema,
21
+ WorkflowCurrentResponseV1Schema,
22
+ type WorkflowCurrentResponseV1,
23
+ type CaptureFidelity,
24
+ type TabBindingV1,
25
+ CORRELATION_HEADER,
26
+ OPERATION_LABELS,
27
+ describeFailure,
28
+ formatDiagEvent,
29
+ makeDiagEvent,
30
+ newCorrelationId,
31
+ sanitizeFieldIssues,
32
+ validCorrelationId,
33
+ type DiagComponent,
34
+ type DiagEventV1,
35
+ type DiagLevel,
36
+ type DiagOutcome,
37
+ type FailureDetailV1,
38
+ type FieldIssue,
39
+ type FieldReason,
40
+ } from '../../../../packages/contracts/dist/index.js';
41
+ import { insertInPage } from '../content/secureInsert.js';
42
+
43
+ /**
44
+ * Secure control worker (C01, B02-D). The ONLY holder of the daemon bearer and the ONLY component that
45
+ * performs loopback HTTP. The side panel is untrusted presentation: it sends six typed messages and
46
+ * receives only sanitized results. There is no generic HTTP proxy action, no storage and no web-page
47
+ * injection. The worker never chooses an executable, arguments, environment, sandbox or effect class: PREPARE names only a
48
+ * project, plugin and operation ID plus the prompt text, and the daemon decides everything else. The worker launches nothing. The bearer lives in worker memory; if Chrome suspends the worker the
49
+ * user must pair again with a fresh one-time code.
50
+ */
51
+
52
+ const FETCH_TIMEOUT_MS = 10_000;
53
+ const MAX_RESPONSE_BYTES = 65_536;
54
+
55
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
56
+ const SECRET_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
57
+ const BEARER_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
58
+ // eslint-disable-next-line no-control-regex
59
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
60
+
61
+ // Capture allowlist (SW-055). Production: exactly the ChatGPT web origin. A test build may add ONE explicit origin through the build-time
62
+ // define below (apps/extension/scripts/build.mjs --capture-test-origin, secure test builds only); there is no runtime or message-driven way
63
+ // to add an origin, and no wildcard.
64
+ declare const __CAPTURE_ORIGINS__: readonly string[] | undefined;
65
+ const captureOrigins = (): readonly string[] => (typeof __CAPTURE_ORIGINS__ !== 'undefined' && Array.isArray(__CAPTURE_ORIGINS__) ? __CAPTURE_ORIGINS__ : ['https://chatgpt.com']);
66
+ const CAPTURE_TTL_MS = 120_000;
67
+ const CAPTURE_MAX_BYTES = 32_768;
68
+
69
+ export type ErrorCode =
70
+ | 'NO_USER_ACTION' | 'TAB_UNAVAILABLE' | 'TAB_NOT_ACTIVE' | 'TAB_ACCESS_NOT_GRANTED' | 'ORIGIN_NOT_ALLOWED' | 'CAPTURE_NOT_PERMITTED' | 'EMPTY_SELECTION'
71
+ | 'SELECTION_TOO_LARGE' | 'EDITABLE_SELECTION' | 'AMBIGUOUS_SELECTION' | 'HIDDEN_SELECTION' | 'NOT_TOP_FRAME' | 'NO_CAPTURE'
72
+ | 'CAPTURE_EXPIRED' | 'TAB_CHANGED' | 'DOCUMENT_CHANGED' | 'SELECTION_CHANGED' | 'ALREADY_DISPATCHED'
73
+ | 'NO_ORIGIN_BINDING' | 'NO_RETURN' | 'RETURN_EXPIRED' | 'ALREADY_INSERTED' | 'RETURN_NOT_AVAILABLE' | 'RETURN_CONFLICT' | 'RETURN_CHANGED' | 'INSERT_NOT_PERMITTED'
74
+ | 'COMPOSER_UNAVAILABLE' | 'COMPOSER_AMBIGUOUS' | 'COMPOSER_UNSUPPORTED' | 'COMPOSER_NOT_EMPTY' | 'READBACK_MISMATCH' | 'INSERT_FAILED'
75
+ | 'SENDER_DENIED' | 'INVALID_REQUEST' | 'INVALID_FIELD' | 'NOT_PAIRED' | 'BUSY'
76
+ | 'DAEMON_UNREACHABLE' | 'DAEMON_TIMEOUT' | 'UNEXPECTED_RESPONSE' | 'INTERNAL_ERROR'
77
+ | 'VALIDATION_FAILED' | 'UNAUTHENTICATED' | 'ORIGIN_DENIED' | 'PAIRING_DENIED' | 'GRANT_DENIED'
78
+ | 'APPROVAL_DENIED' | 'DENIED' | 'NOT_FOUND' | 'STATE_CONFLICT' | 'PAYLOAD_TOO_LARGE' | 'SERVER_ERROR'
79
+ // SW-062
80
+ | 'NATIVE_HOST_MISSING' | 'NATIVE_HOST_FORBIDDEN' | 'NATIVE_HOST_FAILED' | (typeof NATIVE_HOST_ERROR_CODES)[number]
81
+ | 'CAPTURE_NOT_FOUND' | 'CAPTURE_CONFLICT' | 'RETURN_STALE' | 'OPERATION_NOT_SELECTED';
82
+
83
+ /** Daemon error codes the panel may be told about; anything else is collapsed to a status-derived code. */
84
+ const FORWARDED_CODES: ReadonlySet<string> = new Set([
85
+ 'VALIDATION_FAILED', 'UNAUTHENTICATED', 'ORIGIN_DENIED', 'PAIRING_DENIED', 'GRANT_DENIED',
86
+ 'APPROVAL_DENIED', 'NOT_FOUND', 'STATE_CONFLICT', 'PAYLOAD_TOO_LARGE', 'RETURN_NOT_AVAILABLE', 'RETURN_CONFLICT',
87
+ // SW-062 workflow refusals (fixed codes; never daemon text)
88
+ 'CAPTURE_NOT_FOUND', 'CAPTURE_EXPIRED', 'CAPTURE_CONFLICT', 'RETURN_CHANGED', 'ALREADY_INSERTED',
89
+ ]);
90
+
91
+ export type PanelMessage =
92
+ | { type: 'SET_TASK'; captureId: string; text: string; sha256: string; userActivation: boolean }
93
+ | { type: 'PAIR'; port: number; challengeId: string; code: string }
94
+ | { type: 'PREPARE'; projectId: string; pluginId: string; operationId: string; prompt: string }
95
+ | { type: 'CAPTURE'; tabId: number; userActivation: boolean }
96
+ | { type: 'GET_CAPTURE' }
97
+ | { type: 'DISPATCH'; captureId: string; projectId: string; pluginId: string; operationId: string }
98
+ | { type: 'PREPARE_RETURN'; runId: string }
99
+ | { type: 'GET_RETURN' }
100
+ | { type: 'INSERT_RETURN'; returnId: string; userActivation: boolean }
101
+ | { type: 'GET_STATUS'; runId: string }
102
+ | { type: 'APPROVE'; runId: string; approvalId: string; approvalCode: string }
103
+ | { type: 'CANCEL'; runId: string; reason: string }
104
+ | { type: 'DISCONNECT' }
105
+ | { type: 'GET_DIAGNOSTICS' }
106
+ // SW-062 one-click workflow (the daemon holds the state; these carry ids, a tab id and a user-action flag only, never text)
107
+ | { type: 'GET_WORKFLOW'; sinceVersion: number; waitMs: number }
108
+ | { type: 'RUN'; captureId: string; projectId: string; pluginId: string; operationId: string; userActivation: boolean }
109
+ | { type: 'RUN_TRUSTED_CODING'; captureId: string; projectId: string; pluginId: string; operationId: string; userActivation: boolean }
110
+ | { type: 'TRUSTED_CONSENT'; projectId: string; pluginId: string; operationId: string; action: 'status' | 'accept' | 'revoke'; challenge?: string; warningVersion?: 'trusted-cli-proposal-v1'; userActivation: boolean }
111
+ | { type: 'RUN_CODING'; captureId: string; projectId: string; pluginId: string; operationId: string; userActivation: boolean }
112
+ | { type: 'CODING_STATUS'; runId: string }
113
+ | { type: 'REVIEWED_COMMIT'; runId: string; proposalId: string; message: string; challenge: string; review: boolean; userActivation: boolean }
114
+ | { type: 'CODING_ACTION'; runId: string; proposalId: string; digest: string; action: 'apply' | 'reject' | 'test' | 'git' | 'commit' | 'finalize' | 'proposal'; userActivation: boolean }
115
+ | { type: 'REVIEWED_PATCH'; runId: string; proposalId: string; digest: string; projectId: string; baseHead: string; challenge: string; action: 'apply' | 'cancel'; userActivation: boolean }
116
+ | { type: 'REBIND_RETURN'; returnId: string; tabId: number; userActivation: boolean }
117
+ | { type: 'SET_DEFAULT'; projectId: string; pluginId: string; operationId: string }
118
+ | { type: 'DISMISS'; captureId: string }
119
+ | { type: 'REPAIR' }
120
+ // SW-065 explicit clipboard paths. The worker itself never touches the clipboard: CAPTURE_PASTED carries text the USER pasted into the panel
121
+ // (normalized to LF there), COPY_RETURN only hands the panel the digest-verified immutable result; the panel writes it on the user's click.
122
+ | { type: 'CAPTURE_PASTED'; tabId: number; text: string; lineEndingsNormalized: number; userActivation: boolean }
123
+ | { type: 'COPY_RETURN'; returnId: string; userActivation: boolean };
124
+
125
+ export type Reply =
126
+ | { ok: true; type: 'PAIRED'; port: number; expiresAt: string }
127
+ | { ok: true; type: 'CAPTURED'; view: CaptureView }
128
+ | { ok: true; type: 'NO_CAPTURE_HELD' }
129
+ | { ok: true; type: 'RETURN_PREPARED'; view: ReturnView }
130
+ | { ok: true; type: 'NO_RETURN_HELD' }
131
+ | { ok: true; type: 'INSERTED'; receipt: InsertReceipt }
132
+ | { ok: true; type: 'PREPARED'; runId: string; lifecycleState: string; duplicate: boolean; captureSha256?: string }
133
+ | { ok: true; type: 'CANCEL_ACCEPTED'; runId: string; lifecycleState: string; updatedAt: string }
134
+ | { ok: true; type: 'STATUS'; runId: string; lifecycleState: string; updatedAt: string }
135
+ | { ok: true; type: 'DECISION'; runId: string; lifecycleState: string; updatedAt: string; duplicate: boolean }
136
+ | { ok: true; type: 'DISCONNECTED' }
137
+ | { ok: true; type: 'DIAGNOSTICS'; text: string; count: number }
138
+ | { ok: true; type: 'WORKFLOW'; view: WorkflowView }
139
+ | { ok: true; type: 'CODING'; data: unknown }
140
+ | { ok: true; type: 'RUN_STARTED'; runId: string; lifecycleState: string; consent: string; duplicate: boolean }
141
+ | { ok: true; type: 'REBOUND'; returnId: string }
142
+ | { ok: true; type: 'DEFAULT_SAVED' }
143
+ | { ok: true; type: 'DISMISSED' }
144
+ /** SW-065: the exact immutable result, re-fetched and digest-checked just now. Nothing was inserted or sent; the panel decides nothing about it. */
145
+ | { ok: true; type: 'RETURN_TEXT'; returnId: string; runId: string; text: string; sha256: string; bytes: number }
146
+ | { ok: false; code: ErrorCode; diag?: FailureDetailV1; _x?: FailExtra };
147
+
148
+ const EXPECTED_KEYS: Readonly<Record<PanelMessage['type'], readonly string[]>> = {
149
+ SET_TASK: ['captureId', 'sha256', 'text', 'type', 'userActivation'],
150
+ PAIR: ['challengeId', 'code', 'port', 'type'],
151
+ PREPARE: ['operationId', 'pluginId', 'projectId', 'prompt', 'type'],
152
+ CAPTURE: ['tabId', 'type', 'userActivation'],
153
+ GET_CAPTURE: ['type'],
154
+ DISPATCH: ['captureId', 'operationId', 'pluginId', 'projectId', 'type'],
155
+ PREPARE_RETURN: ['runId', 'type'],
156
+ GET_RETURN: ['type'],
157
+ INSERT_RETURN: ['returnId', 'type', 'userActivation'],
158
+ GET_STATUS: ['runId', 'type'],
159
+ APPROVE: ['approvalCode', 'approvalId', 'runId', 'type'],
160
+ CANCEL: ['reason', 'runId', 'type'],
161
+ DISCONNECT: ['type'],
162
+ GET_DIAGNOSTICS: ['type'],
163
+ GET_WORKFLOW: ['sinceVersion', 'type', 'waitMs'],
164
+ RUN: ['captureId', 'operationId', 'pluginId', 'projectId', 'type', 'userActivation'],
165
+ TRUSTED_CONSENT: ['action', 'challenge', 'operationId', 'pluginId', 'projectId', 'type', 'userActivation', 'warningVersion'],
166
+ RUN_TRUSTED_CODING: ['captureId', 'operationId', 'pluginId', 'projectId', 'type', 'userActivation'],
167
+ RUN_CODING: ['captureId', 'operationId', 'pluginId', 'projectId', 'type', 'userActivation'],
168
+ CODING_STATUS: ['runId', 'type'],
169
+ REVIEWED_COMMIT: ['challenge','message','proposalId','review','runId','type','userActivation'],
170
+ CODING_ACTION: ['action', 'digest', 'proposalId', 'runId', 'type', 'userActivation'],
171
+ REVIEWED_PATCH: ['action', 'baseHead', 'challenge', 'digest', 'projectId', 'proposalId', 'runId', 'type', 'userActivation'],
172
+ REBIND_RETURN: ['returnId', 'tabId', 'type', 'userActivation'],
173
+ SET_DEFAULT: ['operationId', 'pluginId', 'projectId', 'type'],
174
+ DISMISS: ['captureId', 'type'],
175
+ REPAIR: ['type'],
176
+ CAPTURE_PASTED: ['lineEndingsNormalized', 'tabId', 'text', 'type', 'userActivation'],
177
+ COPY_RETURN: ['returnId', 'type', 'userActivation'],
178
+ };
179
+
180
+ /** Internal carrier for what a failure site knows; handleMessage turns it into the public `diag` and removes it. */
181
+ interface FailExtra { fields?: FieldIssue[]; httpStatus?: number; component?: DiagComponent; note?: string }
182
+ const fail = (code: ErrorCode, extra?: FailExtra): Reply => (extra ? { ok: false, code, _x: extra } : { ok: false, code });
183
+
184
+ // ---------------------------------------------------------------------------
185
+ // Diagnostics (SW-062): a bounded in-memory ring of sanitised events. Nothing is persisted (the manifest has no storage permission) and
186
+ // nothing sensitive can enter: every event is built by the shared makeDiagEvent (secrets, codes, prompts, page text and paths are removed).
187
+ // A suspended worker loses the ring; the daemon's rotated log is the durable record, joined by the correlation id.
188
+ // ---------------------------------------------------------------------------
189
+
190
+ const DIAG_RING_MAX = 200;
191
+ const diagRing: DiagEventV1[] = [];
192
+ const workerStartedAt = new Date().toISOString();
193
+ let everPaired = false;
194
+ let sessionEnd: 'EXPIRED' | 'REJECTED_BY_DAEMON' | 'DISCONNECTED' | undefined;
195
+
196
+ function wlog(level: DiagLevel, component: DiagComponent, operation: string, event: string, f: { correlationId?: string; outcome?: DiagOutcome; elapsedMs?: number; meta?: unknown } = {}): void {
197
+ try {
198
+ diagRing.push(makeDiagEvent({ level, component, operation, event, ...f }));
199
+ if (diagRing.length > DIAG_RING_MAX) diagRing.splice(0, diagRing.length - DIAG_RING_MAX);
200
+ } catch { /* diagnostics can never change an outcome */ }
201
+ }
202
+ wlog('INFO', 'WORKER', 'worker.start', 'WORKER_STARTED', { outcome: 'OK' });
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Session state: worker memory only. Never persisted, never sent to the panel.
206
+ // ---------------------------------------------------------------------------
207
+
208
+ interface Session {
209
+ readonly endpoint: string; // pinned canonical http://127.0.0.1:<port>
210
+ readonly port: number;
211
+ readonly bearer: string;
212
+ readonly expiresAtMs: number;
213
+ /** SW-062: MANUAL = the diagnostic pair-code path; NATIVE = silently established through the registered native bootstrap host (re-established on loss). */
214
+ readonly source: 'MANUAL' | 'NATIVE';
215
+ }
216
+
217
+ let session: Session | undefined;
218
+ let busy = false;
219
+
220
+ // ---------------------------------------------------------------------------
221
+ // Validation (before any network access)
222
+ // ---------------------------------------------------------------------------
223
+
224
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
225
+ typeof v === 'object' && v !== null && !Array.isArray(v) && Object.prototype.toString.call(v) === '[object Object]';
226
+
227
+ type ParseOutcome = { m: PanelMessage } | { code: 'INVALID_REQUEST' | 'INVALID_FIELD'; fields: FieldIssue[] };
228
+
229
+ const strIssue = (v: unknown, re: RegExp): FieldReason | undefined =>
230
+ v === undefined ? 'MISSING' : typeof v !== 'string' ? 'WRONG_TYPE' : v.length === 0 ? 'EMPTY' : v.length > 128 ? 'TOO_LONG' : re.test(v) ? undefined : 'BAD_FORMAT';
231
+
232
+ /**
233
+ * Validates the panel message and, when it is unacceptable, says WHICH FIELD and WHY (a fixed reason vocabulary). The offending value itself is
234
+ * never read into the result, so a mistyped pairing code or a prompt cannot leak through an error. INVALID_REQUEST is kept only for input that is not
235
+ * a recognisable message at all.
236
+ */
237
+ function parseMessage(raw: unknown): ParseOutcome {
238
+ if (!isPlainObject(raw)) return { code: 'INVALID_REQUEST', fields: [{ field: '(message)', reason: 'WRONG_TYPE' }] };
239
+ const type = raw.type;
240
+ if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(EXPECTED_KEYS, type)) return { code: 'INVALID_REQUEST', fields: [{ field: 'type', reason: type === undefined ? 'MISSING' : 'NOT_ALLOWED' }] };
241
+ const expected = EXPECTED_KEYS[type as PanelMessage['type']];
242
+ const issues: FieldIssue[] = [];
243
+ const add = (field: string, reason: FieldReason | undefined): void => { if (reason !== undefined) issues.push({ field, reason }); };
244
+ for (const k of expected) if (!(type === 'TRUSTED_CONSENT' && (k === 'challenge' || k === 'warningVersion')) && !Object.prototype.hasOwnProperty.call(raw, k)) add(k, 'MISSING');
245
+ for (const k of Object.keys(raw)) if (!expected.includes(k)) add(k, 'UNEXPECTED_FIELD');
246
+ const bad = (): ParseOutcome => ({ code: 'INVALID_FIELD', fields: sanitizeFieldIssues(issues) });
247
+ if (issues.length > 0) return bad();
248
+
249
+ const idIssue = (v: unknown) => strIssue(v, ID_PATTERN);
250
+ const secretIssue = (v: unknown) => strIssue(v, SECRET_PATTERN);
251
+ const boolIssue = (v: unknown): FieldReason | undefined => (typeof v === 'boolean' ? undefined : 'WRONG_TYPE');
252
+
253
+ switch (type) {
254
+ case 'SET_TASK': {
255
+ add('captureId', strIssue(raw.captureId, /^cap\.[a-f0-9]{32}$/));
256
+ add('sha256', strIssue(raw.sha256, /^[a-f0-9]{64}$/));
257
+ add('userActivation', boolIssue(raw.userActivation));
258
+ if (typeof raw.text !== 'string') add('text', 'WRONG_TYPE');
259
+ else if (!raw.text.trim()) add('text', 'EMPTY');
260
+ else if (new TextEncoder().encode(raw.text).length > CAPTURE_MAX_BYTES) add('text', 'TOO_LONG');
261
+ else if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(raw.text)) add('text', 'BAD_FORMAT');
262
+ return issues.length ? bad() : { m: { type, captureId: raw.captureId as string, sha256: raw.sha256 as string, text: raw.text as string, userActivation: raw.userActivation as boolean } };
263
+ }
264
+ case 'PAIR': {
265
+ const { port, challengeId, code } = raw;
266
+ add('port', typeof port !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(port) || port < 1 || port > 65535 ? 'OUT_OF_RANGE' : undefined);
267
+ add('challengeId', idIssue(challengeId));
268
+ add('code', secretIssue(code));
269
+ return issues.length > 0 ? bad() : { m: { type, port: port as number, challengeId: challengeId as string, code: code as string } };
270
+ }
271
+ case 'PREPARE': {
272
+ const { projectId, pluginId, operationId, prompt } = raw;
273
+ add('projectId', idIssue(projectId)); add('pluginId', idIssue(pluginId)); add('operationId', idIssue(operationId));
274
+ // The prompt is exact user text (line breaks, code fences, any Unicode). Only size, emptiness and well-formedness are checked here;
275
+ // the daemon applies the per-operation byte ceiling (16384 by default, up to 32768 for stdin operations) and the 64 KiB body limit.
276
+ if (typeof prompt !== 'string') add('prompt', 'WRONG_TYPE');
277
+ else if (prompt.trim().length === 0) add('prompt', 'EMPTY');
278
+ else if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(prompt)) add('prompt', 'BAD_FORMAT');
279
+ else if (new TextEncoder().encode(prompt).length > PROMPT_MAX_UTF8_BYTES_STDIN_V1) add('prompt', 'TOO_LONG');
280
+ return issues.length > 0 ? bad() : { m: { type, projectId: projectId as string, pluginId: pluginId as string, operationId: operationId as string, prompt: prompt as string } };
281
+ }
282
+ case 'CAPTURE': {
283
+ const { tabId, userActivation } = raw;
284
+ add('tabId', typeof tabId !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(tabId) || tabId < 0 || tabId > 0x7fffffff ? 'OUT_OF_RANGE' : undefined);
285
+ add('userActivation', boolIssue(userActivation));
286
+ return issues.length > 0 ? bad() : { m: { type, tabId: tabId as number, userActivation: userActivation as boolean } };
287
+ }
288
+ case 'GET_CAPTURE':
289
+ return { m: { type } };
290
+ case 'DISPATCH': {
291
+ const { captureId, projectId, pluginId, operationId } = raw;
292
+ add('captureId', idIssue(captureId)); add('projectId', idIssue(projectId)); add('pluginId', idIssue(pluginId)); add('operationId', idIssue(operationId));
293
+ return issues.length > 0 ? bad() : { m: { type, captureId: captureId as string, projectId: projectId as string, pluginId: pluginId as string, operationId: operationId as string } };
294
+ }
295
+ case 'PREPARE_RETURN': {
296
+ add('runId', idIssue(raw.runId));
297
+ return issues.length > 0 ? bad() : { m: { type, runId: raw.runId as string } };
298
+ }
299
+ case 'GET_RETURN':
300
+ return { m: { type } };
301
+ case 'INSERT_RETURN': {
302
+ const { returnId, userActivation } = raw;
303
+ add('returnId', typeof returnId !== 'string' ? 'WRONG_TYPE' : !/^ret\.[a-f0-9]{32}$/.test(returnId) ? 'BAD_FORMAT' : undefined);
304
+ add('userActivation', boolIssue(userActivation));
305
+ return issues.length > 0 ? bad() : { m: { type, returnId: returnId as string, userActivation: userActivation as boolean } };
306
+ }
307
+ case 'GET_STATUS': {
308
+ add('runId', idIssue(raw.runId));
309
+ return issues.length > 0 ? bad() : { m: { type, runId: raw.runId as string } };
310
+ }
311
+ case 'APPROVE': {
312
+ add('runId', idIssue(raw.runId)); add('approvalId', idIssue(raw.approvalId)); add('approvalCode', secretIssue(raw.approvalCode));
313
+ return issues.length > 0 ? bad() : { m: { type, runId: raw.runId as string, approvalId: raw.approvalId as string, approvalCode: raw.approvalCode as string } };
314
+ }
315
+ case 'CANCEL': {
316
+ const { runId, reason } = raw;
317
+ add('runId', idIssue(runId));
318
+ let trimmed = '';
319
+ if (typeof reason !== 'string') add('reason', 'WRONG_TYPE');
320
+ else {
321
+ trimmed = reason.trim();
322
+ add('reason', trimmed.length < 1 ? 'EMPTY' : trimmed.length > 128 ? 'TOO_LONG' : CONTROL_CHARS.test(trimmed) ? 'BAD_FORMAT' : undefined);
323
+ }
324
+ return issues.length > 0 ? bad() : { m: { type, runId: runId as string, reason: trimmed } };
325
+ }
326
+ case 'DISCONNECT':
327
+ return { m: { type } };
328
+ case 'GET_DIAGNOSTICS':
329
+ return { m: { type } };
330
+ case 'GET_WORKFLOW': {
331
+ const { sinceVersion, waitMs } = raw;
332
+ add('sinceVersion', typeof sinceVersion !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(sinceVersion) || sinceVersion < -1 || sinceVersion > 0x7fffffff ? 'OUT_OF_RANGE' : undefined);
333
+ add('waitMs', typeof waitMs !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(waitMs) || waitMs < 0 || waitMs > 25_000 ? 'OUT_OF_RANGE' : undefined);
334
+ return issues.length > 0 ? bad() : { m: { type, sinceVersion: sinceVersion as number, waitMs: waitMs as number } };
335
+ }
336
+ case 'CODING_STATUS': {
337
+ add('runId', strIssue(raw.runId, /^run\.[a-f0-9]{32}$/));
338
+ return issues.length ? bad() : { m: { type, runId: raw.runId as string } };
339
+ }
340
+ case 'REVIEWED_COMMIT': {
341
+ const p=ReviewedCommitRequestSchema.safeParse({schemaVersion:1,proposalId:raw.proposalId,message:raw.message,challenge:raw.challenge});
342
+ add('runId',strIssue(raw.runId,/^run\.[a-f0-9]{32}$/));add('review',boolIssue(raw.review));add('userActivation',boolIssue(raw.userActivation));
343
+ if(!p.success||issues.length)return bad();return{m:{type,runId:raw.runId as string,proposalId:p.data.proposalId,message:p.data.message,challenge:p.data.challenge,review:raw.review as boolean,userActivation:raw.userActivation as boolean}};
344
+ }
345
+ case 'CODING_ACTION': {
346
+ add('runId', strIssue(raw.runId, /^run\.[a-f0-9]{32}$/));
347
+ add('proposalId', strIssue(raw.proposalId, /^prop\.[A-Za-z0-9_-]{16,64}$/));
348
+ add('digest', strIssue(raw.digest, /^[a-f0-9]{64}$/));
349
+ add('action', strIssue(raw.action, /^(apply|reject|test|git|commit|finalize|proposal)$/));
350
+ add('userActivation', boolIssue(raw.userActivation));
351
+ return issues.length ? bad() : { m: { type, runId: raw.runId as string, proposalId: raw.proposalId as string, digest: raw.digest as string, action: raw.action as 'apply' | 'reject' | 'test' | 'git' | 'commit' | 'finalize' | 'proposal', userActivation: raw.userActivation as boolean } };
352
+ }
353
+ case 'TRUSTED_CONSENT': {
354
+ const { type: ignored, userActivation, ...body } = raw;
355
+ const parsed = TrustedCliConsentRequestSchema.safeParse({ schemaVersion: 1, ...body });
356
+ add('userActivation', boolIssue(userActivation));
357
+ if (!parsed.success || issues.length) return bad();
358
+ const { schemaVersion: ignoredVersion, ...values } = parsed.data;
359
+ return { m: { type, ...values, userActivation: userActivation as boolean } };
360
+ }
361
+ case 'REVIEWED_PATCH': {
362
+ const { type: ignored, runId, userActivation, ...body } = raw;
363
+ const parsed = ReviewedPatchRequestV1Schema.safeParse({ schemaVersion: 1, ...body });
364
+ add('runId', strIssue(runId, /^run\.[a-f0-9]{32}$/)); add('userActivation', boolIssue(userActivation));
365
+ if (!parsed.success || issues.length) return bad();
366
+ const { schemaVersion: ignoredVersion, ...values } = parsed.data;
367
+ return { m: { type, runId: runId as string, userActivation: userActivation as boolean, ...values } };
368
+ }
369
+ case 'RUN_TRUSTED_CODING':
370
+ case 'RUN_CODING':
371
+ case 'RUN': {
372
+ const { captureId, projectId, pluginId, operationId, userActivation } = raw;
373
+ add('captureId', typeof captureId !== 'string' ? 'WRONG_TYPE' : !/^cap\.[a-f0-9]{32}$/.test(captureId) ? 'BAD_FORMAT' : undefined);
374
+ add('projectId', idIssue(projectId)); add('pluginId', idIssue(pluginId)); add('operationId', idIssue(operationId)); add('userActivation', boolIssue(userActivation));
375
+ return issues.length > 0 ? bad() : { m: { type, captureId: captureId as string, projectId: projectId as string, pluginId: pluginId as string, operationId: operationId as string, userActivation: userActivation as boolean } };
376
+ }
377
+ case 'REBIND_RETURN': {
378
+ const { returnId, tabId, userActivation } = raw;
379
+ add('returnId', typeof returnId !== 'string' ? 'WRONG_TYPE' : !/^ret\.[a-f0-9]{32}$/.test(returnId) ? 'BAD_FORMAT' : undefined);
380
+ add('tabId', typeof tabId !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(tabId) || tabId < 0 || tabId > 0x7fffffff ? 'OUT_OF_RANGE' : undefined);
381
+ add('userActivation', boolIssue(userActivation));
382
+ return issues.length > 0 ? bad() : { m: { type, returnId: returnId as string, tabId: tabId as number, userActivation: userActivation as boolean } };
383
+ }
384
+ case 'SET_DEFAULT': {
385
+ const { projectId, pluginId, operationId } = raw;
386
+ add('projectId', idIssue(projectId)); add('pluginId', idIssue(pluginId)); add('operationId', idIssue(operationId));
387
+ return issues.length > 0 ? bad() : { m: { type, projectId: projectId as string, pluginId: pluginId as string, operationId: operationId as string } };
388
+ }
389
+ case 'DISMISS': {
390
+ add('captureId', typeof raw.captureId !== 'string' ? 'WRONG_TYPE' : !/^cap\.[a-f0-9]{32}$/.test(raw.captureId) ? 'BAD_FORMAT' : undefined);
391
+ return issues.length > 0 ? bad() : { m: { type, captureId: raw.captureId as string } };
392
+ }
393
+ case 'REPAIR':
394
+ return { m: { type } };
395
+ case 'CAPTURE_PASTED': {
396
+ const { tabId, text, userActivation, lineEndingsNormalized } = raw;
397
+ add('tabId', typeof tabId !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(tabId) || tabId < 0 || tabId > 0x7fffffff ? 'OUT_OF_RANGE' : undefined);
398
+ // SW-066: the panel's count of CRLF/CR breaks it turned into LF (recorded with the capture; the only text change on this path).
399
+ add('lineEndingsNormalized', typeof lineEndingsNormalized !== 'number' ? 'WRONG_TYPE' : !Number.isInteger(lineEndingsNormalized) || lineEndingsNormalized < 0 || lineEndingsNormalized > CAPTURE_MAX_BYTES ? 'OUT_OF_RANGE' : undefined);
400
+ // Exact user text: only emptiness, well-formedness, the canonical LF line break (the panel normalizes; a CR here is refused, never guessed) and size.
401
+ if (typeof text !== 'string') add('text', 'WRONG_TYPE');
402
+ else if (text.trim().length === 0) add('text', 'EMPTY');
403
+ else if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(text) || text.includes('\r')) add('text', 'BAD_FORMAT');
404
+ else if (new TextEncoder().encode(text).length > CAPTURE_MAX_BYTES) add('text', 'TOO_LONG');
405
+ add('userActivation', boolIssue(userActivation));
406
+ return issues.length > 0 ? bad() : { m: { type, tabId: tabId as number, text: text as string, lineEndingsNormalized: lineEndingsNormalized as number, userActivation: userActivation as boolean } };
407
+ }
408
+ case 'COPY_RETURN': {
409
+ const { returnId, userActivation } = raw;
410
+ add('returnId', typeof returnId !== 'string' ? 'WRONG_TYPE' : !/^ret\.[a-f0-9]{32}$/.test(returnId) ? 'BAD_FORMAT' : undefined);
411
+ add('userActivation', boolIssue(userActivation));
412
+ return issues.length > 0 ? bad() : { m: { type, returnId: returnId as string, userActivation: userActivation as boolean } };
413
+ }
414
+ default:
415
+ return { code: 'INVALID_REQUEST', fields: [{ field: 'type', reason: 'NOT_ALLOWED' }] };
416
+ }
417
+ }
418
+
419
+ /** The extension's own origin, built explicitly (URL.origin of a non-special scheme is not portable). */
420
+ const ownOrigin = (): string => `chrome-extension://${chrome.runtime.id}`;
421
+
422
+ /** Only this extension's own side panel page, in its top frame, may drive the worker. */
423
+ function senderAllowed(sender: chrome.runtime.MessageSender | undefined): boolean {
424
+ if (!sender || sender.id !== chrome.runtime.id) return false;
425
+ const panelUrl = chrome.runtime.getURL('sidepanel/index.html');
426
+ if (sender.url !== panelUrl) return false; // rejects web pages, content scripts, query variants, other extension pages
427
+ if (sender.origin !== ownOrigin()) return false;
428
+ return sender.frameId === undefined || sender.frameId === 0; // rejects iframes
429
+ }
430
+
431
+ // ---------------------------------------------------------------------------
432
+ // HTTP to the pinned loopback daemon
433
+ // ---------------------------------------------------------------------------
434
+
435
+ type HttpResult =
436
+ | { kind: 'response'; status: number; json: unknown }
437
+ | { kind: 'failure'; code: ErrorCode; extra: FailExtra };
438
+
439
+ async function readCapped(res: Response): Promise<string | undefined> {
440
+ if (!res.body) return '';
441
+ const reader = res.body.getReader();
442
+ const chunks: Uint8Array[] = [];
443
+ let total = 0;
444
+ for (;;) {
445
+ const { done, value } = await reader.read();
446
+ if (done) break;
447
+ total += value.byteLength;
448
+ if (total > MAX_RESPONSE_BYTES) {
449
+ await reader.cancel().catch(() => undefined);
450
+ return undefined;
451
+ }
452
+ chunks.push(value);
453
+ }
454
+ const all = new Uint8Array(total);
455
+ let off = 0;
456
+ for (const c of chunks) { all.set(c, off); off += c.byteLength; }
457
+ try {
458
+ return new TextDecoder('utf-8', { fatal: true }).decode(all);
459
+ } catch {
460
+ return undefined;
461
+ }
462
+ }
463
+
464
+ /** `/v1/runs/<id>/status` -> `/v1/runs/:runId/status`: a stable route label for logs, with no run id in it. */
465
+ const routeLabel = (path: string): string => path.replace(/^\/v1\/runs\/(?!prepare(?:\/|$))[^/]+/, '/v1/runs/:runId');
466
+
467
+ async function http(corr: string, endpoint: string, method: 'GET' | 'POST', path: string, bearer: string | undefined, body?: unknown): Promise<HttpResult> {
468
+ const t0 = Date.now();
469
+ const op = `${method} ${routeLabel(path)}`;
470
+ const port = Number(new URL(endpoint).port) || 0;
471
+ const fl = (code: ErrorCode, note?: string): HttpResult => {
472
+ wlog('ERROR', 'TRANSPORT', op, code, { correlationId: corr, outcome: 'FAILED', elapsedMs: Date.now() - t0, meta: { port } });
473
+ return { kind: 'failure', code, extra: { component: 'TRANSPORT', ...(note ? { note } : {}) } };
474
+ };
475
+ const headers: Record<string, string> = { accept: 'application/json', [CORRELATION_HEADER]: corr };
476
+ if (bearer !== undefined) headers.authorization = `Bearer ${bearer}`;
477
+ if (body !== undefined) headers['content-type'] = 'application/json';
478
+ let res: Response;
479
+ try {
480
+ res = await fetch(`${endpoint}${path}`, {
481
+ method,
482
+ headers,
483
+ body: body === undefined ? undefined : JSON.stringify(body),
484
+ redirect: 'error', // a 3xx must never replay the bearer elsewhere
485
+ credentials: 'omit',
486
+ cache: 'no-store',
487
+ signal: path === '/v1/workflow/current' && isPlainObject(body) && body.watchOnly === true ? AbortSignal.timeout(30_000) : AbortSignal.timeout(FETCH_TIMEOUT_MS),
488
+ });
489
+ } catch (e) {
490
+ const name = (e as { name?: string } | null)?.name;
491
+ return name === 'TimeoutError' || name === 'AbortError' ? fl('DAEMON_TIMEOUT', `PORT=${port}`) : fl('DAEMON_UNREACHABLE', `PORT=${port}`);
492
+ }
493
+ if (res.redirected || !res.url.startsWith(`${endpoint}/`)) return fl('UNEXPECTED_RESPONSE', 'REDIRECT_OR_FOREIGN_URL');
494
+ let text: string | undefined;
495
+ try {
496
+ text = await readCapped(res);
497
+ } catch (e) {
498
+ const name = (e as { name?: string } | null)?.name;
499
+ return name === 'TimeoutError' || name === 'AbortError' ? fl('DAEMON_TIMEOUT', `PORT=${port}`) : fl('DAEMON_UNREACHABLE', `PORT=${port}`);
500
+ }
501
+ if (text === undefined || !(res.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) return fl('UNEXPECTED_RESPONSE', `NOT_A_DAEMON_RESPONSE PORT=${port}`);
502
+ let json: unknown;
503
+ try {
504
+ json = JSON.parse(text);
505
+ } catch {
506
+ return fl('UNEXPECTED_RESPONSE', `NOT_A_DAEMON_RESPONSE PORT=${port}`);
507
+ }
508
+ const echoed = validCorrelationId(res.headers.get(CORRELATION_HEADER));
509
+ wlog(res.status >= 500 ? 'ERROR' : res.status >= 400 ? 'WARN' : 'INFO', 'TRANSPORT', op, 'HTTP_RESPONSE', {
510
+ correlationId: corr, outcome: res.status < 400 ? 'OK' : 'FAILED', elapsedMs: Date.now() - t0,
511
+ meta: { status: res.status, port, daemonCorrelation: echoed === undefined ? 'ABSENT' : echoed === corr ? 'MATCH' : 'MISMATCH' },
512
+ });
513
+ return { kind: 'response', status: res.status, json };
514
+ }
515
+
516
+ function statusToCode(status: number): ErrorCode {
517
+ if (status === 400) return 'VALIDATION_FAILED';
518
+ if (status === 401) return 'UNAUTHENTICATED';
519
+ if (status === 403) return 'DENIED';
520
+ if (status === 404) return 'NOT_FOUND';
521
+ if (status === 409) return 'STATE_CONFLICT';
522
+ if (status === 413) return 'PAYLOAD_TOO_LARGE';
523
+ if (status >= 500) return 'SERVER_ERROR';
524
+ return 'UNEXPECTED_RESPONSE';
525
+ }
526
+
527
+ /** Never forwards daemon text: only an allowlisted code, or a code derived from the HTTP status. */
528
+ function errorFrom(r: { status: number; json: unknown }): Reply {
529
+ const err = isPlainObject(r.json) && isPlainObject(r.json.error) ? r.json.error.code : undefined;
530
+ // The daemon's typed code is preserved when allowlisted; its safe field-level detail (names + fixed reasons) rides along. Free text is never forwarded.
531
+ const fields = isPlainObject(r.json) && isPlainObject(r.json.error) ? sanitizeFieldIssues(r.json.error.fields) : [];
532
+ const extra: FailExtra = { httpStatus: r.status, ...(fields.length > 0 ? { fields } : {}) };
533
+ if (typeof err === 'string' && FORWARDED_CODES.has(err)) return fail(err as ErrorCode, extra);
534
+ return fail(statusToCode(r.status), extra);
535
+ }
536
+
537
+ function authedSession(): Session | undefined {
538
+ if (!session) return undefined;
539
+ if (session.expiresAtMs <= Date.now()) {
540
+ session = undefined;
541
+ sessionEnd = 'EXPIRED';
542
+ return undefined;
543
+ }
544
+ return session;
545
+ }
546
+
547
+ /**
548
+ * A rejected bearer ends the session at once (fail closed). An origin refusal fails that one request but
549
+ * keeps the session: it does not show the bearer is bad, and the bearer only ever goes to the pinned endpoint.
550
+ */
551
+ function dropSessionIfRejected(s: Session, reply: Reply): void {
552
+ if (!reply.ok && reply.code === 'UNAUTHENTICATED' && session === s) { session = undefined; sessionEnd = 'REJECTED_BY_DAEMON'; }
553
+ }
554
+
555
+ const runPath = (runId: string): string => `/v1/runs/${encodeURIComponent(runId)}`;
556
+
557
+ // ---------------------------------------------------------------------------
558
+ // SW-062 silent session (re-)establishment through the registered native bootstrap host. No code, challenge or port is ever typed: the host (pinned to THIS
559
+ // extension id by Chrome's allowed_origins and by its own pinned config) returns a short-lived bearer for the installation's stable principal. The bearer
560
+ // lives in worker memory only (no extension storage area is used); a stopped worker simply asks again. The manual PAIR path remains for diagnosis.
561
+ // ---------------------------------------------------------------------------
562
+
563
+ const NATIVE_TIMEOUT_MS = 45_000;
564
+ let nativeInFlight: Promise<Session | Reply> | undefined;
565
+ let lastConnectFailure: Reply | undefined;
566
+
567
+ const nativeApiAvailable = (): boolean => typeof (chrome.runtime as unknown as { sendNativeMessage?: unknown }).sendNativeMessage === 'function';
568
+
569
+ function sendNative(message: unknown): Promise<{ response?: unknown; error?: string }> {
570
+ return new Promise((resolve) => {
571
+ const t = setTimeout(() => resolve({ error: 'TIMEOUT' }), NATIVE_TIMEOUT_MS);
572
+ try {
573
+ chrome.runtime.sendNativeMessage(NATIVE_HOST_NAME, message as object, (response: unknown) => {
574
+ clearTimeout(t);
575
+ const le = chrome.runtime.lastError;
576
+ resolve(le ? { error: String(le.message ?? 'native error') } : { response });
577
+ });
578
+ } catch {
579
+ clearTimeout(t);
580
+ resolve({ error: 'THROWN' });
581
+ }
582
+ });
583
+ }
584
+
585
+ async function nativeConnect(corr: string): Promise<Session | Reply> {
586
+ const t0 = Date.now();
587
+ const r = await sendNative({ v: 1, type: 'CONNECT' });
588
+ const failed = (code: ErrorCode, note: string): Reply => {
589
+ wlog('WARN', 'BRIDGE', 'CONNECT', code, { correlationId: corr, outcome: 'FAILED', elapsedMs: Date.now() - t0, meta: { note } });
590
+ return fail(code, { component: 'BRIDGE', note });
591
+ };
592
+ if (r.error !== undefined) {
593
+ // Chrome's fixed wording: "Specified native messaging host not found." / "Access to the specified native messaging host is forbidden."
594
+ if (/not found/i.test(r.error)) return failed('NATIVE_HOST_MISSING', 'HOST_NOT_REGISTERED');
595
+ if (/forbidden/i.test(r.error)) return failed('NATIVE_HOST_FORBIDDEN', 'EXTENSION_ID_NOT_ALLOWED');
596
+ return failed('NATIVE_HOST_FAILED', r.error === 'TIMEOUT' ? 'HOST_TIMEOUT' : 'HOST_EXITED');
597
+ }
598
+ const p = NativeResponseV1Schema.safeParse(r.response);
599
+ if (!p.success) return failed('NATIVE_HOST_FAILED', 'HOST_REPLY_INVALID');
600
+ if (!p.data.ok) return failed(p.data.code, 'HOST_REFUSED');
601
+ if (p.data.type !== 'CONNECTED') return failed('NATIVE_HOST_FAILED', 'HOST_REPLY_INVALID');
602
+ const expiresAtMs = Date.parse(p.data.expiresAt);
603
+ if (!(expiresAtMs > Date.now())) return failed('NATIVE_HOST_FAILED', 'SESSION_ALREADY_EXPIRED');
604
+ const s: Session = { endpoint: `http://127.0.0.1:${p.data.port}`, port: p.data.port, bearer: p.data.bearerToken, expiresAtMs, source: 'NATIVE' };
605
+ wlog('INFO', 'BRIDGE', 'CONNECT', 'SESSION_ESTABLISHED', { correlationId: corr, outcome: 'OK', elapsedMs: Date.now() - t0, meta: { port: s.port, daemonStarted: p.data.daemonStarted } });
606
+ return s;
607
+ }
608
+
609
+ /**
610
+ * The session to use: the current one, or (when the native API exists and the user did not choose manual pairing) a fresh one from the native host.
611
+ * Concurrent callers share one in-flight attempt. Without the native API the B02 behaviour is unchanged (NOT_PAIRED).
612
+ */
613
+ async function sessionFor(corr: string): Promise<Session | Reply> {
614
+ const s = authedSession();
615
+ if (s) return s;
616
+ if (!nativeApiAvailable()) return fail('NOT_PAIRED');
617
+ nativeInFlight ??= nativeConnect(corr).finally(() => { nativeInFlight = undefined; });
618
+ const out = await nativeInFlight;
619
+ if ('ok' in out) { lastConnectFailure = out; return out; }
620
+ lastConnectFailure = undefined;
621
+ session = out; everPaired = true; sessionEnd = undefined;
622
+ return out;
623
+ }
624
+
625
+ /** An authenticated workflow call; a rejected NATIVE bearer is dropped and re-established once (every workflow route is idempotent). */
626
+ async function wcall(corr: string, path: string, body: unknown): Promise<{ status: number; json: unknown } | Reply> {
627
+ for (let attempt = 0; attempt < 2; attempt += 1) {
628
+ const s = await sessionFor(corr);
629
+ if ('ok' in s) return s;
630
+ const r = await http(corr, s.endpoint, 'POST', path, s.bearer, body);
631
+ if (r.kind === 'failure') {
632
+ if (s.source === 'NATIVE' && r.code === 'DAEMON_UNREACHABLE' && attempt === 0 && session === s) { session = undefined; continue; } // daemon restarted on a new port
633
+ return fail(r.code, r.extra);
634
+ }
635
+ if (r.status === 401 && s.source === 'NATIVE' && attempt === 0) { if (session === s) session = undefined; continue; }
636
+ return { status: r.status, json: r.json };
637
+ }
638
+ return fail('UNAUTHENTICATED');
639
+ }
640
+
641
+ async function pair(m: Extract<PanelMessage, { type: 'PAIR' }>, corr: string): Promise<Reply> {
642
+ session = undefined; // pairing always starts from nothing: no bearer can follow the user to a new endpoint
643
+ const endpoint = `http://127.0.0.1:${m.port}`;
644
+ const r = await http(corr, endpoint, 'POST', '/v1/pairing/complete', undefined, {
645
+ schemaVersion: SCHEMA_VERSION_V1,
646
+ challengeId: m.challengeId,
647
+ code: m.code,
648
+ });
649
+ if (r.kind === 'failure') return fail(r.code, r.extra);
650
+ if (r.status !== 200) return errorFrom(r);
651
+ const parsed = PairCompleteResponseV1Schema.safeParse(r.json);
652
+ if (!parsed.success) return fail('UNEXPECTED_RESPONSE');
653
+ const expiresAtMs = Date.parse(parsed.data.expiresAt);
654
+ if (parsed.data.pairedOrigin !== ownOrigin() || !BEARER_PATTERN.test(parsed.data.bearerToken) || !(expiresAtMs > Date.now())) {
655
+ return fail('UNEXPECTED_RESPONSE');
656
+ }
657
+ session = { endpoint, port: m.port, bearer: parsed.data.bearerToken, expiresAtMs, source: 'MANUAL' };
658
+ everPaired = true;
659
+ sessionEnd = undefined;
660
+ return { ok: true, type: 'PAIRED', port: m.port, expiresAt: parsed.data.expiresAt };
661
+ }
662
+
663
+ async function prepare(m: Extract<PanelMessage, { type: 'PREPARE' }>, corr: string): Promise<Reply> {
664
+ return sendPrepare(m.projectId, m.pluginId, m.operationId, m.prompt, corr);
665
+ }
666
+
667
+ async function sendPrepare(projectId: string, pluginId: string, operationId: string, prompt: string, corr: string): Promise<Reply> {
668
+ const s = authedSession();
669
+ if (!s) return fail('NOT_PAIRED');
670
+ const requestId = `req.${crypto.randomUUID()}`;
671
+ const r = await http(corr, s.endpoint, 'POST', '/v1/runs/prepare', s.bearer, {
672
+ schemaVersion: SCHEMA_VERSION_V1,
673
+ requestId,
674
+ projectId,
675
+ pluginId,
676
+ operationId,
677
+ idempotencyKey: `idem.${crypto.randomUUID()}`,
678
+ params: { prompt },
679
+ requestedAt: new Date().toISOString(),
680
+ requiresUserApproval: true,
681
+ });
682
+ if (r.kind === 'failure') return fail(r.code, r.extra);
683
+ if (r.status !== 200 && r.status !== 202) { const e = errorFrom(r); dropSessionIfRejected(s, e); return e; }
684
+ const parsed = PrepareIntentResponseV1Schema.safeParse(r.json);
685
+ if (!parsed.success || parsed.data.requestId !== requestId) return fail('UNEXPECTED_RESPONSE');
686
+ return { ok: true, type: 'PREPARED', runId: parsed.data.runId, lifecycleState: parsed.data.lifecycleState, duplicate: parsed.data.duplicate };
687
+ }
688
+
689
+ // ---------------------------------------------------------------------------
690
+ // Selected-text departure (SW-055): CAPTURE -> PREVIEW (GET_CAPTURE) -> DISPATCH, each a separate explicit message.
691
+ // The snapshot lives ONLY in worker memory (a suspended worker loses it: fail closed). The panel can never supply or alter the text.
692
+ // ---------------------------------------------------------------------------
693
+
694
+ export interface CaptureView {
695
+ readonly captureId: string;
696
+ readonly text: string;
697
+ readonly sha256: string;
698
+ readonly bytes: number;
699
+ readonly source: string;
700
+ readonly capturedAt: string;
701
+ readonly expiresAt: string;
702
+ readonly state: 'CAPTURED' | 'DISPATCHED';
703
+ /**
704
+ * What the bytes ARE. CAPTURED_RENDERED_TEXT: the rendered text of the user's DOM selection (NOT the original Markdown source).
705
+ * PASTED_PLAIN_TEXT (SW-065): the text/plain flavor the user pasted into the panel, LF line breaks; Markdown when copied with ChatGPT's Copy button (unverified).
706
+ */
707
+ readonly fidelity: CaptureFidelity;
708
+ /** SW-066: CRLF/CR line breaks turned into LF before this text was held (pasted path only; 0 for a rendered selection, which is never rewritten). */
709
+ readonly lineEndingsNormalized: number;
710
+ /** Nothing proves the selected node is an assistant message; the user's explicit action is the only attestation. */
711
+ readonly attestation: 'USER_ATTESTED_ONLY';
712
+ readonly warnings: readonly string[];
713
+ }
714
+
715
+ interface Snapshot extends CaptureView {
716
+ readonly tabId: number;
717
+ readonly windowId: number;
718
+ readonly documentId: string;
719
+ readonly nonce: string;
720
+ readonly expiresAtMs: number;
721
+ consumed: boolean;
722
+ /** SW-062: the daemon's id for this capture once it is stored there (encrypted). */
723
+ remoteId?: string;
724
+ }
725
+
726
+ let held: Snapshot | undefined;
727
+
728
+ interface PageResult {
729
+ ok: boolean;
730
+ code?: string;
731
+ text?: string;
732
+ href?: string;
733
+ origin?: string;
734
+ nonce?: string;
735
+ isTop?: boolean;
736
+ }
737
+
738
+ /**
739
+ * Runs INSIDE the target page's isolated world (serialised by Chrome; it must be self-contained). Returns the exact selection string and
740
+ * the document identity (a per-document random nonce kept in the isolated world: a new document, including after navigation, has a new one).
741
+ * It refuses empty, ambiguous, editable, hidden and non-top-frame selections. It never modifies the page or the selection.
742
+ */
743
+ function captureInPage(): PageResult {
744
+ const w = window as unknown as Record<string, unknown>;
745
+ if (typeof w.__centcomDocNonce !== 'string') w.__centcomDocNonce = crypto.randomUUID();
746
+ const base = { href: location.href, origin: location.origin, nonce: w.__centcomDocNonce as string, isTop: window === window.top };
747
+ if (!base.isTop) return { ok: false, code: 'NOT_TOP_FRAME', ...base };
748
+ const sel = window.getSelection();
749
+ if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return { ok: false, code: 'EMPTY_SELECTION', ...base };
750
+ if (sel.rangeCount !== 1) return { ok: false, code: 'AMBIGUOUS_SELECTION', ...base };
751
+ const text = sel.toString();
752
+ if (text.trim().length === 0) return { ok: false, code: 'EMPTY_SELECTION', ...base };
753
+ const range = sel.getRangeAt(0);
754
+ for (const n of [sel.anchorNode, sel.focusNode, range.commonAncestorContainer]) {
755
+ const el = n === null ? null : n.nodeType === 1 ? (n as Element) : n.parentElement;
756
+ if (el === null) return { ok: false, code: 'AMBIGUOUS_SELECTION', ...base };
757
+ if (el.closest('input,textarea,select,[contenteditable=""],[contenteditable="true"],[contenteditable="plaintext-only"]') !== null || (el as HTMLElement).isContentEditable) {
758
+ return { ok: false, code: 'EDITABLE_SELECTION', ...base };
759
+ }
760
+ }
761
+ const host = range.commonAncestorContainer.nodeType === 1 ? (range.commonAncestorContainer as Element) : range.commonAncestorContainer.parentElement;
762
+ if (host === null || host.getClientRects().length === 0 || getComputedStyle(host).visibility === 'hidden') return { ok: false, code: 'HIDDEN_SELECTION', ...base };
763
+ return { ok: true, text, ...base };
764
+ }
765
+
766
+ const toHex = (buf: ArrayBuffer): string => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
767
+
768
+ function viewOf(s: Snapshot): CaptureView {
769
+ return { captureId: s.captureId, text: s.text, sha256: s.sha256, bytes: s.bytes, source: s.source, capturedAt: s.capturedAt, expiresAt: s.expiresAt, state: s.consumed ? 'DISPATCHED' : 'CAPTURED', fidelity: s.fidelity, lineEndingsNormalized: s.lineEndingsNormalized, attestation: s.attestation, warnings: s.warnings };
770
+ }
771
+
772
+ const originOfUrl = (u: unknown): string | undefined => {
773
+ if (typeof u !== 'string') return undefined;
774
+ try { const p = new URL(u); return p.username === '' && p.password === '' && p.hash === '' ? p.origin : undefined; } catch { return undefined; }
775
+ };
776
+
777
+ /** The target must be an allowlisted top-level tab that is the active tab right now. Returns the tab or a refusal. */
778
+ async function targetTab(tabId: number): Promise<{ tab: chrome.tabs.Tab; origin: string } | Reply> {
779
+ let tab: chrome.tabs.Tab;
780
+ try { tab = await chrome.tabs.get(tabId); } catch { return fail('TAB_UNAVAILABLE'); }
781
+ // Without a per-tab activeTab grant (or a host permission) Chrome withholds tab.url entirely. That is "access not granted", not a foreign
782
+ // origin: still fail closed (nothing is injected) but say so, so the operator re-invokes the extension on this tab instead of chasing the allowlist.
783
+ if (tab.url === undefined) return fail('TAB_ACCESS_NOT_GRANTED');
784
+ const origin = originOfUrl(tab.url);
785
+ if (origin === undefined || !captureOrigins().includes(origin)) return fail('ORIGIN_NOT_ALLOWED');
786
+ if (tab.active !== true) return fail('TAB_NOT_ACTIVE');
787
+ return { tab, origin };
788
+ }
789
+
790
+ async function inject(tabId: number): Promise<{ result: PageResult; documentId: string; frameId: number } | Reply> {
791
+ let out: Array<{ result?: unknown; documentId?: string; frameId?: number }>;
792
+ try {
793
+ out = await chrome.scripting.executeScript({ target: { tabId, allFrames: false }, func: captureInPage, world: 'ISOLATED' }) as typeof out;
794
+ } catch { return fail('CAPTURE_NOT_PERMITTED'); } // no activeTab/host grant for this tab: fail closed
795
+ if (!Array.isArray(out) || out.length !== 1 || out[0].frameId !== 0 || typeof out[0].documentId !== 'string' || !isPlainObject(out[0].result)) return fail('CAPTURE_NOT_PERMITTED');
796
+ return { result: out[0].result as unknown as PageResult, documentId: out[0].documentId, frameId: 0 };
797
+ }
798
+
799
+ const PAGE_CODES: ReadonlySet<string> = new Set(['EMPTY_SELECTION', 'AMBIGUOUS_SELECTION', 'EDITABLE_SELECTION', 'HIDDEN_SELECTION', 'NOT_TOP_FRAME']);
800
+
801
+ async function capture(m: Extract<PanelMessage, { type: 'CAPTURE' }>): Promise<Reply> {
802
+ if (m.userActivation !== true) return fail('NO_USER_ACTION');
803
+ held = undefined; // a new capture attempt always discards the previous snapshot
804
+ const t = await targetTab(m.tabId);
805
+ if ('ok' in t) return t;
806
+ const injected = await inject(m.tabId);
807
+ if ('ok' in injected) return injected;
808
+ const r = injected.result;
809
+ if (r.ok !== true) return fail(typeof r.code === 'string' && PAGE_CODES.has(r.code) ? (r.code as ErrorCode) : 'CAPTURE_NOT_PERMITTED');
810
+ if (typeof r.text !== 'string' || typeof r.href !== 'string' || typeof r.nonce !== 'string' || r.isTop !== true || originOfUrl(r.href) !== t.origin || r.href !== t.tab.url) return fail('DOCUMENT_CHANGED');
811
+ const bytes = new TextEncoder().encode(r.text);
812
+ if (bytes.length > CAPTURE_MAX_BYTES) return fail('SELECTION_TOO_LARGE');
813
+ const now = Date.now();
814
+ const snap: Snapshot = {
815
+ captureId: `cap.${crypto.randomUUID()}`, text: r.text, sha256: toHex(await crypto.subtle.digest('SHA-256', bytes)), bytes: bytes.length,
816
+ source: r.href, capturedAt: new Date(now).toISOString(), expiresAt: new Date(now + CAPTURE_TTL_MS).toISOString(), state: 'CAPTURED',
817
+ fidelity: 'CAPTURED_RENDERED_TEXT', lineEndingsNormalized: 0, attestation: 'USER_ATTESTED_ONLY',
818
+ warnings: ['RENDERED_TEXT_NOT_SOURCE_MARKDOWN: code fences or formatting in the original message may not be present in the captured text', 'USER_ATTESTED_ONLY: the page is not verified to be an assistant message'],
819
+ tabId: m.tabId, windowId: t.tab.windowId, documentId: injected.documentId, nonce: r.nonce, expiresAtMs: now + CAPTURE_TTL_MS, consumed: false,
820
+ };
821
+ held = snap;
822
+ return { ok: true, type: 'CAPTURED', view: viewOf(snap) };
823
+ }
824
+
825
+ /**
826
+ * SW-065: text the USER pasted into the side panel (their Ctrl+V; the extension never reads the clipboard itself) becomes a capture bound to the same
827
+ * granted tab/document as a selection capture would be: the toolbar click on that conversation is still what grants access, and the result can later be
828
+ * inserted ONLY there. The page is read for its identity (document id + per-document nonce) only; its selection and text are ignored.
829
+ */
830
+ async function capturePasted(m: Extract<PanelMessage, { type: 'CAPTURE_PASTED' }>): Promise<Reply> {
831
+ if (m.userActivation !== true) return fail('NO_USER_ACTION');
832
+ const t = await targetTab(m.tabId);
833
+ if ('ok' in t) return t;
834
+ const injected = await inject(m.tabId);
835
+ if ('ok' in injected) return injected;
836
+ const r = injected.result;
837
+ if (typeof r.href !== 'string' || typeof r.nonce !== 'string' || r.isTop !== true || r.href !== t.tab.url) return fail('DOCUMENT_CHANGED');
838
+ const bytes = new TextEncoder().encode(m.text);
839
+ const now = Date.now();
840
+ held = {
841
+ captureId: `cap.${crypto.randomUUID()}`, text: m.text, sha256: toHex(await crypto.subtle.digest('SHA-256', bytes)), bytes: bytes.length,
842
+ source: r.href, capturedAt: new Date(now).toISOString(), expiresAt: new Date(now + CAPTURE_TTL_MS).toISOString(), state: 'CAPTURED',
843
+ fidelity: 'PASTED_PLAIN_TEXT', lineEndingsNormalized: m.lineEndingsNormalized, attestation: 'USER_ATTESTED_ONLY',
844
+ warnings: ['PASTED_PLAIN_TEXT: the text/plain content you pasted (line breaks normalized to LF); Markdown if it was copied with the message\'s own Copy button, not verified', 'USER_ATTESTED_ONLY: the text is not verified to come from an assistant message'],
845
+ tabId: m.tabId, windowId: t.tab.windowId, documentId: injected.documentId, nonce: r.nonce, expiresAtMs: now + CAPTURE_TTL_MS, consumed: false,
846
+ };
847
+ wlog('INFO', 'SNAPSHOT', 'CAPTURE_PASTED', 'PASTED_TEXT_HELD', { outcome: 'OK', meta: { bytes: bytes.length } });
848
+ return { ok: true, type: 'CAPTURED', view: viewOf(held) };
849
+ }
850
+
851
+ function getCapture(): Reply {
852
+ if (held && held.expiresAtMs <= Date.now()) held = undefined;
853
+ return held ? { ok: true, type: 'CAPTURED', view: viewOf(held) } : { ok: true, type: 'NO_CAPTURE_HELD' };
854
+ }
855
+
856
+ async function dispatchCapture(m: Extract<PanelMessage, { type: 'DISPATCH' }>, corr: string): Promise<Reply> {
857
+ const snap = held;
858
+ if (!snap || snap.captureId !== m.captureId) return fail('NO_CAPTURE');
859
+ if (snap.consumed) return fail('ALREADY_DISPATCHED');
860
+ if (snap.expiresAtMs <= Date.now()) { held = undefined; return fail('CAPTURE_EXPIRED'); }
861
+ if (!authedSession()) return fail('NOT_PAIRED');
862
+ // Revalidate against the SAME tab, window, document, URL and exact selection. Anything changed or unverifiable needs a fresh capture.
863
+ const t = await targetTab(snap.tabId);
864
+ if ('ok' in t) return !t.ok && t.code === 'TAB_NOT_ACTIVE' ? fail('TAB_CHANGED') : t;
865
+ if (t.tab.windowId !== snap.windowId || t.tab.url !== snap.source) return fail('TAB_CHANGED');
866
+ const now = await inject(snap.tabId);
867
+ if ('ok' in now) return now;
868
+ if (now.documentId !== snap.documentId || now.result.nonce !== snap.nonce || now.result.href !== snap.source) return fail('DOCUMENT_CHANGED');
869
+ if (now.result.ok !== true || now.result.text !== snap.text) return fail('SELECTION_CHANGED');
870
+ if (snap.consumed) return fail('ALREADY_DISPATCHED'); // re-checked after the awaits above
871
+ snap.consumed = true; // spent BEFORE the network call: a lost reply can never become a second durable intent
872
+ const reply = await sendPrepare(m.projectId, m.pluginId, m.operationId, snap.text, corr);
873
+ if (reply.ok && reply.type === 'PREPARED') {
874
+ // B05: remember WHICH tab/document this run departed from, in worker memory only, so a later return can be inserted nowhere else.
875
+ rememberOrigin(reply.runId, { tabId: snap.tabId, windowId: snap.windowId, documentId: snap.documentId, nonce: snap.nonce, source: snap.source, atMs: Date.now() });
876
+ return { ...reply, captureSha256: snap.sha256 };
877
+ }
878
+ return reply;
879
+ }
880
+
881
+ // ---------------------------------------------------------------------------
882
+ // Immutable final-text return (SW-058, B05): PREPARE_RETURN -> preview (GET_RETURN) -> INSERT_RETURN, each a separate explicit message.
883
+ // The text comes ONLY from the daemon's snapshot of the run, never from the panel or the page. It is inserted ONLY into the composer of the
884
+ // tab/document the run departed from, as a DRAFT; this worker never submits, never presses Enter and never clicks anything on the page.
885
+ // ---------------------------------------------------------------------------
886
+
887
+ interface OriginBinding {
888
+ readonly tabId: number;
889
+ readonly windowId: number;
890
+ readonly documentId: string;
891
+ readonly nonce: string;
892
+ readonly source: string;
893
+ readonly atMs: number;
894
+ }
895
+ const ORIGIN_TTL_MS = 30 * 60_000;
896
+ const MAX_ORIGINS = 8;
897
+ const origins = new Map<string, OriginBinding>();
898
+ function rememberOrigin(runId: string, b: OriginBinding): void {
899
+ origins.set(runId, b);
900
+ while (origins.size > MAX_ORIGINS) origins.delete(origins.keys().next().value as string);
901
+ }
902
+
903
+ export interface ReturnView {
904
+ readonly returnId: string;
905
+ readonly runId: string;
906
+ readonly text: string;
907
+ readonly sha256: string;
908
+ readonly bytes: number;
909
+ readonly source: string;
910
+ readonly state: 'PREPARED' | 'INSERTED';
911
+ readonly provenance: 'RUN_FINAL_MESSAGE_AGENT_REPORTED';
912
+ readonly warnings: readonly string[];
913
+ }
914
+ export interface InsertReceipt {
915
+ readonly returnId: string;
916
+ readonly runId: string;
917
+ readonly sha256: string;
918
+ readonly bytes: number;
919
+ readonly insertionMode: 'DOM_TEXTAREA';
920
+ /** Which editor class took the draft (all are DOM writes of literal text, read back after the editor settled; PROSEMIRROR is the validated chatgpt.com composer shape). */
921
+ readonly editor: 'TEXTAREA' | 'CONTENTEDITABLE' | 'PROSEMIRROR';
922
+ readonly readback: 'MATCH';
923
+ /** The extension never submits. USER_SUBMITTED is something only the user can do and this worker never observes. */
924
+ readonly submission: 'NOT_SUBMITTED_BY_EXTENSION';
925
+ }
926
+ interface HeldReturn extends ReturnView {
927
+ readonly binding: OriginBinding;
928
+ state: 'PREPARED' | 'INSERTED';
929
+ }
930
+ let heldReturn: HeldReturn | undefined;
931
+
932
+ const toReturnView = (h: HeldReturn): ReturnView => ({ returnId: h.returnId, runId: h.runId, text: h.text, sha256: h.sha256, bytes: h.bytes, source: h.source, state: h.state, provenance: h.provenance, warnings: h.warnings });
933
+
934
+ /** Asks the daemon for the (idempotent) immutable snapshot and verifies it locally: same run, same digest, same byte length. */
935
+ async function fetchReturn(s: Session, runId: string, corr: string): Promise<{ snap: ReturnView } | Reply> {
936
+ const r = await http(corr, s.endpoint, 'POST', `${runPath(runId)}/return`, s.bearer, { schemaVersion: SCHEMA_VERSION_V1 });
937
+ if (r.kind === 'failure') return fail(r.code, r.extra);
938
+ if (r.status !== 200 && r.status !== 201) { const e = errorFrom(r); dropSessionIfRejected(s, e); return e; }
939
+ const parsed = ReturnSnapshotResponseV1Schema.safeParse(r.json);
940
+ if (!parsed.success || parsed.data.runId !== runId) return fail('UNEXPECTED_RESPONSE');
941
+ const bytes = new TextEncoder().encode(parsed.data.text);
942
+ if (bytes.length !== parsed.data.bytes || toHex(await crypto.subtle.digest('SHA-256', bytes)) !== parsed.data.sha256) return fail('UNEXPECTED_RESPONSE'); // digest-checked before it is held or shown
943
+ return { snap: { returnId: parsed.data.returnId, runId, text: parsed.data.text, sha256: parsed.data.sha256, bytes: parsed.data.bytes, source: '', state: 'PREPARED', provenance: parsed.data.provenance, warnings: [] } };
944
+ }
945
+
946
+ async function prepareReturn(m: Extract<PanelMessage, { type: 'PREPARE_RETURN' }>, corr: string): Promise<Reply> {
947
+ heldReturn = undefined; // a new preparation always discards the previous one
948
+ const s = authedSession();
949
+ if (!s) return fail('NOT_PAIRED');
950
+ const binding = origins.get(m.runId);
951
+ if (!binding || binding.atMs + ORIGIN_TTL_MS <= Date.now()) { origins.delete(m.runId); return fail('NO_ORIGIN_BINDING'); } // only runs dispatched from a captured tab, and only while this worker remembers it
952
+ const f = await fetchReturn(s, m.runId, corr);
953
+ if ('ok' in f) return f;
954
+ heldReturn = {
955
+ ...f.snap, source: binding.source, state: 'PREPARED', binding,
956
+ warnings: ['AGENT_REPORTED_TEXT: the final message is what the agent said it produced; it is not verified output and not original Markdown source'],
957
+ };
958
+ return { ok: true, type: 'RETURN_PREPARED', view: toReturnView(heldReturn) };
959
+ }
960
+
961
+ function getReturn(): Reply {
962
+ return heldReturn ? { ok: true, type: 'RETURN_PREPARED', view: toReturnView(heldReturn) } : { ok: true, type: 'NO_RETURN_HELD' };
963
+ }
964
+
965
+ const INSERT_CODES: ReadonlySet<string> = new Set(['NOT_TOP_FRAME', 'DOCUMENT_CHANGED', 'COMPOSER_UNAVAILABLE', 'COMPOSER_AMBIGUOUS', 'COMPOSER_UNSUPPORTED', 'COMPOSER_NOT_EMPTY', 'READBACK_MISMATCH']);
966
+
967
+ interface InsertTarget { readonly text: string; readonly binding: { readonly tabId: number; readonly nonce: string; readonly documentId: string } }
968
+
969
+ /**
970
+ * The ONE page injection that writes a draft (shared by the legacy held-return path and the SW-062 durable path). Validated textarea or the narrowly
971
+ * defined ProseMirror composer only (secureInsert.ts); plain text; composer-only focus, no keys, clipboard or submit; stable exact readback in the bound document.
972
+ */
973
+ async function injectInsert(h: InsertTarget): Promise<{ inserted: 'TEXTAREA' | 'CONTENTEDITABLE' | 'PROSEMIRROR' } | Reply> {
974
+ let out: Array<{ result?: unknown; frameId?: number; documentId?: string }>;
975
+ try {
976
+ out = await chrome.scripting.executeScript({ target: { tabId: h.binding.tabId, documentIds: [h.binding.documentId] }, func: insertInPage, args: [h.text, h.binding.nonce], world: 'ISOLATED' }) as typeof out;
977
+ } catch { return fail('INSERT_NOT_PERMITTED'); }
978
+ if (!Array.isArray(out) || out.length !== 1 || out[0].frameId !== 0 || typeof out[0].documentId !== 'string' || !isPlainObject(out[0].result)) return fail('INSERT_FAILED');
979
+ const r = out[0].result as { ok?: unknown; code?: unknown; readback?: unknown; editor?: unknown; restored?: unknown; detail?: unknown; diag?: unknown };
980
+ if (r.ok !== true) {
981
+ // fixed-vocabulary, count-only facts from the page function; anything else is dropped (never page text)
982
+ const parts: string[] = [];
983
+ // SW-065: the restore verdict goes FIRST (it says whether the user's message box needs attention), then the count-only detail, then the diag.
984
+ if (r.restored === true) parts.push('DRAFT_RESTORED'); else if (r.restored === false) parts.push('DRAFT_NOT_RESTORED_CHECK_COMPOSER');
985
+ if (typeof r.detail === 'string' && /^[A-Z_]{1,32}(=\d{1,3})?$/.test(r.detail)) parts.push(r.detail);
986
+ // SW-064: stage, byte lengths, short checksums, first mismatch offset and character CATEGORIES only (uppercase token grammar; never page text)
987
+ if (typeof r.diag === 'string' && /^S=[A-Z]{1,12}( [A-Z]=[A-Z0-9]{1,10}(\.[A-F0-9]{8})?){1,9}$/.test(r.diag)) parts.push(r.diag);
988
+ else if (r.diag !== undefined) parts.push('DIAG_DROPPED_NONCONFORMING'); // never silently lose the fact that the page reported something
989
+ return fail(typeof r.code === 'string' && INSERT_CODES.has(r.code) ? (r.code as ErrorCode) : 'INSERT_FAILED', parts.length ? { component: 'SNAPSHOT', note: parts.join(' ') } : undefined);
990
+ }
991
+ // INSERTED is claimed only after the draft read back byte-for-byte, in the document the run departed from
992
+ if (r.readback !== h.text || out[0].documentId !== h.binding.documentId) return fail('READBACK_MISMATCH');
993
+ if (r.editor !== 'TEXTAREA' && r.editor !== 'CONTENTEDITABLE' && r.editor !== 'PROSEMIRROR') return fail('INSERT_FAILED');
994
+ return { inserted: r.editor };
995
+ }
996
+
997
+ async function insertReturn(m: Extract<PanelMessage, { type: 'INSERT_RETURN' }>, corr: string): Promise<Reply> {
998
+ if (m.userActivation !== true) return fail('NO_USER_ACTION'); // a contemporaneous deliberate click, as for capture
999
+ const h = heldReturn;
1000
+ if ((!h || h.returnId !== m.returnId) && lastWorkflow?.ret?.returnId === m.returnId) return insertDurable(m.returnId, corr); // SW-062 daemon-held return
1001
+ if (!h || h.returnId !== m.returnId) return fail('NO_RETURN');
1002
+ if (h.state === 'INSERTED') return fail('ALREADY_INSERTED');
1003
+ const s = authedSession();
1004
+ if (!s) return fail('NOT_PAIRED');
1005
+ if (h.binding.atMs + ORIGIN_TTL_MS <= Date.now()) { heldReturn = undefined; return fail('RETURN_EXPIRED'); }
1006
+ // 1. the daemon must still serve exactly these bytes to this paired, still-granted requester (revoked bearer/grant, tampered or changed snapshot => refuse)
1007
+ const f = await fetchReturn(s, h.runId, corr);
1008
+ if ('ok' in f) return f;
1009
+ if (f.snap.returnId !== h.returnId || f.snap.sha256 !== h.sha256 || f.snap.text !== h.text) return fail('RETURN_CHANGED');
1010
+ // 2. the SAME tab, window and URL, still allowlisted and still the active tab, right now
1011
+ const t = await targetTab(h.binding.tabId);
1012
+ if ('ok' in t) return !t.ok && t.code === 'TAB_NOT_ACTIVE' ? fail('TAB_CHANGED') : t;
1013
+ if (t.tab.windowId !== h.binding.windowId || t.tab.url !== h.binding.source) return fail('TAB_CHANGED');
1014
+ // 3. insert into that document only (the page function re-checks the per-document nonce BEFORE changing anything) and read the draft back
1015
+ const ins = await injectInsert(h);
1016
+ if (!('inserted' in ins)) return ins;
1017
+ h.state = 'INSERTED';
1018
+ const r = { editor: ins.inserted };
1019
+ const nowIso = new Date().toISOString();
1020
+ const cargo = ReturnCargoV1Schema.safeParse({ schemaVersion: SCHEMA_VERSION_V1, shipmentId: `ship.${h.returnId}`, runId: h.runId, conversationId: h.binding.source, userApproved: true, markdownSnippet: h.text, selectedArtifactIds: [], generatedAt: nowIso });
1021
+ const insertion = cargo.success ? ComposerInsertionV1Schema.safeParse({ schemaVersion: SCHEMA_VERSION_V1, cargo: cargo.data, insertionMode: 'DOM_TEXTAREA', status: 'INSERTED', timestamp: nowIso }) : cargo;
1022
+ if (!insertion.success) return fail('INTERNAL_ERROR');
1023
+ return { ok: true, type: 'INSERTED', receipt: { returnId: h.returnId, runId: h.runId, sha256: h.sha256, bytes: h.bytes, insertionMode: 'DOM_TEXTAREA', editor: r.editor, readback: 'MATCH', submission: 'NOT_SUBMITTED_BY_EXTENSION' } };
1024
+ }
1025
+
1026
+ async function getStatus(m: Extract<PanelMessage, { type: 'GET_STATUS' }>, corr: string): Promise<Reply> {
1027
+ const s = authedSession();
1028
+ if (!s) return fail('NOT_PAIRED');
1029
+ // POST, not GET: Chromium attaches the exact extension Origin to a JSON POST but never to an extension GET.
1030
+ const r = await http(corr, s.endpoint, 'POST', `${runPath(m.runId)}/status`, s.bearer, { schemaVersion: SCHEMA_VERSION_V1 });
1031
+ if (r.kind === 'failure') return fail(r.code, r.extra);
1032
+ if (r.status !== 200) { const e = errorFrom(r); dropSessionIfRejected(s, e); return e; }
1033
+ const parsed = RunStatusResponseV1Schema.safeParse(r.json);
1034
+ if (!parsed.success || parsed.data.runId !== m.runId) return fail('UNEXPECTED_RESPONSE');
1035
+ return { ok: true, type: 'STATUS', runId: parsed.data.runId, lifecycleState: parsed.data.lifecycleState, updatedAt: parsed.data.updatedAt };
1036
+ }
1037
+
1038
+ async function decide(runId: string, action: 'approve' | 'cancel', body: Record<string, unknown>, corr: string): Promise<Reply> {
1039
+ const s = authedSession();
1040
+ if (!s) return fail('NOT_PAIRED');
1041
+ const r = await http(corr, s.endpoint, 'POST', `${runPath(runId)}/${action}`, s.bearer, { schemaVersion: SCHEMA_VERSION_V1, ...body });
1042
+ if (r.kind === 'failure') return fail(r.code, r.extra);
1043
+ if (action === 'cancel' && r.status === 202) {
1044
+ // A run that is already starting/running: the daemon persisted CANCEL_REQUESTED; the terminal state arrives via status.
1045
+ const accepted = RunCancelAcceptedResponseV1Schema.safeParse(r.json);
1046
+ if (!accepted.success || accepted.data.runId !== runId) return fail('UNEXPECTED_RESPONSE');
1047
+ return { ok: true, type: 'CANCEL_ACCEPTED', runId: accepted.data.runId, lifecycleState: accepted.data.lifecycleState, updatedAt: accepted.data.updatedAt };
1048
+ }
1049
+ if (r.status !== 200) { const e = errorFrom(r); dropSessionIfRejected(s, e); return e; }
1050
+ const parsed = RunDecisionResponseV1Schema.safeParse(r.json);
1051
+ const expectedState = action === 'approve' ? 'QUEUED' : 'CANCELLED';
1052
+ // An approve must answer QUEUED; a cancel must answer CANCELLED. Anything else is not trusted.
1053
+ if (!parsed.success || parsed.data.runId !== runId || parsed.data.lifecycleState !== expectedState) return fail('UNEXPECTED_RESPONSE');
1054
+ return { ok: true, type: 'DECISION', runId: parsed.data.runId, lifecycleState: parsed.data.lifecycleState, updatedAt: parsed.data.updatedAt, duplicate: parsed.data.duplicate };
1055
+ }
1056
+
1057
+ // ---------------------------------------------------------------------------
1058
+ // SW-062 durable one-click workflow. The daemon's SQLite is authoritative (capture, run, return, receipts); this worker only holds a cache and can be
1059
+ // stopped at any moment: every entry point re-reads the daemon (resume/reconcile) and never replays a dispatch.
1060
+ // ---------------------------------------------------------------------------
1061
+
1062
+ export interface WorkflowView {
1063
+ readonly activity: ActivityResponse | null;
1064
+ readonly daemonHealth: {state:string;version:string;observedAt:string|null;activityFreshness:string};
1065
+ readonly version: number;
1066
+ readonly phase: string;
1067
+ readonly connection: 'CONNECTED' | 'MANUAL' | 'REPAIR';
1068
+ readonly operations: WorkflowCurrentResponseV1['operations'];
1069
+ readonly preferred: WorkflowCurrentResponseV1['preferred'];
1070
+ readonly capture: { captureId: string; text: string; sha256: string; bytes: number; source: string; state: string; expiresAt: string; fidelity: CaptureFidelity; lineEndingsNormalized: number; attestation: 'USER_ATTESTED_ONLY' } | null;
1071
+ readonly run: { runId: string; lifecycleState: string; consent: string; failure: { category: string; basis: string; causeDetermined: boolean; correlationId: string } | null } | null;
1072
+ readonly ret: { returnId: string; text: string; sha256: string; bytes: number; state: string; code: string | null; rebinds: number } | null;
1073
+ /** The last failure the user should see (connection, capture or insertion), already correlated and actionable. */
1074
+ readonly problem: FailureDetailV1 | null;
1075
+ }
1076
+
1077
+ let wfVersion = 0;
1078
+ let lastWorkflow: WorkflowCurrentResponseV1 | undefined;
1079
+ let lastActivity: ActivityResponse | null = null;
1080
+ let activityConnected = false;
1081
+ let activityRetryAt=0,activityFailures=0;
1082
+ const activityUnavailable=():void=>{activityConnected=false;activityRetryAt=Date.now()+Math.min(30_000,1000*2**Math.min(activityFailures++,5));};
1083
+ let daemonHealthState: 'CONNECTED'|'DISCONNECTED'|'RECONNECTING' = 'DISCONNECTED';
1084
+ let connectionObservedAt:string|null=null;
1085
+ let connectionProblem:FailureDetailV1|null=null;
1086
+ let recoveryFailures=0, nextRecoveryAt=0;
1087
+ let workflowDirty=true;
1088
+ let watchInFlight:Promise<void>|undefined;
1089
+ let reconcileInFlight:Promise<void>|undefined;
1090
+ const healthy=()=>{connectionProblem=null;daemonHealthState='CONNECTED';connectionObservedAt=new Date().toISOString();recoveryFailures=0;nextRecoveryAt=0;};
1091
+ const disconnected=()=>{daemonHealthState='DISCONNECTED';activityConnected=false;nextRecoveryAt=Date.now()+Math.min(30_000,1000*2**Math.min(recoveryFailures++,5));};
1092
+
1093
+ async function readActivity(runId: string, timeoutMs: number, corr: string): Promise<void> {
1094
+ const cursor = lastActivity?.runId === runId ? lastActivity.cursor : '0:0:0';
1095
+ const r = await wcall(corr, `${runPath(runId)}/activity`, {schemaVersion:1, cursor, timeoutMs});
1096
+ if ('ok' in r || r.status !== 200) { activityUnavailable(); return; }
1097
+ const p = ActivityResponseSchema.safeParse(r.json);
1098
+ if (!p.success || p.data.runId !== runId || (lastWorkflow?.run && lastWorkflow.run.runId !== runId)) { activityUnavailable(); return; }
1099
+ // A delayed older response must never roll a source cursor backwards or resurrect a previous task.
1100
+ if (lastActivity?.runId === runId && p.data.cursor.split(':').some((n,i)=>Number(n)<Number(lastActivity!.cursor.split(':')[i]))) return;
1101
+ const previous = lastActivity?.runId === runId ? lastActivity.events : [];
1102
+ const merged = new Map(previous.map(e => [e.id,e]));
1103
+ for (const e of p.data.events) merged.set(e.id,e);
1104
+ const events = [...merged.values()].sort((a,b) => a.ts.localeCompare(b.ts) || a.id[0]!.localeCompare(b.id[0]!) || Number(a.id.slice(2))-Number(b.id.slice(2))).slice(-80);
1105
+ lastActivity = {...p.data, events}; activityConnected = true; activityFailures=0;activityRetryAt=0;
1106
+ }
1107
+ let lastWorkflowKey = '';
1108
+ let lastProblem: FailureDetailV1 | null = null;
1109
+ let pendingCapture: Promise<void> | undefined;
1110
+ const versionWaiters = new Set<() => void>();
1111
+ const bump = (): void => { workflowDirty=true; notifyVersion(); };
1112
+ const notifyVersion = (): void => { wfVersion += 1; for (const w of [...versionWaiters]) w(); versionWaiters.clear(); };
1113
+
1114
+ const asDiag = (r: Reply, type: string, corr: string): FailureDetailV1 | null => {
1115
+ const f = finalize(r, type, corr);
1116
+ return !f.ok && f.diag ? f.diag : null;
1117
+ };
1118
+
1119
+ function bindingOf(s: Snapshot): TabBindingV1 {
1120
+ return { tabId: s.tabId, windowId: s.windowId, frameId: 0, documentId: s.documentId, nonce: s.nonce, sourceUrl: s.source };
1121
+ }
1122
+
1123
+ /** Stores the worker-held capture in the daemon (encrypted there). Idempotent per selection and document. */
1124
+ async function persistHeld(corr: string): Promise<Reply | undefined> {
1125
+ const snap = held;
1126
+ if (!snap || snap.remoteId || snap.expiresAtMs <= Date.now()) return undefined;
1127
+ const r = await wcall(corr, '/v1/captures', { schemaVersion: SCHEMA_VERSION_V1, text: snap.text, sha256: snap.sha256, bytes: snap.bytes, fidelity: snap.fidelity, lineEndingsNormalized: snap.lineEndingsNormalized, binding: bindingOf(snap) });
1128
+ if ('ok' in r) return r;
1129
+ if (r.status !== 201 && r.status !== 200) return errorFrom(r);
1130
+ const p = CaptureStoreResponseV1Schema.safeParse(r.json);
1131
+ if (!p.success || p.data.sha256 !== snap.sha256) return fail('UNEXPECTED_RESPONSE');
1132
+ snap.remoteId = p.data.captureId;
1133
+ return undefined;
1134
+ }
1135
+
1136
+ /**
1137
+ * Toolbar click on the source tab: the SAME trusted user gesture grants activeTab for that tab and opens the panel. Chrome requires sidePanel.open to be
1138
+ * called synchronously inside the gesture, so it is called first; capture runs independently (no ordering between the two is assumed: the panel reads the
1139
+ * result through GET_WORKFLOW whenever it arrives).
1140
+ */
1141
+ function toolbarCapture(tabId: number): void {
1142
+ const corr = newCorrelationId();
1143
+ pendingCapture = (async () => {
1144
+ const prev = held;
1145
+ const r = await capture({ type: 'CAPTURE', tabId, userActivation: true });
1146
+ if (!r.ok) {
1147
+ // An empty selection on a tab while a result waits for a target is how the user points at a new tab: keep the workflow, only report the hint.
1148
+ if (r.code === 'EMPTY_SELECTION' && prev) held = prev;
1149
+ lastProblem = asDiag(r, 'CAPTURE', corr);
1150
+ return;
1151
+ }
1152
+ lastProblem = null;
1153
+ const s = await sessionFor(corr); // the toolbar path is the daily path: it connects natively when it can
1154
+ if ('ok' in s) { lastProblem = asDiag(s, 'CONNECT', corr); return; }
1155
+ const p = await persistHeld(corr);
1156
+ if (p) lastProblem = asDiag(p, 'CAPTURE', corr);
1157
+ })().catch(() => { lastProblem = asDiag(fail('INTERNAL_ERROR'), 'CAPTURE', corr); }).finally(() => { pendingCapture = undefined; bump(); });
1158
+ }
1159
+
1160
+ const phaseOf = (w: WorkflowCurrentResponseV1 | undefined, connected: boolean): string => {
1161
+ if (!connected) return 'REPAIR';
1162
+ if (!w) return 'CONNECTING';
1163
+ const run = w.run;
1164
+ if (!run) return w.capture && w.capture.state === 'CAPTURED' ? 'CAPTURED' : 'NO_CAPTURE';
1165
+ switch (run.lifecycleState) {
1166
+ case 'AWAITING_USER_APPROVAL': case 'CREATED': return 'AWAITING_RISK_APPROVAL';
1167
+ case 'QUEUED': return 'QUEUED';
1168
+ case 'STARTING': case 'RUNNING': case 'WAITING_AGENT_APPROVAL': case 'CANCEL_REQUESTED': return 'RUNNING';
1169
+ case 'COMPLETED': return w.ret ? w.ret.state : 'COMPLETED';
1170
+ default: return run.lifecycleState;
1171
+ }
1172
+ };
1173
+
1174
+ async function readCurrent(corr: string): Promise<WorkflowCurrentResponseV1 | Reply> {
1175
+ const r = await wcall(corr, '/v1/workflow/current', { schemaVersion: SCHEMA_VERSION_V1 });
1176
+ if ('ok' in r) return r;
1177
+ if (r.status !== 200) return errorFrom(r);
1178
+ const p = WorkflowCurrentResponseV1Schema.safeParse(r.json);
1179
+ if(p.success) { healthy(); return p.data; }
1180
+ return fail('UNEXPECTED_RESPONSE');
1181
+ }
1182
+
1183
+ /** Reconcile with the daemon; on COMPLETED without a prepared return, prepare the digest-checked preview automatically (insertion stays explicit). */
1184
+ async function reconcile(corr: string): Promise<{ w?: WorkflowCurrentResponseV1; problem?: Reply }> {
1185
+ let w = await readCurrent(corr); // also (re-)establishes the native session when needed
1186
+ if (!('ok' in w) && session && held && !held.remoteId && !held.consumed && held.expiresAtMs > Date.now()) {
1187
+ // a capture the user took (toolbar or Capture button) that is not yet durable is stored now that a connection exists
1188
+ const held0 = await persistHeld(corr);
1189
+ lastProblem = held0 && !held0.ok ? asDiag(held0, 'CAPTURE', corr) : lastProblem;
1190
+ const again = await readCurrent(corr);
1191
+ if (!('ok' in again)) w = again;
1192
+ }
1193
+ if ('ok' in w) return { problem: w };
1194
+ if (w.run && w.run.lifecycleState === 'COMPLETED' && !w.ret) {
1195
+ const s = authedSession();
1196
+ if (s) {
1197
+ const f = await fetchReturn(s, w.run.runId, corr);
1198
+ if ('ok' in f) lastProblem = asDiag(f, 'PREPARE_RETURN', corr);
1199
+ const again = await readCurrent(corr);
1200
+ if (!('ok' in again)) w = again;
1201
+ }
1202
+ }
1203
+ return { w };
1204
+ }
1205
+
1206
+ function viewOfWorkflow(w: WorkflowCurrentResponseV1 | undefined, problem: FailureDetailV1 | null, connected: boolean): WorkflowView {
1207
+ const localOnly = held && !held.remoteId && held.expiresAtMs > Date.now() ? held : undefined;
1208
+ const cap = w?.capture && w.capture.state !== 'EXPIRED'
1209
+ ? { captureId: w.capture.captureId, text: w.capture.text, sha256: w.capture.sha256, bytes: w.capture.bytes, source: w.capture.binding.sourceUrl, state: w.capture.state, expiresAt: w.capture.expiresAt, fidelity: w.capture.fidelity, lineEndingsNormalized: w.capture.lineEndingsNormalized, attestation: 'USER_ATTESTED_ONLY' as const }
1210
+ : localOnly ? { captureId: '', text: localOnly.text, sha256: localOnly.sha256, bytes: localOnly.bytes, source: localOnly.source, state: 'CAPTURED_NOT_STORED', expiresAt: localOnly.expiresAt, fidelity: localOnly.fidelity, lineEndingsNormalized: localOnly.lineEndingsNormalized, attestation: 'USER_ATTESTED_ONLY' as const } : null;
1211
+ return {
1212
+ activity: w?.run && lastActivity?.runId === w.run.runId ? lastActivity : null,
1213
+ daemonHealth: {state:daemonHealthState,version:w?.daemonVersion ?? 'UNAVAILABLE',observedAt:connectionObservedAt,activityFreshness:activityConnected?'OBSERVED':lastActivity?'STALE':'UNKNOWN'},
1214
+ version: wfVersion,
1215
+ phase: phaseOf(w, connected),
1216
+ connection: !connected ? 'REPAIR' : session?.source === 'MANUAL' ? 'MANUAL' : 'CONNECTED',
1217
+ operations: w?.operations ?? [],
1218
+ preferred: w?.preferred ?? null,
1219
+ capture: cap,
1220
+ run: w?.run ? { runId: w.run.runId, lifecycleState: w.run.lifecycleState, consent: w.run.consent, failure: w.run.failure ?? null } : null,
1221
+ ret: w?.ret ? { returnId: w.ret.returnId, text: w.ret.text, sha256: w.ret.sha256, bytes: w.ret.bytes, state: w.ret.state, code: w.ret.code, rebinds: w.ret.rebinds } : null,
1222
+ problem,
1223
+ };
1224
+ }
1225
+
1226
+ /** One shared authenticated conditional wait per worker, including idle/no-run state. Closing the last panel issues no new wait. */
1227
+ async function watchWorkflow(waitMs:number,corr:string):Promise<void>{
1228
+ if(watchInFlight)return watchInFlight;
1229
+ const revision=lastWorkflow?.revision;
1230
+ if(!revision){workflowDirty=true;return;}
1231
+ const task=(async()=>{
1232
+ const r=await wcall(corr,'/v1/workflow/current',{schemaVersion:1,watchOnly:true,sinceRevision:revision,timeoutMs:Math.max(0,Math.min(25000,waitMs-250))});
1233
+ if('ok' in r || r.status!==200){connectionProblem=asDiag('ok' in r?r:errorFrom(r),'CONNECT',corr);disconnected();return;}
1234
+ const p=WorkflowWatchResponseSchema.safeParse(r.json);
1235
+ if(!p.success){connectionProblem=asDiag(fail('UNEXPECTED_RESPONSE'),'CONNECT',corr);disconnected();return;}
1236
+ healthy();
1237
+ if(p.data.revision!==lastWorkflow?.revision)workflowDirty=true;
1238
+ else if(!activityConnected && lastWorkflow?.run && Date.now()>=activityRetryAt)await readActivity(lastWorkflow.run.runId,0,corr);
1239
+ })();
1240
+ watchInFlight=task;
1241
+ try{await task;}finally{if(watchInFlight===task)watchInFlight=undefined;}
1242
+ }
1243
+ async function refreshWorkflow(corr:string):Promise<void>{
1244
+ if(reconcileInFlight)return reconcileInFlight;
1245
+ const task=(async()=>{
1246
+ const startVersion=wfVersion;
1247
+ if(daemonHealthState!=='CONNECTED')daemonHealthState='RECONNECTING';
1248
+ const {w,problem}=await reconcile(corr);
1249
+ if(problem){connectionProblem=asDiag(problem,'CONNECT',corr);disconnected();return;}
1250
+ if(w){lastWorkflow=w;healthy();
1251
+ if(w.run)await readActivity(w.run.runId,0,corr);
1252
+ else activityConnected=false;
1253
+ if(wfVersion===startVersion)workflowDirty=false;
1254
+ }
1255
+ })();
1256
+ reconcileInFlight=task;
1257
+ try{await task;}finally{if(reconcileInFlight===task)reconcileInFlight=undefined;}
1258
+ }
1259
+ async function getWorkflow(m: Extract<PanelMessage, { type: 'GET_WORKFLOW' }>, corr: string): Promise<Reply> {
1260
+ if(pendingCapture)await pendingCapture;
1261
+ if(m.waitMs>0 && m.sinceVersion===wfVersion && (!workflowDirty || daemonHealthState!=='CONNECTED')){
1262
+ let wake:()=>void=()=>undefined;
1263
+ const local=new Promise<void>(r=>{wake=r;versionWaiters.add(r);});
1264
+ let timer:ReturnType<typeof setTimeout>|undefined;
1265
+ const ms=daemonHealthState==='CONNECTED'?m.waitMs:Math.min(m.waitMs,Math.max(0,nextRecoveryAt-Date.now()));
1266
+ const timeout=new Promise<void>(r=>{timer=setTimeout(r,ms);});
1267
+ try{await Promise.race([local,timeout,daemonHealthState==='CONNECTED'?watchWorkflow(m.waitMs,corr):new Promise<void>(()=>undefined)]);}
1268
+ finally{versionWaiters.delete(wake);if(timer)clearTimeout(timer);}
1269
+ }
1270
+ const explicit=m.sinceVersion<0;
1271
+ if((explicit || workflowDirty || daemonHealthState!=='CONNECTED' || !lastWorkflow) && (explicit || Date.now()>=nextRecoveryAt))await refreshWorkflow(corr);
1272
+ const view=viewOfWorkflow(lastWorkflow,daemonHealthState==='CONNECTED'?lastProblem:connectionProblem??lastProblem,daemonHealthState==='CONNECTED');
1273
+ // Observation timestamps prove health, but are not task changes and must not trigger redundant snapshot/coding reads.
1274
+ const key=JSON.stringify({...view,version:0,problem:view.problem?.code??null,daemonHealth:{...view.daemonHealth,observedAt:null},activity:view.activity?{...view.activity,collectedAt:null}:null});
1275
+ if(key!==lastWorkflowKey){lastWorkflowKey=key;notifyVersion();}
1276
+ return{ok:true,type:'WORKFLOW',view:{...view,version:wfVersion}};
1277
+ }
1278
+
1279
+ async function codingCall(m: Extract<PanelMessage, { type: 'CODING_STATUS' | 'CODING_ACTION' }>, corr: string): Promise<Reply> {
1280
+ if (m.type === 'CODING_ACTION' && !m.userActivation) return fail('NO_USER_ACTION');
1281
+ const r = await wcall(corr, `/v1/coding/${encodeURIComponent(m.runId)}/${m.type === 'CODING_STATUS' ? 'status' : 'action'}`,
1282
+ m.type === 'CODING_STATUS' ? { schemaVersion: 1 } : { schemaVersion: 1, proposalId: m.proposalId, digest: m.digest, action: m.action });
1283
+ if ('ok' in r) return r;
1284
+ if (r.status !== 200) return errorFrom(r);
1285
+ if (!isPlainObject(r.json) || r.json.schemaVersion !== 1) return fail('UNEXPECTED_RESPONSE');
1286
+ return { ok: true, type: 'CODING', data: r.json };
1287
+ }
1288
+
1289
+ async function runSelected(m: Extract<PanelMessage, { type: 'RUN' | 'RUN_CODING' | 'RUN_TRUSTED_CODING' }>, corr: string): Promise<Reply> {
1290
+ if (m.userActivation !== true) return fail('NO_USER_ACTION');
1291
+ const cur = await readCurrent(corr);
1292
+ if ('ok' in cur) return cur;
1293
+ const c = cur.capture;
1294
+ if (!c || c.captureId !== m.captureId) return fail('CAPTURE_NOT_FOUND');
1295
+ if (c.state === 'EXPIRED') return fail('CAPTURE_EXPIRED');
1296
+ if (!cur.operations.some((o) => o.projectId === m.projectId && o.pluginId === m.pluginId && o.operationId === m.operationId)) return fail('OPERATION_NOT_SELECTED');
1297
+ if (c.state === 'CAPTURED') {
1298
+ // The capture must still come from the same allowlisted tab, window, URL and document (a navigated or replaced page needs a fresh capture).
1299
+ const t = await targetTab(c.binding.tabId);
1300
+ if ('ok' in t) return !t.ok && t.code === 'TAB_NOT_ACTIVE' ? fail('TAB_CHANGED') : t;
1301
+ if (t.tab.windowId !== c.binding.windowId || t.tab.url !== c.binding.sourceUrl) return fail('TAB_CHANGED');
1302
+ const now = await inject(c.binding.tabId);
1303
+ if ('ok' in now) return now;
1304
+ if (now.documentId !== c.binding.documentId || now.result.nonce !== c.binding.nonce) return fail('DOCUMENT_CHANGED');
1305
+ }
1306
+ // Idempotent at the daemon (keys derived from the capture id): a repeated click or a lost reply can never start a second run.
1307
+ const r = await wcall(corr, `/v1/captures/${encodeURIComponent(m.captureId)}/${m.type !== 'RUN' ? 'coding' : 'run'}`, { schemaVersion: SCHEMA_VERSION_V1, projectId: m.projectId, pluginId: m.pluginId, operationId: m.operationId, ...(m.type === 'RUN_TRUSTED_CODING' ? { executionMode: 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY' } : {}) });
1308
+ if ('ok' in r) return r;
1309
+ if (r.status !== 200 && r.status !== 202) return errorFrom(r);
1310
+ const p = CaptureRunResponseV1Schema.safeParse(r.json);
1311
+ if (!p.success) return fail('UNEXPECTED_RESPONSE');
1312
+ lastProblem = null;
1313
+ bump();
1314
+ return { ok: true, type: 'RUN_STARTED', runId: p.data.runId, lifecycleState: p.data.lifecycleState, consent: p.data.consent, duplicate: p.data.duplicate };
1315
+ }
1316
+
1317
+ async function recordReceipt(corr: string, returnId: string, sha256: string, state: 'INSERTED_UNSENT' | 'RETURN_STALE' | 'INSERT_FAILED', extra: { code?: string; editor?: string } = {}): Promise<void> {
1318
+ await wcall(corr, `/v1/returns/${encodeURIComponent(returnId)}/receipt`, { schemaVersion: SCHEMA_VERSION_V1, state, sha256, ...extra });
1319
+ }
1320
+
1321
+ async function insertDurable(returnId: string, corr: string): Promise<Reply> {
1322
+ const cur = await readCurrent(corr);
1323
+ if ('ok' in cur) return cur;
1324
+ const ret = cur.ret;
1325
+ if (!ret || ret.returnId !== returnId) return fail('NO_RETURN');
1326
+ if (ret.state === 'INSERTED_UNSENT') return fail('ALREADY_INSERTED');
1327
+ const s = authedSession();
1328
+ if (!s || !cur.run) return fail('NOT_PAIRED');
1329
+ // 1. the daemon must still serve exactly these bytes to this still-granted requester
1330
+ const f = await fetchReturn(s, cur.run.runId, corr);
1331
+ if ('ok' in f) return f;
1332
+ if (f.snap.returnId !== ret.returnId || f.snap.sha256 !== ret.sha256 || f.snap.text !== ret.text) return fail('RETURN_CHANGED');
1333
+ // 2. the bound tab, window and URL, still allowlisted and active; a changed target is RETURN_STALE (never auto-rebound)
1334
+ const b = ret.binding;
1335
+ const t = await targetTab(b.tabId);
1336
+ const stale = async (why: string): Promise<Reply> => { await recordReceipt(corr, ret.returnId, ret.sha256, 'RETURN_STALE', { code: why }); bump(); return fail('RETURN_STALE', { component: 'SNAPSHOT', note: why }); };
1337
+ if ('ok' in t) return !t.ok && (t.code === 'TAB_NOT_ACTIVE' || t.code === 'TAB_UNAVAILABLE' || t.code === 'ORIGIN_NOT_ALLOWED') ? stale(t.code) : t;
1338
+ if (t.tab.windowId !== b.windowId || t.tab.url !== b.sourceUrl) return stale('TAB_CHANGED');
1339
+ // 3. write the draft into that document only, read it back exactly; never submit
1340
+ const ins = await injectInsert({ text: ret.text, binding: { tabId: b.tabId, nonce: b.nonce, documentId: b.documentId } });
1341
+ if (!('inserted' in ins)) {
1342
+ if (!ins.ok && ins.code === 'DOCUMENT_CHANGED') return stale('DOCUMENT_CHANGED');
1343
+ if (!ins.ok) await recordReceipt(corr, ret.returnId, ret.sha256, 'INSERT_FAILED', { code: ins.code.slice(0, 40) });
1344
+ bump();
1345
+ return ins;
1346
+ }
1347
+ await recordReceipt(corr, ret.returnId, ret.sha256, 'INSERTED_UNSENT', { editor: ins.inserted });
1348
+ bump();
1349
+ return { ok: true, type: 'INSERTED', receipt: { returnId: ret.returnId, runId: cur.run.runId, sha256: ret.sha256, bytes: ret.bytes, insertionMode: 'DOM_TEXTAREA', editor: ins.inserted, readback: 'MATCH', submission: 'NOT_SUBMITTED_BY_EXTENSION' } };
1350
+ }
1351
+
1352
+ /**
1353
+ * SW-065 Copy Result. Hands the panel the EXACT immutable result for the user's own clipboard write: the daemon must still serve exactly these bytes to this
1354
+ * still-granted requester right now (digest, length and text re-checked), otherwise nothing is released. No tab is touched and no receipt is recorded:
1355
+ * copying is not insertion, the return state machine is unchanged, and the user decides where (and whether) to paste. Repeating it is harmless.
1356
+ */
1357
+ async function copyReturn(m: Extract<PanelMessage, { type: 'COPY_RETURN' }>, corr: string): Promise<Reply> {
1358
+ if (m.userActivation !== true) return fail('NO_USER_ACTION');
1359
+ const released = (returnId: string, runId: string, snap: ReturnView): Reply => {
1360
+ wlog('INFO', 'SNAPSHOT', 'COPY_RETURN', 'RESULT_RELEASED_FOR_COPY', { correlationId: corr, outcome: 'OK', meta: { bytes: snap.bytes } });
1361
+ return { ok: true, type: 'RETURN_TEXT', returnId, runId, text: snap.text, sha256: snap.sha256, bytes: snap.bytes };
1362
+ };
1363
+ const h = heldReturn;
1364
+ if (h && h.returnId === m.returnId) { // the legacy (advanced section) held return
1365
+ const s = authedSession();
1366
+ if (!s) return fail('NOT_PAIRED');
1367
+ const f = await fetchReturn(s, h.runId, corr);
1368
+ if ('ok' in f) return f;
1369
+ if (f.snap.returnId !== h.returnId || f.snap.sha256 !== h.sha256 || f.snap.text !== h.text) return fail('RETURN_CHANGED');
1370
+ return released(h.returnId, h.runId, f.snap);
1371
+ }
1372
+ const cur = await readCurrent(corr);
1373
+ if ('ok' in cur) return cur;
1374
+ const ret = cur.ret;
1375
+ if (!ret || ret.returnId !== m.returnId || !cur.run) return fail('NO_RETURN');
1376
+ const s = authedSession();
1377
+ if (!s) return fail('NOT_PAIRED');
1378
+ const f = await fetchReturn(s, cur.run.runId, corr);
1379
+ if ('ok' in f) return f;
1380
+ if (f.snap.returnId !== ret.returnId || f.snap.sha256 !== ret.sha256 || f.snap.text !== ret.text) return fail('RETURN_CHANGED');
1381
+ return released(ret.returnId, cur.run.runId, f.snap);
1382
+ }
1383
+
1384
+ /** The user's explicit choice to put the SAME finished result into the conversation open in `tabId` (after clicking the toolbar icon there). No re-run. */
1385
+ async function rebindReturn(m: Extract<PanelMessage, { type: 'REBIND_RETURN' }>, corr: string): Promise<Reply> {
1386
+ if (m.userActivation !== true) return fail('NO_USER_ACTION');
1387
+ const cur = await readCurrent(corr);
1388
+ if ('ok' in cur) return cur;
1389
+ const ret = cur.ret;
1390
+ if (!ret || ret.returnId !== m.returnId) return fail('NO_RETURN');
1391
+ if (ret.state === 'INSERTED_UNSENT') return fail('ALREADY_INSERTED');
1392
+ const t = await targetTab(m.tabId);
1393
+ if ('ok' in t) return t;
1394
+ const doc = await inject(m.tabId); // identity only (document id + per-document nonce); an empty selection is expected here
1395
+ if ('ok' in doc) return doc;
1396
+ if (typeof doc.result.nonce !== 'string' || doc.result.isTop !== true || doc.result.href !== t.tab.url) return fail('DOCUMENT_CHANGED');
1397
+ const r = await wcall(corr, `/v1/returns/${encodeURIComponent(m.returnId)}/rebind`, {
1398
+ schemaVersion: SCHEMA_VERSION_V1, sha256: ret.sha256, binding: { tabId: m.tabId, windowId: t.tab.windowId, frameId: 0, documentId: doc.documentId, nonce: doc.result.nonce, sourceUrl: t.tab.url as string },
1399
+ });
1400
+ if ('ok' in r) return r;
1401
+ if (r.status !== 200) return errorFrom(r);
1402
+ bump();
1403
+ return { ok: true, type: 'REBOUND', returnId: m.returnId };
1404
+ }
1405
+
1406
+ async function setDefault(m: Extract<PanelMessage, { type: 'SET_DEFAULT' }>, corr: string): Promise<Reply> {
1407
+ const r = await wcall(corr, '/v1/workflow/preference', { schemaVersion: SCHEMA_VERSION_V1, projectId: m.projectId, pluginId: m.pluginId, operationId: m.operationId });
1408
+ if ('ok' in r) return r;
1409
+ if (r.status !== 200) return errorFrom(r);
1410
+ bump();
1411
+ return { ok: true, type: 'DEFAULT_SAVED' };
1412
+ }
1413
+
1414
+ async function dismiss(m: Extract<PanelMessage, { type: 'DISMISS' }>, corr: string): Promise<Reply> {
1415
+ if (held?.remoteId === m.captureId) held = undefined;
1416
+ const r = await wcall(corr, '/v1/workflow/dismiss', { schemaVersion: SCHEMA_VERSION_V1, captureId: m.captureId });
1417
+ if ('ok' in r) return r;
1418
+ if (r.status !== 200) return errorFrom(r);
1419
+ lastProblem = null;
1420
+ bump();
1421
+ return { ok: true, type: 'DISMISSED' };
1422
+ }
1423
+
1424
+ async function repair(corr: string): Promise<Reply> {
1425
+ if (session?.source === 'NATIVE') session = undefined; // a manual (diagnostic) pairing is never silently replaced
1426
+ lastProblem = null; nextRecoveryAt=0; recoveryFailures=0;
1427
+ bump();
1428
+ return getWorkflow({ type: 'GET_WORKFLOW', sinceVersion: -1, waitMs: 0 }, corr);
1429
+ }
1430
+
1431
+ function diagnosticsExport(): string {
1432
+ const currentActivity = lastWorkflow?.run?.runId === lastActivity?.runId ? lastActivity : null;
1433
+ let version = 'unknown';
1434
+ try { const mf = (chrome.runtime as unknown as { getManifest?: () => { version?: string; version_name?: string } }).getManifest?.(); version = (mf?.version_name ?? mf?.version ?? 'unknown').replace(/\s+/g, '_'); } catch { /* not available */ }
1435
+ const head = [
1436
+ '# my-centcom extension diagnostics (redacted: no secrets, codes, tokens, prompts, page text or paths)',
1437
+ `extensionVersion=${version} workerStartedAt=${workerStartedAt} exportedAt=${new Date().toISOString()}`,
1438
+ `paired=${session !== undefined && session.expiresAtMs > Date.now()}${session ? ` port=${session.port} sessionExpiresAt=${new Date(session.expiresAtMs).toISOString()}` : ''} everPairedThisWorkerRun=${everPaired}${sessionEnd ? ` lastSessionEnd=${sessionEnd}` : ''}`,
1439
+ `heldCapture=${held !== undefined} heldReturn=${heldReturn !== undefined} knownRunOrigins=${origins.size} events=${diagRing.length}`,
1440
+ `daemonVersion=${lastWorkflow?.daemonVersion ?? currentActivity?.daemonVersion ?? 'UNAVAILABLE'} connection=${daemonHealthState} authenticatedObservedAt=${connectionObservedAt ?? 'UNAVAILABLE'} activityFreshness=${activityConnected?'OBSERVED':currentActivity?'STALE':'UNKNOWN'}`,
1441
+ `project=${lastWorkflow?.preferred?.projectId ?? 'UNAVAILABLE'} agent=${lastWorkflow?.preferred?.pluginId ?? 'UNAVAILABLE'} operation=${lastWorkflow?.preferred?.operationId ?? 'UNAVAILABLE'}`,
1442
+ `run=${lastWorkflow?.run?.runId ?? 'UNAVAILABLE'} phase=${lastWorkflow?.run?.lifecycleState ?? 'UNAVAILABLE'} processStatus=${describeObservedProcess(currentActivity?.events ?? [],lastWorkflow?.run?.lifecycleState).text} processEvidence=${activityConnected?describeObservedProcess(currentActivity?.events ?? [],lastWorkflow?.run?.lifecycleState).evidence:currentActivity?'STALE':'UNKNOWN'} recovery=${lastWorkflow?.run?.lifecycleState === 'UNKNOWN' ? 'UNKNOWN; not restarted' : 'durable cursor replay'}`,
1443
+ `failureCategory=${lastWorkflow?.run?.failure?.category ?? 'UNAVAILABLE / no recorded failure'} failureBasis=${lastWorkflow?.run?.failure?.basis ?? 'UNAVAILABLE'} correlation=${lastWorkflow?.run?.failure?.correlationId ?? 'UNAVAILABLE'}`,
1444
+ `productionTEST=DISABLED TEST_BOUNDARY_UNVERIFIED; strict OS isolation NOT_VERIFIED; trusted consent is separate`,
1445
+ 'UNAVAILABLE/REDACTED: credentials, private paths, prompts, model output, file contents, hidden reasoning; stdout/stderr only when sanitized telemetry recorded it.',
1446
+ ];
1447
+ const activity = currentActivity?.events.map(e => `${e.ts} ${e.severity} ${e.component} ${activityConnected ? e.status : 'STALE'} ${e.runId} ${e.id} ${e.kind}: ${e.summary}`) ?? ['Backend events UNAVAILABLE.'];
1448
+ const report = [...head, ...activity, ...diagRing.slice(-40).map(formatDiagEvent)].join('\n');
1449
+ return report.length <= 32000 ? report : report.slice(0,31920) + '\nEXPORT_TRUNCATED: diagnostic size limit; older records remain subject to retention.';
1450
+ }
1451
+
1452
+ /** Turns an internal failure into the public, correlated, actionable one. The typed code is never replaced. */
1453
+ function finalize(r: Reply, type: string, corr: string): Reply {
1454
+ if (r.ok) return r;
1455
+ let note = r._x?.note;
1456
+ if (r.code === 'NOT_PAIRED') {
1457
+ note = sessionEnd === 'EXPIRED' ? 'PAIRING_EXPIRED' : sessionEnd === 'REJECTED_BY_DAEMON' ? 'DAEMON_REJECTED_THE_SESSION' : sessionEnd === 'DISCONNECTED' ? 'DISCONNECTED_BY_USER'
1458
+ : everPaired ? 'NO_ACTIVE_SESSION' : `NEVER_PAIRED_SINCE_WORKER_START=${workerStartedAt}`;
1459
+ }
1460
+ const diag = describeFailure({
1461
+ operation: OPERATION_LABELS[type] ?? type, code: r.code, correlationId: corr, fields: r._x?.fields, httpStatus: r._x?.httpStatus, component: r._x?.component, note,
1462
+ });
1463
+ wlog(r.code === 'INTERNAL_ERROR' || r.code === 'SERVER_ERROR' ? 'ERROR' : 'WARN', diag.component, type, r.code, {
1464
+ correlationId: corr, outcome: 'FAILED', meta: { ...(diag.fields ? { fields: diag.fields.map((f) => `${f.field}:${f.reason}`).join(',') } : {}), ...(diag.httpStatus ? { status: diag.httpStatus } : {}), ...(diag.note ? { note: diag.note } : {}) },
1465
+ });
1466
+ return { ok: false, code: r.code, diag };
1467
+ }
1468
+
1469
+ export async function handleMessage(raw: unknown, sender: chrome.runtime.MessageSender | undefined): Promise<Reply> {
1470
+ const corr = newCorrelationId();
1471
+ const t0 = Date.now();
1472
+ const type = isPlainObject(raw) && typeof raw.type === 'string' && Object.prototype.hasOwnProperty.call(EXPECTED_KEYS, raw.type) ? raw.type : '(unknown)';
1473
+ let out: Reply;
1474
+ try {
1475
+ out = await route(raw, sender, corr);
1476
+ } catch {
1477
+ out = fail('INTERNAL_ERROR'); // an unknown failure is never disguised as a validation or permission problem
1478
+ }
1479
+ if (out.ok) wlog(type === 'GET_STATUS' || type === 'GET_CAPTURE' || type === 'GET_RETURN' || type === 'GET_DIAGNOSTICS' ? 'DEBUG' : 'INFO', 'WORKER', type, out.type, { correlationId: corr, outcome: 'OK', elapsedMs: Date.now() - t0 });
1480
+ const fin = finalize(out, type, corr);
1481
+ // SW-065: an Insert Draft failure stays visible in the workflow view (code, Detail and correlation id) until the next successful step, instead of
1482
+ // living only in the one reply the panel happened to render before its next refresh.
1483
+ if (type === 'INSERT_RETURN' && !(fin.ok === false && fin.code === 'BUSY')) { const before = lastProblem; lastProblem = fin.ok ? null : fin.diag ?? null; if (before !== lastProblem) bump(); }
1484
+ return fin;
1485
+ }
1486
+
1487
+ async function route(raw: unknown, sender: chrome.runtime.MessageSender | undefined, corr: string): Promise<Reply> {
1488
+ if (!senderAllowed(sender)) return fail('SENDER_DENIED');
1489
+ const parsed = parseMessage(raw);
1490
+ if (!('m' in parsed)) return fail(parsed.code, { fields: parsed.fields });
1491
+ const m = parsed.m;
1492
+ if (m.type === 'DISCONNECT') {
1493
+ session = undefined;
1494
+ sessionEnd = 'DISCONNECTED'; daemonHealthState='DISCONNECTED'; activityConnected=false;
1495
+ heldReturn = undefined; origins.clear();
1496
+ return { ok: true, type: 'DISCONNECTED' };
1497
+ }
1498
+ if (m.type === 'GET_DIAGNOSTICS') return { ok: true, type: 'DIAGNOSTICS', text: diagnosticsExport(), count: diagRing.length };
1499
+ if (m.type === 'GET_STATUS') return getStatus(m, corr); // read-only; may overlap with other calls
1500
+ if (m.type === 'GET_CAPTURE') return getCapture(); // read-only preview of the held snapshot
1501
+ if (m.type === 'GET_RETURN') return getReturn(); // read-only preview of the held return snapshot
1502
+ if (m.type === 'GET_WORKFLOW') return getWorkflow(m, corr); // read-only resume/reconcile; may overlap with other calls
1503
+ if (m.type === 'CODING_STATUS') return codingCall(m, corr);
1504
+ if (m.type === 'COPY_RETURN') return copyReturn(m, corr); // read-only (idempotent snapshot read); never blocked by an unrelated action in flight
1505
+ // Pairing and decisions are serialised: one in flight at a time, never auto-retried.
1506
+ if (busy) return fail('BUSY');
1507
+ busy = true;
1508
+ try {
1509
+ if (m.type === 'SET_TASK') {
1510
+ if (!m.userActivation) return fail('NO_USER_ACTION');
1511
+ const bytes = new TextEncoder().encode(m.text);
1512
+ if (toHex(await crypto.subtle.digest('SHA-256', bytes)) !== m.sha256) return fail('READBACK_MISMATCH');
1513
+ const cur = await readCurrent(corr); if ('ok' in cur) return cur;
1514
+ const c = cur.capture;
1515
+ if (!c || c.captureId !== m.captureId || c.state !== 'CAPTURED') return fail('CAPTURE_CONFLICT');
1516
+ const t = await targetTab(c.binding.tabId); if ('ok' in t) return t;
1517
+ if (t.tab.url !== c.binding.sourceUrl || t.tab.windowId !== c.binding.windowId) return fail('TAB_CHANGED');
1518
+ const page = await inject(c.binding.tabId); if ('ok' in page) return page;
1519
+ if (page.documentId !== c.binding.documentId || page.result.nonce !== c.binding.nonce) return fail('DOCUMENT_CHANGED');
1520
+ if (c.text === m.text && c.sha256 === m.sha256 && c.bytes === bytes.length) return {ok:true,type:'CAPTURED',view: { ...c, state:'CAPTURED', source:c.binding.sourceUrl, capturedAt:c.createdAt, attestation:'USER_ATTESTED_ONLY', warnings:[] }};
1521
+ const r = await wcall(corr, '/v1/captures', {schemaVersion:1, text:m.text, sha256:m.sha256, bytes:bytes.length, binding:c.binding, fidelity:'EDITED_TASK_TEXT', lineEndingsNormalized:0, editOf:c.captureId});
1522
+ if ('ok' in r) return r;
1523
+ const p = CaptureStoreResponseV1Schema.safeParse(r.json);
1524
+ if ((r.status !== 200 && r.status !== 201) || !p.success || p.data.sha256 !== m.sha256 || p.data.bytes !== bytes.length) return fail('READBACK_MISMATCH');
1525
+ const check = await readCurrent(corr);
1526
+ if ('ok' in check || check.capture?.captureId !== p.data.captureId || check.capture.text !== m.text) return fail('READBACK_MISMATCH');
1527
+ bump();
1528
+ return {ok:true,type:'CAPTURED',view:{...check.capture,state:'CAPTURED',source:c.binding.sourceUrl,capturedAt:p.data.createdAt,attestation:'USER_ATTESTED_ONLY',warnings:[]}};
1529
+ }
1530
+ if(m.type==='REVIEWED_COMMIT'){
1531
+ if(!m.userActivation)return fail('NO_USER_ACTION');
1532
+ const r=await wcall(corr,`/v1/coding/${encodeURIComponent(m.runId)}/${m.review?'commit-review':'reviewed-commit'}`,{schemaVersion:1,proposalId:m.proposalId,message:m.message,challenge:m.challenge});
1533
+ if('ok'in r)return r;return r.status===200?{ok:true,type:'CODING',data:r.json}:errorFrom(r);
1534
+ }
1535
+ if (m.type === 'REVIEWED_PATCH') {
1536
+ if (!m.userActivation) return fail('NO_USER_ACTION');
1537
+ const { type: ignored, runId, userActivation: ignoredActivation, ...body } = m;
1538
+ const r = await wcall(corr, `/v1/coding/${encodeURIComponent(runId)}/reviewed-patch`, { schemaVersion: 1, ...body });
1539
+ if ('ok' in r) return r;
1540
+ return r.status === 200 ? { ok: true, type: 'CODING', data: r.json } : errorFrom(r);
1541
+ }
1542
+ if (m.type === 'TRUSTED_CONSENT') {
1543
+ if (m.action !== 'status' && !m.userActivation) return fail('NO_USER_ACTION');
1544
+ const r = await wcall(corr, '/v1/coding/trusted-consent', { schemaVersion: 1, projectId: m.projectId, pluginId: m.pluginId, operationId: m.operationId, action: m.action, ...(m.challenge ? { challenge: m.challenge } : {}), ...(m.warningVersion ? { warningVersion: m.warningVersion } : {}) });
1545
+ if ('ok' in r) return r;
1546
+ return r.status === 200 ? { ok: true, type: 'CODING', data: r.json } : errorFrom(r);
1547
+ }
1548
+ if (m.type === 'PAIR') return await pair(m, corr);
1549
+ if (m.type === 'PREPARE') return await prepare(m, corr);
1550
+ if (m.type === 'CAPTURE') {
1551
+ const c = await capture(m);
1552
+ // SW-062: with a native session the capture is also stored durably (a manual diagnostic pairing keeps the B04 worker-memory behaviour).
1553
+ if (c.ok && session?.source === 'NATIVE') { const p = await persistHeld(corr); lastProblem = p ? asDiag(p, 'CAPTURE', corr) : null; bump(); }
1554
+ return c;
1555
+ }
1556
+ if (m.type === 'CAPTURE_PASTED') {
1557
+ const c = await capturePasted(m);
1558
+ if (c.ok) { lastProblem = null; if (session?.source === 'NATIVE') { const p = await persistHeld(corr); lastProblem = p ? asDiag(p, 'CAPTURE_PASTED', corr) : null; } bump(); }
1559
+ return c;
1560
+ }
1561
+ if (m.type === 'DISPATCH') return await dispatchCapture(m, corr);
1562
+ if (m.type === 'PREPARE_RETURN') return await prepareReturn(m, corr);
1563
+ if (m.type === 'INSERT_RETURN') return await insertReturn(m, corr);
1564
+ if (m.type === 'RUN' || m.type === 'RUN_CODING' || m.type === 'RUN_TRUSTED_CODING') return await runSelected(m, corr);
1565
+ if (m.type === 'CODING_ACTION') return await codingCall(m, corr);
1566
+ if (m.type === 'REBIND_RETURN') return await rebindReturn(m, corr);
1567
+ if (m.type === 'SET_DEFAULT') return await setDefault(m, corr);
1568
+ if (m.type === 'DISMISS') return await dismiss(m, corr);
1569
+ if (m.type === 'REPAIR') return await repair(corr);
1570
+ if (m.type === 'APPROVE') return await decide(m.runId, 'approve', { approvalId: m.approvalId, approvalCode: m.approvalCode }, corr);
1571
+ return await decide(m.runId, 'cancel', { reason: m.reason }, corr);
1572
+ } finally {
1573
+ busy = false;
1574
+ }
1575
+ }
1576
+
1577
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
1578
+ handleMessage(message, sender).then(sendResponse, () => sendResponse(fail('INTERNAL_ERROR')));
1579
+ return true; // asynchronous response
1580
+ });
1581
+
1582
+ // The panel is opened from the toolbar action's onClicked handler, NOT with openPanelOnActionClick. Executing the action on a tab is what grants
1583
+ // activeTab for THAT tab (its url and one-shot scripting), and the extension holds no standing host permission for the capture origin. A panel
1584
+ // opened any other way (Chrome's side-panel menu) carries no grant, and CAPTURE then fails closed with TAB_ACCESS_NOT_GRANTED.
1585
+ try {
1586
+ void chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }).catch(() => undefined);
1587
+ chrome.action.onClicked.addListener((tab) => {
1588
+ if (typeof tab?.id !== 'number') return;
1589
+ // FIRST and synchronously: Chrome only honours sidePanel.open inside the user gesture. Then (SW-062) capture from the same gesture's activeTab grant.
1590
+ void chrome.sidePanel.open({ tabId: tab.id }).catch(() => undefined);
1591
+ toolbarCapture(tab.id);
1592
+ });
1593
+ } catch {
1594
+ /* sidePanel/action unavailable */
1595
+ }