@tomflow/chatloop-tools 0.9.64 → 0.9.70

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/node_modules/@tomflow/chatloop-context/README.md +296 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  45. package/node_modules/@tomflow/chatloop-context/package.json +38 -0
  46. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  47. package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
  48. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
  49. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  126. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  127. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  128. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  129. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  130. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  131. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  132. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  133. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  134. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  135. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
  136. package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
  137. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
  138. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
  139. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
  140. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
  141. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  142. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
  143. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
  144. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  145. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  146. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  147. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  148. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  149. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  150. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  151. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  152. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  153. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  154. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
  155. package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
  156. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
  157. package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
  158. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  159. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  160. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  161. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  162. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  163. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
  164. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
  165. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
  166. package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
  167. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  168. package/node_modules/ps-list/index.d.ts +76 -0
  169. package/node_modules/ps-list/index.js +366 -0
  170. package/node_modules/ps-list/license +9 -0
  171. package/node_modules/ps-list/package.json +44 -0
  172. package/node_modules/ps-list/readme.md +56 -0
  173. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  174. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  175. package/package.json +12 -4
@@ -0,0 +1,378 @@
1
+ import {randomBytes,randomUUID} from 'node:crypto';
2
+ import {existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync} from 'node:fs';
3
+ import {homedir, tmpdir} from 'node:os';
4
+ import {join} from 'node:path';
5
+
6
+ export const HOST_NAME = 'com.tomflow.chatloop.extension';
7
+ export let ACTIONS=Object.freeze([]);
8
+ let readApiParent=()=>null;
9
+ const API_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
+ const validParent=p=>p&&API_UUID.test(p.traceId||'')&&API_UUID.test(p.spanId||'');
11
+ export function configureBridgeActions(actions,parentReader=()=>null){
12
+ if(ACTIONS.length)throw Error('EXTENSION_ACTIONS_ALREADY_CONFIGURED');
13
+ if(!Array.isArray(actions)||!actions.length||
14
+ actions.some(action=>typeof action?.id!=='string'))
15
+ throw Error('EXTENSION_ACTIONS_INVALID');
16
+ ACTIONS=Object.freeze(actions.map(action=>action.id));
17
+ if(typeof parentReader!=='function')throw Error('EXTENSION_TRACE_PORT_INVALID');
18
+ readApiParent=parentReader;
19
+ }
20
+ const ID = /^[a-f0-9]{32}$/;
21
+ const MAX_TEXT = 8 * 1024 * 1024;
22
+ const MAX_PNG = 24 * 1024 * 1024;
23
+ const TTL_MS = 20 * 60 * 1000;
24
+ // Only V2 model proposals must outlive the assistant's final Turn. This is
25
+ // bounded by one normal Task/Chat execution window and never grants send.
26
+ const TASK_INTENT_TTL_MS = 4 * 60 * 60 * 1000;
27
+ const requestTtl=(action,intent)=>intent?.taskFirst===true
28
+ &&['continue','handoff'].includes(action)?TASK_INTENT_TTL_MS:TTL_MS;
29
+ const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
30
+ function pathEntryExists(path){
31
+ try{lstatSync(path);return true}
32
+ catch(error){if(error.code==='ENOENT')return false;throw error}
33
+ }
34
+ export const configFile = () => join(homedir(), '.chat-loop', 'extension', 'config.json');
35
+ // The CLI and Chrome Native Host have independent environments. A fixed
36
+ // v2 namespace also fences unresolved requests from the former TMPDIR-based
37
+ // transport: never scan, migrate or replay those records.
38
+ export const tempRoot = () => {
39
+ const base=process.platform==='darwin'?'/private/tmp':process.platform==='linux'?'/tmp':tmpdir();
40
+ if(process.platform!=='win32'){
41
+ const st=lstatSync(base);
42
+ if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==0
43
+ ||!(st.mode&0o1000)||!(st.mode&0o002))
44
+ throw Object.assign(Error('Untrusted IPC temp root'),{code:'UNTRUSTED_STATE'});
45
+ }
46
+ return join(base,'chatloop-extension-v2-'+(process.getuid?.()??process.env.USERNAME??'user'));
47
+ };
48
+ export function privateDir(path) {
49
+ mkdirSync(path, {recursive:true, mode:0o700});
50
+ const st=lstatSync(path);
51
+ if(!st.isDirectory() || st.isSymbolicLink() || (process.getuid && st.uid!==process.getuid())
52
+ || (process.platform!=='win32' && (st.mode&0o077)))
53
+ throw Object.assign(Error('Untrusted extension state directory'),{code:'UNTRUSTED_STATE'});
54
+ return path;
55
+ }
56
+ // Both request and reply are private IPC records; never trust a symlink or
57
+ // a file with broader permissions merely because its directory is private.
58
+ function privateRecord(file,code){
59
+ const st=lstatSync(file);
60
+ if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
61
+ ||(process.platform!=='win32'&&(st.mode&0o077)))
62
+ throw Object.assign(Error('Untrusted extension record'),{code});
63
+ }
64
+ export function requestDir(id) {
65
+ if(typeof id!=='string'||!ID.test(id))throw Object.assign(Error('Invalid request ID'),{code:'INVALID_REQUEST_ID'});
66
+ return join(tempRoot(),id);
67
+ }
68
+ function validateIntent(action, intent, fromStoredRequest=false) {
69
+ if(action==='status'){
70
+ // Existing no-argument V1 Status remains unchanged. A Task-first read
71
+ // must explicitly name both identities; there is no "latest Task".
72
+ if(intent===undefined)return null;
73
+ const id=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
74
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
75
+ ||Object.keys(intent).length!==2
76
+ ||!id.test(intent.projectId||'')||!id.test(intent.taskId||''))
77
+ throw Object.assign(Error('Exact Task status required'),
78
+ {code:'INVALID_TASK_STATUS_INTENT'});
79
+ return {projectId:intent.projectId,taskId:intent.taskId};
80
+ }
81
+ if(action==='session'){
82
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
83
+ if(intent?.operation==='recover-handoff'){
84
+ const names=['operation','projectId','taskId','sessionId',
85
+ 'generation','expectedNativeRevision','originalAttemptId',
86
+ 'confirmed','taskFirst',...(fromStoredRequest?['newRunCredential']:[])];
87
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
88
+ ||Object.keys(intent).length!==names.length
89
+ ||names.some(k=>!Object.hasOwn(intent,k))
90
+ ||!ID.test(intent.projectId||'')||!ID.test(intent.taskId||'')
91
+ ||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f-]{12}$/i.test(intent.sessionId||'')
92
+ ||!Number.isSafeInteger(intent.generation)||intent.generation<0
93
+ ||!Number.isSafeInteger(intent.expectedNativeRevision)
94
+ ||intent.expectedNativeRevision<2
95
+ ||!/^[a-f0-9]{32}$/.test(intent.originalAttemptId||'')
96
+ ||intent.confirmed!==true||intent.taskFirst!==true
97
+ ||fromStoredRequest&&!/^[0-9a-f]{64}$/.test(intent.newRunCredential||''))
98
+ throw Object.assign(Error('Exact fenced Handoff recovery required'),
99
+ {code:'INVALID_HANDOFF_RECOVERY_INTENT'});
100
+ return {...intent};
101
+ }
102
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
103
+ const scoped=intent?.taskFirst===true;
104
+ const keys=['operation','projectId','taskId','sessionId','generation',
105
+ scoped?'expectedNativeRevision':'expectedNativeUpdatedAt',
106
+ 'expectedTaskRevision','expectedBindingRevision',
107
+ 'contextStoreEpoch','confirmed',...(scoped?['taskFirst']:[])];
108
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
109
+ ||Object.keys(intent).length!==keys.length
110
+ ||keys.some(k=>!Object.hasOwn(intent,k))
111
+ ||intent.operation!=='cancel'||intent.confirmed!==true
112
+ ||!ID.test(intent.projectId||'')||!ID.test(intent.taskId||'')
113
+ ||!UUID.test(intent.sessionId||'')
114
+ ||!Number.isSafeInteger(intent.generation)||intent.generation<0
115
+ ||(scoped
116
+ ?!Number.isSafeInteger(intent.expectedNativeRevision)
117
+ ||intent.expectedNativeRevision<1
118
+ :!Number.isSafeInteger(intent.expectedNativeUpdatedAt)
119
+ ||intent.expectedNativeUpdatedAt<=0)
120
+ ||!Number.isSafeInteger(intent.expectedTaskRevision)
121
+ ||intent.expectedTaskRevision<1
122
+ ||!Number.isSafeInteger(intent.expectedBindingRevision)
123
+ ||intent.expectedBindingRevision<1
124
+ ||typeof intent.contextStoreEpoch!=='string'
125
+ ||intent.contextStoreEpoch.length<10||intent.contextStoreEpoch.length>128)
126
+ throw Object.assign(Error('Exact session cancellation required'),
127
+ {code:'INVALID_SESSION_INTENT'});
128
+ return {...intent};
129
+ }
130
+ if(action==='entry_test'){
131
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
132
+ ||Object.keys(intent).some(k=>!['prompt','appId','testOnly','confirmed','recoverTestAt','recoverExactDraft','verifyChatUrl'].includes(k))
133
+ ||typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
134
+ ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)
135
+ ||typeof intent.appId!=='string'||!/^asdk_app_[a-z0-9]{20,64}$/.test(intent.appId)
136
+ ||intent.testOnly!==true||intent.confirmed!==true
137
+ ||(intent.verifyChatUrl!==undefined&&(
138
+ typeof intent.verifyChatUrl!=='string'
139
+ ||!/^https:\/\/chatgpt\.com\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.verifyChatUrl)
140
+ ||intent.recoverTestAt!==undefined||intent.recoverExactDraft!==undefined))
141
+ ||(intent.recoverTestAt!==undefined&&intent.recoverTestAt!==true)
142
+ ||(intent.recoverExactDraft!==undefined
143
+ &&(typeof intent.recoverExactDraft!=='string'
144
+ ||!intent.recoverExactDraft.trim()
145
+ ||intent.recoverExactDraft.length>4000)))
146
+ throw Object.assign(Error('Explicit test-only entry intent required'),{code:'INVALID_ENTRY_TEST_INTENT'});
147
+ return {prompt:intent.prompt,appId:intent.appId,testOnly:true,confirmed:true,
148
+ ...(intent.recoverTestAt?{recoverTestAt:true}:{}),
149
+ ...(intent.recoverExactDraft?{recoverExactDraft:intent.recoverExactDraft}:{}),
150
+ ...(intent.verifyChatUrl?{verifyChatUrl:intent.verifyChatUrl}:{})};
151
+ }
152
+ if(action==='start'){
153
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
154
+ ||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision','taskFirst'].includes(k))
155
+ ||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.projectId||'')
156
+ ||(intent.taskId!==undefined && !(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.taskId))
157
+ ||(intent.purpose!==undefined && (intent.purpose!=='REPAIR_SAME_SCOPE'
158
+ ||intent.mode!=='adopt'||!intent.taskId||!intent.contextLeaseRef))
159
+ ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
160
+ .some(k=>Object.hasOwn(intent,k))
161
+ &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
162
+ ||intent.contextLeaseRef.length<8
163
+ ||typeof intent.contextStoreEpoch!=='string'||intent.contextStoreEpoch.length<10
164
+ ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
165
+ ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
166
+ // Public Extension CLI must not bypass the managed Context Start lease.
167
+ ||(intent.mode==='adopt'&&!Object.hasOwn(intent,'contextLeaseRef'))
168
+ ||(intent.taskFirst!==undefined
169
+ &&(intent.taskFirst!==true||intent.mode!=='adopt'
170
+ ||!intent.taskId||!intent.chatUrl||!intent.contextLeaseRef
171
+ ||intent.purpose!==undefined
172
+ ||intent.replaceBlockedSessionId!==undefined))
173
+ ||intent.confirmed!==true || (intent.mode!==undefined && intent.mode!=='adopt')
174
+ || (intent.replaceBlockedSessionId!==undefined
175
+ && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId))
176
+ ||(intent.chatUrl!==undefined
177
+ && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'||!CHAT_URL.test(intent.chatUrl)))
178
+ ||(intent.mode==='adopt'
179
+ ? Object.hasOwn(intent,'prompt')
180
+ : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
181
+ ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)))
182
+ throw Object.assign(Error('Explicit confirmed task and project required'),{code:'INVALID_START_INTENT'});
183
+ return {projectId:intent.projectId,confirmed:true,
184
+ ...(intent.taskFirst===true?{taskFirst:true}:{}),
185
+ ...(intent.taskId?{taskId:intent.taskId}:{}),
186
+ ...(intent.purpose?{purpose:intent.purpose}:{}),
187
+ ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
188
+ contextStoreEpoch:intent.contextStoreEpoch,
189
+ contextTaskRevision:intent.contextTaskRevision,
190
+ contextApprovalRevision:intent.contextApprovalRevision}:{}),
191
+ ...(intent.mode==='adopt'?{mode:'adopt',...(intent.chatUrl?{chatUrl:intent.chatUrl}:{})}:{prompt:intent.prompt}),
192
+ ...(intent.replaceBlockedSessionId?{replaceBlockedSessionId:intent.replaceBlockedSessionId}:{})};
193
+ }
194
+ if(action==='clean'){
195
+ if(!intent || typeof intent!=='object' || Array.isArray(intent)
196
+ || Object.keys(intent).length!==1 || !Number.isSafeInteger(intent.tabId)
197
+ || intent.tabId<1)
198
+ throw Object.assign(Error('Clean requires an exact tabId'),{code:'INVALID_CLEAN_TARGET'});
199
+ return {tabId:intent.tabId};
200
+ }
201
+ if(!['continue','handoff'].includes(action)) {
202
+ if(intent!==undefined)throw Object.assign(Error('Unexpected intent'),{code:'INVALID_INTENT'});
203
+ return null;
204
+ }
205
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
206
+ ||(intent.taskFirst!==undefined&&intent.taskFirst!==true)
207
+ || typeof intent.turnToken!=='string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(intent.turnToken))
208
+ throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
209
+ // Query is read-only and uses the same formal Action page; no seventh Action.
210
+ if(Object.hasOwn(intent,'intentId')||intent.lookup===true){
211
+ const latest=intent.lookup===true;
212
+ if(Object.keys(intent).some(k=>k!=='turnToken'&&k!=='taskFirst'
213
+ &&k!==(latest?'lookup':'intentId'))
214
+ ||latest&&Object.hasOwn(intent,'intentId')
215
+ ||!latest&&(typeof intent.intentId!=='string'||!/^[a-f0-9]{32}$/.test(intent.intentId)))
216
+ throw Object.assign(Error('Invalid intent query'),{code:'INVALID_INTENT'});
217
+ return latest?{turnToken:intent.turnToken,lookup:true,
218
+ ...(intent.taskFirst===true?{taskFirst:true}:{})}
219
+ :{turnToken:intent.turnToken,intentId:intent.intentId,
220
+ ...(intent.taskFirst===true?{taskFirst:true}:{})};
221
+ }
222
+ if(Object.keys(intent).some(k=>k!=='turnToken'&&k!=='taskFirst'
223
+ &&(action==='continue'?k!=='nextPrompt':k!=='reason')))
224
+ throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
225
+ if(action==='continue' && (typeof intent.nextPrompt!=='string'
226
+ || !intent.nextPrompt.trim() || intent.nextPrompt.length>4000
227
+ || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.nextPrompt)))
228
+ throw Object.assign(Error('Invalid continuation text'),{code:'INVALID_INTENT'});
229
+ if(action==='handoff' && intent.reason!==undefined
230
+ && (typeof intent.reason!=='string'||intent.reason.length>400
231
+ || /[\x00-\x1f]/.test(intent.reason)))
232
+ throw Object.assign(Error('Invalid handoff reason'),{code:'INVALID_INTENT'});
233
+ return action==='continue' ? {turnToken:intent.turnToken,
234
+ nextPrompt:intent.nextPrompt,
235
+ ...(intent.taskFirst===true?{taskFirst:true}:{})}
236
+ : {turnToken:intent.turnToken,reason:intent.reason||'',
237
+ ...(intent.taskFirst===true?{taskFirst:true}:{})};
238
+ }
239
+ export function prepare(action,intent) {
240
+ if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown extension action'),{code:'UNKNOWN_ACTION'});
241
+ const input=validateIntent(action,intent);
242
+ const validated=action==='session'&&input?.operation==='recover-handoff'
243
+ ?{...input,newRunCredential:randomBytes(32).toString('hex')}:input;
244
+ privateDir(tempRoot());
245
+ cleanup();
246
+ const id=randomUUID().replaceAll('-',''), nonce=randomUUID().replaceAll('-',''), at=Date.now();
247
+ const dir=privateDir(requestDir(id));
248
+ // This private request is the already-authorized CLI → Native transport.
249
+ // Correlation is soft: never promote it to a capability or Owner proof.
250
+ let traceParent=null;
251
+ try{const current=readApiParent();if(validParent(current))traceParent=current}catch{}
252
+ writeFileSync(join(dir,'request.json'), JSON.stringify({id,nonce,action,at,
253
+ expiresAt:at+requestTtl(action,validated),
254
+ ...(traceParent?{traceParent}:{}),...(validated ? {intent:validated} : {})}),
255
+ {flag:'wx',mode:0o600});
256
+ return {id,nonce,action,dir};
257
+ }
258
+ export function readRequest(id) {
259
+ const dir=requestDir(id);
260
+ if(!pathEntryExists(dir))throw Object.assign(Error('No request'),{code:'NO_REQUEST'});
261
+ privateDir(dir);
262
+ const p=join(dir,'request.json');
263
+ privateRecord(p,'UNTRUSTED_REQUEST');
264
+ const r=JSON.parse(readFileSync(p,'utf8'));
265
+ if(r.id!==id||!ACTIONS.includes(r.action)
266
+ ||!Number.isSafeInteger(r.at)||!Number.isSafeInteger(r.expiresAt)
267
+ ||r.expiresAt!==r.at+requestTtl(r.action,r.intent)
268
+ ||Date.now()>r.expiresAt)
269
+ throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
270
+ if(['continue','handoff','clean','start','status','session',
271
+ 'entry_test'].includes(r.action))validateIntent(r.action,r.intent,true);
272
+ if(r.traceParent!==undefined&&!validParent(r.traceParent))delete r.traceParent;
273
+ return r;
274
+ }
275
+ export function finish({id,nonce,action,status,payload='',code=null}) {
276
+ const r=readRequest(id);
277
+ if(nonce!==r.nonce||action!==r.action)throw Object.assign(Error('Request mismatch'),{code:'REQUEST_MISMATCH'});
278
+ if(status!=='OK'&&status!=='FAILED')throw Object.assign(Error('Invalid status'),{code:'INVALID_RESULT'});
279
+ const dir=requestDir(id);
280
+ const resultPath=join(dir,'result.json');
281
+ if(pathEntryExists(resultPath))throw Object.assign(Error('Duplicate result'),{code:'ALREADY_FINISHED'});
282
+ let bytes=0,mimeType=null,filename=null;
283
+ if(status==='OK'){
284
+ if(typeof payload!=='string')throw Object.assign(Error('Invalid payload'),{code:'INVALID_PAYLOAD'});
285
+ let buf;
286
+ if(action==='chat_screenshot'){
287
+ if(!/^[A-Za-z0-9+/]*={0,2}$/.test(payload))throw Object.assign(Error('Invalid PNG encoding'),{code:'INVALID_PNG'});
288
+ buf=Buffer.from(payload,'base64');
289
+ if(buf.subarray(0,8).toString('hex')!=='89504e470d0a1a0a')throw Object.assign(Error('Invalid PNG signature'),{code:'INVALID_PNG'});
290
+ mimeType='image/png';filename='result.png';
291
+ if(buf.length>MAX_PNG)throw Object.assign(Error('PNG too large'),{code:'RESULT_TOO_LARGE'});
292
+ }else{
293
+ buf=Buffer.from(payload,'utf8');
294
+ if(buf.length>MAX_TEXT)throw Object.assign(Error('Text too large'),{code:'RESULT_TOO_LARGE'});
295
+ mimeType=action==='chat_dom'?'text/html':'text/plain';
296
+ filename=action==='reload'?null:action==='chat_dom'?'result.html':'result.txt';
297
+ }
298
+ bytes=buf.length;
299
+ if(filename)writeFileSync(join(dir,filename),buf,{flag:'wx',mode:0o600});
300
+ }
301
+ const failureCode=typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
302
+ ?code:'ACTION_FAILED';
303
+ const rec={id,action,status,code:status==='FAILED'?failureCode:null,
304
+ path:filename?join(dir,filename):null,bytes,mimeType,at:Date.now(),
305
+ verified:action!=='reload'};
306
+ writeFileSync(resultPath+'.tmp',JSON.stringify(rec),{flag:'wx',mode:0o600});
307
+ renameSync(resultPath+'.tmp',resultPath);
308
+ return rec;
309
+ }
310
+ export function readResult(id) {
311
+ const dir=requestDir(id),p=join(dir,'result.json');
312
+ if(!pathEntryExists(p))return null;
313
+ privateDir(dir);
314
+ privateRecord(p,'UNTRUSTED_RESULT');
315
+ let rec;
316
+ try{rec=JSON.parse(readFileSync(p,'utf8'))}catch{
317
+ throw Object.assign(Error('Untrusted result'),{code:'UNTRUSTED_RESULT'});
318
+ }
319
+ const request=readRequest(id);
320
+ const expectedFile=request.action==='reload'?null:
321
+ request.action==='chat_screenshot'?'result.png':
322
+ request.action==='chat_dom'?'result.html':'result.txt';
323
+ const expectedMime=request.action==='chat_screenshot'?'image/png':
324
+ request.action==='chat_dom'?'text/html':'text/plain';
325
+ const invalid=()=>Object.assign(Error('Untrusted result'),{code:'UNTRUSTED_RESULT'});
326
+ if(!rec||typeof rec!=='object'||Array.isArray(rec)
327
+ ||Object.keys(rec).some(k=>!['id','action','status','code','path',
328
+ 'bytes','mimeType','at','verified'].includes(k))
329
+ ||rec.id!==id||rec.action!==request.action
330
+ ||!['OK','FAILED'].includes(rec.status)
331
+ ||rec.verified!==(request.action!=='reload')
332
+ ||!Number.isSafeInteger(rec.at)||rec.at<request.at||rec.at>request.expiresAt
333
+ ||!Number.isSafeInteger(rec.bytes)||rec.bytes<0
334
+ ||(rec.status==='FAILED'
335
+ ?rec.path!==null||rec.mimeType!==null||rec.bytes!==0
336
+ ||typeof rec.code!=='string'||!/^[A-Z][A-Z0-9_]{1,95}$/.test(rec.code)
337
+ :rec.code!==null||rec.mimeType!==expectedMime
338
+ ||rec.path!==(expectedFile?join(dir,expectedFile):null)
339
+ ||rec.bytes>(request.action==='chat_screenshot'?MAX_PNG:MAX_TEXT)))
340
+ throw invalid();
341
+ if(rec.status==='OK'&&expectedFile){
342
+ try{
343
+ privateRecord(rec.path,'UNTRUSTED_RESULT');
344
+ if(lstatSync(rec.path).size!==rec.bytes)throw invalid();
345
+ }catch{throw invalid()}
346
+ }
347
+ return rec;
348
+ }
349
+ export function cleanup(){
350
+ const root=tempRoot();
351
+ if(!existsSync(root))return;
352
+ privateDir(root);
353
+ for(const f of readdirSync(root)){
354
+ if(!ID.test(f))continue;
355
+ const p=join(root,f);
356
+ try{
357
+ const st=lstatSync(p);
358
+ if(st.isDirectory()&&!st.isSymbolicLink()
359
+ &&Date.now()-st.mtimeMs>TTL_MS){
360
+ // Preserve ONLY an unexpired signed Task-first model proposal while
361
+ // its original assistant reply is still running. Ordinary V1 temp
362
+ // requests retain the original 20-minute cleanup and expiry.
363
+ let active=false;
364
+ try{
365
+ const source=readRequest(f);
366
+ active=source.intent?.taskFirst===true
367
+ &&['continue','handoff'].includes(source.action)
368
+ &&source.expiresAt>Date.now();
369
+ }catch{/* Expired/untrusted requests are never authority. */}
370
+ if(!active)rmSync(p,{recursive:true,force:true});
371
+ }
372
+ }catch{}
373
+ }
374
+ }
375
+ export function validateExtensionId(id) {
376
+ if(!/^[a-p]{32}$/.test(id||''))throw Object.assign(Error('Invalid Chrome extension ID'),{code:'INVALID_EXTENSION_ID'});
377
+ return id;
378
+ }
@@ -0,0 +1,89 @@
1
+ import {spawnSync} from 'node:child_process';
2
+
3
+ // Open a formal extension Action page in the existing Chrome window that owns
4
+ // the ChatGPT conversation. "open -a Google Chrome <url>" chooses the last
5
+ // active *profile*, which can be a different profile without this extension.
6
+ // This script does not read or modify a Chat tab; it creates only an Action tab.
7
+ // Ambiguous ownership fails closed rather than sending an Action elsewhere.
8
+ const OPEN_IN_CHAT_WINDOW = `on run argv
9
+ set destination to item 1 of argv
10
+ tell application "Google Chrome"
11
+ set candidateIds to {}
12
+ repeat with w in windows
13
+ set hasChat to false
14
+ repeat with t in tabs of w
15
+ try
16
+ if (URL of t) starts with "https://chatgpt.com/" then set hasChat to true
17
+ end try
18
+ end repeat
19
+ if hasChat then set end of candidateIds to id of w
20
+ end repeat
21
+ if (count of candidateIds) is not 1 then error "CHATGPT_WINDOW_AMBIGUOUS_OR_ABSENT" number 103
22
+ set ownWindow to window id (item 1 of candidateIds)
23
+ make new tab at end of tabs of ownWindow with properties {URL:destination}
24
+ return "WINDOW=" & (id of ownWindow)
25
+ end tell
26
+ end run`;
27
+
28
+ // Entry TEST_ONLY may bootstrap a normal Chat when there is no existing
29
+ // ChatGPT tab. In that case require exactly one Chrome window containing the
30
+ // explicitly verified Chat Loop extension details page. Never select a random
31
+ // Chrome window or another profile, and never create a Chat tab here.
32
+ const OPEN_TEST_ENTRY_WINDOW = `on run argv
33
+ set destination to item 1 of argv
34
+ set managerURL to item 2 of argv
35
+ tell application "Google Chrome"
36
+ set chatWindowIds to {}
37
+ repeat with w in windows
38
+ set hasChat to false
39
+ repeat with t in tabs of w
40
+ try
41
+ if (URL of t) starts with "https://chatgpt.com/" then set hasChat to true
42
+ end try
43
+ end repeat
44
+ if hasChat then set end of chatWindowIds to id of w
45
+ end repeat
46
+ if (count of chatWindowIds) is 1 then
47
+ set ownWindow to window id (item 1 of chatWindowIds)
48
+ else
49
+ if (count of chatWindowIds) is not 0 then error "CHATGPT_WINDOW_AMBIGUOUS" number 103
50
+ set managerWindowIds to {}
51
+ repeat with w in windows
52
+ set hasManager to false
53
+ repeat with t in tabs of w
54
+ try
55
+ if (URL of t) is managerURL then set hasManager to true
56
+ end try
57
+ end repeat
58
+ if hasManager then set end of managerWindowIds to id of w
59
+ end repeat
60
+ if (count of managerWindowIds) is not 1 then error "ENTRY_TEST_WINDOW_UNVERIFIED" number 103
61
+ set ownWindow to window id (item 1 of managerWindowIds)
62
+ end if
63
+ make new tab at end of tabs of ownWindow with properties {URL:destination}
64
+ return "WINDOW=" & (id of ownWindow)
65
+ end tell
66
+ end run`;
67
+
68
+ export function openExtensionActionPage(url,{platform=process.platform,spawn=spawnSync}={}){
69
+ if(platform!=='darwin')
70
+ throw Object.assign(Error('Browser launcher not yet verified on this OS'),
71
+ {code:'BROWSER_LAUNCH_UNSUPPORTED'});
72
+ // The private session Action uses a fixed operation selector in addition to
73
+ // its request locator. No other Action may accept arbitrary URL arguments.
74
+ const ordinary=/^chrome-extension:\/\/[a-p]{32}\/(?!session\.html)[a-z_]+\.html\?requestId=[a-f0-9]{32}$/;
75
+ const session=/^chrome-extension:\/\/[a-p]{32}\/session\.html\?requestId=[a-f0-9]{32}&operation=(?:cancel|recover-handoff)$/;
76
+ if(!ordinary.test(url)&&!session.test(url))
77
+ throw Object.assign(Error('Untrusted Extension Action URL'),{code:'INVALID_ACTION_URL'});
78
+ // An orphaned Owner may have no Chat tab at all. The existing verified
79
+ // extension-details window is the only supported fallback for that case.
80
+ const entry=url.match(/^chrome-extension:\/\/([a-p]{32})\/(?:entry_test|session)\.html\?requestId=[a-f0-9]{32}(?:&operation=(?:cancel|recover-handoff))?$/);
81
+ const launchArgs=entry
82
+ ?['-e',OPEN_TEST_ENTRY_WINDOW,url,'chrome://extensions/?id='+entry[1]]
83
+ :['-e',OPEN_IN_CHAT_WINDOW,url];
84
+ const receipt=spawn('osascript',launchArgs,{encoding:'utf8',timeout:7000});
85
+ if(receipt.error||receipt.status!==0||!/\bWINDOW=\d+\b/.test(receipt.stdout||''))
86
+ throw Object.assign(Error('Existing ChatGPT Chrome window unavailable or ambiguous'),
87
+ {code:'CHROME_TARGET_WINDOW_UNVERIFIED'});
88
+ return {status:'OPENED',windowVerified:true};
89
+ }
@@ -0,0 +1,45 @@
1
+ // Read only operator-owned references from the existing Extension configuration.
2
+ // The files retain the task/approval truth; this index never grants execution.
3
+ import {existsSync,lstatSync,readFileSync,realpathSync} from 'node:fs';
4
+ import {dirname,isAbsolute} from 'node:path';
5
+ let configFile;
6
+ export function configureContextBinding(api){
7
+ if(configFile)throw Error('EXTENSION_MODULE_ALREADY_COMPOSED');
8
+ if(typeof api?.configFile!=='function')throw Error('EXTENSION_PORT_MISSING:configFile');
9
+ configFile=api.configFile;
10
+ }
11
+ const invalid=()=>Object.assign(Error('CONTEXT_BINDING_UNVERIFIED'),{code:'CONTEXT_BINDING_UNVERIFIED'});
12
+ const trusted=(p,directory=false)=>{
13
+ const s=lstatSync(p);
14
+ if(s.isSymbolicLink()||(directory?!s.isDirectory():!s.isFile())
15
+ ||process.getuid&&s.uid!==process.getuid()
16
+ ||process.platform!=='win32'&&(s.mode&0o077))throw invalid();
17
+ return s;
18
+ };
19
+ const pathValue=(value,directory=false)=>{
20
+ if(typeof value!=='string'||!isAbsolute(value)||value.length>2048||/[\x00-\x1f]/.test(value))
21
+ throw invalid();
22
+ const s=lstatSync(realpathSync(value));
23
+ if(directory?!s.isDirectory():!s.isFile())throw invalid();
24
+ return value;
25
+ };
26
+ export function registeredContext(projectId){
27
+ const file=configFile();
28
+ if(!existsSync(file))return null;
29
+ try{
30
+ trusted(dirname(file),true);
31
+ if(trusted(file).size>65536)throw invalid();
32
+ const config=JSON.parse(readFileSync(file,'utf8')),entry=config.projectContext;
33
+ if(entry===undefined||entry?.projectId!==projectId)return null;
34
+ if(!entry||Array.isArray(entry)||typeof entry!=='object'
35
+ ||Object.keys(entry).some(k=>!['projectId','sourceRoots','contextPath','taskDocPath','approvalDocPath'].includes(k))
36
+ ||!Array.isArray(entry.sourceRoots)||entry.sourceRoots.length<1||entry.sourceRoots.length>8)
37
+ throw invalid();
38
+ const result={projectId,sourceRoots:entry.sourceRoots.map(p=>pathValue(p,true)),
39
+ contextPath:pathValue(entry.contextPath),
40
+ ...(entry.taskDocPath!==undefined?{taskDocPath:pathValue(entry.taskDocPath)}:{}),
41
+ ...(entry.approvalDocPath!==undefined?{approvalDocPath:pathValue(entry.approvalDocPath)}:{})};
42
+ if(JSON.stringify(result).length>8192)throw invalid();
43
+ return result;
44
+ }catch(error){throw invalid();}
45
+ }
@@ -0,0 +1,122 @@
1
+ // Browser Native Host -> existing Local Tools Supervisor narrow IPC.
2
+ // This file deliberately does not import Local Tools internals or create
3
+ // another Context service. A same-UID shell remains within the trusted local boundary.
4
+ import {createHmac,randomUUID} from 'node:crypto';
5
+ import {connect} from 'node:net';
6
+ import {existsSync,lstatSync,readFileSync} from 'node:fs';
7
+ import {homedir} from 'node:os';
8
+ import {join} from 'node:path';
9
+ const fail=code=>Object.assign(new Error(code),{code});
10
+ const base=()=>process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR||
11
+ join(homedir(),'.chat-loop','local-tools');
12
+ function privateFile(path,type){
13
+ if(!existsSync(path))throw fail('CONTEXT_CONTROL_NOT_INSTALLED');
14
+ const st=lstatSync(path);
15
+ if((type==='socket'?!st.isSocket():!st.isFile())
16
+ ||st.isSymbolicLink()||(st.mode&0o077)
17
+ ||(process.getuid && st.uid!==process.getuid()))
18
+ throw fail('CONTEXT_CONTROL_UNTRUSTED');
19
+ return st;
20
+ }
21
+ const ipc=(request,timeout=4000)=>new Promise((resolve,reject)=>{
22
+ const socket=connect(join(base(),'control.sock'));
23
+ socket.setEncoding('utf8'); // Preserve JSON code points split by socket chunks.
24
+ let text='',done=false;
25
+ const timer=setTimeout(()=>finish(fail('CONTEXT_CONTROL_TIMEOUT')),timeout);
26
+ function finish(error,value){
27
+ if(done)return;done=true;clearTimeout(timer);socket.destroy();
28
+ error?reject(error):resolve(value);
29
+ }
30
+ socket.on('connect',()=>socket.write(JSON.stringify(request)+'\n'));
31
+ socket.on('error',e=>finish(e));
32
+ socket.on('end',()=>{if(!done)finish(fail('CONTEXT_CONTROL_UNCONFIRMED'))});
33
+ socket.on('data',chunk=>{
34
+ text+=chunk;
35
+ if(Buffer.byteLength(text,'utf8')>1_000_000)return finish(fail('CONTEXT_CONTROL_REPLY_TOO_LARGE'));
36
+ const n=text.indexOf('\n');if(n<0)return;
37
+ try{finish(null,JSON.parse(text.slice(0,n)))}catch{finish(fail('CONTEXT_CONTROL_REPLY_INVALID'))}
38
+ });
39
+ });
40
+ export async function nativeContextControl(command,args,{ownerProofV2}={}){
41
+ // Only the Native Host may supply this scoped projection. The Supervisor
42
+ // verifies the signed shape against its independently read current Ledger.
43
+ if(ownerProofV2!==undefined&&(!ownerProofV2
44
+ ||typeof ownerProofV2!=='object'||Array.isArray(ownerProofV2)
45
+ ||Object.keys(ownerProofV2).length!==7))
46
+ throw fail('NATIVE_SCOPED_PROOF_INVALID');
47
+ const dir=base();
48
+ const st=lstatSync(dir);
49
+ if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)
50
+ ||(process.getuid&&st.uid!==process.getuid()))
51
+ throw fail('CONTEXT_CONTROL_UNTRUSTED');
52
+ privateFile(join(dir,'control.sock'),'socket');
53
+ privateFile(join(dir,'manager.lock'),'file');
54
+ const key=join(dir,'context-control.secret');
55
+ const secretStats=privateFile(key,'file');
56
+ if(secretStats.size!==32)throw fail('CONTEXT_CONTROL_UNTRUSTED');
57
+ const hello=await ipc({action:'__ping'},2000);
58
+ const lock=JSON.parse(readFileSync(join(dir,'manager.lock'),'utf8'));
59
+ if(hello.contract!=='chat-loop.local-control.v1'
60
+ ||lock.nonce!==hello.ownerNonce||lock.pid!==hello.managerPid
61
+ ||lock.version!==hello.version||hello.version!==hello.packageVersion)
62
+ throw fail('CONTEXT_CONTROL_OWNER_MISMATCH');
63
+ const secret=readFileSync(key);
64
+ const signed={contract:'chat-loop.context-control.v1',
65
+ requestId:randomUUID(),issuedAt:Date.now(),payload:{command,args,
66
+ ...(ownerProofV2?{ownerProofV2}:{})}};
67
+ const mac=createHmac('sha256',secret).update(JSON.stringify(signed)).digest('hex');
68
+ const reply=await ipc({...signed,action:'context-control',mac},6000);
69
+ if(reply.contract!==hello.contract||reply.requestId!==signed.requestId)
70
+ throw fail('CONTEXT_CONTROL_REPLY_INVALID');
71
+ if(reply.status!=='OK'){
72
+ const code=reply.error?.code;
73
+ throw fail(typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
74
+ ?code:'CONTEXT_CONTROL_FAILED');
75
+ }
76
+ return reply.result;
77
+ }
78
+
79
+ // Independent, best-effort observation channel. No business data.
80
+ // A separate identity ping for every event (or a shared ping for a burst)
81
+ // caused the observed Supervisor IPC timeout fan-out. The existing private
82
+ // manager.lock contains the current Manager identity: include it on the
83
+ // observation itself, then let the Supervisor verify it atomically on receipt.
84
+ const API_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
85
+ const API_NAME=/^extension\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
86
+ const API_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
87
+ export async function nativeApiObservation(record){
88
+ if(!record||typeof record!=='object'||Array.isArray(record)||
89
+ Object.keys(record).some(key=>!['callId','traceId','spanId','parentSpanId',
90
+ 'apiName','phase','durationMs','errorCode'].includes(key))||
91
+ !API_UUID.test(record.callId||'')||
92
+ !API_UUID.test(record.traceId||'')||
93
+ record.spanId!==record.callId||
94
+ (record.parentSpanId!==undefined&&
95
+ (!API_UUID.test(record.parentSpanId)||record.parentSpanId===record.spanId))||
96
+ !API_NAME.test(record.apiName||'')||
97
+ !['BEGIN','OK','FAILED'].includes(record.phase)||
98
+ (record.phase==='BEGIN'
99
+ ?record.durationMs!==undefined||record.errorCode!==undefined
100
+ :!Number.isSafeInteger(record.durationMs)||record.durationMs<0||
101
+ (record.phase==='FAILED'?!API_CODE.test(record.errorCode||'')
102
+ :record.errorCode!==undefined)))
103
+ throw fail('API_OBSERVATION_INVALID');
104
+ const dir=base(),stat=lstatSync(dir);
105
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o077)||
106
+ (process.getuid&&stat.uid!==process.getuid()))
107
+ throw fail('API_OBSERVATION_UNTRUSTED');
108
+ privateFile(join(dir,'control.sock'),'socket');
109
+ const lockFile=join(dir,'manager.lock');
110
+ privateFile(lockFile,'file');
111
+ const manager=JSON.parse(readFileSync(lockFile,'utf8'));
112
+ if(!API_UUID.test(manager.nonce||'')||!Number.isSafeInteger(manager.pid)
113
+ ||manager.pid<1||typeof manager.version!=='string')
114
+ throw fail('API_OBSERVATION_OWNER_UNTRUSTED');
115
+ const request={contract:'chat-loop.local-control.v1',action:'__api_observation',
116
+ requestId:randomUUID(),ownerNonce:manager.nonce,managerPid:manager.pid,...record};
117
+ // The Supervisor verifies ownerNonce and managerPid before appending.
118
+ // This is one socket and one ACK per event, never an Action retry.
119
+ const response=await ipc(request,3500);
120
+ return response.contract===request.contract&&
121
+ response.requestId===request.requestId&&response.status==='OK';
122
+ }