@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,73 @@
1
+ import { z } from 'zod';
2
+ import { SchemaVersionV1Schema, PromptSnapshotIdSchema, ProjectIdSchema, } from './identity.js';
3
+ /**
4
+ * Prompt snapshot captured from ChatGPT Web conversation tab.
5
+ */
6
+ export const PromptSnapshotV1Schema = z.object({
7
+ schemaVersion: SchemaVersionV1Schema,
8
+ promptSnapshotId: PromptSnapshotIdSchema,
9
+ projectId: ProjectIdSchema,
10
+ conversationId: z.string().min(1),
11
+ turnIndex: z.number().int().nonnegative(),
12
+ rawPrompt: z.string().min(1),
13
+ capturedAt: z.string().datetime(),
14
+ selectionRange: z
15
+ .object({
16
+ start: z.number().int().nonnegative(),
17
+ end: z.number().int().nonnegative(),
18
+ })
19
+ .optional(),
20
+ });
21
+ /**
22
+ * Request contract for bounded project file retrieval.
23
+ */
24
+ export const BoundedFileRequestV1Schema = z.object({
25
+ schemaVersion: SchemaVersionV1Schema,
26
+ projectId: ProjectIdSchema,
27
+ relativePath: z.string().min(1),
28
+ maxBytes: z.number().int().positive().max(10 * 1024 * 1024), // 10MB bound
29
+ maxLines: z.number().int().positive().optional(),
30
+ encoding: z.enum(['utf-8', 'ascii', 'base64']).default('utf-8'),
31
+ });
32
+ /**
33
+ * Response contract for bounded project file retrieval.
34
+ */
35
+ export const BoundedFileResponseV1Schema = z.object({
36
+ schemaVersion: SchemaVersionV1Schema,
37
+ projectId: ProjectIdSchema,
38
+ relativePath: z.string().min(1),
39
+ canonicalPath: z.string().min(1),
40
+ sizeBytes: z.number().int().nonnegative(),
41
+ lineCount: z.number().int().nonnegative(),
42
+ truncated: z.boolean(),
43
+ content: z.string(),
44
+ sha256: z.string().regex(/^[a-f0-9]{64}$/i),
45
+ retrievedAt: z.string().datetime(),
46
+ });
47
+ /**
48
+ * Pure path containment boundary check.
49
+ * Invariant: Must compare canonical physical paths to prevent NTFS junction / symlink escapes.
50
+ */
51
+ export const assertPathContained = (canonicalRoot, canonicalTarget) => {
52
+ const normRoot = canonicalRoot.toLowerCase().replace(/\\/g, '/').replace(/\/+$/, '');
53
+ const normTarget = canonicalTarget.toLowerCase().replace(/\\/g, '/');
54
+ if (normTarget === normRoot || normTarget.startsWith(normRoot + '/')) {
55
+ return true;
56
+ }
57
+ throw new Error(`Security denial: Target path '${canonicalTarget}' escapes canonical project root '${canonicalRoot}'`);
58
+ };
59
+ /**
60
+ * Git Working Tree State Record (C07 Project Context & Git Service).
61
+ * Invariant: Captures truthful Git status, branch, and commit evidence without ungrounded claims.
62
+ */
63
+ export const GitWorkingTreeStateV1Schema = z.object({
64
+ schemaVersion: SchemaVersionV1Schema,
65
+ projectId: ProjectIdSchema,
66
+ branch: z.string().min(1),
67
+ headCommit: z.string().regex(/^[a-f0-9]{40}$/i),
68
+ clean: z.boolean(),
69
+ dirtyFiles: z.array(z.string()),
70
+ untrackedFiles: z.array(z.string()),
71
+ observedAt: z.string().datetime(),
72
+ });
73
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1,99 @@
1
+ /**
2
+ * SW-062: the ONE diagnostics vocabulary shared by the side panel, the service worker, the daemon HTTP transport and the operator console.
3
+ *
4
+ * - Structured event shape and levels.
5
+ * - Correlation id format + header name (one id follows a request from the panel through the worker into the daemon and back).
6
+ * - A single redaction/sanitising function. Everything that is written to a log, returned to the panel or exported goes through it.
7
+ * - The user-facing error guide: for every code, what it means and what to do next. The code itself is never replaced by a generic one.
8
+ *
9
+ * Pure functions only: no I/O, no Node or Chrome API besides the platform `crypto.getRandomValues`.
10
+ */
11
+ export declare const DIAG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"];
12
+ export type DiagLevel = (typeof DIAG_LEVELS)[number];
13
+ export declare const DIAG_LEVEL_RANK: Readonly<Record<DiagLevel, number>>;
14
+ export declare const CORRELATION_HEADER = "x-centcom-correlation-id";
15
+ export declare const CORRELATION_ID_PATTERN: RegExp;
16
+ export type DiagComponent = 'PANEL' | 'WORKER' | 'TRANSPORT' | 'DAEMON' | 'AUTH' | 'OPERATOR' | 'PROVISIONING' | 'RUN' | 'SNAPSHOT' | 'BRIDGE' | 'SETUP';
17
+ export type DiagOutcome = 'OK' | 'FAILED' | 'DENIED' | 'REFUSED' | 'STARTED';
18
+ export type DiagMetaValue = string | number | boolean | null;
19
+ export interface DiagEventV1 {
20
+ readonly ts: string;
21
+ readonly level: DiagLevel;
22
+ readonly component: DiagComponent;
23
+ readonly operation: string;
24
+ /** Stable machine-readable event or error code, e.g. PAIRING_DENIED. */
25
+ readonly event: string;
26
+ readonly correlationId?: string;
27
+ readonly outcome?: DiagOutcome;
28
+ readonly elapsedMs?: number;
29
+ readonly meta?: Readonly<Record<string, DiagMetaValue>>;
30
+ }
31
+ export declare function newCorrelationId(): string;
32
+ /** Returns the id when it is a well-formed correlation id, otherwise undefined (a foreign or hostile value is never trusted or logged). */
33
+ export declare const validCorrelationId: (v: unknown) => string | undefined;
34
+ export declare const META_MAX_KEYS = 16;
35
+ export declare const META_MAX_STRING = 200;
36
+ export declare const REDACTED = "[REDACTED]";
37
+ /** Scrubs one free-text value: bearer strings, long secret-looking tokens, filesystem paths. Bounded in length. */
38
+ export declare function redactText(input: string): string;
39
+ /** Reduces arbitrary metadata to a small flat record of primitives with secrets, content and paths removed. Never throws. */
40
+ export declare function redactMeta(meta: unknown): Record<string, DiagMetaValue>;
41
+ /** Builds a sanitised event. The component, operation and event are constrained to short code-like strings. */
42
+ export declare function makeDiagEvent(e: Omit<DiagEventV1, 'ts' | 'meta'> & {
43
+ ts?: string;
44
+ meta?: unknown;
45
+ }): DiagEventV1;
46
+ export declare const FIELD_REASONS: readonly ["MISSING", "EMPTY", "WRONG_TYPE", "BAD_FORMAT", "OUT_OF_RANGE", "TOO_LONG", "TOO_SHORT", "UNEXPECTED_FIELD", "NOT_ALLOWED"];
47
+ export type FieldReason = (typeof FIELD_REASONS)[number];
48
+ export interface FieldIssue {
49
+ readonly field: string;
50
+ readonly reason: FieldReason;
51
+ }
52
+ export declare const sanitizeFieldIssues: (v: unknown) => FieldIssue[];
53
+ export interface ErrorGuideEntry {
54
+ readonly component: DiagComponent;
55
+ readonly message: string;
56
+ readonly action: string;
57
+ }
58
+ /** Keyed by the stable code. Messages are fixed text (never daemon- or page-supplied). The code is always shown with them. */
59
+ export declare const ERROR_GUIDE: Readonly<Record<string, ErrorGuideEntry>>;
60
+ export interface FailureDetailV1 {
61
+ readonly operation: string;
62
+ readonly code: string;
63
+ readonly component: DiagComponent;
64
+ readonly message: string;
65
+ readonly action: string;
66
+ readonly correlationId?: string;
67
+ readonly fields?: readonly FieldIssue[];
68
+ readonly httpStatus?: number;
69
+ /** A short FIXED-vocabulary hint (never user data), e.g. WORKER_RESTARTED_SINCE_LAST_PAIRING. */
70
+ readonly note?: string;
71
+ }
72
+ export declare const COMPONENT_LABEL: Readonly<Record<DiagComponent, string>>;
73
+ /** Human operation names for each panel message type. */
74
+ export declare const OPERATION_LABELS: Readonly<Record<string, string>>;
75
+ /** Longest fixed-vocabulary note kept on a failure. A longer or non-conforming note is dropped, so producers order the most important token first. */
76
+ export declare const FAILURE_NOTE_MAX = 200;
77
+ export declare function formatDiagEvent(e: DiagEventV1): string;
78
+ export declare function describeFailure(input: {
79
+ operation: string;
80
+ code: string;
81
+ correlationId?: string;
82
+ fields?: readonly FieldIssue[];
83
+ httpStatus?: number;
84
+ component?: DiagComponent;
85
+ note?: string;
86
+ }): FailureDetailV1;
87
+ /** The first line is always `FAILED <CODE>` (stable for tooling); the following lines say what, who, why, next, and the correlation id. */
88
+ export declare function formatFailure(d: FailureDetailV1): string;
89
+ /** SW-097-R1: process facts are not workflow success or event categories. Only trusted C06 host lifecycle records count. */
90
+ export declare function describeObservedProcess(events: readonly {
91
+ component: string;
92
+ kind: string;
93
+ summary: string;
94
+ status: string;
95
+ }[], workflowState?: string): {
96
+ text: string;
97
+ evidence: string;
98
+ };
99
+ //# sourceMappingURL=diagnostics.d.ts.map
@@ -0,0 +1,284 @@
1
+ /**
2
+ * SW-062: the ONE diagnostics vocabulary shared by the side panel, the service worker, the daemon HTTP transport and the operator console.
3
+ *
4
+ * - Structured event shape and levels.
5
+ * - Correlation id format + header name (one id follows a request from the panel through the worker into the daemon and back).
6
+ * - A single redaction/sanitising function. Everything that is written to a log, returned to the panel or exported goes through it.
7
+ * - The user-facing error guide: for every code, what it means and what to do next. The code itself is never replaced by a generic one.
8
+ *
9
+ * Pure functions only: no I/O, no Node or Chrome API besides the platform `crypto.getRandomValues`.
10
+ */
11
+ export const DIAG_LEVELS = ['DEBUG', 'INFO', 'WARN', 'ERROR'];
12
+ export const DIAG_LEVEL_RANK = { DEBUG: 10, INFO: 20, WARN: 30, ERROR: 40 };
13
+ export const CORRELATION_HEADER = 'x-centcom-correlation-id';
14
+ export const CORRELATION_ID_PATTERN = /^corr\.[A-Za-z0-9_-]{8,40}$/;
15
+ const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
16
+ export function newCorrelationId() {
17
+ const bytes = new Uint8Array(12);
18
+ globalThis.crypto.getRandomValues(bytes);
19
+ let out = '';
20
+ for (let i = 0; i < bytes.length; i += 3) { // 12 bytes -> 16 base64url characters, no padding, no btoa dependency
21
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
22
+ out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63] + B64URL[(n >> 6) & 63] + B64URL[n & 63];
23
+ }
24
+ return `corr.${out}`;
25
+ }
26
+ /** Returns the id when it is a well-formed correlation id, otherwise undefined (a foreign or hostile value is never trusted or logged). */
27
+ export const validCorrelationId = (v) => (typeof v === 'string' && CORRELATION_ID_PATTERN.test(v) ? v : undefined);
28
+ // ---------------------------------------------------------------------------
29
+ // Redaction
30
+ // ---------------------------------------------------------------------------
31
+ /** Keys whose VALUE is never recorded, whatever it looks like (secrets, challenge/approval codes, conversation or prompt content, credentials). */
32
+ const SENSITIVE_KEY = /^(code|pairingcode|approvalcode|approval_code|bearer|bearertoken|token|accesstoken|secret|password|passwd|authorization|cookie|credential|credentials|prompt|text|body|content|message|selection|reason_text|apikey|api_key|key)$/i;
33
+ const SAFE_ID_WORD = /^(corr|run|req|chal|prin|grant|cap|ret|idem|appr|project|plugin|op)[.:][A-Za-z0-9._-]{1,128}$/;
34
+ const HEX_DIGEST = /^[a-f0-9]{64}$/;
35
+ const LONG_TOKEN = /[A-Za-z0-9_-]{24,}/;
36
+ const WIN_PATH = /[A-Za-z]:[\\/][^\s"'<>|]*/g;
37
+ const UNC_OR_POSIX_HOME = /(?:\\\\[^\s\\]+\\[^\s"'<>|]*|\/(?:home|Users|root|tmp|var|etc)\/[^\s"'<>|]*)/g;
38
+ const BEARER_VALUE = /\bBearer\s+\S+/gi;
39
+ export const META_MAX_KEYS = 16;
40
+ export const META_MAX_STRING = 200;
41
+ export const REDACTED = '[REDACTED]';
42
+ /** Scrubs one free-text value: bearer strings, long secret-looking tokens, filesystem paths. Bounded in length. */
43
+ export function redactText(input) {
44
+ let s = input.replace(BEARER_VALUE, `Bearer ${REDACTED}`).replace(WIN_PATH, '<path>').replace(UNC_OR_POSIX_HOME, '<path>');
45
+ s = s.split(/(\s+)/).map((w) => (/^\s+$/.test(w) || SAFE_ID_WORD.test(w) || HEX_DIGEST.test(w) || !LONG_TOKEN.test(w) ? w : REDACTED)).join('');
46
+ return s.length > META_MAX_STRING ? `${s.slice(0, META_MAX_STRING)}…` : s;
47
+ }
48
+ /** Reduces arbitrary metadata to a small flat record of primitives with secrets, content and paths removed. Never throws. */
49
+ export function redactMeta(meta) {
50
+ const out = {};
51
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta))
52
+ return out;
53
+ let n = 0;
54
+ for (const [k, v] of Object.entries(meta)) {
55
+ if (n >= META_MAX_KEYS) {
56
+ out._truncated = true;
57
+ break;
58
+ }
59
+ const key = k.slice(0, 48);
60
+ if (SENSITIVE_KEY.test(key)) {
61
+ out[key] = REDACTED;
62
+ n += 1;
63
+ continue;
64
+ }
65
+ if (typeof v === 'string')
66
+ out[key] = redactText(v);
67
+ else if (typeof v === 'number')
68
+ out[key] = Number.isFinite(v) ? v : null;
69
+ else if (typeof v === 'boolean' || v === null)
70
+ out[key] = v;
71
+ else if (v === undefined)
72
+ continue;
73
+ else if (Array.isArray(v))
74
+ out[key] = redactText(v.filter((x) => typeof x === 'string' || typeof x === 'number').slice(0, 8).join(','));
75
+ else
76
+ out[key] = '[OBJECT]';
77
+ n += 1;
78
+ }
79
+ return out;
80
+ }
81
+ /** Builds a sanitised event. The component, operation and event are constrained to short code-like strings. */
82
+ export function makeDiagEvent(e) {
83
+ const code = (s) => String(s).replace(/[^A-Za-z0-9_.:-]/g, '_').slice(0, 64);
84
+ const route = (s) => String(s).replace(/[^A-Za-z0-9_.:/ -]/g, '_').slice(0, 64); // an operation may be "POST /v1/runs/:runId/status"
85
+ const meta = e.meta === undefined ? undefined : redactMeta(e.meta);
86
+ return {
87
+ ts: e.ts ?? new Date().toISOString(),
88
+ level: e.level,
89
+ component: e.component,
90
+ operation: route(e.operation),
91
+ event: code(e.event),
92
+ ...(validCorrelationId(e.correlationId) ? { correlationId: e.correlationId } : {}),
93
+ ...(e.outcome ? { outcome: e.outcome } : {}),
94
+ ...(typeof e.elapsedMs === 'number' && Number.isFinite(e.elapsedMs) ? { elapsedMs: Math.max(0, Math.round(e.elapsedMs)) } : {}),
95
+ ...(meta && Object.keys(meta).length > 0 ? { meta } : {}),
96
+ };
97
+ }
98
+ // ---------------------------------------------------------------------------
99
+ // Field-level validation detail (safe: field names and a fixed reason vocabulary only, never a received value)
100
+ // ---------------------------------------------------------------------------
101
+ export const FIELD_REASONS = ['MISSING', 'EMPTY', 'WRONG_TYPE', 'BAD_FORMAT', 'OUT_OF_RANGE', 'TOO_LONG', 'TOO_SHORT', 'UNEXPECTED_FIELD', 'NOT_ALLOWED'];
102
+ const FIELD_NAME = /^[A-Za-z0-9_.[\]]{1,64}$/;
103
+ export const sanitizeFieldIssues = (v) => {
104
+ if (!Array.isArray(v))
105
+ return [];
106
+ const out = [];
107
+ for (const x of v.slice(0, 8)) {
108
+ const f = x?.field;
109
+ const r = x?.reason;
110
+ if (typeof f === 'string' && FIELD_NAME.test(f) && typeof r === 'string' && FIELD_REASONS.includes(r))
111
+ out.push({ field: f, reason: r });
112
+ }
113
+ return out;
114
+ };
115
+ const G = (component, message, action) => ({ component, message, action });
116
+ /** Keyed by the stable code. Messages are fixed text (never daemon- or page-supplied). The code is always shown with them. */
117
+ export const ERROR_GUIDE = {
118
+ INVALID_FIELD: G('WORKER', 'A field in the request is missing or malformed (see the named fields).', 'Correct the named field(s) and retry. Copy only the bare value, not a label such as "code=" or "challenge-id=".'),
119
+ INVALID_REQUEST: G('WORKER', 'The side panel sent a request the service worker does not recognise.', 'Reload the extension and the side panel. If it persists, export diagnostics and report the correlation id.'),
120
+ SENDER_DENIED: G('WORKER', 'The service worker refused the caller: only the extension side panel may drive it.', 'Open the panel from the toolbar icon; do not use a copy of the page.'),
121
+ NOT_PAIRED: G('WORKER', 'The extension has no active pairing with the daemon (never paired, expired, or the service worker restarted and lost it).', 'Issue a fresh pair code in the daemon operator console (pair <extension-id>) and pair again.'),
122
+ BUSY: G('WORKER', 'Another action is still running in the service worker.', 'Wait for it to finish, then retry once.'),
123
+ DAEMON_UNREACHABLE: G('TRANSPORT', 'The extension could not connect to the daemon at the entered port.', 'Check the daemon is running and that the port equals the one it printed ("listening at http://127.0.0.1:<port>").'),
124
+ DAEMON_TIMEOUT: G('TRANSPORT', 'The daemon did not answer in time.', 'Check the daemon process is responsive, then retry.'),
125
+ UNEXPECTED_RESPONSE: G('TRANSPORT', 'The endpoint answered, but not with a my-centcom daemon response.', 'Confirm the port belongs to the my-centcom daemon (not another local program) and that the extension and daemon are the same version.'),
126
+ VALIDATION_FAILED: G('DAEMON', 'The daemon rejected the request fields (see the named fields).', 'Correct the named field(s) and retry; if none are named, export diagnostics.'),
127
+ PAYLOAD_TOO_LARGE: G('DAEMON', 'The request is larger than the daemon accepts.', 'Shorten the text and retry.'),
128
+ UNAUTHENTICATED: G('AUTH', 'The daemon no longer accepts this extension session (token expired, revoked, or the daemon was reset).', 'Pair again with a fresh code.'),
129
+ ORIGIN_DENIED: G('AUTH', 'The daemon does not recognise this extension identity for the request.', 'Make sure the daemon was paired from this same extension (the extension id in "pair <id>" must match chrome://extensions).'),
130
+ PAIRING_DENIED: G('AUTH', 'The daemon did not accept this pairing attempt. The code may be expired, already used, mistyped, or issued for another extension.', 'Issue a new code in the operator console for THIS extension id and pair within its lifetime. (The daemon deliberately does not say which.)'),
131
+ GRANT_DENIED: G('AUTH', 'This pairing has no current grant for that project/plugin/operation.', 'In the operator console run: grant <principal-id> <plugin> <operation>.'),
132
+ DENIED: G('AUTH', 'The daemon denied the request.', 'Check the operator console for the matching correlation id.'),
133
+ APPROVAL_DENIED: G('AUTH', 'The approval id/code was not accepted (wrong, expired or already used).', 'Issue a new approval in the operator console (approve <run-id>) and enter it exactly.'),
134
+ NOT_FOUND: G('DAEMON', 'The daemon does not know that run (or it belongs to another pairing).', 'Check the run id; re-run Prepare if needed.'),
135
+ STATE_CONFLICT: G('RUN', 'The run is not in a state that allows this action.', 'Check run status first.'),
136
+ RETURN_NOT_AVAILABLE: G('SNAPSHOT', 'That run has no final result to return yet.', 'Wait until the run is COMPLETED, then prepare the return.'),
137
+ RETURN_CONFLICT: G('SNAPSHOT', 'A different return snapshot already exists for that run.', 'Use the existing snapshot; do not re-prepare.'),
138
+ SERVER_ERROR: G('DAEMON', 'The daemon failed internally while handling the request.', 'Look up the correlation id in the daemon log (see Diagnostics) and report it.'),
139
+ INTERNAL_ERROR: G('WORKER', 'An unexpected internal failure occurred (not a validation or permission problem).', 'Export diagnostics and report the correlation id.'),
140
+ WORKER_UNAVAILABLE: G('PANEL', 'The side panel could not reach the extension service worker.', 'Reload the extension in chrome://extensions and reopen the panel.'),
141
+ NO_USER_ACTION: G('WORKER', 'The action needs a real click in the panel.', 'Click the button yourself.'),
142
+ TAB_UNAVAILABLE: G('WORKER', 'The target browser tab no longer exists.', 'Switch to the conversation tab and retry.'),
143
+ TAB_NOT_ACTIVE: G('WORKER', 'The target tab is not the active tab.', 'Bring the conversation tab to the front and retry.'),
144
+ TAB_ACCESS_NOT_GRANTED: G('WORKER', 'Chrome has not given the extension access to this tab (no activeTab grant, or the tab is on a site the extension may not read).', 'Open the https://chatgpt.com conversation tab, close the panel, then click the my-centcom toolbar icon while that tab is active.'),
145
+ ORIGIN_NOT_ALLOWED: G('WORKER', 'The active tab is not on the allowed site.', 'Open the https://chatgpt.com conversation tab and retry.'),
146
+ CAPTURE_NOT_PERMITTED: G('WORKER', 'Chrome refused script access to the page, or the page answered unexpectedly.', 'Click the toolbar icon on the conversation tab to re-grant access, then retry.'),
147
+ EMPTY_SELECTION: G('SNAPSHOT', 'Nothing is selected on the page.', 'Select the message text and click the toolbar icon again, or copy the message with ChatGPT\'s Copy button and use "Paste copied text" in this panel.'),
148
+ AMBIGUOUS_SELECTION: G('SNAPSHOT', 'The selection spans several separate ranges.', 'Select one continuous passage.'),
149
+ EDITABLE_SELECTION: G('SNAPSHOT', 'The selection is inside an editable field.', 'Select text from a rendered message instead.'),
150
+ HIDDEN_SELECTION: G('SNAPSHOT', 'The selection is hidden.', 'Select visible text.'),
151
+ NOT_TOP_FRAME: G('SNAPSHOT', 'The selection is inside an embedded frame.', 'Select text in the main conversation.'),
152
+ SELECTION_TOO_LARGE: G('SNAPSHOT', 'The selection exceeds the size limit.', 'Select a shorter passage.'),
153
+ NO_CAPTURE: G('SNAPSHOT', 'There is no captured selection to dispatch.', 'Capture again.'),
154
+ CAPTURE_EXPIRED: G('SNAPSHOT', 'The captured selection expired.', 'Capture again.'),
155
+ TAB_CHANGED: G('SNAPSHOT', 'The tab or page changed since the capture.', 'Capture again on the current page.'),
156
+ DOCUMENT_CHANGED: G('SNAPSHOT', 'The page document changed since the capture.', 'Capture again.'),
157
+ SELECTION_CHANGED: G('SNAPSHOT', 'The selection changed since the capture.', 'Re-select and capture again.'),
158
+ ALREADY_DISPATCHED: G('SNAPSHOT', 'That capture was already sent.', 'Capture again for a new request.'),
159
+ NO_ORIGIN_BINDING: G('SNAPSHOT', 'The worker does not remember which tab this run came from (it restarted, or the run began elsewhere).', 'Return the result manually; the panel will not insert it into an unknown tab.'),
160
+ NO_RETURN: G('SNAPSHOT', 'There is no prepared return to insert.', 'Prepare the return first.'),
161
+ RETURN_EXPIRED: G('SNAPSHOT', 'The prepared return expired.', 'Prepare the return again.'),
162
+ ALREADY_INSERTED: G('SNAPSHOT', 'That return was already inserted.', 'Nothing to do.'),
163
+ RETURN_CHANGED: G('SNAPSHOT', 'The returned text no longer matches what was previewed.', 'Prepare the return again.'),
164
+ INSERT_NOT_PERMITTED: G('SNAPSHOT', 'Chrome refused script access to the originating tab.', 'Click the toolbar icon on that tab to re-grant access, then retry.'),
165
+ COMPOSER_UNAVAILABLE: G('SNAPSHOT', 'The message box was not found on the page.', 'Open the original conversation and retry, or click Copy Result and paste it yourself (Ctrl+V).'),
166
+ COMPOSER_AMBIGUOUS: G('SNAPSHOT', 'More than one message box matched, so the extension did not guess which one to write to.', 'Close extra editors (for example an open message edit) and retry, or click Copy Result and paste it yourself.'),
167
+ COMPOSER_UNSUPPORTED: G('SNAPSHOT', 'The message box is of a type the extension cannot safely write to.', 'Click Copy Result, then paste it into the message box yourself (Ctrl+V). Nothing was sent.'),
168
+ COMPOSER_NOT_EMPTY: G('SNAPSHOT', 'The message box already contains text; nothing was overwritten.', 'Clear the message box and retry, or click Copy Result and paste it where you want it.'),
169
+ READBACK_MISMATCH: G('SNAPSHOT', 'The page did not keep the inserted text exactly, so the extension did not claim it was inserted (see Detail for whether the message box was restored).', 'Click Copy Result, then paste it into the message box yourself (Ctrl+V). The result is kept; nothing was sent and the operation is not run again.'),
170
+ INSERT_FAILED: G('SNAPSHOT', 'Inserting into the message box failed.', 'Click Copy Result, then paste it into the message box yourself (Ctrl+V). Nothing was sent.'),
171
+ // SW-065 explicit clipboard input/output. The extension never reads the clipboard by itself: input is only what the user pastes into the panel.
172
+ PASTE_EMPTY: G('PANEL', 'The paste contained no text.', 'Copy the message with ChatGPT\'s Copy button, click into the paste box and press Ctrl+V.'),
173
+ PASTE_NO_PLAIN_TEXT: G('PANEL', 'The paste contained no plain text (only another format such as HTML or an image), so nothing was used.', 'Copy the message with ChatGPT\'s Copy button (it provides plain text), then paste again.'),
174
+ PASTE_TOO_LARGE: G('PANEL', 'The pasted text exceeds the size limit.', 'Copy a shorter passage and paste again.'),
175
+ CLIPBOARD_WRITE_DENIED: G('PANEL', 'The browser refused to write to the clipboard (permission denied, or the panel did not have focus). Nothing was copied.', 'Click into the panel and click Copy Result again, or select the result text above and press Ctrl+C.'),
176
+ CLIPBOARD_UNAVAILABLE: G('PANEL', 'This browser offers no clipboard writing to the panel. Nothing was copied.', 'Select the result text above and press Ctrl+C.'),
177
+ MALFORMED_REQUEST: G('DAEMON', 'The daemon could not parse the request body.', 'Reload the extension; if it persists export diagnostics.'),
178
+ // SW-062 integrated automation: one actionable message per connection failure (never a raw id dump).
179
+ NATIVE_HOST_MISSING: G('BRIDGE', 'my-centcom is not installed for this browser profile (the local connection helper is not registered).', 'Run the one-time setup (npm run centcom -- install ...), then click Repair connection.'),
180
+ NATIVE_HOST_FORBIDDEN: G('BRIDGE', 'The local connection helper is registered for a different extension identity.', 'Re-run setup so the helper and this extension are installed together (npm run centcom -- install ...).'),
181
+ NATIVE_HOST_FAILED: G('BRIDGE', 'The local connection helper could not be started or answered unexpectedly.', 'Click Repair connection; if it persists run npm run centcom -- selftest and report its correlation id.'),
182
+ HOST_ORIGIN_MISMATCH: G('BRIDGE', 'The local connection helper refused this extension identity.', 'Re-run setup for this extension (npm run centcom -- install ...).'),
183
+ HOST_NOT_INSTALLED: G('BRIDGE', 'The local connection helper has no installation record.', 'Run the one-time setup (npm run centcom -- install ...).'),
184
+ HOST_CONFIG_INVALID: G('BRIDGE', 'The local installation record is unreadable.', 'Re-run setup (npm run centcom -- update).'),
185
+ HOST_CONFIG_TAMPERED: G('BRIDGE', 'The local installation record failed its integrity check, so nothing was started.', 'Re-run setup (npm run centcom -- update) and review what changed.'),
186
+ INSTALL_INTEGRITY_FAILED: G('BRIDGE', 'The installed daemon files differ from the pinned installation, so nothing was started.', 'If you updated my-centcom on purpose, run npm run centcom -- update to re-pin it; otherwise investigate before continuing.'),
187
+ UPDATE_REQUIRES_RECONSENT: G('BRIDGE', 'my-centcom was updated; the new version must be confirmed once before it runs.', 'Run npm run centcom -- update (your existing grants are kept, never widened).'),
188
+ INSTALLATION_REVOKED: G('BRIDGE', 'This installation was revoked.', 'Run the setup again if you want to use my-centcom on this profile.'),
189
+ DAEMON_START_FAILED: G('BRIDGE', 'The local daemon could not be started.', 'Run npm run centcom -- selftest; it names the failing stage.'),
190
+ DAEMON_NOT_RESPONDING: G('BRIDGE', 'The local daemon did not answer.', 'Click Repair connection; if it persists run npm run centcom -- selftest.'),
191
+ SESSION_REFUSED: G('BRIDGE', 'The daemon refused to open a session for this installation.', 'Run npm run centcom -- selftest; re-run setup if the installation was revoked.'),
192
+ HOST_MESSAGE_INVALID: G('BRIDGE', 'The local connection helper rejected the request format.', 'Reload the extension; the extension and helper must be the same version.'),
193
+ HOST_MESSAGE_TOO_LARGE: G('BRIDGE', 'The local connection helper rejected an oversized request.', 'Reload the extension.'),
194
+ HOST_CONFIG_UNAVAILABLE: G('BRIDGE', 'The local installation record could not be read.', 'Re-run setup (npm run centcom -- update).'),
195
+ HOST_INTERNAL_ERROR: G('BRIDGE', 'The local connection helper failed internally.', 'Run npm run centcom -- selftest and report its correlation id.'),
196
+ CAPTURE_NOT_FOUND: G('SNAPSHOT', 'The captured selection is no longer held by the daemon (expired or replaced).', 'Select the text again and click the toolbar icon.'),
197
+ CAPTURE_CONFLICT: G('SNAPSHOT', 'That capture was already used for a different operation.', 'Select the text again and click the toolbar icon for a new run.'),
198
+ RETURN_STALE: G('SNAPSHOT', 'The original conversation tab or page changed, so the result was not inserted there.', 'Open the conversation where you want the draft, click the toolbar icon there, then choose "Use this tab" (the run is not repeated).'),
199
+ RUN_NOT_RUNNABLE: G('RUN', 'This run cannot be started from here (it ended, or its state is uncertain).', 'Review the status shown; an UNKNOWN run is never started again automatically.'),
200
+ RISK_APPROVAL_REQUIRED: G('RUN', 'This operation needs a separate local confirmation before it runs.', 'Confirm it on this computer: npm run centcom -- confirm'),
201
+ OPERATION_NOT_SELECTED: G('PANEL', 'No approved operation is selected.', 'Choose one of the approved operations, then click Run.'),
202
+ };
203
+ const FALLBACK_GUIDE = G('WORKER', 'The operation failed with a code this panel does not know.', 'Export diagnostics and report the code and correlation id.');
204
+ export const COMPONENT_LABEL = {
205
+ PANEL: 'side panel', WORKER: 'extension service worker', TRANSPORT: 'browser-to-daemon connection', DAEMON: 'daemon',
206
+ AUTH: 'daemon authorization', OPERATOR: 'operator console', PROVISIONING: 'plugin provisioning', RUN: 'daemon run lifecycle', SNAPSHOT: 'snapshot / composer workflow',
207
+ BRIDGE: 'local connection helper', SETUP: 'setup / self-test',
208
+ };
209
+ /** Human operation names for each panel message type. */
210
+ export const OPERATION_LABELS = {
211
+ PAIR: 'Pairing with the daemon', PREPARE: 'Preparing a run', CAPTURE: 'Capturing the selection', GET_CAPTURE: 'Reading the captured selection', DISPATCH: 'Sending the captured selection',
212
+ PREPARE_RETURN: 'Preparing the result for return', GET_RETURN: 'Reading the prepared result', INSERT_RETURN: 'Inserting the result into the composer',
213
+ GET_STATUS: 'Reading run status', APPROVE: 'Approving the run', CANCEL: 'Cancelling the run', DISCONNECT: 'Disconnecting', GET_DIAGNOSTICS: 'Reading diagnostics',
214
+ GET_WORKFLOW: 'Reading the current workflow', RUN: 'Running the selected operation', REBIND_RETURN: 'Using this tab for the result', SET_DEFAULT: 'Saving the default operation',
215
+ REPAIR: 'Repairing the connection', DISMISS: 'Starting over', CONNECT: 'Connecting to the local daemon',
216
+ COPY_RETURN: 'Copying the result to the clipboard', CAPTURE_PASTED: 'Using the pasted text',
217
+ };
218
+ /** Longest fixed-vocabulary note kept on a failure. A longer or non-conforming note is dropped, so producers order the most important token first. */
219
+ export const FAILURE_NOTE_MAX = 200;
220
+ export function formatDiagEvent(e) {
221
+ const meta = e.meta ? ` ${Object.entries(e.meta).map(([k, v]) => `${k}=${String(v)}`).join(' ')}` : '';
222
+ return `${e.ts} ${e.level} ${e.component}/${e.operation} ${e.event}${e.outcome ? ` outcome=${e.outcome}` : ''}${typeof e.elapsedMs === 'number' ? ` ms=${e.elapsedMs}` : ''}${e.correlationId ? ` corr=${e.correlationId}` : ''}${meta}`;
223
+ }
224
+ export function describeFailure(input) {
225
+ const g = ERROR_GUIDE[input.code] ?? FALLBACK_GUIDE;
226
+ const fields = input.fields && input.fields.length > 0 ? input.fields : undefined;
227
+ return {
228
+ operation: input.operation,
229
+ code: input.code,
230
+ component: input.component ?? g.component,
231
+ message: g.message,
232
+ action: g.action,
233
+ ...(input.correlationId ? { correlationId: input.correlationId } : {}),
234
+ ...(fields ? { fields } : {}),
235
+ ...(typeof input.httpStatus === 'number' ? { httpStatus: input.httpStatus } : {}),
236
+ ...(input.note && input.note.length <= FAILURE_NOTE_MAX && /^[A-Z0-9_=:. -]+$/.test(input.note) ? { note: input.note } : {}),
237
+ };
238
+ }
239
+ /** The first line is always `FAILED <CODE>` (stable for tooling); the following lines say what, who, why, next, and the correlation id. */
240
+ export function formatFailure(d) {
241
+ const lines = [`FAILED ${d.code}`, `${d.operation} failed (reported by: ${COMPONENT_LABEL[d.component] ?? d.component}${typeof d.httpStatus === 'number' ? `, HTTP ${d.httpStatus}` : ''}).`, d.message];
242
+ if (d.fields && d.fields.length > 0)
243
+ lines.push(`Fields: ${d.fields.map((f) => `${f.field} (${f.reason})`).join(', ')}`);
244
+ if (d.note)
245
+ lines.push(`Detail: ${d.note}`);
246
+ lines.push(`Next: ${d.action}`);
247
+ if (d.correlationId)
248
+ lines.push(`Correlation id: ${d.correlationId}`);
249
+ return lines.join('\n');
250
+ }
251
+ /** SW-097-R1: process facts are not workflow success or event categories. Only trusted C06 host lifecycle records count. */
252
+ export function describeObservedProcess(events, workflowState) {
253
+ const facts = events.filter(e => e.component === 'C06' && e.kind === 'LIFECYCLE');
254
+ const settled = [...facts].reverse().find(e => /^HOST_SETTLED\b/.test(e.summary));
255
+ const exited = [...facts].reverse().find(e => /^PROCESS_EXITED\b/.test(e.summary));
256
+ const field = (text, key) => new RegExp('(?:^|\\s)' + key + '=([A-Za-z0-9_-]+)').exec(text)?.[1];
257
+ const event = settled ?? exited, evidence = event?.status ?? 'UNKNOWN';
258
+ if (event) {
259
+ const outcome = settled ? field(settled.summary, 'outcome') : 'EXITED';
260
+ const raw = field(event.summary, settled ? 'exitCode' : 'code'), exit = raw && /^-?\d+$/.test(raw) && Number.isSafeInteger(Number(raw)) ? Number(raw) : null;
261
+ const rawSignal = field(event.summary, 'signal'), signal = rawSignal && /^(SIG[A-Z0-9]+|[0-9]+)$/.test(rawSignal) ? rawSignal : null;
262
+ const detail = exit !== null ? ` - exit code ${exit}` : signal ? ` - signal ${signal}` : '';
263
+ if (outcome === 'TIMEOUT')
264
+ return { text: 'Timed out' + detail, evidence };
265
+ if (outcome === 'CANCELLED')
266
+ return { text: 'Cancelled' + detail, evidence };
267
+ if (outcome === 'EXITED')
268
+ return { text: (exit === 0 ? 'Completed' : exit !== null ? 'Failed' : signal ? 'Terminated' : 'Exited - code unavailable') + detail, evidence };
269
+ if (['SPAWN_FAILED', 'OUTPUT_LIMIT_EXCEEDED', 'SUPERVISION_FAILED'].includes(outcome ?? ''))
270
+ return { text: { SPAWN_FAILED: 'Launch failed', OUTPUT_LIMIT_EXCEEDED: 'Output limit exceeded', SUPERVISION_FAILED: 'Supervision failed' }[outcome] + detail, evidence };
271
+ }
272
+ const launchFailure = [...facts].reverse().find(e => /^FAILED_NOT_LAUNCHED\b/.test(e.summary));
273
+ if (launchFailure)
274
+ return { text: 'Launch failed - process not started', evidence: launchFailure.status };
275
+ if (['COMPLETED', 'FAILED', 'CANCELLED', 'UNKNOWN'].includes(workflowState ?? ''))
276
+ return { text: 'Unknown - no observed process outcome', evidence: 'UNKNOWN' };
277
+ if (workflowState === 'CANCEL_REQUESTED')
278
+ return { text: 'Cancellation requested - process outcome pending', evidence: 'UNKNOWN' };
279
+ const started = [...facts].reverse().find(e => /^PROCESS_(SPAWNED|STARTED)\b/.test(e.summary));
280
+ if (started)
281
+ return { text: 'Running - process observed', evidence: started.status };
282
+ return { text: 'Not started - no observed process', evidence: workflowState ? 'UNKNOWN' : 'OBSERVED' };
283
+ }
284
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Bounded effect classes for all plugin operations.
4
+ * Invariant: Every operation must be classified into one of these explicit categories.
5
+ */
6
+ export declare const EffectClassSchema: z.ZodEnum<{
7
+ read: "read";
8
+ write_project: "write_project";
9
+ external_network: "external_network";
10
+ destructive: "destructive";
11
+ }>;
12
+ export type EffectClass = z.infer<typeof EffectClassSchema>;
13
+ /**
14
+ * Effective security tier for process and filesystem containment.
15
+ * Invariant: OS_ENFORCED must not be claimed unless kernel/OS containment is implemented and verified.
16
+ */
17
+ export declare const SecurityTierSchema: z.ZodEnum<{
18
+ PATH_CHECKS_ONLY: "PATH_CHECKS_ONLY";
19
+ OS_ENFORCED: "OS_ENFORCED";
20
+ }>;
21
+ export type SecurityTier = z.infer<typeof SecurityTierSchema>;
22
+ /**
23
+ * Policy governing child process execution for command and agent plugins.
24
+ * Invariant: Arbitrary shell-string passthrough is strictly forbidden (allowShell must be false).
25
+ */
26
+ export declare const ExecutablePolicyV1Schema: z.ZodObject<{
27
+ executable: z.ZodString;
28
+ args: z.ZodArray<z.ZodString>;
29
+ allowShell: z.ZodLiteral<false>;
30
+ windowsHide: z.ZodLiteral<true>;
31
+ stdio: z.ZodTuple<[z.ZodLiteral<"ignore">, z.ZodLiteral<"pipe">, z.ZodLiteral<"pipe">], null>;
32
+ }, z.core.$strip>;
33
+ export type ExecutablePolicyV1 = z.infer<typeof ExecutablePolicyV1Schema>;
34
+ /**
35
+ * Output boundary constraints to protect memory and storage bounds.
36
+ */
37
+ export declare const OutputBoundsV1Schema: z.ZodObject<{
38
+ maxOutputBytes: z.ZodNumber;
39
+ maxLineCount: z.ZodOptional<z.ZodNumber>;
40
+ }, z.core.$strip>;
41
+ export type OutputBoundsV1 = z.infer<typeof OutputBoundsV1Schema>;
42
+ //# sourceMappingURL=effects.d.ts.map
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Bounded effect classes for all plugin operations.
4
+ * Invariant: Every operation must be classified into one of these explicit categories.
5
+ */
6
+ export const EffectClassSchema = z.enum([
7
+ 'read',
8
+ 'write_project',
9
+ 'external_network',
10
+ 'destructive',
11
+ ]);
12
+ /**
13
+ * Effective security tier for process and filesystem containment.
14
+ * Invariant: OS_ENFORCED must not be claimed unless kernel/OS containment is implemented and verified.
15
+ */
16
+ export const SecurityTierSchema = z.enum([
17
+ 'PATH_CHECKS_ONLY',
18
+ 'OS_ENFORCED',
19
+ ]);
20
+ /**
21
+ * Policy governing child process execution for command and agent plugins.
22
+ * Invariant: Arbitrary shell-string passthrough is strictly forbidden (allowShell must be false).
23
+ */
24
+ export const ExecutablePolicyV1Schema = z.object({
25
+ executable: z.string().min(1),
26
+ args: z.array(z.string()),
27
+ allowShell: z.literal(false),
28
+ windowsHide: z.literal(true),
29
+ stdio: z.tuple([
30
+ z.literal('ignore'),
31
+ z.literal('pipe'),
32
+ z.literal('pipe'),
33
+ ]),
34
+ });
35
+ /**
36
+ * Output boundary constraints to protect memory and storage bounds.
37
+ */
38
+ export const OutputBoundsV1Schema = z.object({
39
+ maxOutputBytes: z.number().int().positive().max(50 * 1024 * 1024), // 50MB upper limit
40
+ maxLineCount: z.number().int().positive().optional(),
41
+ });
42
+ //# sourceMappingURL=effects.js.map
@@ -0,0 +1,75 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Normalized transport and operational error codes.
4
+ * Invariant: Never mix transport failure, process outcome, and implementation validation into one status.
5
+ */
6
+ export declare const ContractErrorCodeSchema: z.ZodEnum<{
7
+ CANCELLED: "CANCELLED";
8
+ TIMEOUT: "TIMEOUT";
9
+ UNSUPPORTED_PROTOCOL_VERSION: "UNSUPPORTED_PROTOCOL_VERSION";
10
+ INVALID_PAYLOAD: "INVALID_PAYLOAD";
11
+ MISSING_OR_INVALID_AUTHORIZATION: "MISSING_OR_INVALID_AUTHORIZATION";
12
+ UNAUTHORIZED_PROJECT_OR_OPERATION: "UNAUTHORIZED_PROJECT_OR_OPERATION";
13
+ STALE_REQUEST_OR_SELECTION: "STALE_REQUEST_OR_SELECTION";
14
+ OFFLINE_OR_UNAVAILABLE_SERVICE: "OFFLINE_OR_UNAVAILABLE_SERVICE";
15
+ DUPLICATE_OR_CONFLICTING_INVOCATION: "DUPLICATE_OR_CONFLICTING_INVOCATION";
16
+ DUPLICATE_REQUEST: "DUPLICATE_REQUEST";
17
+ IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT";
18
+ WORKTREE_BUSY: "WORKTREE_BUSY";
19
+ NATIVE_CLI_FAILURE: "NATIVE_CLI_FAILURE";
20
+ UNKNOWN_PROCESS_OUTCOME: "UNKNOWN_PROCESS_OUTCOME";
21
+ CONTENT_BOUNDS_OR_PATH_DENIAL: "CONTENT_BOUNDS_OR_PATH_DENIAL";
22
+ INTERNAL_ERROR: "INTERNAL_ERROR";
23
+ }>;
24
+ export type ContractErrorCode = z.infer<typeof ContractErrorCodeSchema>;
25
+ /**
26
+ * Structured transport error contract.
27
+ * Invariant: Preserves correlation identity and explicit error categorization.
28
+ */
29
+ export declare const ContractErrorV1Schema: z.ZodObject<{
30
+ schemaVersion: z.ZodLiteral<1>;
31
+ errorCode: z.ZodEnum<{
32
+ CANCELLED: "CANCELLED";
33
+ TIMEOUT: "TIMEOUT";
34
+ UNSUPPORTED_PROTOCOL_VERSION: "UNSUPPORTED_PROTOCOL_VERSION";
35
+ INVALID_PAYLOAD: "INVALID_PAYLOAD";
36
+ MISSING_OR_INVALID_AUTHORIZATION: "MISSING_OR_INVALID_AUTHORIZATION";
37
+ UNAUTHORIZED_PROJECT_OR_OPERATION: "UNAUTHORIZED_PROJECT_OR_OPERATION";
38
+ STALE_REQUEST_OR_SELECTION: "STALE_REQUEST_OR_SELECTION";
39
+ OFFLINE_OR_UNAVAILABLE_SERVICE: "OFFLINE_OR_UNAVAILABLE_SERVICE";
40
+ DUPLICATE_OR_CONFLICTING_INVOCATION: "DUPLICATE_OR_CONFLICTING_INVOCATION";
41
+ DUPLICATE_REQUEST: "DUPLICATE_REQUEST";
42
+ IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT";
43
+ WORKTREE_BUSY: "WORKTREE_BUSY";
44
+ NATIVE_CLI_FAILURE: "NATIVE_CLI_FAILURE";
45
+ UNKNOWN_PROCESS_OUTCOME: "UNKNOWN_PROCESS_OUTCOME";
46
+ CONTENT_BOUNDS_OR_PATH_DENIAL: "CONTENT_BOUNDS_OR_PATH_DENIAL";
47
+ INTERNAL_ERROR: "INTERNAL_ERROR";
48
+ }>;
49
+ message: z.ZodString;
50
+ correlationId: z.ZodString;
51
+ runId: z.ZodOptional<z.ZodString>;
52
+ projectId: z.ZodOptional<z.ZodString>;
53
+ timestamp: z.ZodString;
54
+ details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
55
+ }, z.core.$strip>;
56
+ export type ContractErrorV1 = z.infer<typeof ContractErrorV1Schema>;
57
+ export declare class ContractError extends Error {
58
+ readonly schemaVersion: 1;
59
+ readonly errorCode: ContractErrorCode;
60
+ readonly correlationId: string;
61
+ readonly runId?: string;
62
+ readonly projectId?: string;
63
+ readonly timestamp: string;
64
+ readonly details?: Record<string, unknown>;
65
+ constructor(payload: {
66
+ errorCode: ContractErrorCode;
67
+ message: string;
68
+ correlationId: string;
69
+ runId?: string;
70
+ projectId?: string;
71
+ details?: Record<string, unknown>;
72
+ });
73
+ toJSON(): ContractErrorV1;
74
+ }
75
+ //# sourceMappingURL=errors.d.ts.map