@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
@@ -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
  }
@@ -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"
@@ -23,8 +23,6 @@
23
23
  "scripts": {
24
24
  "build:events": "node ./scripts/build-events.mjs",
25
25
  "build:events:check": "node ./scripts/build-events.mjs --check",
26
- "pretest": "node ./scripts/build-events.mjs --check",
27
- "prepack": "node ./scripts/build-events.mjs --check",
28
- "test": "node --test test/*.test.mjs"
26
+ "prepack": "node ./scripts/build-events.mjs --check"
29
27
  }
30
28
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.63",
6
+ "version": "0.9.70",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -22,29 +22,21 @@
22
22
  ],
23
23
  "scripts": {
24
24
  "doctor": "node ./bin/cli.mjs doctor",
25
- "test": "node --test ./test/*.test.mjs",
26
25
  "build:providers": "node ./scripts/build-providers.mjs",
27
26
  "build:providers:check": "node ./scripts/build-providers.mjs --check",
28
27
  "build:form": "node ./scripts/build-form-app.mjs",
29
28
  "build:form:check": "node ./scripts/build-form-app.mjs --check",
30
29
  "build:document": "node ./scripts/build-document-app.mjs",
31
30
  "build:document:check": "node ./scripts/build-document-app.mjs --check",
32
- "pretest": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check",
33
31
  "prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check"
34
32
  },
35
33
  "dependencies": {
36
- "@tomflow/chatloop-context": "0.6.26",
34
+ "@tomflow/chatloop-context": "0.6.32",
37
35
  "@tomflow/chatloop-trace": "0.4.6",
38
36
  "@wonderwhy-er/desktop-commander": "0.2.44",
39
37
  "ps-list": "9.0.0",
40
38
  "@tomflow/chatloop-extension": "0.4.34"
41
39
  },
42
- "bundleDependencies": [
43
- "@tomflow/chatloop-context",
44
- "@tomflow/chatloop-trace",
45
- "ps-list",
46
- "@tomflow/chatloop-extension"
47
- ],
48
40
  "engines": {
49
41
  "node": ">=24"
50
42
  },
@@ -60,5 +52,11 @@
60
52
  "esbuild": "0.28.2",
61
53
  "happy-dom": "20.8.4",
62
54
  "marked": "16.3.0"
63
- }
55
+ },
56
+ "bundleDependencies": [
57
+ "@tomflow/chatloop-context",
58
+ "@tomflow/chatloop-trace",
59
+ "ps-list",
60
+ "@tomflow/chatloop-extension"
61
+ ]
64
62
  }
@@ -18,27 +18,33 @@ const endpoints=[
18
18
  [['extension','clean'],extensionTool('clean','Clear composer text in one exact verified ChatGPT tab; never sends.',false,
19
19
  {tabId:{type:'integer',minimum:1}},['tabId'])],
20
20
  [['extension','reload'],extensionTool('reload','Request reload of Chat Loop Extension; final health is unverified.',false)],
21
- [['extension','status'],extensionTool('status','Read the unique current Mac Chrome Web Chat Owner; never starts or sends.',true)],
21
+ [['extension','status'],extensionTool('status',
22
+ 'Read legacy Owner with no selector, or one exact authorized Task Owner with projectId+taskId; never starts or sends.',true,
23
+ {projectId:{type:'string',pattern:PROJECT_ID.source},
24
+ taskId:{type:'string',pattern:PROJECT_ID.source}})],
22
25
  [['extension','session'],extensionTool('session',
23
- 'Exact Context-managed idle Adopt cancellation. User authorization required; no delivery or Chat send. Refuses live work, unknown effects and identity drift.',false,
24
- {operation:{type:'string',enum:['cancel']},
26
+ 'Exact idle Adopt cancellation, or separately confirmed recovery of a fenced unsent Handoff in the original Task/Chat. Recovery requires a real click in the signed session Action; neither operation sends a Chat message.',false,
27
+ {operation:{type:'string',enum:['cancel','recover-handoff']},
25
28
  projectId:{type:'string',pattern:PROJECT_ID.source},
26
29
  taskId:{type:'string',pattern:PROJECT_ID.source},
27
30
  sessionId:{type:'string',pattern:REPLACE_SESSION.source},
28
31
  generation:{type:'integer',minimum:0},
29
32
  expectedNativeUpdatedAt:{type:'integer',minimum:1},
33
+ expectedNativeRevision:{type:'integer',minimum:1},
34
+ originalAttemptId:{type:'string',pattern:INTENT_ID.source},
35
+ taskFirst:{type:'boolean',const:true},
30
36
  expectedTaskRevision:{type:'integer',minimum:1},
31
37
  expectedBindingRevision:{type:'integer',minimum:1},
32
38
  contextStoreEpoch:{type:'string',minLength:10,maxLength:128},
33
39
  confirmed:{const:true}},
34
- ['operation','projectId','taskId','sessionId','generation',
35
- 'expectedNativeUpdatedAt','expectedTaskRevision','expectedBindingRevision',
36
- 'contextStoreEpoch','confirmed'])],
40
+ ['operation','projectId','taskId','sessionId','generation','confirmed'])],
37
41
  [['extension','start'],extensionTool('start',
38
42
  'Controlled execution ONLY: in Stage 03, mode=adopt requires a fresh Context start.reserve lease (taskId, contextLeaseRef, store epoch and revisions); Native validates the real R/P-approved original Chat without resending. The prompt-based branch creates a machine-owned execution session and requires the model status protocol; it is NOT a native @ Chat Loop user entry or Stage 01/02 testing mechanism. For TEST_ONLY native @ App entry, use the separate Extension entry test action, not Start.',false,
39
43
  {projectId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
40
44
  taskId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
41
45
  purpose:{type:'string',enum:['REPAIR_SAME_SCOPE']},
46
+ taskFirst:{type:'boolean',const:true,
47
+ description:'Task-first isolated original-Chat Adopt; no new message.'},
42
48
  contextLeaseRef:{type:'string',minLength:8,maxLength:128},
43
49
  contextStoreEpoch:{type:'string',minLength:10,maxLength:128},
44
50
  contextTaskRevision:{type:'integer',minimum:1},
@@ -49,10 +55,14 @@ const endpoints=[
49
55
  replaceBlockedSessionId:{type:'string',pattern:REPLACE_SESSION.source}},
50
56
  ['projectId','confirmed'])],
51
57
  [['extension','continue'],extensionTool('continue','Submit next-turn text with turnToken and nextPrompt; alternatively query its final status with turnToken and intentId. Only the Extension can send after Turn completion.',false,
52
- {turnToken:{type:'string',pattern:TURN_TOKEN.source},nextPrompt:{type:'string',minLength:1,maxLength:4000,pattern:'\\S'},
58
+ {turnToken:{type:'string',pattern:TURN_TOKEN.source},
59
+ taskFirst:{type:'boolean',const:true},
60
+ nextPrompt:{type:'string',minLength:1,maxLength:4000,pattern:'\\S'},
53
61
  intentId:{type:'string',pattern:INTENT_ID.source},lookup:{type:'boolean'}},['turnToken'])],
54
62
  [['extension','handoff'],extensionTool('handoff','Submit an early Handoff with turnToken and optional reason; alternatively query receipt with turnToken and intentId. Extension still owns the timing and send.',false,
55
- {turnToken:{type:'string',pattern:TURN_TOKEN.source},reason:{type:'string',maxLength:400},
63
+ {turnToken:{type:'string',pattern:TURN_TOKEN.source},
64
+ taskFirst:{type:'boolean',const:true},
65
+ reason:{type:'string',maxLength:400},
56
66
  intentId:{type:'string',pattern:INTENT_ID.source},lookup:{type:'boolean'}},['turnToken'])],
57
67
  ];
58
68
  export const extensionTools=endpoints.map(([,tool])=>tool);
@@ -70,11 +80,33 @@ export function validExtensionArgs(name,args){
70
80
  if(name==='clean'){
71
81
  if(Object.keys(args).length!==1||!Number.isSafeInteger(args.tabId)||args.tabId<1)
72
82
  return false;
83
+ }else if(name==='status'){
84
+ if(Object.keys(args).length!==0
85
+ &&!(Object.keys(args).length===2
86
+ &&PROJECT_ID.test(args.projectId||'')
87
+ &&PROJECT_ID.test(args.taskId||'')))return false;
73
88
  }else if(!control && Object.keys(args).length)return false;
74
89
  if(name==='session'){
90
+ if(args.operation==='recover-handoff'){
91
+ const keys=['operation','projectId','taskId','sessionId',
92
+ 'generation','expectedNativeRevision','originalAttemptId',
93
+ 'confirmed','taskFirst'];
94
+ return Object.keys(args).length===keys.length
95
+ &&keys.every(k=>Object.hasOwn(args,k))
96
+ &&PROJECT_ID.test(args.projectId||'')
97
+ &&PROJECT_ID.test(args.taskId||'')
98
+ &&REPLACE_SESSION.test(args.sessionId||'')
99
+ &&Number.isSafeInteger(args.generation)&&args.generation>=0
100
+ &&Number.isSafeInteger(args.expectedNativeRevision)
101
+ &&args.expectedNativeRevision>=2
102
+ &&INTENT_ID.test(args.originalAttemptId||'')
103
+ &&args.confirmed===true&&args.taskFirst===true;
104
+ }
105
+ const scoped=args.taskFirst===true;
75
106
  const k=['operation','projectId','taskId','sessionId','generation',
76
- 'expectedNativeUpdatedAt','expectedTaskRevision',
77
- 'expectedBindingRevision','contextStoreEpoch','confirmed'];
107
+ scoped?'expectedNativeRevision':'expectedNativeUpdatedAt',
108
+ 'expectedTaskRevision','expectedBindingRevision',
109
+ 'contextStoreEpoch','confirmed',...(scoped?['taskFirst']:[])];
78
110
  if(Object.keys(args).length!==k.length
79
111
  ||k.some(key=>!Object.hasOwn(args,key))
80
112
  ||args.operation!=='cancel'||args.confirmed!==true
@@ -82,8 +114,11 @@ export function validExtensionArgs(name,args){
82
114
  ||!PROJECT_ID.test(args.taskId||'')
83
115
  ||!REPLACE_SESSION.test(args.sessionId||'')
84
116
  ||!Number.isSafeInteger(args.generation)||args.generation<0
85
- ||!Number.isSafeInteger(args.expectedNativeUpdatedAt)
86
- ||args.expectedNativeUpdatedAt<=0
117
+ ||(scoped
118
+ ?!Number.isSafeInteger(args.expectedNativeRevision)
119
+ ||args.expectedNativeRevision<1
120
+ :!Number.isSafeInteger(args.expectedNativeUpdatedAt)
121
+ ||args.expectedNativeUpdatedAt<=0)
87
122
  ||!Number.isSafeInteger(args.expectedTaskRevision)
88
123
  ||args.expectedTaskRevision<1
89
124
  ||!Number.isSafeInteger(args.expectedBindingRevision)
@@ -105,6 +140,10 @@ export function validExtensionArgs(name,args){
105
140
  ||!Number.isSafeInteger(args.contextTaskRevision)||args.contextTaskRevision<1
106
141
  ||!Number.isSafeInteger(args.contextApprovalRevision)||args.contextApprovalRevision<1))
107
142
  ||args.confirmed!==true
143
+ ||(args.taskFirst!==undefined
144
+ &&(args.taskFirst!==true||args.mode!=='adopt'
145
+ ||!args.taskId||!args.chatUrl||!args.contextLeaseRef
146
+ ||args.purpose!==undefined||args.replaceBlockedSessionId!==undefined))
108
147
  // A managed original-Chat Adopt must carry a Context start.reserve lease.
109
148
  // The exact lease/approval is checked by Native permit.consume, not here.
110
149
  ||(args.mode==='adopt'&&!Object.hasOwn(args,'contextLeaseRef'))
@@ -119,25 +158,29 @@ export function validExtensionArgs(name,args){
119
158
  return false;
120
159
  }
121
160
  if(control&&!['start','session'].includes(name)){
122
- if(typeof args.turnToken!=='string'||!TURN_TOKEN.test(args.turnToken))
161
+ if(typeof args.turnToken!=='string'||!TURN_TOKEN.test(args.turnToken)
162
+ ||args.taskFirst!==undefined&&args.taskFirst!==true)
123
163
  return false;
164
+ const v2=args.taskFirst===true;
124
165
  const hasId=Object.hasOwn(args,'intentId');
125
166
  const hasLookup=Object.hasOwn(args,'lookup');
126
167
  // Receipt query and newest-receipt lookup are mutually exclusive.
127
168
  if(hasId||hasLookup){
128
- if(hasId===hasLookup||Object.keys(args).length!==2)return false;
169
+ if(hasId===hasLookup||Object.keys(args).length!==(v2?3:2))return false;
129
170
  return hasId
130
171
  ? typeof args.intentId==='string'&&INTENT_ID.test(args.intentId)
131
172
  : args.lookup===true;
132
173
  }
133
174
  if(name==='continue'){
134
- return Object.keys(args).length===2
175
+ return Object.keys(args).length===(v2?3:2)
135
176
  && typeof args.nextPrompt==='string' && !!args.nextPrompt.trim()
136
177
  && args.nextPrompt.length<=4000
137
178
  && !/[\x00-\x1f]/.test(args.nextPrompt.replaceAll('\n',''));
138
179
  }
139
180
  // Handoff only needs the bound token; its short reason is optional.
140
- return (Object.keys(args).length===1||Object.hasOwn(args,'reason'))
181
+ return (Object.keys(args).length===(v2?2:1)
182
+ ||Object.hasOwn(args,'reason')
183
+ &&Object.keys(args).length===(v2?3:2))
141
184
  && (args.reason===undefined || (typeof args.reason==='string'
142
185
  && args.reason.length<=400 && !/[\x00-\x1f]/.test(args.reason)));
143
186
  }