@tomflow/chatloop-tools 0.9.63 → 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 (83) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +16 -7
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/node_modules/@tomflow/chatloop-context/README.md +56 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +24 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +1 -1
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +2 -2
  12. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +69 -0
  13. package/node_modules/@tomflow/chatloop-context/index.mjs +3 -1
  14. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +50 -3
  15. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +54 -1
  16. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +2 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +61 -2
  18. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +33 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +14 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +31 -39
  22. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +6 -5
  23. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +84 -3
  24. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +52 -7
  25. package/node_modules/@tomflow/chatloop-context/package.json +2 -4
  26. package/node_modules/@tomflow/chatloop-extension/README.md +66 -0
  27. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +19 -4
  28. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +40 -1
  29. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -1
  30. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +54 -4
  31. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +9 -3
  33. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +9 -5
  34. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +53 -10
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +34 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +16 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +1 -1
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +7 -6
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +64 -7
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +235 -95
  43. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/session.html +1 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +3 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +73 -16
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +23 -6
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +237 -13
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  65. package/node_modules/@tomflow/chatloop-extension/index.mjs +7 -0
  66. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +94 -19
  67. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +3 -3
  68. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +9 -2
  69. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  76. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  77. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  78. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  79. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +50 -7
  80. package/node_modules/@tomflow/chatloop-extension/package.json +1 -3
  81. package/node_modules/@tomflow/chatloop-trace/package.json +1 -3
  82. package/package.json +9 -11
  83. package/providers/extension.mjs +59 -16
@@ -1,4 +1,4 @@
1
- import {randomUUID} from 'node:crypto';
1
+ import {randomBytes,randomUUID} from 'node:crypto';
2
2
  import {existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync} from 'node:fs';
3
3
  import {homedir, tmpdir} from 'node:os';
4
4
  import {join} from 'node:path';
@@ -21,6 +21,11 @@ const ID = /^[a-f0-9]{32}$/;
21
21
  const MAX_TEXT = 8 * 1024 * 1024;
22
22
  const MAX_PNG = 24 * 1024 * 1024;
23
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;
24
29
  const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
25
30
  function pathEntryExists(path){
26
31
  try{lstatSync(path);return true}
@@ -60,13 +65,46 @@ export function requestDir(id) {
60
65
  if(typeof id!=='string'||!ID.test(id))throw Object.assign(Error('Invalid request ID'),{code:'INVALID_REQUEST_ID'});
61
66
  return join(tempRoot(),id);
62
67
  }
63
- function validateIntent(action, intent) {
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
+ }
64
81
  if(action==='session'){
65
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
+ }
66
102
  const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
103
+ const scoped=intent?.taskFirst===true;
67
104
  const keys=['operation','projectId','taskId','sessionId','generation',
68
- 'expectedNativeUpdatedAt','expectedTaskRevision',
69
- 'expectedBindingRevision','contextStoreEpoch','confirmed'];
105
+ scoped?'expectedNativeRevision':'expectedNativeUpdatedAt',
106
+ 'expectedTaskRevision','expectedBindingRevision',
107
+ 'contextStoreEpoch','confirmed',...(scoped?['taskFirst']:[])];
70
108
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
71
109
  ||Object.keys(intent).length!==keys.length
72
110
  ||keys.some(k=>!Object.hasOwn(intent,k))
@@ -74,8 +112,11 @@ function validateIntent(action, intent) {
74
112
  ||!ID.test(intent.projectId||'')||!ID.test(intent.taskId||'')
75
113
  ||!UUID.test(intent.sessionId||'')
76
114
  ||!Number.isSafeInteger(intent.generation)||intent.generation<0
77
- ||!Number.isSafeInteger(intent.expectedNativeUpdatedAt)
78
- ||intent.expectedNativeUpdatedAt<=0
115
+ ||(scoped
116
+ ?!Number.isSafeInteger(intent.expectedNativeRevision)
117
+ ||intent.expectedNativeRevision<1
118
+ :!Number.isSafeInteger(intent.expectedNativeUpdatedAt)
119
+ ||intent.expectedNativeUpdatedAt<=0)
79
120
  ||!Number.isSafeInteger(intent.expectedTaskRevision)
80
121
  ||intent.expectedTaskRevision<1
81
122
  ||!Number.isSafeInteger(intent.expectedBindingRevision)
@@ -110,7 +151,7 @@ function validateIntent(action, intent) {
110
151
  }
111
152
  if(action==='start'){
112
153
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
113
- ||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision'].includes(k))
154
+ ||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision','taskFirst'].includes(k))
114
155
  ||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.projectId||'')
115
156
  ||(intent.taskId!==undefined && !(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.taskId))
116
157
  ||(intent.purpose!==undefined && (intent.purpose!=='REPAIR_SAME_SCOPE'
@@ -124,6 +165,11 @@ function validateIntent(action, intent) {
124
165
  ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
125
166
  // Public Extension CLI must not bypass the managed Context Start lease.
126
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))
127
173
  ||intent.confirmed!==true || (intent.mode!==undefined && intent.mode!=='adopt')
128
174
  || (intent.replaceBlockedSessionId!==undefined
129
175
  && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId))
@@ -135,6 +181,7 @@ function validateIntent(action, intent) {
135
181
  ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)))
136
182
  throw Object.assign(Error('Explicit confirmed task and project required'),{code:'INVALID_START_INTENT'});
137
183
  return {projectId:intent.projectId,confirmed:true,
184
+ ...(intent.taskFirst===true?{taskFirst:true}:{}),
138
185
  ...(intent.taskId?{taskId:intent.taskId}:{}),
139
186
  ...(intent.purpose?{purpose:intent.purpose}:{}),
140
187
  ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
@@ -156,19 +203,24 @@ function validateIntent(action, intent) {
156
203
  return null;
157
204
  }
158
205
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
206
+ ||(intent.taskFirst!==undefined&&intent.taskFirst!==true)
159
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))
160
208
  throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
161
209
  // Query is read-only and uses the same formal Action page; no seventh Action.
162
210
  if(Object.hasOwn(intent,'intentId')||intent.lookup===true){
163
211
  const latest=intent.lookup===true;
164
- if(Object.keys(intent).some(k=>k!=='turnToken'&&k!==(latest?'lookup':'intentId'))
212
+ if(Object.keys(intent).some(k=>k!=='turnToken'&&k!=='taskFirst'
213
+ &&k!==(latest?'lookup':'intentId'))
165
214
  ||latest&&Object.hasOwn(intent,'intentId')
166
215
  ||!latest&&(typeof intent.intentId!=='string'||!/^[a-f0-9]{32}$/.test(intent.intentId)))
167
216
  throw Object.assign(Error('Invalid intent query'),{code:'INVALID_INTENT'});
168
- return latest?{turnToken:intent.turnToken,lookup:true}
169
- :{turnToken:intent.turnToken,intentId:intent.intentId};
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}:{})};
170
221
  }
171
- if(Object.keys(intent).some(k=>k!=='turnToken'&&(action==='continue'?k!=='nextPrompt':k!=='reason')))
222
+ if(Object.keys(intent).some(k=>k!=='turnToken'&&k!=='taskFirst'
223
+ &&(action==='continue'?k!=='nextPrompt':k!=='reason')))
172
224
  throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
173
225
  if(action==='continue' && (typeof intent.nextPrompt!=='string'
174
226
  || !intent.nextPrompt.trim() || intent.nextPrompt.length>4000
@@ -178,12 +230,17 @@ function validateIntent(action, intent) {
178
230
  && (typeof intent.reason!=='string'||intent.reason.length>400
179
231
  || /[\x00-\x1f]/.test(intent.reason)))
180
232
  throw Object.assign(Error('Invalid handoff reason'),{code:'INVALID_INTENT'});
181
- return action==='continue' ? {turnToken:intent.turnToken,nextPrompt:intent.nextPrompt}
182
- : {turnToken:intent.turnToken,reason:intent.reason||''};
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}:{})};
183
238
  }
184
239
  export function prepare(action,intent) {
185
240
  if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown extension action'),{code:'UNKNOWN_ACTION'});
186
- const validated=validateIntent(action,intent);
241
+ const input=validateIntent(action,intent);
242
+ const validated=action==='session'&&input?.operation==='recover-handoff'
243
+ ?{...input,newRunCredential:randomBytes(32).toString('hex')}:input;
187
244
  privateDir(tempRoot());
188
245
  cleanup();
189
246
  const id=randomUUID().replaceAll('-',''), nonce=randomUUID().replaceAll('-',''), at=Date.now();
@@ -192,7 +249,9 @@ export function prepare(action,intent) {
192
249
  // Correlation is soft: never promote it to a capability or Owner proof.
193
250
  let traceParent=null;
194
251
  try{const current=readApiParent();if(validParent(current))traceParent=current}catch{}
195
- writeFileSync(join(dir,'request.json'), JSON.stringify({id,nonce,action,at,expiresAt:at+TTL_MS,...(traceParent?{traceParent}:{}),...(validated ? {intent:validated} : {})}),
252
+ writeFileSync(join(dir,'request.json'), JSON.stringify({id,nonce,action,at,
253
+ expiresAt:at+requestTtl(action,validated),
254
+ ...(traceParent?{traceParent}:{}),...(validated ? {intent:validated} : {})}),
196
255
  {flag:'wx',mode:0o600});
197
256
  return {id,nonce,action,dir};
198
257
  }
@@ -203,9 +262,13 @@ export function readRequest(id) {
203
262
  const p=join(dir,'request.json');
204
263
  privateRecord(p,'UNTRUSTED_REQUEST');
205
264
  const r=JSON.parse(readFileSync(p,'utf8'));
206
- if(r.id!==id||!ACTIONS.includes(r.action)||Date.now()>r.expiresAt)
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)
207
269
  throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
208
- if(['continue','handoff','clean','start','session','entry_test'].includes(r.action))validateIntent(r.action,r.intent);
270
+ if(['continue','handoff','clean','start','status','session',
271
+ 'entry_test'].includes(r.action))validateIntent(r.action,r.intent,true);
209
272
  if(r.traceParent!==undefined&&!validParent(r.traceParent))delete r.traceParent;
210
273
  return r;
211
274
  }
@@ -292,8 +355,20 @@ export function cleanup(){
292
355
  const p=join(root,f);
293
356
  try{
294
357
  const st=lstatSync(p);
295
- if(st.isDirectory()&&!st.isSymbolicLink()&&Date.now()-st.mtimeMs>TTL_MS)
296
- rmSync(p,{recursive:true,force:true});
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
+ }
297
372
  }catch{}
298
373
  }
299
374
  }
@@ -72,12 +72,12 @@ export function openExtensionActionPage(url,{platform=process.platform,spawn=spa
72
72
  // The private session Action uses a fixed operation selector in addition to
73
73
  // its request locator. No other Action may accept arbitrary URL arguments.
74
74
  const ordinary=/^chrome-extension:\/\/[a-p]{32}\/(?!session\.html)[a-z_]+\.html\?requestId=[a-f0-9]{32}$/;
75
- const cancel=/^chrome-extension:\/\/[a-p]{32}\/session\.html\?requestId=[a-f0-9]{32}&operation=cancel$/;
76
- if(!ordinary.test(url)&&!cancel.test(url))
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
77
  throw Object.assign(Error('Untrusted Extension Action URL'),{code:'INVALID_ACTION_URL'});
78
78
  // An orphaned Owner may have no Chat tab at all. The existing verified
79
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)?$/);
80
+ const entry=url.match(/^chrome-extension:\/\/([a-p]{32})\/(?:entry_test|session)\.html\?requestId=[a-f0-9]{32}(?:&operation=(?:cancel|recover-handoff))?$/);
81
81
  const launchArgs=entry
82
82
  ?['-e',OPEN_TEST_ENTRY_WINDOW,url,'chrome://extensions/?id='+entry[1]]
83
83
  :['-e',OPEN_IN_CHAT_WINDOW,url];
@@ -37,7 +37,13 @@ const ipc=(request,timeout=4000)=>new Promise((resolve,reject)=>{
37
37
  try{finish(null,JSON.parse(text.slice(0,n)))}catch{finish(fail('CONTEXT_CONTROL_REPLY_INVALID'))}
38
38
  });
39
39
  });
40
- export async function nativeContextControl(command,args){
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');
41
47
  const dir=base();
42
48
  const st=lstatSync(dir);
43
49
  if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)
@@ -56,7 +62,8 @@ export async function nativeContextControl(command,args){
56
62
  throw fail('CONTEXT_CONTROL_OWNER_MISMATCH');
57
63
  const secret=readFileSync(key);
58
64
  const signed={contract:'chat-loop.context-control.v1',
59
- requestId:randomUUID(),issuedAt:Date.now(),payload:{command,args}};
65
+ requestId:randomUUID(),issuedAt:Date.now(),payload:{command,args,
66
+ ...(ownerProofV2?{ownerProofV2}:{})}};
60
67
  const mac=createHmac('sha256',secret).update(JSON.stringify(signed)).digest('hex');
61
68
  const reply=await ipc({...signed,action:'context-control',mac},6000);
62
69
  if(reply.contract!==hello.contract||reply.requestId!==signed.requestId)
@@ -0,0 +1,106 @@
1
+ // One Native-only V1/V2 Owner mutation lock on macOS.
2
+ // A permanent 0600 marker fences the old O_EXCL writers; lockf -k holds
3
+ // the kernel lock across the entire CAS in a one-shot private subprocess.
4
+ // Never unlink or infer an abandoned legacy lock from its age/PID.
5
+ import {openSync,closeSync,lstatSync,mkdirSync,readFileSync,writeFileSync,
6
+ fsyncSync,unlinkSync} from 'node:fs';
7
+ import {homedir} from 'node:os';
8
+ import {join} from 'node:path';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {spawnSync} from 'node:child_process';
11
+
12
+ const fail=code=>Object.assign(Error(code),{code});
13
+ const marker='CHAT_LOOP_OWNER_KERNEL_LOCK_V1\n';
14
+ const path=()=>join(homedir(),'.chat-loop','session','owner-registry.lock');
15
+ const helper=fileURLToPath(new URL('./owner-locked-write.mjs',import.meta.url));
16
+ const stat=p=>{try{return lstatSync(p)}catch(e){if(e.code==='ENOENT')return null;throw e;}};
17
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
18
+ const terminal=s=>['DONE','CANCELLED'].includes(s?.phase);
19
+ function checkedOwnerSnapshot(p){
20
+ const st=stat(p);
21
+ if(!st)return null;
22
+ if(!st.isFile()||st.isSymbolicLink()||st.size>128*1024
23
+ ||(st.mode&0o077)||(process.getuid&&st.uid!==process.getuid()))
24
+ throw fail('OWNER_LOCK_CUTOVER_UNVERIFIED');
25
+ try{return JSON.parse(readFileSync(p,'utf8'))}
26
+ catch{throw fail('OWNER_LOCK_CUTOVER_UNVERIFIED')}
27
+ }
28
+ function assertLegacyQuiescent(dir){
29
+ // The old O_EXCL lock is held throughout these reads. A live old Writer
30
+ // cannot mutate V1/V2 under us; never strand an ACTIVE legacy Owner by
31
+ // installing a permanent marker before the old session terminates.
32
+ const v1=checkedOwnerSnapshot(join(dir,'active-session.json'));
33
+ if(v1&&(!terminal(v1)||!UUID.test(v1.sessionId||'')
34
+ ||typeof v1.projectId!=='string'))
35
+ throw fail('OWNER_LOCK_CUTOVER_ACTIVE');
36
+ const v2=checkedOwnerSnapshot(join(dir,'owner-ledger-v2.json'));
37
+ if(v2&&(v2.schemaVersion!==2||!Number.isSafeInteger(v2.ledgerRevision)
38
+ ||!v2.sessions||typeof v2.sessions!=='object'
39
+ ||Array.isArray(v2.sessions)
40
+ ||Object.values(v2.sessions).some(s=>!terminal(s)
41
+ ||!UUID.test(s.sessionId||''))))
42
+ throw fail('OWNER_LOCK_CUTOVER_ACTIVE');
43
+ }
44
+ function ensureMarker(){
45
+ if(process.platform!=='darwin')throw fail('OWNER_KERNEL_LOCK_UNSUPPORTED');
46
+ const file=path(),dir=join(homedir(),'.chat-loop','session');
47
+ // Legacy V1 and V2 both supported a fresh private Session directory.
48
+ if(!stat(dir)){
49
+ try{mkdirSync(dir,{recursive:true,mode:0o700})}
50
+ catch{throw fail('OWNER_LOCK_DIRECTORY_UNTRUSTED')}
51
+ }
52
+ const d=stat(dir);
53
+ if(!d?.isDirectory()||d.isSymbolicLink()||(d.mode&0o077)
54
+ ||(process.getuid&&d.uid!==process.getuid()))
55
+ throw fail('OWNER_LOCK_DIRECTORY_UNTRUSTED');
56
+ if(!stat(file)){
57
+ let fd,created=false,promoting=false;
58
+ try{
59
+ // This 'wx' is the LAST use of the old protocol: it excludes every
60
+ // installed V1/V2 writer during both idle checks and marker promotion.
61
+ fd=openSync(file,'wx',0o600);created=true;
62
+ assertLegacyQuiescent(dir);
63
+ // Once promotion begins, never unlink a possibly valid marker:
64
+ // another new process may already be holding a kernel lock on it.
65
+ promoting=true;
66
+ writeFileSync(fd,marker);fsyncSync(fd);
67
+ const parent=openSync(dir,'r');
68
+ try{fsyncSync(parent)}finally{closeSync(parent)}
69
+ }catch(e){
70
+ if(created&&!promoting){try{unlinkSync(file)}catch{}}
71
+ if(e.code!=='EEXIST')
72
+ throw e?.code&&e.code.startsWith('OWNER_')?e
73
+ :fail('OWNER_LOCK_MARKER_WRITE_FAILED');
74
+ }finally{if(fd!==undefined)closeSync(fd)}
75
+ }
76
+ const st=stat(file);
77
+ if(!st?.isFile()||st.isSymbolicLink()||st.size!==Buffer.byteLength(marker)
78
+ ||(st.mode&0o077)||(process.getuid&&st.uid!==process.getuid())
79
+ ||readFileSync(file,'utf8')!==marker)
80
+ throw fail('OWNER_LOCK_MIGRATION_REQUIRED');
81
+ return file;
82
+ }
83
+ export function withOwnerKernelLock(kind,args){
84
+ if(!['legacy-write','scoped-write','scoped-retire'].includes(kind)
85
+ ||!Array.isArray(args))throw fail('OWNER_LOCK_REQUEST_INVALID');
86
+ const file=ensureMarker();
87
+ const result=spawnSync('/usr/bin/lockf',
88
+ ['-k','-n','-t','2',file,process.execPath,helper],{
89
+ // Do not kill lockf after acquisition: its child could outlive it
90
+ // and keep writing without the parent-held kernel lock.
91
+ input:JSON.stringify({kind,args}),encoding:'utf8',
92
+ maxBuffer:512*1024
93
+ });
94
+ // A crashed helper may already have committed its atomic rename.
95
+ // Only the kernel's lock-contention exit is a proven no-write result.
96
+ if(result.status===75)throw fail('OWNER_LEDGER_LOCKED');
97
+ if(result.error||result.status!==0||result.signal)
98
+ throw fail('OWNER_WRITE_RECEIPT_UNKNOWN');
99
+ let reply;
100
+ try{reply=JSON.parse(result.stdout)}catch{throw fail('OWNER_WRITE_RECEIPT_UNKNOWN')}
101
+ if(reply?.status==='FAILED'&&typeof reply.code==='string'
102
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(reply.code))throw fail(reply.code);
103
+ if(reply?.status!=='OK'||!Object.hasOwn(reply,'result'))
104
+ throw fail('OWNER_WRITE_RECEIPT_UNKNOWN');
105
+ return reply.result;
106
+ }