@tomflow/chatloop-tools 0.9.17 → 0.9.19

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 (140) hide show
  1. package/package.json +3 -11
  2. package/providers/form.mjs +13 -5
  3. package/ui/form/review-app.js +122 -71
  4. package/ui/form/review.html +1 -814
  5. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  6. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  7. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  8. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  10. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  11. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  12. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  13. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  14. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  15. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  16. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  17. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -182
  18. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  19. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -233
  20. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  21. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -24
  22. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  23. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -67
  24. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -280
  25. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  26. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -280
  27. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  28. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  29. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -55
  30. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  31. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  32. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  33. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -343
  34. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -391
  35. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -166
  36. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  37. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  38. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  39. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -117
  40. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  41. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -312
  42. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  43. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  44. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -115
  45. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -86
  46. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  47. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  48. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  49. package/node_modules/@tomflow/chatloop-extension/README.md +0 -94
  50. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -11
  51. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -141
  52. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -109
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -120
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -180
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -322
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -378
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -54
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -69
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -287
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -23
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  75. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -16
  76. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  77. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  78. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  80. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -76
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -227
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -254
  92. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  93. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  94. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -93
  95. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  96. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  97. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  98. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  99. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -220
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -122
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -155
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -185
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -120
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -172
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -165
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -244
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -181
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -147
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -200
  113. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  114. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -18
  115. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -74
  116. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -208
  117. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -40
  118. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  119. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -111
  120. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -67
  121. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -120
  122. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  123. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -133
  124. package/node_modules/@tomflow/chatloop-trace/README.md +0 -105
  125. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  126. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  127. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  128. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  129. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  130. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -265
  131. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -205
  132. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  133. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  134. package/node_modules/ps-list/index.d.ts +0 -76
  135. package/node_modules/ps-list/index.js +0 -366
  136. package/node_modules/ps-list/license +0 -9
  137. package/node_modules/ps-list/package.json +0 -44
  138. package/node_modules/ps-list/readme.md +0 -56
  139. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  140. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,208 +0,0 @@
1
- import {randomUUID} from 'node:crypto';
2
- import {existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, 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
- const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
25
- function pathEntryExists(path){
26
- try{lstatSync(path);return true}
27
- catch(error){if(error.code==='ENOENT')return false;throw error}
28
- }
29
- export const configFile = () => join(homedir(), '.chat-loop', 'extension', 'config.json');
30
- export const tempRoot = () => join(tmpdir(), 'chatloop-extension-' + (process.getuid?.() ?? process.env.USERNAME ?? 'user'));
31
- export function privateDir(path) {
32
- mkdirSync(path, {recursive:true, mode:0o700});
33
- const st=lstatSync(path);
34
- if(!st.isDirectory() || st.isSymbolicLink() || (process.getuid && st.uid!==process.getuid())
35
- || (process.platform!=='win32' && (st.mode&0o077)))
36
- throw Object.assign(Error('Untrusted extension state directory'),{code:'UNTRUSTED_STATE'});
37
- return path;
38
- }
39
- // Both request and reply are private IPC records; never trust a symlink or
40
- // a file with broader permissions merely because its directory is private.
41
- function privateRecord(file,code){
42
- const st=lstatSync(file);
43
- if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
44
- ||(process.platform!=='win32'&&(st.mode&0o077)))
45
- throw Object.assign(Error('Untrusted extension record'),{code});
46
- }
47
- export function requestDir(id) {
48
- if(typeof id!=='string'||!ID.test(id))throw Object.assign(Error('Invalid request ID'),{code:'INVALID_REQUEST_ID'});
49
- return join(tempRoot(),id);
50
- }
51
- function validateIntent(action, intent) {
52
- if(action==='start'){
53
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
54
- ||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision'].includes(k))
55
- ||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.projectId||'')
56
- ||(intent.taskId!==undefined && !(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.taskId))
57
- ||(intent.purpose!==undefined && (intent.purpose!=='REPAIR_SAME_SCOPE'
58
- ||intent.mode!=='adopt'||!intent.taskId||!intent.contextLeaseRef))
59
- ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
60
- .some(k=>Object.hasOwn(intent,k))
61
- &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
62
- ||intent.contextLeaseRef.length<8
63
- ||typeof intent.contextStoreEpoch!=='string'||intent.contextStoreEpoch.length<10
64
- ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
65
- ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
66
- ||intent.confirmed!==true || (intent.mode!==undefined && intent.mode!=='adopt')
67
- || (intent.replaceBlockedSessionId!==undefined
68
- && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId))
69
- ||(intent.chatUrl!==undefined
70
- && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'||!CHAT_URL.test(intent.chatUrl)))
71
- ||(intent.mode==='adopt'
72
- ? Object.hasOwn(intent,'prompt')
73
- : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
74
- ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)))
75
- throw Object.assign(Error('Explicit confirmed task and project required'),{code:'INVALID_START_INTENT'});
76
- return {projectId:intent.projectId,confirmed:true,
77
- ...(intent.taskId?{taskId:intent.taskId}:{}),
78
- ...(intent.purpose?{purpose:intent.purpose}:{}),
79
- ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
80
- contextStoreEpoch:intent.contextStoreEpoch,
81
- contextTaskRevision:intent.contextTaskRevision,
82
- contextApprovalRevision:intent.contextApprovalRevision}:{}),
83
- ...(intent.mode==='adopt'?{mode:'adopt',...(intent.chatUrl?{chatUrl:intent.chatUrl}:{})}:{prompt:intent.prompt}),
84
- ...(intent.replaceBlockedSessionId?{replaceBlockedSessionId:intent.replaceBlockedSessionId}:{})};
85
- }
86
- if(action==='clean'){
87
- if(!intent || typeof intent!=='object' || Array.isArray(intent)
88
- || Object.keys(intent).length!==1 || !Number.isSafeInteger(intent.tabId)
89
- || intent.tabId<1)
90
- throw Object.assign(Error('Clean requires an exact tabId'),{code:'INVALID_CLEAN_TARGET'});
91
- return {tabId:intent.tabId};
92
- }
93
- if(!['continue','handoff'].includes(action)) {
94
- if(intent!==undefined)throw Object.assign(Error('Unexpected intent'),{code:'INVALID_INTENT'});
95
- return null;
96
- }
97
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
98
- || 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))
99
- throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
100
- // Query is read-only and uses the same formal Action page; no seventh Action.
101
- if(Object.hasOwn(intent,'intentId')||intent.lookup===true){
102
- const latest=intent.lookup===true;
103
- if(Object.keys(intent).some(k=>k!=='turnToken'&&k!==(latest?'lookup':'intentId'))
104
- ||latest&&Object.hasOwn(intent,'intentId')
105
- ||!latest&&(typeof intent.intentId!=='string'||!/^[a-f0-9]{32}$/.test(intent.intentId)))
106
- throw Object.assign(Error('Invalid intent query'),{code:'INVALID_INTENT'});
107
- return latest?{turnToken:intent.turnToken,lookup:true}
108
- :{turnToken:intent.turnToken,intentId:intent.intentId};
109
- }
110
- if(Object.keys(intent).some(k=>k!=='turnToken'&&(action==='continue'?k!=='nextPrompt':k!=='reason')))
111
- throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
112
- if(action==='continue' && (typeof intent.nextPrompt!=='string'
113
- || !intent.nextPrompt.trim() || intent.nextPrompt.length>4000
114
- || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.nextPrompt)))
115
- throw Object.assign(Error('Invalid continuation text'),{code:'INVALID_INTENT'});
116
- if(action==='handoff' && intent.reason!==undefined
117
- && (typeof intent.reason!=='string'||intent.reason.length>400
118
- || /[\x00-\x1f]/.test(intent.reason)))
119
- throw Object.assign(Error('Invalid handoff reason'),{code:'INVALID_INTENT'});
120
- return action==='continue' ? {turnToken:intent.turnToken,nextPrompt:intent.nextPrompt}
121
- : {turnToken:intent.turnToken,reason:intent.reason||''};
122
- }
123
- export function prepare(action,intent) {
124
- if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown extension action'),{code:'UNKNOWN_ACTION'});
125
- const validated=validateIntent(action,intent);
126
- privateDir(tempRoot());
127
- cleanup();
128
- const id=randomUUID().replaceAll('-',''), nonce=randomUUID().replaceAll('-',''), at=Date.now();
129
- const dir=privateDir(requestDir(id));
130
- // This private request is the already-authorized CLI → Native transport.
131
- // Correlation is soft: never promote it to a capability or Owner proof.
132
- let traceParent=null;
133
- try{const current=readApiParent();if(validParent(current))traceParent=current}catch{}
134
- writeFileSync(join(dir,'request.json'), JSON.stringify({id,nonce,action,at,expiresAt:at+TTL_MS,...(traceParent?{traceParent}:{}),...(validated ? {intent:validated} : {})}),
135
- {flag:'wx',mode:0o600});
136
- return {id,nonce,action,dir};
137
- }
138
- export function readRequest(id) {
139
- const dir=requestDir(id);
140
- if(!pathEntryExists(dir))throw Object.assign(Error('No request'),{code:'NO_REQUEST'});
141
- privateDir(dir);
142
- const p=join(dir,'request.json');
143
- privateRecord(p,'UNTRUSTED_REQUEST');
144
- const r=JSON.parse(readFileSync(p,'utf8'));
145
- if(r.id!==id||!ACTIONS.includes(r.action)||Date.now()>r.expiresAt)
146
- throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
147
- if(['continue','handoff','clean','start'].includes(r.action))validateIntent(r.action,r.intent);
148
- if(r.traceParent!==undefined&&!validParent(r.traceParent))delete r.traceParent;
149
- return r;
150
- }
151
- export function finish({id,nonce,action,status,payload='',code=null}) {
152
- const r=readRequest(id);
153
- if(nonce!==r.nonce||action!==r.action)throw Object.assign(Error('Request mismatch'),{code:'REQUEST_MISMATCH'});
154
- if(status!=='OK'&&status!=='FAILED')throw Object.assign(Error('Invalid status'),{code:'INVALID_RESULT'});
155
- const dir=requestDir(id);
156
- const resultPath=join(dir,'result.json');
157
- if(pathEntryExists(resultPath))throw Object.assign(Error('Duplicate result'),{code:'ALREADY_FINISHED'});
158
- let bytes=0,mimeType=null,filename=null;
159
- if(status==='OK'){
160
- if(typeof payload!=='string')throw Object.assign(Error('Invalid payload'),{code:'INVALID_PAYLOAD'});
161
- let buf;
162
- if(action==='chat_screenshot'){
163
- if(!/^[A-Za-z0-9+/]*={0,2}$/.test(payload))throw Object.assign(Error('Invalid PNG encoding'),{code:'INVALID_PNG'});
164
- buf=Buffer.from(payload,'base64');
165
- if(buf.subarray(0,8).toString('hex')!=='89504e470d0a1a0a')throw Object.assign(Error('Invalid PNG signature'),{code:'INVALID_PNG'});
166
- mimeType='image/png';filename='result.png';
167
- if(buf.length>MAX_PNG)throw Object.assign(Error('PNG too large'),{code:'RESULT_TOO_LARGE'});
168
- }else{
169
- buf=Buffer.from(payload,'utf8');
170
- if(buf.length>MAX_TEXT)throw Object.assign(Error('Text too large'),{code:'RESULT_TOO_LARGE'});
171
- mimeType=action==='chat_dom'?'text/html':'text/plain';
172
- filename=action==='reload'?null:action==='chat_dom'?'result.html':'result.txt';
173
- }
174
- bytes=buf.length;
175
- if(filename)writeFileSync(join(dir,filename),buf,{flag:'wx',mode:0o600});
176
- }
177
- const rec={id,action,status,code:status==='FAILED'?(String(code||'ACTION_FAILED').slice(0,120)):null,
178
- path:filename?join(dir,filename):null,bytes,mimeType,at:Date.now(),
179
- verified:action!=='reload'};
180
- writeFileSync(resultPath+'.tmp',JSON.stringify(rec),{flag:'wx',mode:0o600});
181
- renameSync(resultPath+'.tmp',resultPath);
182
- return rec;
183
- }
184
- export function readResult(id) {
185
- const p=join(requestDir(id),'result.json');
186
- if(!pathEntryExists(p))return null;
187
- privateDir(requestDir(id));
188
- privateRecord(p,'UNTRUSTED_RESULT');
189
- return JSON.parse(readFileSync(p,'utf8'));
190
- }
191
- export function cleanup(){
192
- const root=tempRoot();
193
- if(!existsSync(root))return;
194
- privateDir(root);
195
- for(const f of readdirSync(root)){
196
- if(!ID.test(f))continue;
197
- const p=join(root,f);
198
- try{
199
- const st=lstatSync(p);
200
- if(st.isDirectory()&&!st.isSymbolicLink()&&Date.now()-st.mtimeMs>TTL_MS)
201
- rmSync(p,{recursive:true,force:true});
202
- }catch{}
203
- }
204
- }
205
- export function validateExtensionId(id) {
206
- if(!/^[a-p]{32}$/.test(id||''))throw Object.assign(Error('Invalid Chrome extension ID'),{code:'INVALID_EXTENSION_ID'});
207
- return id;
208
- }
@@ -1,40 +0,0 @@
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
- export function openExtensionActionPage(url,{platform=process.platform,spawn=spawnSync}={}){
29
- if(platform!=='darwin')
30
- throw Object.assign(Error('Browser launcher not yet verified on this OS'),
31
- {code:'BROWSER_LAUNCH_UNSUPPORTED'});
32
- if(!/^chrome-extension:\/\/[a-p]{32}\/[a-z_]+\.html\?requestId=[a-f0-9]{32}$/.test(url))
33
- throw Object.assign(Error('Untrusted Extension Action URL'),{code:'INVALID_ACTION_URL'});
34
- const receipt=spawn('osascript',['-e',OPEN_IN_CHAT_WINDOW,url],
35
- {encoding:'utf8',timeout:7000});
36
- if(receipt.error||receipt.status!==0||!/\bWINDOW=\d+\b/.test(receipt.stdout||''))
37
- throw Object.assign(Error('Existing ChatGPT Chrome window unavailable or ambiguous'),
38
- {code:'CHROME_TARGET_WINDOW_UNVERIFIED'});
39
- return {status:'OPENED',windowVerified:true};
40
- }
@@ -1,45 +0,0 @@
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
- }
@@ -1,111 +0,0 @@
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){
41
- const dir=base();
42
- const st=lstatSync(dir);
43
- if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)
44
- ||(process.getuid&&st.uid!==process.getuid()))
45
- throw fail('CONTEXT_CONTROL_UNTRUSTED');
46
- privateFile(join(dir,'control.sock'),'socket');
47
- privateFile(join(dir,'manager.lock'),'file');
48
- const key=join(dir,'context-control.secret');
49
- const secretStats=privateFile(key,'file');
50
- if(secretStats.size!==32)throw fail('CONTEXT_CONTROL_UNTRUSTED');
51
- const hello=await ipc({action:'__ping'},2000);
52
- const lock=JSON.parse(readFileSync(join(dir,'manager.lock'),'utf8'));
53
- if(hello.contract!=='chat-loop.local-control.v1'
54
- ||lock.nonce!==hello.ownerNonce||lock.pid!==hello.managerPid
55
- ||lock.version!==hello.version||hello.version!==hello.packageVersion)
56
- throw fail('CONTEXT_CONTROL_OWNER_MISMATCH');
57
- const secret=readFileSync(key);
58
- const signed={contract:'chat-loop.context-control.v1',
59
- requestId:randomUUID(),issuedAt:Date.now(),payload:{command,args}};
60
- const mac=createHmac('sha256',secret).update(JSON.stringify(signed)).digest('hex');
61
- const reply=await ipc({...signed,action:'context-control',mac},6000);
62
- if(reply.contract!==hello.contract||reply.requestId!==signed.requestId)
63
- throw fail('CONTEXT_CONTROL_REPLY_INVALID');
64
- if(reply.status!=='OK')throw fail(reply.error?.code||'CONTEXT_CONTROL_FAILED');
65
- return reply.result;
66
- }
67
-
68
- // Independent, best-effort observation channel. No business data.
69
- // A separate identity ping for every event (or a shared ping for a burst)
70
- // caused the observed Supervisor IPC timeout fan-out. The existing private
71
- // manager.lock contains the current Manager identity: include it on the
72
- // observation itself, then let the Supervisor verify it atomically on receipt.
73
- 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;
74
- const API_NAME=/^extension\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
75
- const API_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
76
- export async function nativeApiObservation(record){
77
- if(!record||typeof record!=='object'||Array.isArray(record)||
78
- Object.keys(record).some(key=>!['callId','traceId','spanId','parentSpanId',
79
- 'apiName','phase','durationMs','errorCode'].includes(key))||
80
- !API_UUID.test(record.callId||'')||
81
- !API_UUID.test(record.traceId||'')||
82
- record.spanId!==record.callId||
83
- (record.parentSpanId!==undefined&&
84
- (!API_UUID.test(record.parentSpanId)||record.parentSpanId===record.spanId))||
85
- !API_NAME.test(record.apiName||'')||
86
- !['BEGIN','OK','FAILED'].includes(record.phase)||
87
- (record.phase==='BEGIN'
88
- ?record.durationMs!==undefined||record.errorCode!==undefined
89
- :!Number.isSafeInteger(record.durationMs)||record.durationMs<0||
90
- (record.phase==='FAILED'?!API_CODE.test(record.errorCode||'')
91
- :record.errorCode!==undefined)))
92
- throw fail('API_OBSERVATION_INVALID');
93
- const dir=base(),stat=lstatSync(dir);
94
- if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o077)||
95
- (process.getuid&&stat.uid!==process.getuid()))
96
- throw fail('API_OBSERVATION_UNTRUSTED');
97
- privateFile(join(dir,'control.sock'),'socket');
98
- const lockFile=join(dir,'manager.lock');
99
- privateFile(lockFile,'file');
100
- const manager=JSON.parse(readFileSync(lockFile,'utf8'));
101
- if(!API_UUID.test(manager.nonce||'')||!Number.isSafeInteger(manager.pid)
102
- ||manager.pid<1||typeof manager.version!=='string')
103
- throw fail('API_OBSERVATION_OWNER_UNTRUSTED');
104
- const request={contract:'chat-loop.local-control.v1',action:'__api_observation',
105
- requestId:randomUUID(),ownerNonce:manager.nonce,managerPid:manager.pid,...record};
106
- // The Supervisor verifies ownerNonce and managerPid before appending.
107
- // This is one socket and one ACK per event, never an Action retry.
108
- const response=await ipc(request,3500);
109
- return response.contract===request.contract&&
110
- response.requestId===request.requestId&&response.status==='OK';
111
- }
@@ -1,67 +0,0 @@
1
- // Official Extension/Native owner-evidence contract for Context's reviewed
2
- // orphan fence. Browser Owner remains Extension's authority, not Context's.
3
- import {execFileSync} from 'node:child_process';
4
- import {createHash} from 'node:crypto';
5
- import {readFileSync,lstatSync} from 'node:fs';
6
- let readSession,sessionPath,cliPath;
7
- export function configureOwnerEvidence(api){
8
- if(readSession)throw Error('EXTENSION_MODULE_ALREADY_COMPOSED');
9
- for(const name of ['readSession','sessionPath','cliPath'])
10
- if(typeof api?.[name]!=='function')throw Error('EXTENSION_PORT_MISSING:'+name);
11
- ({readSession,sessionPath,cliPath}=api);
12
- }
13
-
14
- const fail=code=>Object.assign(new Error(code),{code});
15
- const ensure=(ok,code)=>{if(!ok)throw fail(code)};
16
- const sha=raw=>createHash('sha256').update(raw).digest('hex');
17
-
18
- function checkedNative(){
19
- const session=readSession();
20
- ensure(session?.phase==='DONE'&&typeof session.sessionId==='string'
21
- &&Number.isSafeInteger(session.updatedAt),'NATIVE_NOT_TERMINAL');
22
- const raw=readFileSync(sessionPath());
23
- ensure(sha(Buffer.from(JSON.stringify(session)))===
24
- sha(Buffer.from(JSON.stringify(JSON.parse(raw.toString('utf8'))))),
25
- 'NATIVE_POINTER_UNTRUSTED');
26
- return {sessionId:session.sessionId,projectId:session.projectId,
27
- taskId:session.taskId||null,phase:session.phase,
28
- updatedAt:session.updatedAt,rawHash:sha(raw)};
29
- }
30
-
31
- function checkedExtensionIdle(){
32
- // This is the Extension-owned CLI, resolved from this installed package.
33
- // Context never composes an Extension install path or parses its CLI output.
34
- const cli=cliPath();
35
- const st=lstatSync(cli);
36
- ensure(st.isFile()&&!st.isSymbolicLink(),'EXTENSION_CLI_UNTRUSTED');
37
- const out=execFileSync(process.execPath,[cli,'extension','status'],{
38
- encoding:'utf8',timeout:14000,maxBuffer:524288,stdio:['ignore','pipe','pipe']});
39
- const rows=out.trim().split('\n').map(s=>JSON.parse(s));
40
- const result=rows.findLast(x=>x.event==='RESULT');
41
- ensure(result?.ok===true&&result.value?.verified===true
42
- &&result.value?.truncated===false,'EXTENSION_STATUS_UNVERIFIED');
43
- const v=JSON.parse(result.value.content||'{}');
44
- ensure(v.status==='OK'&&v.state==='IDLE'
45
- &&v.lastSession?.phase==='DONE','EXTENSION_OWNER_NOT_IDLE');
46
- return v;
47
- }
48
-
49
- /**
50
- * Read-only owner proof; NEVER grants execution or signs R/P approval.
51
- * Re-run before the final Context fence to detect Native/Worker drift.
52
- */
53
- export function verifyOrphanOwnerIdle({oldRunRef,projectId}){
54
- const native=checkedNative(),extension=checkedExtensionIdle();
55
- const oldId=oldRunRef.split(':')[0];
56
- ensure(native.sessionId!==oldId&&native.projectId!==projectId,
57
- 'ORPHAN_OWNER_STILL_CURRENT');
58
- const live=readSession();
59
- ensure(live?.phase==='DONE'&&
60
- extension.lastSession.sessionId===native.sessionId
61
- &&extension.lastSession.projectId===native.projectId
62
- &&extension.lastSession.updatedAt===native.updatedAt
63
- &&extension.lastSession.activeChatId===live.activeChatId
64
- &&checkedNative().rawHash===native.rawHash,
65
- 'EXTENSION_NATIVE_POINTER_MISMATCH');
66
- return native;
67
- }
@@ -1,120 +0,0 @@
1
- // Single-Mac durable session pointer. Extension Worker is the only admission/sending authority.
2
- // This file is a checked, minimal projection, not a second executor or task engine.
3
- import {openSync,closeSync,readFileSync,writeFileSync,renameSync,unlinkSync,lstatSync,mkdirSync} from 'node:fs';
4
- import {homedir} from 'node:os';
5
- import {join,dirname} from 'node:path';
6
- import {randomUUID} from 'node:crypto';
7
-
8
- const ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
- const CHAT=/^[0-9a-f-]{12,}$/i;
10
- const PROJECT=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
11
- const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY','DONE','BLOCKED']);
12
- const fail=code=>Object.assign(Error(code),{code});
13
- export const sessionPath=()=>join(homedir(),'.chat-loop','session','active-session.json');
14
- // An absent path differs from a dangling symlink: existsSync follows the
15
- // link and would otherwise silently erase the Native Owner projection.
16
- const entryOrMissing=path=>{
17
- try{return lstatSync(path)}
18
- catch(error){if(error.code==='ENOENT')return null;throw error}
19
- };
20
- const verifyPrivateDirectory=dir=>{
21
- const st=entryOrMissing(dir);
22
- if(st&&(!st.isDirectory()||st.isSymbolicLink()
23
- ||(process.getuid&&st.uid!==process.getuid())
24
- ||(process.platform!=='win32'&&(st.mode&0o077))))
25
- throw fail('SESSION_DIRECTORY_UNTRUSTED');
26
- return Boolean(st);
27
- };
28
- const ensurePrivate=dir=>{
29
- if(!verifyPrivateDirectory(dir))mkdirSync(dir,{recursive:true,mode:0o700});
30
- if(!verifyPrivateDirectory(dir))throw fail('SESSION_DIRECTORY_UNTRUSTED');
31
- };
32
- const validate=r=>{
33
- if(!r||typeof r!=='object'||Array.isArray(r)||
34
- !ID.test(r.sessionId||'')||!PROJECT.test(r.projectId||'')||
35
- (r.taskId!==undefined && !PROJECT.test(r.taskId))||
36
- !PHASE.has(r.phase)||!Number.isSafeInteger(r.generation)||r.generation<0||
37
- !Number.isSafeInteger(r.updatedAt)||r.updatedAt<=0)
38
- throw fail('SESSION_INVALID');
39
- if(r.activeChatId!==null&&(typeof r.activeChatId!=='string'||!CHAT.test(r.activeChatId)))
40
- throw fail('SESSION_CHAT_INVALID');
41
- if(r.activeChatUrl!==null&&(typeof r.activeChatUrl!=='string'
42
- || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(r.activeChatUrl)))
43
- throw fail('SESSION_CHAT_INVALID');
44
- if((r.activeChatId===null)!==(r.activeChatUrl===null))
45
- throw fail('SESSION_CHAT_INVALID');
46
- if(r.activeChatUrl!==null&&!r.activeChatUrl.endsWith('/'+r.activeChatId))
47
- throw fail('SESSION_CHAT_INVALID');
48
- if(r.activeChatId===null&&r.phase==='WAITING_REPLY')throw fail('SESSION_CHAT_INVALID');
49
- const keys=['sessionId','projectId','phase','generation','activeChatId','activeChatUrl','updatedAt','taskId'];
50
- if(Object.keys(r).some(k=>!keys.includes(k)))throw fail('SESSION_EXTRA_FIELDS');
51
- return Object.fromEntries(keys.filter(k=>Object.hasOwn(r,k)).map(k=>[k,r[k]]));
52
- };
53
- export function readSession(){
54
- const file=sessionPath();
55
- if(!verifyPrivateDirectory(dirname(file)))return null;
56
- const st=entryOrMissing(file);
57
- if(!st)return null;
58
- if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
59
- ||(process.platform!=='win32'&&(st.mode&0o077)))throw fail('SESSION_FILE_UNTRUSTED');
60
- try{return validate(JSON.parse(readFileSync(file,'utf8')));}
61
- catch(e){if(e.code)throw e;throw fail('SESSION_FILE_CORRUPT');}
62
- }
63
- export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSessionId=null,resumeBlockedUpdatedAt=null){
64
- const next=validate(input),file=sessionPath(),dir=dirname(file),lock=file+'.lock';
65
- ensurePrivate(dir);
66
- let fd;
67
- try{fd=openSync(lock,'wx',0o600);}catch{throw fail('SESSION_CONCURRENT_UPDATE');}
68
- try{
69
- const old=readSession();
70
- if(resumeBlockedSessionId){
71
- // A BLOCKED session is terminal except for an exact-same-owner,
72
- // same-Chat, same-generation, one-shot recovery CAS. No new Chat,
73
- // task, project, approval or Handoff may be smuggled into recovery.
74
- if(replaceBlockedSessionId || !old || old.phase!=='BLOCKED'
75
- ||resumeBlockedUpdatedAt!==null&&old.updatedAt!==resumeBlockedUpdatedAt
76
- ||old.sessionId!==resumeBlockedSessionId
77
- ||next.sessionId!==old.sessionId
78
- ||next.projectId!==old.projectId
79
- ||next.taskId!==old.taskId
80
- ||next.generation!==old.generation
81
- ||next.activeChatId!==old.activeChatId
82
- ||next.activeChatUrl!==old.activeChatUrl
83
- ||next.phase!=='RESERVED')
84
- throw fail('SESSION_RECOVERY_MISMATCH');
85
- }
86
- if(replaceBlockedSessionId && (!old||old.sessionId!==next.sessionId
87
- && (old.phase!=='BLOCKED'||old.sessionId!==replaceBlockedSessionId)))
88
- throw fail('SESSION_REPLACEMENT_MISMATCH');
89
- if(old&&old.sessionId!==next.sessionId&&old.phase!=='DONE'
90
- && !(old.phase==='BLOCKED' && next.phase==='STARTING'
91
- && replaceBlockedSessionId===old.sessionId && next.projectId!==old.projectId))
92
- throw fail('SESSION_ALREADY_ACTIVE');
93
- if(old&&old.sessionId===next.sessionId){
94
- if(next.projectId!==old.projectId)throw fail('SESSION_PROJECT_CHANGED');
95
- if(next.taskId!==old.taskId)throw fail('SESSION_TASK_CHANGED');
96
- if(next.generation<old.generation)throw fail('SESSION_STALE_GENERATION');
97
- if(old.phase==='DONE'&&next.phase!=='DONE'||old.phase==='BLOCKED'
98
- && !['BLOCKED','DONE'].includes(next.phase)
99
- &&!(resumeBlockedSessionId===old.sessionId
100
- &&next.phase==='RESERVED'))
101
- throw fail('SESSION_TERMINAL_LOCKED');
102
- if(old.activeChatId!==null&&next.generation===old.generation&&
103
- next.activeChatId!==null&&old.activeChatId!==next.activeChatId)
104
- throw fail('SESSION_CHAT_CHANGED_WITHOUT_HANDOFF');
105
- }
106
- // A read-only Status query and non-authoritative Worker diagnostics can
107
- // re-sync the SAME durable projection. These are not a new Session
108
- // transition: preserve Native's CAS timestamp and avoid rewriting disk.
109
- // A genuine phase/identity/generation change still advances the record.
110
- if(old && !replaceBlockedSessionId && !resumeBlockedSessionId
111
- && ['sessionId','projectId','taskId','phase','generation',
112
- 'activeChatId','activeChatUrl'].every(key=>old[key]===next[key]))
113
- return old;
114
- const temp=join(dir,'.active-session-'+randomUUID()+'.tmp');
115
- try{writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{flag:'wx',mode:0o600});
116
- renameSync(temp,file);
117
- }catch(e){try{unlinkSync(temp);}catch{}throw e;}
118
- return next;
119
- }finally{closeSync(fd);unlinkSync(lock);}
120
- }
@@ -1,38 +0,0 @@
1
- {
2
- "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.11",
4
- "type": "module",
5
- "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
- "bin": {
7
- "chatloop-extension": "bin/cli.mjs"
8
- },
9
- "engines": {
10
- "node": ">=20"
11
- },
12
- "publishConfig": {
13
- "access": "public"
14
- },
15
- "files": [
16
- "index.mjs",
17
- "actions.generated.mjs",
18
- "capabilities/",
19
- "scripts/",
20
- "extension/",
21
- "bin/",
22
- "lib/",
23
- "README.md"
24
- ],
25
- "scripts": {
26
- "build:actions": "node ./scripts/build-actions.mjs",
27
- "build:actions:check": "node ./scripts/build-actions.mjs --check",
28
- "pretest": "node ./scripts/build-actions.mjs --check",
29
- "prepack": "node ./scripts/build-actions.mjs --check",
30
- "test": "node --test ./test/*.test.mjs"
31
- },
32
- "exports": {
33
- ".": "./index.mjs"
34
- },
35
- "dependencies": {
36
- "@tomflow/chatloop-trace": "0.4.4"
37
- }
38
- }