@tomflow/chatloop-extension 0.4.34 → 0.4.35

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 (56) hide show
  1. package/README.md +66 -0
  2. package/bin/cli.mjs +19 -4
  3. package/bin/native-host.mjs +40 -1
  4. package/capabilities/session.mjs +1 -1
  5. package/extension/actions/continue.js +54 -4
  6. package/extension/actions/handoff-scoped.js +143 -0
  7. package/extension/actions/handoff.js +9 -3
  8. package/extension/actions/model-intent.js +9 -5
  9. package/extension/actions/session.js +53 -10
  10. package/extension/actions/start.js +34 -0
  11. package/extension/actions/status.js +16 -2
  12. package/extension/background.js +16 -0
  13. package/extension/loop/index.js +1 -1
  14. package/extension/loop/observer-approval.js +19 -10
  15. package/extension/loop/observer-poll.js +7 -6
  16. package/extension/loop/observer.js +64 -7
  17. package/extension/loop/resource-maintenance.js +159 -0
  18. package/extension/loop/resources.js +235 -95
  19. package/extension/manifest.json +2 -1
  20. package/extension/session.html +1 -0
  21. package/extension/worker/admission.js +3 -0
  22. package/extension/worker/bootstrap.js +73 -16
  23. package/extension/worker/router.js +23 -6
  24. package/extension/worker/scheduler.js +237 -13
  25. package/extension/worker/task-action-v2.js +278 -0
  26. package/extension/worker/task-cancel-recovery-v2.js +52 -0
  27. package/extension/worker/task-cancel-v2.js +93 -0
  28. package/extension/worker/task-continue-recovery-v2.js +78 -0
  29. package/extension/worker/task-handoff-recovery-v2.js +148 -0
  30. package/extension/worker/task-handoff-v2.js +325 -0
  31. package/extension/worker/task-hold-recovery-v2.js +109 -0
  32. package/extension/worker/task-intent-dispatch-v2.js +220 -0
  33. package/extension/worker/task-intent-v2.js +106 -0
  34. package/extension/worker/task-owner-resolver.js +110 -0
  35. package/extension/worker/task-recover-v2.js +209 -0
  36. package/extension/worker/task-routes-v2.js +357 -0
  37. package/extension/worker/task-run-store.js +400 -0
  38. package/extension/worker/task-scheduler.js +78 -0
  39. package/extension/worker/task-start-v2.js +361 -0
  40. package/extension/worker/task-terminal-v2.js +235 -0
  41. package/index.mjs +7 -0
  42. package/lib/bridge.mjs +94 -19
  43. package/lib/browser-launch.mjs +3 -3
  44. package/lib/context-ipc.mjs +9 -2
  45. package/lib/owner-kernel-lock.mjs +106 -0
  46. package/lib/owner-ledger.mjs +316 -0
  47. package/lib/owner-locked-write.mjs +30 -0
  48. package/lib/scoped-cancel-v2.mjs +190 -0
  49. package/lib/scoped-continue-v2.mjs +214 -0
  50. package/lib/scoped-handoff-v2.mjs +338 -0
  51. package/lib/scoped-native-control.mjs +398 -0
  52. package/lib/scoped-recovery-v2.mjs +234 -0
  53. package/lib/scoped-retire-v2.mjs +70 -0
  54. package/lib/scoped-terminal-v2.mjs +143 -0
  55. package/lib/session-file.mjs +50 -7
  56. package/package.json +2 -4
@@ -0,0 +1,70 @@
1
+ // Native-only terminal retention. Context is still the permanent Task truth.
2
+ // Never retire BLOCKED/UNKNOWN or infer safety from a closed Chrome tab.
3
+ export function createScopedRetireControl(ports){
4
+ const {readScopedOwner,retireScopedOwner,nativeContextControl}=ports;
5
+ const fail=code=>Object.assign(Error(code),{code});
6
+ const assert=(condition,code)=>{if(!condition)throw fail(code)};
7
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f-]{12}$/i;
9
+ async function handle(m){
10
+ assert(m&&Object.keys(m).length===6
11
+ &&typeof retireScopedOwner==='function'
12
+ &&m.op==='task-retire-v2'
13
+ &&ID.test(m.projectId||'')&&ID.test(m.taskId||'')
14
+ &&UUID.test(m.sessionId||'')
15
+ &&Number.isSafeInteger(m.generation)&&m.generation>=0
16
+ &&Number.isSafeInteger(m.expectedSessionRevision)
17
+ &&m.expectedSessionRevision>=1,'SCOPED_RETIRE_SOURCE_INVALID');
18
+ const observed=readScopedOwner(m.projectId,m.taskId).session;
19
+ if(!observed){
20
+ // The original Context-approved Native deletion may have committed
21
+ // before its one-shot ACK was delivered. Read ONLY the exact Native
22
+ // retirement receipt; never infer a deletion from an absent Owner.
23
+ const recorded=retireScopedOwner(m.projectId,m.taskId,{
24
+ expectedSessionId:m.sessionId,
25
+ expectedGeneration:m.generation,
26
+ expectedSessionRevision:m.expectedSessionRevision});
27
+ assert(recorded?.status==='RETIRED'&&recorded.alreadyRetired===true,
28
+ 'SCOPED_RETIRE_TOMBSTONE_UNVERIFIED');
29
+ return {status:'OK',scope:'TASK_SCOPED_RETIRED',
30
+ projectId:m.projectId,taskId:m.taskId,sessionId:m.sessionId,
31
+ generation:m.generation,nativeOwnerRevision:m.expectedSessionRevision,
32
+ terminal:recorded.terminal,alreadyRetired:true};
33
+ }
34
+ assert(observed&&observed.sessionId===m.sessionId
35
+ &&observed.generation===m.generation
36
+ &&observed.revision===m.expectedSessionRevision
37
+ &&['DONE','CANCELLED'].includes(observed.phase)
38
+ &&Date.now()-observed.updatedAt>=24*60*60*1000,
39
+ 'SCOPED_RETIRE_NOT_READY');
40
+ const proof=Object.fromEntries(['projectId','taskId','sessionId',
41
+ 'generation','revision','phase','activeChatId']
42
+ .map(k=>[k,observed[k]]));
43
+ const state=await nativeContextControl('run.terminalStatus',{
44
+ projectId:observed.projectId,taskId:observed.taskId,
45
+ sessionId:observed.sessionId,generation:observed.generation,
46
+ activeChatId:observed.activeChatId},{ownerProofV2:proof});
47
+ assert(state?.projectId===observed.projectId
48
+ &&state.taskId===observed.taskId&&state.runRef===null
49
+ &&state.pendingHandoff===false
50
+ &&state.pendingCheckpointId===null
51
+ &&state.unknownEffectCount===0
52
+ &&(observed.phase!=='DONE'
53
+ ||state.executionOutcome==='DONE'
54
+ &&typeof state.deliveryRef==='string'&&state.deliveryRef)
55
+ &&(observed.phase!=='CANCELLED'
56
+ ||state.sessionCancellation?.status==='CANCELLED_NOT_DELIVERED'
57
+ &&state.sessionCancellation.sessionId===observed.sessionId
58
+ &&state.sessionCancellation.generation===observed.generation),
59
+ 'SCOPED_RETIRE_CONTEXT_UNVERIFIED');
60
+ const retired=retireScopedOwner(m.projectId,m.taskId,{
61
+ expectedSessionId:observed.sessionId,
62
+ expectedGeneration:observed.generation,
63
+ expectedSessionRevision:observed.revision});
64
+ return {status:'OK',scope:'TASK_SCOPED_RETIRED',
65
+ projectId:observed.projectId,taskId:observed.taskId,
66
+ sessionId:observed.sessionId,generation:observed.generation,
67
+ nativeOwnerRevision:observed.revision,terminal:retired.terminal};
68
+ }
69
+ return Object.freeze({handle});
70
+ }
@@ -0,0 +1,143 @@
1
+ // Model terminal marker -> independent Context terminal proof -> Native CAS.
2
+ // Task-specific, no Chat send, no Context identity from the browser message.
3
+ export function createScopedTerminalControl(ports){
4
+ const {readScopedOwner,writeScopedOwner,nativeContextControl}=ports;
5
+ const fail=code=>Object.assign(Error(code),{code});
6
+ const require=(yes,code)=>{if(!yes)throw fail(code)};
7
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
9
+ const proof=s=>Object.fromEntries(['projectId','taskId','sessionId',
10
+ 'generation','revision','phase','activeChatId'].map(k=>[k,s[k]]));
11
+ async function readCommitted(m){
12
+ // A Native terminal CAS may have committed before the Worker saw its
13
+ // response. Reconcile ONLY the same Session/Chat and authoritative
14
+ // Context outcome; this function never writes to Context or Ledger.
15
+ require(m&&Object.keys(m).length===8
16
+ &&m.op==='task-terminal-read-v2'
17
+ &&ID.test(m.projectId||'')&&ID.test(m.taskId||'')
18
+ &&UUID.test(m.sessionId||'')
19
+ &&Number.isSafeInteger(m.generation)&&m.generation>=0
20
+ &&Number.isSafeInteger(m.expectedPriorSessionRevision)
21
+ &&m.expectedPriorSessionRevision>=1
22
+ &&['DONE','BLOCKED'].includes(m.terminal)
23
+ &&typeof m.activeChatUrl==='string'
24
+ &&/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i
25
+ .test(m.activeChatUrl),
26
+ 'SCOPED_TERMINAL_READ_SCOPE_INVALID');
27
+ const scoped=readScopedOwner(m.projectId,m.taskId),s=scoped.session;
28
+ require(s&&s.sessionId===m.sessionId
29
+ &&s.generation===m.generation
30
+ &&s.revision===m.expectedPriorSessionRevision+1
31
+ &&s.phase===m.terminal
32
+ &&s.activeChatUrl===m.activeChatUrl,
33
+ 'SCOPED_TERMINAL_READ_OWNER_CHANGED');
34
+ const state=await nativeContextControl('run.terminalStatus',{
35
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
36
+ generation:s.generation,activeChatId:s.activeChatId},
37
+ {ownerProofV2:proof(s)});
38
+ require(state?.projectId===s.projectId&&state.taskId===s.taskId
39
+ &&state.pendingHandoff===false
40
+ &&state.pendingCheckpointId===null
41
+ &&state.unknownEffectCount===0
42
+ &&state.sessionCancellation===null
43
+ &&(m.terminal==='DONE'
44
+ ?state.runRef===null&&state.executionOutcome==='DONE'
45
+ &&typeof state.deliveryRef==='string'&&state.deliveryRef
46
+ :state.runRef===s.sessionId+':'+s.taskId+':'+s.generation
47
+ &&state.executionOutcome!=='DONE'),
48
+ 'SCOPED_TERMINAL_READ_CONTEXT_UNVERIFIED');
49
+ const after=readScopedOwner(m.projectId,m.taskId).session;
50
+ require(after?.revision===s.revision&&after.phase===s.phase
51
+ &&after.sessionId===s.sessionId
52
+ &&after.activeChatUrl===s.activeChatUrl,
53
+ 'SCOPED_TERMINAL_READ_OWNER_RACED');
54
+ return {status:'CONFIRMED',scope:'TASK_SCOPED_TERMINAL',
55
+ terminal:s.phase,nativeOwnerRevision:s.revision,
56
+ readOnly:true};
57
+ }
58
+ async function handle(m){
59
+ require(m&&Object.keys(m).length===11
60
+ &&m.op==='task-terminal-v2'
61
+ &&ID.test(m.projectId||'')&&ID.test(m.taskId||'')
62
+ &&UUID.test(m.sessionId||'')
63
+ &&UUID.test(m.turnToken||'')
64
+ &&Number.isSafeInteger(m.generation)&&m.generation>=0
65
+ &&Number.isSafeInteger(m.expectedSessionRevision)
66
+ &&m.expectedSessionRevision>=1
67
+ &&['DONE','BLOCKED'].includes(m.terminal)
68
+ &&/^user:[^\s]{8,}$/.test(m.sourceUserKey||'')
69
+ &&/^assistant:[^\s]{8,}$/.test(m.sourceAssistantKey||'')
70
+ &&typeof m.page==='string'
71
+ &&/^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(m.page),
72
+ 'SCOPED_TERMINAL_SOURCE_INVALID');
73
+ const before=readScopedOwner(m.projectId,m.taskId),s=before.session;
74
+ require(s&&s.sessionId===m.sessionId
75
+ &&s.generation===m.generation
76
+ &&s.revision===m.expectedSessionRevision
77
+ &&s.phase==='WAITING_REPLY'
78
+ &&s.activeChatUrl==='https://chatgpt.com'+m.page,
79
+ 'SCOPED_TERMINAL_OWNER_CHANGED');
80
+ const context=async(command,args)=>nativeContextControl(command,{
81
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
82
+ generation:s.generation,activeChatId:s.activeChatId,...args},
83
+ {ownerProofV2:proof(s)});
84
+ const state=await context('run.terminalStatus',{});
85
+ require(state?.projectId===s.projectId&&state.taskId===s.taskId
86
+ &&state.pendingHandoff===false
87
+ &&state.pendingCheckpointId===null
88
+ &&state.unknownEffectCount===0
89
+ &&state.sessionCancellation===null
90
+ &&state.projectRulesDrift===false
91
+ &&Number.isSafeInteger(state.bindingRevision)
92
+ &&state.bindingRevision>0,
93
+ 'SCOPED_TERMINAL_CONTEXT_UNVERIFIED');
94
+ if(m.terminal==='DONE'){
95
+ require(state.executionOutcome==='DONE'
96
+ &&typeof state.deliveryRef==='string'&&state.deliveryRef
97
+ &&(state.runRef===null
98
+ ||state.runRef===s.sessionId+':'+s.taskId+':'+s.generation),
99
+ 'SCOPED_DONE_DELIVERY_NOT_COMMITTED');
100
+ if(state.runRef!==null){
101
+ const fenced=await context('run.fence.terminal',{
102
+ expectedStoreEpoch:state.storeEpoch,
103
+ expectedTaskRevision:state.taskRevision,
104
+ expectedBindingRevision:state.bindingRevision,
105
+ writeRequestId:'task-terminal:'+s.sessionId+':'+s.generation,
106
+ runRef:state.runRef});
107
+ require(fenced?.status==='TERMINAL_FENCED',
108
+ 'SCOPED_TERMINAL_FENCE_UNKNOWN');
109
+ }
110
+ const after=await context('run.terminalStatus',{});
111
+ require(after?.runRef===null
112
+ &&after.executionOutcome==='DONE'
113
+ &&after.deliveryRef===state.deliveryRef
114
+ &&after.pendingHandoff===false
115
+ &&after.unknownEffectCount===0,
116
+ 'SCOPED_TERMINAL_CONTEXT_FENCE_UNVERIFIED');
117
+ }else{
118
+ require(state.executionOutcome!== 'DONE'
119
+ &&state.runRef===s.sessionId+':'+s.taskId+':'+s.generation,
120
+ 'SCOPED_BLOCKED_RUN_UNVERIFIED');
121
+ }
122
+ const fresh=readScopedOwner(s.projectId,s.taskId);
123
+ require(fresh.session?.sessionId===s.sessionId
124
+ &&fresh.session.generation===s.generation
125
+ &&fresh.session.revision===s.revision
126
+ &&fresh.session.phase==='WAITING_REPLY'
127
+ &&fresh.session.activeChatId===s.activeChatId,
128
+ 'SCOPED_TERMINAL_OWNER_RACED');
129
+ const committed=writeScopedOwner({
130
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
131
+ generation:s.generation,phase:m.terminal,
132
+ activeChatId:s.activeChatId,activeChatUrl:s.activeChatUrl,
133
+ updatedAt:Date.now()},{
134
+ expectedLedgerRevision:fresh.ledgerRevision,
135
+ expectedSessionRevision:s.revision});
136
+ require(committed.session.phase===m.terminal
137
+ &&committed.session.revision===s.revision+1,
138
+ 'SCOPED_TERMINAL_NATIVE_UNKNOWN');
139
+ return {status:'CONFIRMED',scope:'TASK_SCOPED_TERMINAL',
140
+ terminal:m.terminal,nativeOwnerRevision:committed.session.revision};
141
+ }
142
+ return Object.freeze({handle,readCommitted});
143
+ }
@@ -1,9 +1,12 @@
1
1
  // Single-Mac durable session pointer. Extension Worker is the only admission/sending authority.
2
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';
3
+ import {openSync,closeSync,readFileSync,writeFileSync,renameSync,
4
+ unlinkSync,lstatSync,mkdirSync} from 'node:fs';
4
5
  import {homedir} from 'node:os';
5
6
  import {join,dirname} from 'node:path';
6
7
  import {randomUUID} from 'node:crypto';
8
+ import {hasActiveLedgerOwner,ownerLedgerLockPath} from './owner-ledger.mjs';
9
+ import {withOwnerKernelLock} from './owner-kernel-lock.mjs';
7
10
 
8
11
  const ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
12
  const CHAT=/^[0-9a-f-]{12,}$/i;
@@ -53,6 +56,9 @@ const validate=r=>{
53
56
  export function readSession(){
54
57
  const file=sessionPath();
55
58
  if(!verifyPrivateDirectory(dirname(file)))return null;
59
+ // Preserve the original V1 directory integrity error before examining V2.
60
+ // A V1 status must not misreport IDLE while V2 owns another Chat.
61
+ if(hasActiveLedgerOwner())throw fail('OWNER_LEDGER_ACTIVE_USE_SCOPED_QUERY');
56
62
  const st=entryOrMissing(file);
57
63
  if(!st)return null;
58
64
  if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
@@ -60,13 +66,50 @@ export function readSession(){
60
66
  try{return validate(JSON.parse(readFileSync(file,'utf8')));}
61
67
  catch(e){if(e.code)throw e;throw fail('SESSION_FILE_CORRUPT');}
62
68
  }
63
- export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSessionId=null,resumeBlockedUpdatedAt=null,sameTaskPrePermitUpdatedAt=null,cancelBlockedUpdatedAt=null,
69
+ function completeExistingLegacySession(args){
70
+ // During staged upgrade, an already-active V1 Session may still need
71
+ // its original terminal CAS before a permanent kernel marker can exist.
72
+ // Reuse both legacy O_EXCL locks, but NEVER admit a different V1 Session
73
+ // or allow this fallback once the new persistent marker has been written.
74
+ const file=sessionPath(),shared=ownerLedgerLockPath(),own=file+'.lock';
75
+ ensurePrivate(dirname(file));
76
+ let sharedFd,ownFd;
77
+ try{
78
+ try{sharedFd=openSync(shared,'wx',0o600)}
79
+ catch{throw fail('SESSION_CONCURRENT_UPDATE')}
80
+ try{ownFd=openSync(own,'wx',0o600)}
81
+ catch{throw fail('SESSION_CONCURRENT_UPDATE')}
82
+ const old=readSession(),next=validate(args[0]);
83
+ if(!old||['DONE','CANCELLED'].includes(old.phase)
84
+ ||old.sessionId!==next.sessionId||old.projectId!==next.projectId
85
+ ||old.taskId!==next.taskId)
86
+ throw fail('OWNER_LOCK_CUTOVER_LEGACY_REPLACEMENT_DENIED');
87
+ return writeSessionLocked(...args);
88
+ }finally{
89
+ if(ownFd!==undefined){closeSync(ownFd);unlinkSync(own)}
90
+ if(sharedFd!==undefined){closeSync(sharedFd);unlinkSync(shared)}
91
+ }
92
+ }
93
+ export function writeSession(...args){
94
+ try{return withOwnerKernelLock('legacy-write',args)}
95
+ catch(e){
96
+ if(e?.code==='OWNER_LOCK_CUTOVER_ACTIVE')
97
+ return completeExistingLegacySession(args);
98
+ // Preserve the existing V1 lock-contention API; UNKNOWN remains
99
+ // distinct because its one-shot child may already have committed.
100
+ if(e?.code==='OWNER_LEDGER_LOCKED')throw fail('SESSION_CONCURRENT_UPDATE');
101
+ throw e;
102
+ }
103
+ }
104
+ export function writeSessionLocked(input,replaceBlockedSessionId=null,resumeBlockedSessionId=null,resumeBlockedUpdatedAt=null,sameTaskPrePermitUpdatedAt=null,cancelBlockedUpdatedAt=null,
64
105
  cancelFreezeExpectedAt=null){
65
- const next=validate(input),file=sessionPath(),dir=dirname(file),lock=file+'.lock';
106
+ const next=validate(input),file=sessionPath(),dir=dirname(file);
66
107
  ensurePrivate(dir);
67
- let fd;
68
- try{fd=openSync(lock,'wx',0o600);}catch{throw fail('SESSION_CONCURRENT_UPDATE');}
69
- try{
108
+ // The one-shot Native helper holds the same crash-released kernel lock
109
+ // as V2 for the entire legacy CAS; old O_EXCL writers cannot pass
110
+ // the persistent migration marker.
111
+ {
112
+ if(hasActiveLedgerOwner())throw fail('OWNER_LEDGER_ACTIVE');
70
113
  const old=readSession();
71
114
  // A canceled idle Adopt is terminal only after Context writer fencing.
72
115
  // The Native Host independently verifies the authoritative Context
@@ -181,5 +224,5 @@ export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSes
181
224
  renameSync(temp,file);
182
225
  }catch(e){try{unlinkSync(temp);}catch{}throw e;}
183
226
  return committed;
184
- }finally{closeSync(fd);unlinkSync(lock);}
227
+ }
185
228
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.34",
3
+ "version": "0.4.35",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension: reviewed formal Action pages, including TEST_ONLY native App entry",
6
6
  "bin": {
@@ -25,9 +25,7 @@
25
25
  "scripts": {
26
26
  "build:actions": "node ./scripts/build-actions.mjs",
27
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"
28
+ "prepack": "node ./scripts/build-actions.mjs --check"
31
29
  },
32
30
  "exports": {
33
31
  ".": "./index.mjs"