@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,400 @@
1
+ // V2 Task-scoped Worker state. Not a Chat send/Owner authority.
2
+ (() => {
3
+ const KEY='chat-loop.action.runs.v2';
4
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
5
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
6
+ const CHAT=/^[0-9a-f-]{12,}$/i;
7
+ const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY',
8
+ 'DONE','BLOCKED','CANCELLED']);
9
+ const NEXT=Object.freeze({
10
+ STARTING:['STARTING','RESERVED','PENDING','WAITING_REPLY','BLOCKED'],
11
+ RESERVED:['RESERVED','PENDING','WAITING_REPLY','BLOCKED'],
12
+ PENDING:['PENDING','WAITING_REPLY','BLOCKED'],
13
+ WAITING_REPLY:['WAITING_REPLY','BLOCKED','DONE'],
14
+ BLOCKED:['BLOCKED']
15
+ });
16
+ const terminal=p=>p==='DONE'||p==='CANCELLED';
17
+ const fail=code=>Object.assign(Error(code),{code});
18
+ const assert=(v,code)=>{if(!v)throw fail(code);};
19
+ const taskKey=(projectId,taskId)=>JSON.stringify([projectId,taskId]);
20
+ const clone=v=>JSON.parse(JSON.stringify(v));
21
+ const safeRun=run=>{
22
+ assert(run&&typeof run==='object'&&!Array.isArray(run)&&
23
+ ID.test(run.projectId||'')&&ID.test(run.taskId||'')&&
24
+ UUID.test(run.sessionId||'')&&
25
+ Number.isSafeInteger(run.generation)&&run.generation>=0&&
26
+ PHASE.has(run.phase),'TASK_RUN_INVALID');
27
+ const ownerChatId=run.ownerChatId??null;
28
+ assert(ownerChatId===null||typeof ownerChatId==='string'&&CHAT.test(ownerChatId),
29
+ 'TASK_CHAT_INVALID');
30
+ assert(run.phase!=='WAITING_REPLY'||ownerChatId!==null,
31
+ 'TASK_CHAT_INVALID');
32
+ assert(run.phase!=='WAITING_REPLY'||
33
+ Number.isSafeInteger(run.tabId)&&run.tabId>0,
34
+ 'TASK_TAB_INVALID');
35
+ assert(Number.isSafeInteger(run.nativeOwnerRevision)&&
36
+ run.nativeOwnerRevision>=0,'TASK_NATIVE_REVISION_REQUIRED');
37
+ if(run.turnToken!==undefined)
38
+ assert(UUID.test(run.turnToken||''),'TASK_TURN_TOKEN_INVALID');
39
+ if(run.awaitingUserKey!==undefined)
40
+ assert(typeof run.awaitingUserKey==='string'&&run.awaitingUserKey.length<=1024
41
+ &&/^user:[^\s]{8,}$/.test(run.awaitingUserKey)
42
+ &&run.phase==='WAITING_REPLY','TASK_AWAITED_USER_INVALID');
43
+ if(run.startedAt!==undefined||run.deadlineAt!==undefined)
44
+ assert(Number.isSafeInteger(run.startedAt)&&run.startedAt>0
45
+ &&Number.isSafeInteger(run.deadlineAt)&&run.deadlineAt>run.startedAt
46
+ &&run.deadlineAt-run.startedAt<=4*60*60*1000,'TASK_CHAT_WINDOW_INVALID');
47
+ if(run.recoveryRequestId!==undefined)assert(/^[a-f0-9]{32}$/.test(run.recoveryRequestId),'TASK_RECOVERY_REQUEST_INVALID');
48
+ if(run.terminalAt!==undefined)
49
+ assert(Number.isSafeInteger(run.terminalAt)
50
+ &&run.terminalAt>0
51
+ &&terminal(run.phase),'TASK_TERMINAL_TIME_INVALID');
52
+ if(run.contextStoreEpoch!==undefined)
53
+ assert(typeof run.contextStoreEpoch==='string'
54
+ &&run.contextStoreEpoch.length>=10&&run.contextStoreEpoch.length<=128,
55
+ 'TASK_CONTEXT_EPOCH_INVALID');
56
+ if(run.preSendAbort!==undefined){
57
+ const a=run.preSendAbort;
58
+ assert(a&&typeof a==='object'&&!Array.isArray(a)
59
+ &&Object.keys(a).length===3
60
+ &&run.phase==='BLOCKED'
61
+ &&run.modelIntent?.action==='HANDOFF'
62
+ &&run.modelIntent.state==='ACTION_UNVERIFIED'
63
+ &&a.id===run.modelIntent.id&&a.id===run.nextAttempt?.id
64
+ &&run.lastIntentReceipt?.id===a.id
65
+ &&run.lastIntentReceipt?.action==='HANDOFF'
66
+ &&run.lastIntentReceipt.status==='NOT_SENT'&&run.lastIntentReceipt.turnToken===run.turnToken
67
+ &&Number.isSafeInteger(a.actionTabId)&&a.actionTabId>0
68
+ &&a.actionTabId===run.modelIntent.actionTabId
69
+ &&Number.isSafeInteger(a.recordedAt)&&a.recordedAt>0
70
+ &&run.nextAttempt?.sendBeginAt===null,'TASK_PRE_SEND_ABORT_INVALID');
71
+ }
72
+ if(run.resourceTransfer!==undefined){
73
+ const r=run.resourceTransfer;
74
+ assert(r&&typeof r==='object'&&!Array.isArray(r)&&Object.keys(r).length===3
75
+ &&Number.isSafeInteger(r.sourceTabId)&&r.sourceTabId>0
76
+ &&r.sourceTabId!==run.tabId
77
+ &&typeof r.sourcePage==='string'
78
+ &&/^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(r.sourcePage)
79
+ &&r.sourcePage!==run.page&&run.generation>=1
80
+ &&typeof r.attemptId==='string'&&/^[a-f0-9]{32}$/.test(r.attemptId),
81
+ 'TASK_RESOURCE_TRANSFER_INVALID');
82
+ }
83
+ if(run.lastFault!==undefined){
84
+ const f=run.lastFault;
85
+ assert(f&&typeof f==='object'&&!Array.isArray(f)
86
+ &&Object.keys(f).length===4
87
+ &&['PAGE_ERROR','CONTEXT_LIMIT','SECURITY_CHALLENGE'].includes(f.reason)
88
+ &&typeof f.userKey==='string'&&f.userKey.length<=1024
89
+ &&/^user:[^\s]{8,}$/.test(f.userKey)
90
+ &&typeof f.retryAvailable==='boolean'
91
+ &&Number.isSafeInteger(f.at)&&f.at>0,'TASK_FAULT_INVALID');
92
+ }
93
+ if(run.resourceHoldSettledAt!==undefined)
94
+ assert(run.preSendAbort
95
+ &&Number.isSafeInteger(run.resourceHoldSettledAt)
96
+ &&run.resourceHoldSettledAt>=run.preSendAbort.recordedAt,
97
+ 'TASK_RESOURCE_HOLD_SETTLEMENT_INVALID');
98
+ if(run.continueReceipt!==undefined){
99
+ const r=run.continueReceipt;
100
+ assert(r&&typeof r==='object'&&!Array.isArray(r)
101
+ &&Object.keys(r).length===4
102
+ &&run.phase==='PENDING'
103
+ &&r.id===run.nextAttempt?.id
104
+ &&r.newPage===run.page
105
+ &&typeof r.newUserKey==='string'
106
+ &&/^user:[^\s]{8,}$/.test(r.newUserKey)
107
+ &&r.newUserKey!==run.nextAttempt.sourceUserKey
108
+ &&Number.isSafeInteger(r.observedAt)&&r.observedAt>0,
109
+ 'TASK_CONTINUE_RECEIPT_INVALID');
110
+ }
111
+ if(run.handoffReceipt!==undefined){
112
+ const r=run.handoffReceipt;
113
+ assert(r&&typeof r==='object'&&!Array.isArray(r)
114
+ &&Object.keys(r).length===4
115
+ &&run.phase==='PENDING'
116
+ &&Number.isSafeInteger(r.newTabId)&&r.newTabId>0
117
+ &&typeof r.newPage==='string'
118
+ &&/^\/c\/[0-9a-f-]{12,}$/i.test(r.newPage)
119
+ &&typeof r.newUserKey==='string'
120
+ &&/^user:[^\s]{8,}$/.test(r.newUserKey)
121
+ &&Number.isSafeInteger(r.observedAt)&&r.observedAt>0,
122
+ 'TASK_HANDOFF_RECEIPT_INVALID');
123
+ }
124
+ if(run.handoffFence!==undefined){
125
+ const h=run.handoffFence;
126
+ assert(h&&typeof h==='object'&&!Array.isArray(h)
127
+ &&Object.keys(h).length===7
128
+ &&/^[a-f0-9]{32}$/.test(h.attemptId||'')
129
+ &&ID.test(h.checkpointId||'')
130
+ &&Number.isSafeInteger(h.taskRevision)&&h.taskRevision>=1
131
+ &&Number.isSafeInteger(h.fencedBindingRevision)
132
+ &&h.fencedBindingRevision===run.contextBindingRevision+1
133
+ // Handoff credentials remain in the one-shot Action, never the Store.
134
+ &&h.targetGeneration===run.generation+1
135
+ &&h.nextRunRef===run.sessionId+':'+run.taskId+':'
136
+ +(run.generation+1)
137
+ &&h.contextStoreEpoch===run.contextStoreEpoch,
138
+ 'TASK_HANDOFF_FENCE_INVALID');
139
+ }
140
+ if(run.nextAttempt!==undefined){
141
+ const attempt=run.nextAttempt;
142
+ assert(attempt&&typeof attempt==='object'
143
+ &&!Array.isArray(attempt)
144
+ &&Object.keys(attempt).length===6
145
+ &&/^[a-f0-9]{32}$/.test(attempt.id||'')
146
+ &&attempt.turnToken===run.turnToken
147
+ &&typeof attempt.sourceUserKey==='string'
148
+ &&/^user:[^\s]{8,}$/.test(attempt.sourceUserKey)
149
+ &&typeof attempt.sourceAssistantKey==='string'
150
+ &&/^assistant:[^\s]{8,}$/.test(attempt.sourceAssistantKey)
151
+ &&UUID.test(attempt.nextTurnToken||'')
152
+ &&Number.isSafeInteger(attempt.sendBeginAt??0)
153
+ &&(attempt.sendBeginAt===null||attempt.sendBeginAt>0),
154
+ 'TASK_SEND_ATTEMPT_INVALID');
155
+ }
156
+ if(run.lastIntentReceipt!==undefined){
157
+ const receipt=run.lastIntentReceipt;
158
+ assert(receipt&&typeof receipt==='object'
159
+ &&!Array.isArray(receipt)&&Object.keys(receipt).length===5
160
+ &&UUID.test(receipt.turnToken||'')
161
+ &&/^[a-f0-9]{32}$/.test(receipt.id||'')
162
+ &&['CONTINUE','HANDOFF'].includes(receipt.action)
163
+ &&['SENT_CONFIRMED','UNKNOWN','NOT_SENT'].includes(receipt.status)
164
+ &&Number.isSafeInteger(receipt.updatedAt)
165
+ &&receipt.updatedAt>0,'TASK_INTENT_RECEIPT_INVALID');
166
+ }
167
+ if(run.modelIntent!==undefined){
168
+ const intent=run.modelIntent;
169
+ assert(intent&&typeof intent==='object'&&!Array.isArray(intent)
170
+ &&Object.keys(intent).length===7
171
+ &&/^[a-f0-9]{32}$/.test(intent.id||'')
172
+ &&['CONTINUE','HANDOFF'].includes(intent.action)
173
+ &&intent.turnToken===run.turnToken
174
+ &&typeof intent.targetUserKey==='string'
175
+ &&/^user:[^\s]{8,}$/.test(intent.targetUserKey)
176
+ &&Number.isSafeInteger(intent.requestedAt)
177
+ &&intent.requestedAt>0
178
+ &&(intent.actionTabId===null
179
+ ||Number.isSafeInteger(intent.actionTabId)
180
+ &&intent.actionTabId>0)
181
+ &&['QUEUED','CAPACITY_BLOCKED','LAUNCHING','TAKEN',
182
+ 'SEND_BEGIN','ACTION_UNVERIFIED'].includes(intent.state),
183
+ 'TASK_INTENT_INVALID');
184
+ }
185
+ if(run.lastObservedTurn!==undefined){
186
+ const observed=run.lastObservedTurn;
187
+ assert(observed&&typeof observed==='object'
188
+ &&!Array.isArray(observed)&&Object.keys(observed).length===6
189
+ &&observed.page===run.page
190
+ &&typeof observed.userKey==='string'
191
+ &&observed.userKey.length<=1024
192
+ &&/^user:[^\s]{8,}$/.test(observed.userKey)
193
+ &&typeof observed.assistantKey==='string'
194
+ &&observed.assistantKey.length<=1024
195
+ &&/^assistant:[^\s]{8,}$/.test(observed.assistantKey)
196
+ &&['CONTINUE','DONE','BLOCKED','HANDOFF','UNKNOWN']
197
+ .includes(observed.outcome)
198
+ &&typeof observed.pendingConfirmation==='boolean'
199
+ &&Number.isSafeInteger(observed.observedAt)
200
+ &&observed.observedAt>0,'TASK_OBSERVATION_INVALID');
201
+ }
202
+ if(['WAITING_REPLY','PENDING'].includes(run.phase))
203
+ assert(run.nativeOwnerRevision>0,'TASK_OWNER_UNVERIFIED');
204
+ return clone(run);
205
+ };
206
+ const verifiedState=raw=>{
207
+ if(raw===undefined)return {schemaVersion:2,storeRevision:0,items:{}};
208
+ assert(raw&&raw.schemaVersion===2&&
209
+ Number.isSafeInteger(raw.storeRevision)&&raw.storeRevision>=0&&
210
+ raw.items&&typeof raw.items==='object'&&!Array.isArray(raw.items)&&
211
+ Object.keys(raw).length===3,'TASK_RUN_STORE_INVALID');
212
+ const entries=Object.entries(raw.items),items=Object.create(null);
213
+ assert(entries.length<=32,'TASK_RUN_CAPACITY');
214
+ const claims=new Set(),sessionIds=new Set(),tabs=new Set(),turnTokens=new Set();
215
+ for(const [key,item] of entries){
216
+ assert(item&&typeof item==='object'&&Object.keys(item).length===2
217
+ &&Number.isSafeInteger(item.revision)&&item.revision>=1,
218
+ 'TASK_RUN_STORE_INVALID');
219
+ const run=safeRun(item.run);
220
+ assert(key===taskKey(run.projectId,run.taskId),'TASK_RUN_KEY_INVALID');
221
+ assert(!sessionIds.has(run.sessionId.toLowerCase()),'TASK_SESSION_DUPLICATE');
222
+ sessionIds.add(run.sessionId.toLowerCase());
223
+ if(!terminal(run.phase)&&run.turnToken){
224
+ assert(!turnTokens.has(run.turnToken.toLowerCase()),'TASK_TURN_TOKEN_DUPLICATE');
225
+ turnTokens.add(run.turnToken.toLowerCase());
226
+ }
227
+ if(!terminal(run.phase)&&run.ownerChatId){
228
+ assert(!claims.has(run.ownerChatId.toLowerCase()),'TASK_CHAT_DUPLICATE');
229
+ claims.add(run.ownerChatId.toLowerCase());
230
+ // A Chrome tab cannot host two active Task Owners.
231
+ if(Number.isSafeInteger(run.tabId)&&run.tabId>0){
232
+ assert(!tabs.has(run.tabId),'TASK_TAB_DUPLICATE');
233
+ tabs.add(run.tabId);
234
+ }
235
+ }
236
+ items[key]={revision:item.revision,run};
237
+ }
238
+ return {schemaVersion:2,storeRevision:raw.storeRevision,items};
239
+ };
240
+ const storeInstances=new WeakMap();
241
+ function create(storage){
242
+ assert(typeof storage?.get==='function'&&typeof storage.set==='function',
243
+ 'TASK_STORE_PORT_INVALID');
244
+ const established=storeInstances.get(storage);
245
+ if(established)return established;
246
+ let queue=Promise.resolve();
247
+ const read=async()=>{
248
+ const snapshot=(await storage.get(KEY))?.[KEY];
249
+ return verifiedState(snapshot);
250
+ };
251
+ const get=async(projectId,taskId)=>{
252
+ assert(ID.test(projectId||'')&&ID.test(taskId||''),'TASK_SCOPE_INVALID');
253
+ const state=await read(),item=state.items[taskKey(projectId,taskId)]||null;
254
+ return {storeRevision:state.storeRevision,
255
+ runRevision:item?.revision??null,run:item?clone(item.run):null};
256
+ };
257
+ const put=(next,{expectedStoreRevision,
258
+ expectedRunRevision=null,transitionKind=null})=>{
259
+ const work=queue.then(async()=>{
260
+ const run=safeRun(next),state=await read();
261
+ assert(transitionKind===null
262
+ ||['CONTEXT_CONTINUE_PERMITTED','CONTEXT_HANDOFF_PERMITTED',
263
+ 'CONTEXT_IDLE_CANCELLED','CONTEXT_HANDOFF_RECOVERED'].includes(transitionKind),
264
+ 'TASK_TRANSITION_AUTHORITY_INVALID');
265
+ assert(Number.isSafeInteger(expectedStoreRevision)
266
+ &&expectedStoreRevision>=0&&expectedStoreRevision<=state.storeRevision,
267
+ 'TASK_STORE_CAS_MISMATCH');
268
+ const key=taskKey(run.projectId,run.taskId),prior=state.items[key]||null;
269
+ assert((prior?.revision??null)===expectedRunRevision,
270
+ 'TASK_RUN_CAS_MISMATCH');
271
+ assert(!run.resourceTransfer||prior&&!terminal(prior.run.phase),'TASK_RESOURCE_TRANSFER_UNVERIFIED');
272
+ if(prior?.run.resourceTransfer&&run.resourceTransfer===undefined){
273
+ const {resourceTransfer,...rest}=prior.run;
274
+ assert(transitionKind===null&&JSON.stringify(run)===JSON.stringify(rest),'TASK_RESOURCE_SETTLEMENT_INVALID');
275
+ }else if(prior){
276
+ const old=prior.run;
277
+ if(terminal(old.phase)){
278
+ assert(old.sessionId.toLowerCase()!==run.sessionId.toLowerCase()&&run.phase==='STARTING'
279
+ &&run.generation===0&&run.ownerChatId===null,
280
+ 'TASK_RESTART_UNVERIFIED');
281
+ }else{
282
+ const permittedContinue=['CONTEXT_CONTINUE_PERMITTED',
283
+ 'CONTEXT_HANDOFF_PERMITTED'].includes(transitionKind)
284
+ &&old.phase==='WAITING_REPLY'&&run.phase==='PENDING'
285
+ &&old.sessionId===run.sessionId
286
+ &&old.generation===run.generation
287
+ &&old.tabId===run.tabId
288
+ &&old.ownerChatId===run.ownerChatId
289
+ &&old.turnToken===run.turnToken
290
+ &&run.nextAttempt?.id===old.modelIntent?.id
291
+ &&run.nativeOwnerRevision===old.nativeOwnerRevision+1;
292
+ const permittedRecover=transitionKind==='CONTEXT_HANDOFF_RECOVERED'
293
+ &&old.phase==='BLOCKED'&&run.phase==='WAITING_REPLY'
294
+ &&old.preSendAbort&&old.resourceHoldSettledAt&&old.nextAttempt?.sendBeginAt===null
295
+ &&old.recoveryRequestId&&run.recoveryRequestId===old.recoveryRequestId
296
+ &&run.nativeOwnerRevision===old.nativeOwnerRevision+2
297
+ &&run.contextBindingRevision===old.contextBindingRevision+2
298
+ &&run.sessionId===old.sessionId&&run.generation===old.generation
299
+ &&run.ownerChatId===old.ownerChatId&&run.tabId===old.tabId
300
+ &&run.page===old.page&&run.contextStoreEpoch===old.contextStoreEpoch
301
+ &&run.reason==='HANDOFF_NOT_SENT_RECOVERED'
302
+ &&/^[a-f0-9]{32}$/.test(run.recoveryRequestId||'')
303
+ &&run.turnToken!==old.turnToken&&!run.preSendAbort
304
+ &&!run.nextAttempt&&!run.modelIntent;
305
+ const permittedCancel=transitionKind==='CONTEXT_IDLE_CANCELLED'
306
+ &&old.phase==='BLOCKED'&&run.phase==='CANCELLED'
307
+ &&old.sessionId===run.sessionId
308
+ &&old.generation===run.generation
309
+ &&old.ownerChatId===run.ownerChatId
310
+ &&run.nativeOwnerRevision===old.nativeOwnerRevision+2;
311
+ assert((transitionKind===null&&NEXT[old.phase]?.includes(run.phase))
312
+ ||permittedContinue||permittedCancel||permittedRecover,
313
+ 'TASK_PHASE_TRANSITION_INVALID');
314
+ assert(run.nativeOwnerRevision>=old.nativeOwnerRevision,'TASK_NATIVE_REVISION_STALE');
315
+ if(old.phase==='PENDING'&&run.phase==='WAITING_REPLY'
316
+ ||old.phase==='WAITING_REPLY'&&run.phase==='DONE')
317
+ assert(run.nativeOwnerRevision===old.nativeOwnerRevision+1,
318
+ 'TASK_NATIVE_COMMIT_REQUIRED');
319
+ if(old.phase==='BLOCKED'&&!terminal(run.phase)&&run.phase!=='BLOCKED')
320
+ assert(run.nativeOwnerRevision>old.nativeOwnerRevision,
321
+ 'TASK_RECOVERY_NATIVE_CAS_REQUIRED');
322
+ if(run.resourceTransfer&&JSON.stringify(run.resourceTransfer)!==JSON.stringify(old.resourceTransfer))
323
+ assert(!old.resourceTransfer&&old.phase==='PENDING'
324
+ &&run.phase==='WAITING_REPLY'&&run.generation===old.generation+1
325
+ &&old.modelIntent?.action==='HANDOFF'&&old.modelIntent.state==='SEND_BEGIN'
326
+ &&old.nextAttempt?.id===old.modelIntent.id&&old.nextAttempt.sendBeginAt>0
327
+ &&run.resourceTransfer.sourceTabId===old.tabId
328
+ &&run.resourceTransfer.sourcePage===old.page
329
+ &&run.resourceTransfer.attemptId===old.modelIntent.id
330
+ &&run.nativeOwnerRevision===old.nativeOwnerRevision+1
331
+ &&run.contextBindingRevision===old.handoffFence?.fencedBindingRevision+1
332
+ &&run.lastIntentReceipt?.id===old.modelIntent.id
333
+ &&run.lastIntentReceipt.action==='HANDOFF'&&run.lastIntentReceipt.turnToken===old.turnToken
334
+ &&run.lastIntentReceipt.status==='SENT_CONFIRMED','TASK_RESOURCE_TRANSFER_UNVERIFIED');
335
+ assert(old.sessionId===run.sessionId,'TASK_SESSION_CHANGED');
336
+ assert(run.generation>=old.generation
337
+ &&run.generation<=old.generation+1,'TASK_GENERATION_MISMATCH');
338
+ if(run.generation===old.generation)
339
+ assert(!old.ownerChatId||!run.ownerChatId
340
+ ||old.ownerChatId===run.ownerChatId,'TASK_CHAT_CHANGED');
341
+ else assert(old.ownerChatId&&run.ownerChatId
342
+ &&old.ownerChatId!==run.ownerChatId
343
+ &&run.nativeOwnerRevision===old.nativeOwnerRevision+1,
344
+ 'TASK_HANDOFF_UNVERIFIED');
345
+ }
346
+ }
347
+ const items={...state.items,[key]:{revision:(prior?.revision||0)+1,run}};
348
+ const result=verifiedState({schemaVersion:2,
349
+ storeRevision:state.storeRevision+1,items});
350
+ assert(JSON.stringify(result).length<=512*1024,'TASK_STORE_TOO_LARGE');
351
+ await storage.set({[KEY]:result});
352
+ return {storeRevision:result.storeRevision,
353
+ runRevision:result.items[key].revision};
354
+ });
355
+ queue=work.catch(()=>{});
356
+ return work;
357
+ };
358
+ const retire=(projectId,taskId,{expectedRunRevision,receipt}={})=>{
359
+ const work=queue.then(async()=>{
360
+ assert(ID.test(projectId||'')&&ID.test(taskId||''),'TASK_RETIRE_SCOPE_INVALID');
361
+ const state=await read(),key=taskKey(projectId,taskId);
362
+ const prior=state.items[key];
363
+ assert(prior&&prior.revision===expectedRunRevision
364
+ &&terminal(prior.run.phase)
365
+ &&receipt?.status==='OK'
366
+ &&receipt.scope==='TASK_SCOPED_RETIRED'
367
+ &&receipt.projectId===projectId&&receipt.taskId===taskId
368
+ &&receipt.sessionId===prior.run.sessionId
369
+ &&receipt.generation===prior.run.generation
370
+ &&receipt.nativeOwnerRevision===prior.run.nativeOwnerRevision
371
+ &&receipt.terminal===prior.run.phase,
372
+ 'TASK_RETIRE_AUTHORITY_UNVERIFIED');
373
+ const items={...state.items};
374
+ delete items[key];
375
+ const next=verifiedState({schemaVersion:2,
376
+ storeRevision:state.storeRevision+1,items});
377
+ await storage.set({[KEY]:next});
378
+ return {status:'RETIRED',storeRevision:next.storeRevision};
379
+ });
380
+ queue=work.catch(()=>{});
381
+ return work;
382
+ };
383
+ const resolveTab=async(tabId,chatId)=>{
384
+ assert(Number.isSafeInteger(tabId)&&tabId>0&&CHAT.test(chatId||''),
385
+ 'TASK_TAB_INVALID');
386
+ const state=await read(),hits=Object.values(state.items).filter(item=>
387
+ !terminal(item.run.phase)&&item.run.tabId===tabId&&
388
+ item.run.ownerChatId===chatId);
389
+ assert(hits.length<=1,'TASK_TAB_AMBIGUOUS');
390
+ return hits[0]?{projectId:hits[0].run.projectId,
391
+ taskId:hits[0].run.taskId,sessionId:hits[0].run.sessionId,
392
+ generation:hits[0].run.generation,
393
+ nativeOwnerRevision:hits[0].run.nativeOwnerRevision}:null;
394
+ };
395
+ const api=Object.freeze({read,get,put,retire,resolveTab});
396
+ storeInstances.set(storage,api);
397
+ return api;
398
+ }
399
+ globalThis.ChatLoopTaskRunStoreV2=Object.freeze({KEY,taskKey,create});
400
+ })();
@@ -0,0 +1,78 @@
1
+ // Task-scoped scheduling primitive, not an independent Chrome Worker or sender.
2
+ // No alarm or DOM side effect is created by this module.
3
+ (() => {
4
+ const fail=code=>Object.assign(Error(code),{code});
5
+ const assert=(yes,code)=>{if(!yes)throw fail(code);};
6
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
+ const active=new Set(['RESERVED','PENDING','WAITING_REPLY']);
8
+ const keyOf=run=>JSON.stringify([run.projectId,run.taskId]);
9
+ const boundedTimestamp=n=>Number.isSafeInteger(n)&&n>0?n:null;
10
+ function create(taskStore,{maxPerTick=8}={}){
11
+ assert(taskStore&&typeof taskStore.read==='function'&&
12
+ Number.isSafeInteger(maxPerTick)&&maxPerTick>=1&&maxPerTick<=32,
13
+ 'TASK_SCHEDULER_INVALID');
14
+ const queues=new Map();
15
+ let lastVisited=null;
16
+ const due=async(now=Date.now())=>{
17
+ assert(Number.isSafeInteger(now)&&now>=0,'TASK_CLOCK_INVALID');
18
+ const state=await taskStore.read(),available=[];
19
+ for(const entry of Object.values(state.items)){
20
+ const run=entry.run;
21
+ if(!active.has(run.phase))continue;
22
+ const poll=boundedTimestamp(run.nextPollAt);
23
+ const deadline=boundedTimestamp(run.deadlineAt);
24
+ if((poll!==null&&poll<=now)||(deadline!==null&&deadline<=now))
25
+ available.push({projectId:run.projectId,taskId:run.taskId,
26
+ sessionId:run.sessionId,generation:run.generation,
27
+ nativeOwnerRevision:run.nativeOwnerRevision,
28
+ phase:run.phase,dueAt:Math.min(poll??Infinity,deadline??Infinity),
29
+ runRevision:entry.revision,storeRevision:state.storeRevision});
30
+ }
31
+ available.sort((a,b)=>a.dueAt-b.dueAt||
32
+ keyOf(a).localeCompare(keyOf(b)));
33
+ // Bounded round robin among already-due tasks. A hot or blocked
34
+ // owner must not consume every dispatch slot forever.
35
+ if(lastVisited){
36
+ const idx=available.findIndex(item=>keyOf(item)===lastVisited);
37
+ if(idx>=0)available.push(...available.splice(0,idx+1));
38
+ }
39
+ const selected=available.slice(0,maxPerTick);
40
+ if(selected.length)lastVisited=keyOf(selected.at(-1));
41
+ return selected;
42
+ };
43
+ const perTask=(projectId,taskId,work)=>{
44
+ assert(typeof projectId==='string'&&ID.test(projectId)&&
45
+ typeof taskId==='string'&&ID.test(taskId)&&
46
+ typeof work==='function','TASK_SCOPE_INVALID');
47
+ const key=JSON.stringify([projectId,taskId]);
48
+ const previous=queues.get(key)||Promise.resolve();
49
+ const executing=previous.then(work);
50
+ const settled=executing.catch(()=>{});
51
+ queues.set(key,settled);
52
+ void settled.then(()=>{if(queues.get(key)===settled)queues.delete(key)});
53
+ return executing;
54
+ };
55
+ // A timer snapshot is not a permission to dispatch a later Owner.
56
+ // Revalidate the exact Task generation after its own queue becomes free.
57
+ // Another Task's storeRevision may change without invalidating this one.
58
+ const dispatchDue=(candidate,work)=>{
59
+ assert(candidate&&typeof candidate==='object'&&
60
+ typeof work==='function'&&Number.isSafeInteger(candidate.runRevision)
61
+ &&candidate.runRevision>=1,'TASK_DUE_CANDIDATE_INVALID');
62
+ return perTask(candidate.projectId,candidate.taskId,async()=>{
63
+ const current=await taskStore.get(candidate.projectId,candidate.taskId);
64
+ const run=current?.run;
65
+ assert(run&&current.runRevision===candidate.runRevision
66
+ &&run.sessionId===candidate.sessionId
67
+ &&run.generation===candidate.generation
68
+ &&run.nativeOwnerRevision===candidate.nativeOwnerRevision
69
+ &&run.phase===candidate.phase,'TASK_DUE_CANDIDATE_STALE');
70
+ // The next action/Turn boundary separately checks Native, Context
71
+ // and Chrome. This is a stale timer fence, NOT a send permission.
72
+ return work(Object.freeze({...candidate}));
73
+ });
74
+ };
75
+ return Object.freeze({due,perTask,dispatchDue});
76
+ }
77
+ globalThis.ChatLoopTaskSchedulerV2=Object.freeze({create});
78
+ })();