@tomflow/chatloop-tools 0.9.58 → 0.9.59

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.
@@ -102,6 +102,14 @@ The Tools private handler passes a signed-IPC-verified Native projection into th
102
102
 
103
103
  The Browser Native Host now permits the Worker-used `run.reopenStatus`
104
104
  through the same signed private IPC path; it is not a public MCP method.
105
+ For first-Start recovery, `run.terminalStatus` accepts the private
106
+ `startRecoveryLeaseRef` only for a generation-zero Native BLOCKED pointer
107
+ without an active Chat. It returns `UNBOUND_NO_PERMIT` only when the exact
108
+ fresh lease is the sole valid reservation, no prior permit was consumed,
109
+ no writer/unknown effect exists, and current approvals remain valid.
110
+ `start.reserve` rejects a previously consumed initial permit and removes
111
+ expired unused initial leases transactionally; the read-only proof does not
112
+ grant a permit, bind a writer, or replace a Session.
105
113
 
106
114
  ## 5. Context → external dependencies (reverse direction)
107
115
 
@@ -1,6 +1,6 @@
1
1
  // Context Core health methods. Shared access and transactions are injected from store.mjs.
2
2
  export function createHealthMethods(values) {
3
- const {assert, parse, db, epoch, storeMode, hasApprovedPlan, required, checkIds, admin, readAuth, unresolvedEffects} = values;
3
+ const {assert, parse, db, epoch, storeMode, hasApprovedPlan, required, checkIds, admin, readAuth, unresolvedEffects, readSnapshot, projectDrift, ensureNoPendingIssue} = values;
4
4
  return {
5
5
  pragmas:()=>({
6
6
  journalMode:db.prepare('PRAGMA journal_mode').get().journal_mode,
@@ -28,14 +28,33 @@ export function createHealthMethods(values) {
28
28
  reopenUserTurn:c.reopenRequest?.userTurn??null,
29
29
  previousDeliveryRef:c.deliveryRef??null};
30
30
  },
31
- terminalStatus(projectId,taskId){
31
+ terminalStatus(projectId,taskId,startRecoveryLeaseRef=null){
32
32
  checkIds(projectId,taskId);readAuth(projectId,taskId,'run.terminalStatus');
33
- const r=required(projectId,taskId),c=parse(r.context_json);
34
- return {projectId,taskId,taskRevision:r.business_revision,
35
- bindingRevision:r.binding_revision,approvalRevision:r.approval_revision,
36
- unknownEffectCount:unresolvedEffects(c).length,
37
- runRef:r.writable_ref,executionOutcome:c.executionOutcome??null,
38
- deliveryRef:c.deliveryRef??null};
33
+ return readSnapshot(()=>{
34
+ const r=required(projectId,taskId),c=parse(r.context_json);
35
+ const state={projectId,taskId,taskRevision:r.business_revision,
36
+ bindingRevision:r.binding_revision,approvalRevision:r.approval_revision,
37
+ unknownEffectCount:unresolvedEffects(c).length,
38
+ runRef:r.writable_ref,executionOutcome:c.executionOutcome??null,
39
+ deliveryRef:c.deliveryRef??null};
40
+ if(startRecoveryLeaseRef===null)return state;
41
+ // Read-only, scoped to the fresh lease. The prior expired leases were
42
+ // removed transactionally by reserve; no prior permit may exist.
43
+ assert(r.binding_revision===0&&r.writable_ref===null&&r.pending_attempt===null
44
+ &&state.unknownEffectCount===0&&state.executionOutcome===null
45
+ &&!['ARCHIVED','DELIVERED','REOPENED'].includes(c.stage)
46
+ &&!projectDrift(r).projectDrift&&hasApprovedPlan(parse(r.approval_json)),
47
+ 'START_RECOVERY_UNSAFE');
48
+ ensureNoPendingIssue(projectId,taskId);
49
+ const leases=db.prepare('SELECT * FROM start_leases WHERE project_id=? AND task_id=?')
50
+ .all(projectId,taskId);
51
+ assert(leases.length===1&&leases[0].lease_ref===startRecoveryLeaseRef
52
+ &&leases[0].expires_at>Date.now()&&leases[0].business_revision===r.business_revision
53
+ &&leases[0].approval_revision===r.approval_revision,'START_RECOVERY_LEASE_UNVERIFIED');
54
+ assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
55
+ .get(projectId,taskId),'START_PERMIT_ALREADY_CONSUMED');
56
+ return {...state,storeEpoch:epoch,startRecovery:{status:'UNBOUND_NO_PERMIT',leaseRef:startRecoveryLeaseRef}};
57
+ });
39
58
  },
40
59
  latestCheckpoint(projectId,taskId){
41
60
  checkIds(projectId,taskId);readAuth(projectId,taskId,'context.latestCheckpoint');
@@ -25,6 +25,14 @@ export function createRunMethods(values) {
25
25
  assert(current.executionOutcome!=='DONE'&&current.stage!=='ARCHIVED',
26
26
  'TASK_ALREADY_DELIVERED');
27
27
  }
28
+ // Never re-reserve an initial Start whose execution permit may have
29
+ // been consumed. Expired, unconsumed leases cannot commit later.
30
+ if(r.binding_revision===0){
31
+ assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
32
+ .get(a.projectId,a.taskId),'START_PERMIT_ALREADY_CONSUMED');
33
+ db.prepare('DELETE FROM start_leases WHERE project_id=? AND task_id=? AND expires_at<=?')
34
+ .run(a.projectId,a.taskId,Date.now());
35
+ }
28
36
  const leaseRef=randomUUID();
29
37
  db.prepare('INSERT INTO start_leases VALUES(?,?,?,?,?,?)').run(leaseRef,
30
38
  a.projectId,a.taskId,r.approval_revision,r.business_revision,Date.now()+60000);
@@ -28,11 +28,17 @@ export function executeTrustedRun(command,args,native){
28
28
  assert(!['principal','role','internalAuthorized','ownerCommitted',
29
29
  'nativeCommitted'].some(k=>Object.hasOwn(args,k)),
30
30
  'CLIENT_AUTH_FIELD_FORBIDDEN');
31
+ const startRecovery=command==='run.terminalStatus'&&Object.hasOwn(args,'startRecoveryLeaseRef');
32
+ if(startRecovery)assert(native.phase==='BLOCKED'&&native.generation===0
33
+ &&native.activeChatId===null&&native.activeChatUrl===null
34
+ &&typeof args.startRecoveryLeaseRef==='string'
35
+ &&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(args.startRecoveryLeaseRef),
36
+ 'START_RECOVERY_NATIVE_UNVERIFIED');
31
37
  assert(native.projectId===args.projectId && native.taskId===args.taskId
32
38
  && native.sessionId===args.sessionId
33
39
  && native.generation===args.generation
34
40
  && native.activeChatId===args.activeChatId
35
- && (native.activeChatId!==null || command==='permit.consume'&&args.kind==='START'),
41
+ && (native.activeChatId!==null || command==='permit.consume'&&args.kind==='START'||startRecovery),
36
42
  'CONTEXT_NATIVE_BINDING_MISMATCH');
37
43
  const allowed=allowedProjects();
38
44
  assert(allowed.has(native.projectId),'PROJECT_ACCESS_DENIED');
@@ -59,11 +65,12 @@ export function executeTrustedRun(command,args,native){
59
65
  const db=openContextProtocol(file,{principalId:'native-controlled',
60
66
  authorizeData:(_access,p)=>allowed.has(p),authorizeInternal:()=>true});
61
67
  try{
62
- if(!['run.terminalStatus','run.reopenStatus','run.snapshot'].includes(command)
68
+ if((startRecovery||!['run.terminalStatus','run.reopenStatus','run.snapshot'].includes(command))
63
69
  &&!db.projectBusinessAuthority(args.projectId).writable)
64
70
  throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
65
71
  switch(command){
66
- case 'run.terminalStatus':return db.terminalStatus(args.projectId,args.taskId);
72
+ case 'run.terminalStatus':return db.terminalStatus(args.projectId,args.taskId,
73
+ startRecovery?args.startRecoveryLeaseRef:null);
67
74
  case 'run.reopenStatus':return db.reopenStatus(args.projectId,args.taskId);
68
75
  case 'run.snapshot':return db.latestCheckpoint(args.projectId,args.taskId);
69
76
  case 'permit.consume':return db.consumePermit(args);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.6.21",
3
+ "version": "0.6.22",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "ps-list": "9.0.0",
37
- "@tomflow/chatloop-extension": "0.4.29",
37
+ "@tomflow/chatloop-extension": "0.4.30",
38
38
  "@tomflow/chatloop-trace": "0.4.6"
39
39
  }
40
40
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.29",
4
+ "version": "0.4.30",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -62,8 +62,8 @@ async function sessionStartPrepare(message,sender){
62
62
  &&prior.contextStoreEpoch===intent.contextStoreEpoch
63
63
  &&prior.contextTaskRevision===intent.contextTaskRevision
64
64
  &&prior.contextApprovalRevision===intent.contextApprovalRevision
65
- &&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
66
- &&!prior.userKey&&!prior.attemptedNewTabId
65
+ &&prior.generation===0&&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
66
+ &&!prior.userKey&&!prior.assistantKey&&!prior.attemptedNewTabId&&!prior.lastStartActionTabId
67
67
  &&!!intent.chatUrl&&prior.adoptPage===pathOf(intent.chatUrl)
68
68
  &&Number.isInteger(prior.adoptTabId)
69
69
  &&typeof prior.adoptUserKey==='string');
@@ -71,7 +71,9 @@ async function sessionStartPrepare(message,sender){
71
71
  // rejected its CAS, Worker/Native disagree. No send was attempted, but this
72
72
  // is NOT a free retry: one exact native-BLOCKED repair with a fresh lease
73
73
  // is allowed; any managed writer, late send or second repair remains denied.
74
- const preNativeGhost=Boolean(prior?.phase==='STARTING'
74
+ const timedOutGhost=prior?.phase==='BLOCKED'
75
+ &&prior.reason==='ACTION_RESULT_TIMEOUT_UNVERIFIED';
76
+ const preNativeGhost=Boolean((prior?.phase==='STARTING'||timedOutGhost)
75
77
  &&prior.action==='START'&&prior.mode==='adopt'
76
78
  &&prior.prePermitRetryUsed===true&&!prior.preNativeRepairUsed
77
79
  &&prior.replacedBlockedSessionId===replace
@@ -82,8 +84,8 @@ async function sessionStartPrepare(message,sender){
82
84
  &&prior.contextStoreEpoch===intent.contextStoreEpoch
83
85
  &&prior.contextTaskRevision===intent.contextTaskRevision
84
86
  &&prior.contextApprovalRevision===intent.contextApprovalRevision
85
- &&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
86
- &&!prior.userKey&&!prior.attemptedNewTabId
87
+ &&prior.generation===0&&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
88
+ &&!prior.userKey&&!prior.assistantKey&&!prior.attemptedNewTabId&&!prior.lastStartActionTabId
87
89
  &&!!intent.chatUrl&&prior.adoptPage===pathOf(intent.chatUrl)
88
90
  &&Number.isInteger(prior.adoptTabId)
89
91
  &&typeof prior.adoptUserKey==='string');
@@ -114,8 +116,24 @@ async function sessionStartPrepare(message,sender){
114
116
  &&disk.session.updatedAt>0);
115
117
  if((matchingBlocked&&!(ownerMatches||(preNativeGhost&&sameTaskNative)
116
118
  ||driftReplacement))
117
- ||((prePermitRecovery||preNativeGhost)&&!sameTaskNative))
119
+ ||((prePermitRecovery||preNativeGhost)&&!sameTaskNative)
120
+ ||(preNativeGhost&&timedOutGhost&&!independentBlockedAdoptDrift(prior,disk.session)))
118
121
  return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
122
+ if(prePermitRecovery||preNativeGhost){
123
+ // Native's durable old pointer scopes this read. A new lease or null
124
+ // runRef alone cannot prove the old START permit was never consumed.
125
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
126
+ op:'context-control',command:'run.terminalStatus',
127
+ args:{startRecoveryLeaseRef:intent.contextLeaseRef}}).catch(()=>null);
128
+ const s=proof?.result;
129
+ if(proof?.status!=='OK'||s?.projectId!==intent.projectId||s?.taskId!==intent.taskId
130
+ ||s.storeEpoch!==intent.contextStoreEpoch||s.taskRevision!==intent.contextTaskRevision
131
+ ||s.approvalRevision!==intent.contextApprovalRevision||s.bindingRevision!==0
132
+ ||s.runRef!==null||s.unknownEffectCount!==0||s.executionOutcome!==null
133
+ ||s.startRecovery?.status!=='UNBOUND_NO_PERMIT'
134
+ ||s.startRecovery.leaseRef!==intent.contextLeaseRef)
135
+ return {status:'DENIED',code:'START_RECOVERY_PERMIT_UNVERIFIED'};
136
+ }
119
137
  // A terminal Worker record cannot authorize a new Start if a different
120
138
  // durable Native Owner exists under the same Browser installation.
121
139
  if(prior?.phase==='DONE'&&prior.sessionId&&disk.session&&!ownerMatches)
@@ -144,6 +162,8 @@ async function sessionStartPrepare(message,sender){
144
162
  :await approvedAdoptionTarget(intent.chatUrl||null,
145
163
  intent.contextLeaseRef?intent.taskId:null):null;
146
164
  if(adoption?.error)return {status:'DENIED',code:adoption.error};
165
+ if((prePermitRecovery||preNativeGhost)&&adoption?.target?.userKey!==prior.adoptUserKey)
166
+ return {status:'DENIED',code:'START_RECOVERY_APPROVAL_CHANGED'};
147
167
  if((matchingBlocked&&adoption?.target?.page===prior.page&&prior.page)
148
168
  ||(driftReplacement&&adoption?.target?.page===prior.adoptPage))
149
169
  return {status:'DENIED',code:'BLOCKED_REPLACEMENT_CHAT_REUSE'};
@@ -93,6 +93,10 @@ async function saveRun(run) {
93
93
  if(recoveryCommit&&(!Number.isSafeInteger(next.recoveryExpectedNativeAt)
94
94
  ||next.recoveryExpectedNativeAt<=0))
95
95
  throw Error('SESSION_RECOVERY_CAS_MISSING');
96
+ // Native must commit first for the exact terminal CAS transitions.
97
+ const replacementCommit=Boolean(next.replacedBlockedSessionId
98
+ &&next.phase==='STARTING'&&stored?.sessionId!==next.sessionId);
99
+ const nativeFirst=recoveryCommit||replacementCommit;
96
100
  const syncNative=async()=>{
97
101
  if(!next.sessionId)return;
98
102
  const record=sessionProjection(next);
@@ -104,18 +108,26 @@ async function saveRun(run) {
104
108
  ?{sameTaskPrePermitUpdatedAt:next.sameTaskPrePermitUpdatedAt}:{})}:{}),
105
109
  ...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
106
110
  resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}).catch(()=>null);
111
+ // A fresh replacement Session ID identifies this exact CAS. If its
112
+ // transport reply was lost, confirm the durable projection once, without
113
+ // replaying the write. Same-ID recovery has no such unique commit proof.
114
+ if(!saved&&replacementCommit){
115
+ const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,
116
+ {op:'session-read'}).catch(()=>null);
117
+ if(observed?.status==='OK'&&matchesNativeProjection(record,observed.session))return;
118
+ }
107
119
  // Native acknowledgment must match the whole immutable Owner pointer,
108
120
  // not merely its sessionId and phase. updatedAt is CAS metadata, not
109
121
  // part of this identity projection.
110
122
  if(saved?.status!=="OK"||!matchesNativeProjection(record,saved.session))
111
123
  throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
112
124
  };
113
- // A terminal BLOCKED session may resume only after native CAS first.
114
- // Do not leave a Chrome RESERVED owner behind if native rejects the
115
- // transition: that mismatch previously made all status calls unreadable.
116
- if(recoveryCommit)await syncNative();
125
+ // BLOCKED recovery and replacement both require a Native CAS first.
126
+ // Do not publish a new Worker reservation when Native rejects the CAS.
127
+ // An unknown acknowledgement stays fail-closed; never replay a Start.
128
+ if(nativeFirst)await syncNative();
117
129
  await chrome.storage.local.set({[RUN_KEY]:next});
118
- if(!recoveryCommit)await syncNative();
130
+ if(!nativeFirst)await syncNative();
119
131
  // The resource inventory is derived evidence; it never grants browser Owner.
120
132
  if (["DONE","BLOCKED"].includes(next.phase)
121
133
  && next.contextTerminalFence !== "PENDING"
@@ -150,7 +162,8 @@ const sessionProjectionDrift=(projected,native)=>SESSION_POINTER_KEYS.filter(
150
162
  key=>projected[key]!==native?.[key]);
151
163
  // Two distinct durable IDs may exist after an interrupted Adopt reservation.
152
164
  // This narrow read-only shape proves NEITHER a previous send nor authority to
153
- // replace it; only a DIFFERENT freshly approved Task can request Native CAS.
165
+ // replace it. Adopt admission separately verifies independent Task replacement
166
+ // or the exact same-Task pre-permit recovery contract before Native CAS.
154
167
  const independentBlockedAdoptDrift=(run,native)=>Boolean(
155
168
  run?.phase==='BLOCKED'&&run.reason==='ACTION_RESULT_TIMEOUT_UNVERIFIED'
156
169
  &&run.action==='START'&&run.mode==='adopt'
@@ -156,13 +156,24 @@ async function sessionStatus(message,sender){
156
156
  const projection=run?.sessionId?sessionProjection(run):null;
157
157
  if(projection&&!matchesNativeProjection(projection,disk.session)){
158
158
  const mismatchedFields=sessionProjectionDrift(projection,disk.session);
159
- return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH',
160
- mismatchedFields,
161
- ...(mismatchedFields.length===1&&mismatchedFields[0]==='sessionId'
162
- &&independentBlockedAdoptDrift(run,disk.session)
163
- ?{independentTaskReplacementCandidate:{
164
- replaceBlockedSessionId:disk.session.sessionId,
165
- requires:'FRESH_APPROVED_DISTINCT_TASK_AND_NATIVE_CAS'}}:{})};
159
+ const blockedAdoptDrift=mismatchedFields.length===1&&mismatchedFields[0]==='sessionId'
160
+ &&independentBlockedAdoptDrift(run,disk.session);
161
+ // Only a locator for the exact old reservation, never a permit or Owner.
162
+ const prePermitCandidate=blockedAdoptDrift&&run.prePermitRetryUsed===true
163
+ &&!run.preNativeRepairUsed&&run.replacedBlockedSessionId===disk.session.sessionId
164
+ &&typeof run.contextStoreEpoch==='string'&&Number.isSafeInteger(run.contextTaskRevision)
165
+ &&Number.isSafeInteger(run.contextApprovalRevision)
166
+ &&pathOf('https://chatgpt.com'+run.adoptPage)===run.adoptPage;
167
+ return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH',mismatchedFields,
168
+ diagnostics:{extensionVersion:chrome.runtime.getManifest?.().version||null},
169
+ ...(blockedAdoptDrift?{independentTaskReplacementCandidate:{
170
+ replaceBlockedSessionId:disk.session.sessionId,
171
+ requires:'FRESH_APPROVED_DISTINCT_TASK_AND_NATIVE_CAS'}}:{}),
172
+ ...(prePermitCandidate?{sameTaskPrePermitRecoveryCandidate:{
173
+ projectId:run.projectId,taskId:run.taskId,
174
+ replaceBlockedSessionId:disk.session.sessionId,
175
+ originalChatUrl:'https://chatgpt.com'+run.adoptPage,
176
+ requires:'FRESH_LEASE_NO_PRIOR_PERMIT_ORIGINAL_APPROVAL_AND_NATIVE_CAS'}}:{})};
166
177
  }
167
178
  if(!run?.sessionId&&disk.session&&disk.session.phase!=='DONE')
168
179
  return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.29",
3
+ "version": "0.4.30",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension: reviewed formal Action pages, including TEST_ONLY native App entry",
6
6
  "bin": {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.58",
6
+ "version": "0.9.59",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -33,11 +33,11 @@
33
33
  "prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check"
34
34
  },
35
35
  "dependencies": {
36
- "@tomflow/chatloop-context": "0.6.21",
36
+ "@tomflow/chatloop-context": "0.6.22",
37
37
  "@tomflow/chatloop-trace": "0.4.6",
38
38
  "@wonderwhy-er/desktop-commander": "0.2.44",
39
39
  "ps-list": "9.0.0",
40
- "@tomflow/chatloop-extension": "0.4.29"
40
+ "@tomflow/chatloop-extension": "0.4.30"
41
41
  },
42
42
  "bundleDependencies": [
43
43
  "@tomflow/chatloop-context",