@tomflow/chatloop-tools 0.9.21 → 0.9.23
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.
- package/README.md +3 -1
- package/node_modules/@tomflow/chatloop-context/package.json +3 -3
- package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +10 -3
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +4 -2
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +109 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +12 -5
- package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
- package/package.json +9 -5
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// Chat Loop Worker — turn-failure. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
+
async function onTurnBlocked(message, sender) {
|
|
3
|
+
const reason = message.reason;
|
|
4
|
+
if (!["PAGE_ERROR", "CONTEXT_LIMIT", "SECURITY_CHALLENGE"].includes(reason)
|
|
5
|
+
|| !await eligible(sender, message.page)
|
|
6
|
+
|| typeof message.userKey !== "string" || !/^user:[^\s]{8,}$/.test(message.userKey))
|
|
7
|
+
return {status: "DENIED", code: "ERROR_SOURCE_UNVERIFIED"};
|
|
8
|
+
const previous = await readRun();
|
|
9
|
+
if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== sender.tab.id
|
|
10
|
+
|| previous.page !== message.page)
|
|
11
|
+
return {status: "IGNORED", code: "NOT_OWNED_RUNNING_TURN"};
|
|
12
|
+
// An unanswered confirmation can be followed by a new human user Turn.
|
|
13
|
+
// If THAT Turn fails, stop the same Owner; never silently ignore its error
|
|
14
|
+
// or treat it as an automatically sent Turn eligible for Retry/Handoff.
|
|
15
|
+
if(message.userKey!==previous.newUserKey){
|
|
16
|
+
const proof=await chrome.tabs.sendMessage(previous.tabId,
|
|
17
|
+
{type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
|
|
18
|
+
const humanFault=proof?.contract==="chat-loop.turn-observer.v1"
|
|
19
|
+
&&proof.page===previous.page&&proof.status==="BLOCKED"
|
|
20
|
+
&&proof.userKey===message.userKey
|
|
21
|
+
&&proof.priorAssistantKey===previous.assistantKey
|
|
22
|
+
&&proof.priorAssistantUserKey===previous.userKey
|
|
23
|
+
&&proof.directReplyAfterPriorAssistant===true;
|
|
24
|
+
if(!humanFault)return {status:"IGNORED",code:"NOT_OWNED_RUNNING_TURN"};
|
|
25
|
+
await saveRun({...previous,phase:"BLOCKED",reason:"HUMAN_RESPONSE_PAGE_ERROR"});
|
|
26
|
+
return {status:"BLOCKED",code:"HUMAN_RESPONSE_PAGE_ERROR"};
|
|
27
|
+
}
|
|
28
|
+
const verify = async () => {
|
|
29
|
+
const proof = await chrome.tabs.sendMessage(previous.tabId,
|
|
30
|
+
{type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
|
|
31
|
+
return proof?.contract === "chat-loop.turn-observer.v1"
|
|
32
|
+
&& proof.status === "BLOCKED" && proof.reason === reason
|
|
33
|
+
&& proof.page === previous.page && proof.userKey === previous.newUserKey
|
|
34
|
+
? proof : null;
|
|
35
|
+
};
|
|
36
|
+
const first = await verify();
|
|
37
|
+
if (!first) return {status: "IGNORED", code: "ERROR_NOT_CONFIRMED"};
|
|
38
|
+
await new Promise(resolve => setTimeout(resolve, 400));
|
|
39
|
+
const second = await verify();
|
|
40
|
+
if (!second || first.retryAvailable !== second.retryAvailable)
|
|
41
|
+
return {status: "IGNORED", code: "ERROR_NOT_STABLE"};
|
|
42
|
+
// A bounded non-content receipt lets the existing Audit prove which
|
|
43
|
+
// decision the ONLY Worker actually took. Never log raw Chat text.
|
|
44
|
+
const faultProof = code => ({code, reason, userKey: message.userKey, at: Date.now()});
|
|
45
|
+
const recordFault = async code => {
|
|
46
|
+
await saveRun({...previous, lastFaultProof: faultProof(code)});
|
|
47
|
+
return {status: "IGNORED", code};
|
|
48
|
+
};
|
|
49
|
+
await saveRun({...previous, lastFaultProof: faultProof("ERROR_CONFIRMED")});
|
|
50
|
+
// A network interruption may show a transient page error without a native
|
|
51
|
+
// Retry button. Only *observe* for a bounded grace period: never resend an
|
|
52
|
+
// uncertain user Turn. Resume normal observation only if the EXACT submitted
|
|
53
|
+
// user identity stays present and two consecutive polls show no page fault.
|
|
54
|
+
// If the optimistic user message disappears, this is NOT proof of no send.
|
|
55
|
+
if (reason === "PAGE_ERROR" && second.retryAvailable !== true) {
|
|
56
|
+
let recovered = 0;
|
|
57
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
58
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
59
|
+
const proof = await chrome.tabs.sendMessage(previous.tabId,
|
|
60
|
+
{type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
|
|
61
|
+
const sameTurn = proof?.contract === "chat-loop.turn-observer.v1"
|
|
62
|
+
&& proof.page === previous.page
|
|
63
|
+
&& proof.userKey === previous.newUserKey;
|
|
64
|
+
// The Observer may emit its verified completion while this error handler
|
|
65
|
+
// owns the serialized Worker queue. That completion message is waiting
|
|
66
|
+
// behind us: fail-closing here would discard a real, finished Turn.
|
|
67
|
+
// TURN_FINISHED or the exact already-emitted state is sufficient proof
|
|
68
|
+
// that the SAME user Turn recovered; do not invent/send another message.
|
|
69
|
+
if (sameTurn && (proof.status === "TURN_FINISHED"
|
|
70
|
+
|| proof.status === "IDLE" && proof.reason === "TURN_ALREADY_EMITTED"))
|
|
71
|
+
return recordFault("PAGE_ERROR_COMPLETION_QUEUED");
|
|
72
|
+
if (sameTurn && ["RUNNING", "UNKNOWN"].includes(proof.status)) {
|
|
73
|
+
recovered++;
|
|
74
|
+
if (recovered === 2) return recordFault("PAGE_ERROR_CLEARED_SAME_TURN");
|
|
75
|
+
} else recovered = 0;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// A security challenge is an explicit stop condition, not a prompt to retry
|
|
79
|
+
// or evade site access controls. Keep the original Chat and user Turn intact.
|
|
80
|
+
if (reason === "SECURITY_CHALLENGE") {
|
|
81
|
+
await saveRun({...previous, phase:"BLOCKED", reason,
|
|
82
|
+
lastFaultProof:faultProof("SECURITY_CHALLENGE")});
|
|
83
|
+
return {status:"BLOCKED", code:reason};
|
|
84
|
+
}
|
|
85
|
+
// The second capacity failure immediately after an ERROR Handoff must not
|
|
86
|
+
// start an infinite series of new ChatGPT conversations.
|
|
87
|
+
const errorHandoffCount = previous.errorHandoffCount || 0;
|
|
88
|
+
if (reason === "CONTEXT_LIMIT" && errorHandoffCount < 1
|
|
89
|
+
|| reason === "PAGE_ERROR" && previous.retryCount !== 1 && second.retryAvailable === true) {
|
|
90
|
+
const retry = reason === "PAGE_ERROR";
|
|
91
|
+
const token = crypto.randomUUID();
|
|
92
|
+
let next = {...previous, phase: "RESERVED", action: retry ? "CONTINUE" : "HANDOFF",
|
|
93
|
+
token, reason: "", lastFaultProof:faultProof(retry ? "NATIVE_RETRY_ONCE" : "CONTEXT_HANDOFF"),
|
|
94
|
+
...(retry ? {retryMode: "NATIVE", retryCount: 1}
|
|
95
|
+
: {handoffMode: "ERROR", errorReason: reason})};
|
|
96
|
+
if (previous.modelIntent) {
|
|
97
|
+
next=updateModelReceipt(next,previous.modelIntent.id,{
|
|
98
|
+
status:"OVERRIDDEN_BY_ERROR",reason,actualAction:next.action});
|
|
99
|
+
delete next.modelIntent;
|
|
100
|
+
}
|
|
101
|
+
await saveRun(next); // Durable before opening the only authorized Action.
|
|
102
|
+
try {
|
|
103
|
+
const url = chrome.runtime.getURL(retry ? "continue.html" : "handoff.html")
|
|
104
|
+
+ "?tabId=" + previous.tabId + "&token=" + encodeURIComponent(token);
|
|
105
|
+
const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
|
|
106
|
+
return {status: "QUEUED", actionTabId: actionTab.id, code: retry ? "NATIVE_RETRY_ONCE" : "CONTEXT_HANDOFF"};
|
|
107
|
+
} catch {
|
|
108
|
+
await saveRun({...next, phase: "BLOCKED", reason: "ERROR_ACTION_CREATE_FAILED"});
|
|
109
|
+
return {status: "BLOCKED", code: "ERROR_ACTION_CREATE_FAILED"};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const finalReason = reason === "PAGE_ERROR"
|
|
113
|
+
? previous.retryCount === 1 ? "PAGE_ERROR_AFTER_RETRY" : "PAGE_ERROR_NO_RETRY_BUTTON"
|
|
114
|
+
: "CONTEXT_HANDOFF_REPEATED";
|
|
115
|
+
await saveRun({...previous, phase:"BLOCKED", reason:finalReason,
|
|
116
|
+
lastFaultProof:faultProof(finalReason)});
|
|
117
|
+
return {status: "BLOCKED", code: reason === "PAGE_ERROR" ? "PAGE_ERROR" : "CONTEXT_HANDOFF_REPEATED"};
|
|
118
|
+
}
|
|
119
|
+
// A model-driven request can only be queued against a currently RUNNING,
|
|
120
|
+
// already-owned user Turn. The MCP call returns immediately: waiting for this
|
|
121
|
+
// assistant to finish inside the tool call would deadlock the Turn.
|
|
122
|
+
async function onModelIntent(message,sender) {
|
|
123
|
+
const action=message?.action;
|
|
124
|
+
const file=action==='HANDOFF'?'handoff.html':action==='CONTINUE'?'continue.html':null;
|
|
125
|
+
const id=message?.id;
|
|
126
|
+
if(!file||!Number.isInteger(sender.tab?.id)||!/^[a-f0-9]{32}$/.test(id||'')
|
|
127
|
+
||sender.url!==chrome.runtime.getURL(file)+'?requestId='+id)
|
|
128
|
+
return {status:'DENIED',code:'INVALID_MODEL_INTENT_SOURCE'};
|
|
129
|
+
const intent=message.intent;
|
|
130
|
+
if(!intent||typeof intent!=='object'||Array.isArray(intent)
|
|
131
|
+
||Object.keys(intent).some(k=>k!=='turnToken' && (action==='CONTINUE'?k!=='nextPrompt':k!=='reason'))
|
|
132
|
+
||typeof intent.turnToken!=='string'
|
|
133
|
+
||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(intent.turnToken))
|
|
134
|
+
return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
|
|
135
|
+
if(action==='CONTINUE' && (typeof intent.nextPrompt!=='string'
|
|
136
|
+
||!intent.nextPrompt.trim()||intent.nextPrompt.length>4000
|
|
137
|
+
||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.nextPrompt))
|
|
138
|
+
||action==='HANDOFF' && intent.reason!==undefined
|
|
139
|
+
&&(typeof intent.reason!=='string'||intent.reason.length>400
|
|
140
|
+
||/[\x00-\x1f]/.test(intent.reason)))
|
|
141
|
+
return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
|
|
142
|
+
const run=await readRun();
|
|
143
|
+
if(!run||run.phase!=='WAITING_REPLY'||run.modelTurnToken!==intent.turnToken)
|
|
144
|
+
return {status:'DENIED',code:'MODEL_INTENT_OWNER_NOT_RUNNING'};
|
|
145
|
+
if(run.modelIntent)
|
|
146
|
+
return {status:'DENIED',code:'MODEL_INTENT_ALREADY_QUEUED'};
|
|
147
|
+
const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
|
|
148
|
+
if(!tab||pathOf(tab.url)!==run.page)
|
|
149
|
+
return {status:'DENIED',code:'MODEL_INTENT_OWNER_CHANGED'};
|
|
150
|
+
const proof=await chrome.tabs.sendMessage(run.tabId,{
|
|
151
|
+
type:'CHAT_LOOP_TURN_OBSERVE_V1',poll:true}).catch(()=>null);
|
|
152
|
+
if(proof?.contract!=='chat-loop.turn-observer.v1'||proof.status!=='RUNNING'
|
|
153
|
+
||proof.page!==run.page||proof.userKey!==run.newUserKey)
|
|
154
|
+
return {status:'DENIED',code:'MODEL_INTENT_TURN_NOT_RUNNING'};
|
|
155
|
+
const next = {...run,modelIntent:{
|
|
156
|
+
id, action, page:run.page, userKey:run.newUserKey,
|
|
157
|
+
...(action==='CONTINUE'?{nextPrompt:intent.nextPrompt}
|
|
158
|
+
:{reason:intent.reason||''}), queuedAt:Date.now()
|
|
159
|
+
}};
|
|
160
|
+
const correlation=run.sessionId&&run.projectId?{
|
|
161
|
+
sessionId:run.sessionId,projectId:run.projectId,
|
|
162
|
+
...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{};
|
|
163
|
+
await saveRun(updateModelReceipt(next,id,{action,turnToken:intent.turnToken,
|
|
164
|
+
...correlation,status:'QUEUED',reason:null,actualAction:null,
|
|
165
|
+
checkpointForwarded:false}));
|
|
166
|
+
// Scoped correlation metadata only. This is an intent queue receipt,
|
|
167
|
+
// never proof that a browser send happened.
|
|
168
|
+
return {status:'QUEUED',action,intentId:id,...correlation};
|
|
169
|
+
}
|
|
170
|
+
async function onModelIntentStatus(message,sender) {
|
|
171
|
+
const action=message?.action;
|
|
172
|
+
const file=action==='HANDOFF'?'handoff.html':action==='CONTINUE'?'continue.html':null;
|
|
173
|
+
const id=message?.id, intent=message?.intent;
|
|
174
|
+
if(!file||!Number.isInteger(sender.tab?.id)||!/^[a-f0-9]{32}$/.test(id||'')
|
|
175
|
+
||sender.url!==chrome.runtime.getURL(file)+'?requestId='+id
|
|
176
|
+
||!intent||typeof intent!=='object'||Array.isArray(intent)
|
|
177
|
+
||typeof intent.turnToken!=='string'
|
|
178
|
+
||!(intent.lookup===true||typeof intent.intentId==='string')
|
|
179
|
+
||Object.keys(intent).some(k=>k!=='turnToken'&&
|
|
180
|
+
k!==(intent.lookup===true?'lookup':'intentId'))
|
|
181
|
+
||intent.lookup!==true&& !/^[a-f0-9]{32}$/.test(intent.intentId||''))
|
|
182
|
+
return {status:'DENIED',code:'INTENT_QUERY_UNAUTHORIZED'};
|
|
183
|
+
const run=await readRun();
|
|
184
|
+
const receipts=receiptHistory(run).filter(x=>x.turnToken===intent.turnToken
|
|
185
|
+
&&x.action===action);
|
|
186
|
+
const receipt=intent.lookup===true?receipts.at(-1)
|
|
187
|
+
:receipts.find(x=>x.id===intent.intentId);
|
|
188
|
+
if(!receipt)return {status:'DENIED',code:'INTENT_RECEIPT_NOT_FOUND'};
|
|
189
|
+
return {status:'STATUS',action,intentId:receipt.id,phase:receipt.status,
|
|
190
|
+
...(receipt.sessionId&&receipt.projectId?{
|
|
191
|
+
sessionId:receipt.sessionId,projectId:receipt.projectId,
|
|
192
|
+
...(receipt.taskId?{taskId:receipt.taskId}:{}),
|
|
193
|
+
generation:receipt.generation}:{}),
|
|
194
|
+
actualAction:receipt.actualAction||null,reason:receipt.reason||null,
|
|
195
|
+
checkpointForwarded:receipt.checkpointForwarded===true,
|
|
196
|
+
updatedAt:receipt.updatedAt};
|
|
197
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Chat Loop Worker — turn-finished. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
+
async function onTurnFinished(message, sender) {
|
|
3
|
+
if (!await eligible(sender, message.page)
|
|
4
|
+
|| typeof message.userKey !== "string" || !/^user:[^\s]{8,}$/.test(message.userKey)
|
|
5
|
+
|| typeof message.assistantKey !== "string"
|
|
6
|
+
|| !/^assistant:[^\s]{8,}$/.test(message.assistantKey)
|
|
7
|
+
|| typeof message.replyText !== "string" || message.replyText.length > 100000) {
|
|
8
|
+
return {status: "DENIED", code: "UNVERIFIED_TURN_SOURCE"};
|
|
9
|
+
}
|
|
10
|
+
const tabId = sender.tab.id;
|
|
11
|
+
const previous = await readRun();
|
|
12
|
+
// A Chat is owned only after an extension Action has explicitly reserved
|
|
13
|
+
// and confirmed its user Turn. A status marker on an arbitrary Chat never
|
|
14
|
+
// starts or reactivates a loop, including after DONE/BLOCKED.
|
|
15
|
+
if (!previous || ["DONE", "BLOCKED"].includes(previous.phase))
|
|
16
|
+
return {status: "IGNORED", code: "NO_ACTIVE_OWNER"};
|
|
17
|
+
if (previous.tabId !== tabId || previous.page !== message.page)
|
|
18
|
+
return {status: "IGNORED", code: "ANOTHER_CHAT_OWNS_LOOP"};
|
|
19
|
+
if (["PENDING", "RESERVED"].includes(previous.phase))
|
|
20
|
+
return {status: "IGNORED", code: previous.phase};
|
|
21
|
+
if (previous.assistantKey === message.assistantKey
|
|
22
|
+
|| previous.userKey === message.userKey)
|
|
23
|
+
return {status: "IGNORED", code: "ALREADY_HANDLED"};
|
|
24
|
+
if (previous.phase !== "WAITING_REPLY")
|
|
25
|
+
return {status: "IGNORED", code: "INVALID_PHASE"};
|
|
26
|
+
// A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
|
|
27
|
+
// assistant must be the exact already-handled question from this Owner, with
|
|
28
|
+
// no intervening user messages. This keeps the old identity boundary
|
|
29
|
+
// without adding a WAITING_USER phase or a second communication channel.
|
|
30
|
+
const humanReply=["PENDING_CONFIRMATION_DOM","ADOPTED_IDLE_BASELINE"].includes(previous.reason)
|
|
31
|
+
&& message.userKey!==previous.newUserKey
|
|
32
|
+
&& previous.userKey && previous.assistantKey
|
|
33
|
+
&& message.userKey!==previous.userKey
|
|
34
|
+
&& message.priorAssistantKey===previous.assistantKey
|
|
35
|
+
&& message.priorAssistantUserKey===previous.userKey
|
|
36
|
+
&& message.directReplyAfterPriorAssistant===true;
|
|
37
|
+
if (message.userKey !== previous.newUserKey && !humanReply) {
|
|
38
|
+
await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
|
|
39
|
+
return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
|
|
40
|
+
}
|
|
41
|
+
const confirmation=await currentConfirmation(tabId,message.page,
|
|
42
|
+
message.userKey,message.assistantKey);
|
|
43
|
+
if (message.pendingConfirmation===true || confirmation===true) {
|
|
44
|
+
// The current assistant still has an unanswered confirmation widget.
|
|
45
|
+
// Do not open a Continue/Handoff Action, even after its old deadline.
|
|
46
|
+
const held=settleModelIntent({...previous,phase:"WAITING_REPLY",
|
|
47
|
+
userKey:message.userKey,assistantKey:message.assistantKey,
|
|
48
|
+
reason:"PENDING_CONFIRMATION_DOM"},
|
|
49
|
+
"CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
|
|
50
|
+
await saveRun(held);
|
|
51
|
+
return {status:"IGNORED",code:"PENDING_CONFIRMATION_DOM"};
|
|
52
|
+
}
|
|
53
|
+
if (confirmation===null) {
|
|
54
|
+
await saveRun({...previous,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
|
|
55
|
+
return {status:"BLOCKED",code:"CONFIRMATION_DOM_UNVERIFIED"};
|
|
56
|
+
}
|
|
57
|
+
let replyText = message.replyText;
|
|
58
|
+
let status = workerApi.parseStatus(replyText);
|
|
59
|
+
if (status === "UNKNOWN") {
|
|
60
|
+
const recovery = await recheckUnknownTurn(message, previous, tabId);
|
|
61
|
+
if (recovery) {status = recovery.status; replyText = recovery.replyText;}
|
|
62
|
+
}
|
|
63
|
+
const now = Date.now();
|
|
64
|
+
// Keep the same clock throughout one Chat. A successful Handoff resets it.
|
|
65
|
+
const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
|
|
66
|
+
&& message.startedAt <= now ? message.startedAt : now;
|
|
67
|
+
const startedAt = previous?.phase === "WAITING_REPLY"
|
|
68
|
+
? previous.startedAt || now : initial;
|
|
69
|
+
const timeExpired = now >= startedAt + windowMsOf(previous);
|
|
70
|
+
// Deadline intent can be persisted by the timer even while a Turn RUNS.
|
|
71
|
+
// The decision below still waits for the observer's complete Turn proof.
|
|
72
|
+
const queued = !humanReply && previous?.modelIntent?.page===message.page
|
|
73
|
+
&& previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
|
|
74
|
+
// Existing DONE/BLOCKED, deadline and page-error policies still win.
|
|
75
|
+
// A queued model request only changes a still-eligible CONTINUE Turn.
|
|
76
|
+
let nextAction = status === "HANDOFF" ? "UNSUPPORTED_MODEL_HANDOFF"
|
|
77
|
+
: (previous?.handoffPending || timeExpired) && status === "CONTINUE"
|
|
78
|
+
? "HANDOFF" : status === "CONTINUE" && queued
|
|
79
|
+
? queued.action : status;
|
|
80
|
+
if (nextAction !== "CONTINUE" && nextAction !== "HANDOFF") {
|
|
81
|
+
if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
|
|
82
|
+
const terminal={...previous, phase:status==="DONE"?"DONE":"BLOCKED",
|
|
83
|
+
reason:status,userKey:message.userKey,assistantKey:message.assistantKey};
|
|
84
|
+
if(status==="DONE"&&previous.contextManaged&&previous.taskId){
|
|
85
|
+
// Check the actual Context delivery BEFORE publishing a durable DONE.
|
|
86
|
+
// A model's machine marker alone is never a committed Task outcome.
|
|
87
|
+
const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
88
|
+
op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
|
|
89
|
+
const fact=observed?.result;
|
|
90
|
+
if(observed?.status!=="OK"||fact?.executionOutcome!=="DONE"
|
|
91
|
+
||!fact.deliveryRef
|
|
92
|
+
||fact.runRef!==previous.sessionId+":"+previous.taskId+":"+(previous.generation||0)){
|
|
93
|
+
await saveRun({...terminal,phase:"BLOCKED",
|
|
94
|
+
reason:"CONTEXT_TERMINAL_NOT_COMMITTED",contextTerminalFence:"UNVERIFIED"});
|
|
95
|
+
return {status:"BLOCKED",code:"CONTEXT_TERMINAL_NOT_COMMITTED"};
|
|
96
|
+
}
|
|
97
|
+
// The signed Native fence requires phase DONE; keep a durable
|
|
98
|
+
// PENDING marker that denies IDLE/Start until the fence is verified.
|
|
99
|
+
await saveRun({...terminal,contextTerminalFence:"PENDING"});
|
|
100
|
+
const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
101
|
+
op:"context-control",command:"run.fence.terminal",
|
|
102
|
+
args:{expectedStoreEpoch:previous.contextManaged.storeEpoch,
|
|
103
|
+
writeRequestId:"terminal:"+previous.sessionId+":"+(previous.generation||0),
|
|
104
|
+
expectedTaskRevision:fact.taskRevision,
|
|
105
|
+
expectedBindingRevision:fact.bindingRevision}
|
|
106
|
+
}).catch(()=>null);
|
|
107
|
+
if(fenced?.status!=="OK"||fenced.result?.status!=="TERMINAL_FENCED"){
|
|
108
|
+
// Native DONE cannot regress to BLOCKED. Leave that truthful
|
|
109
|
+
// projection in place, but never treat it as released write rights.
|
|
110
|
+
await saveRun({...terminal,reason:"CONTEXT_TERMINAL_FENCE_UNVERIFIED",
|
|
111
|
+
contextTerminalFence:"UNVERIFIED"});
|
|
112
|
+
return {status:"BLOCKED",code:"CONTEXT_TERMINAL_FENCE_UNVERIFIED"};
|
|
113
|
+
}
|
|
114
|
+
await saveRun({...terminal,contextTerminalFence:"CONFIRMED"});
|
|
115
|
+
}else await saveRun(terminal);
|
|
116
|
+
}
|
|
117
|
+
return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
|
|
118
|
+
? "MODEL_HANDOFF_DISABLED" : status};
|
|
119
|
+
}
|
|
120
|
+
// Recheck at the last new-authorization boundary, even if a periodic or
|
|
121
|
+
// one-shot alarm was delayed while the Worker handled completion evidence.
|
|
122
|
+
const newlyDue = Date.now() >= startedAt + windowMsOf(previous);
|
|
123
|
+
if (nextAction === "CONTINUE" && newlyDue) nextAction = "HANDOFF";
|
|
124
|
+
const token = crypto.randomUUID();
|
|
125
|
+
const run = {...(previous?.sessionId ? {sessionId: previous.sessionId,
|
|
126
|
+
projectId: previous.projectId,...(previous.taskId?{taskId:previous.taskId}:{}),
|
|
127
|
+
...(previous.contextManaged?{contextManaged:previous.contextManaged}:{}),
|
|
128
|
+
generation: previous.generation || 0} : {}),
|
|
129
|
+
tabId, page: message.page, userKey: message.userKey,
|
|
130
|
+
assistantKey: message.assistantKey, phase: "RESERVED", token,
|
|
131
|
+
action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
|
|
132
|
+
// Preserve the last recovered message across normal progress: a repair
|
|
133
|
+
// acknowledgement cannot replay that same failed Turn.
|
|
134
|
+
...(previous?.recoveryAttempts ? {recoveryAttempts:previous.recoveryAttempts,
|
|
135
|
+
...(previous.recoveryProtocol?{recoveryProtocol:previous.recoveryProtocol}:{}),
|
|
136
|
+
...(previous.recoverySourceAssistantKey?{recoverySourceAssistantKey:previous.recoverySourceAssistantKey}:{})} : {}),
|
|
137
|
+
// Preserve an explicitly configured window through every Continue and
|
|
138
|
+
// Handoff. Otherwise the clock silently falls back to the default
|
|
139
|
+
// after the first completed Turn, breaking the persisted deadline.
|
|
140
|
+
...(Number.isSafeInteger(previous?.windowMs) && previous.windowMs > 0
|
|
141
|
+
? {windowMs:previous.windowMs} : {}),
|
|
142
|
+
...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
|
|
143
|
+
...((previous?.handoffPending || newlyDue) ? {
|
|
144
|
+
handoffPending: true,
|
|
145
|
+
handoffPendingAt: previous?.handoffPendingAt || Date.now()} : {}),
|
|
146
|
+
// A completed Turn is a successful recovery and clears the consecutive error-Handoff guard.
|
|
147
|
+
errorHandoffCount: 0,
|
|
148
|
+
// A timed Handoff uses an Action-local read-only snapshot. Do not keep
|
|
149
|
+
// the entire conversation in storage or embed it in the Action URL.
|
|
150
|
+
handoffMode: nextAction === "HANDOFF" ? "TIMED" : null,
|
|
151
|
+
...(status==="CONTINUE" && queued
|
|
152
|
+
&& (queued.action===nextAction
|
|
153
|
+
||queued.action==="CONTINUE"&&nextAction==="HANDOFF")
|
|
154
|
+
? {modelIntent:queued} : {})};
|
|
155
|
+
// Deadline wins, but the queued continuation is retained as a *proposal*
|
|
156
|
+
// in the bounded Handoff packet instead of silently losing task progress.
|
|
157
|
+
const overridden=queued?.action==="CONTINUE"&&nextAction==="HANDOFF";
|
|
158
|
+
const recorded=queued?updateModelReceipt(run,queued.id,{
|
|
159
|
+
status:overridden?"OVERRIDDEN_BY_DEADLINE":"RESERVED",
|
|
160
|
+
actualAction:nextAction,
|
|
161
|
+
reason:overridden?"OVERRIDDEN_BY_DEADLINE":null,
|
|
162
|
+
checkpointForwarded:false}):run;
|
|
163
|
+
// Durable before opening an Action; an uncertain outcome must never be retried.
|
|
164
|
+
await saveRun(recorded);
|
|
165
|
+
try {
|
|
166
|
+
const url = chrome.runtime.getURL(nextAction === "HANDOFF" ? "handoff.html" : "continue.html")
|
|
167
|
+
+ "?tabId=" + tabId + "&token=" + encodeURIComponent(token);
|
|
168
|
+
const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
|
|
169
|
+
return {status: "QUEUED", actionTabId: actionTab.id};
|
|
170
|
+
} catch (error) {
|
|
171
|
+
await saveRun({...recorded, phase: "BLOCKED", reason: "ACTION_PAGE_CREATE_FAILED"});
|
|
172
|
+
return {status: "BLOCKED", code: error.message || "ACTION_PAGE_CREATE_FAILED"};
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Recover ONLY an interrupted pre-send reservation from the old Worker
|
|
176
|
+
// implementation: Chrome said RESERVED, native still said BLOCKED, so no
|
|
177
|
+
// ACTION_TAKE/PENDING/DOM click could have occurred. Invalidate that token
|
|
178
|
+
// through the same authorized scheduler, never by editing the disk file.
|
|
179
|
+
async function repairUncommittedBlockedRecovery(){
|
|
180
|
+
const run=await readRun();
|
|
181
|
+
if(run?.phase!=="RESERVED"
|
|
182
|
+
||run.recoveryMode!=="TOOL_PREFLIGHT_REPAIRED"
|
|
183
|
+
||run.recoveryAttempts!==1 || run.recoveryProtocol || !run.sessionId
|
|
184
|
+
||!Number.isInteger(run.manualActionTabId))
|
|
185
|
+
return run;
|
|
186
|
+
const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
187
|
+
{op:"session-read"}).catch(()=>null);
|
|
188
|
+
if(disk?.status!=="OK"||disk.session?.phase!=="BLOCKED"
|
|
189
|
+
||disk.session.sessionId!==run.sessionId
|
|
190
|
+
||disk.session.projectId!==run.projectId
|
|
191
|
+
||disk.session.generation!==(run.generation||0)
|
|
192
|
+
||disk.session.activeChatId!==chatIdOf("https://chatgpt.com"+run.page))
|
|
193
|
+
return run;
|
|
194
|
+
const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
|
|
195
|
+
for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
|
|
196
|
+
"manualActionTabId","actionPendingAt","resourceToken"])
|
|
197
|
+
delete restored[field];
|
|
198
|
+
await saveRun(restored);
|
|
199
|
+
return restored;
|
|
200
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Sole npm SDK entry: all private module dependencies are composed here.
|
|
2
|
+
// Node-native Worker entrypoints consume these APIs, never lib/* paths.
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {actionCapabilities} from './actions.generated.mjs';
|
|
5
|
+
import {matchExtensionAction} from './lib/action-routing.mjs';
|
|
6
|
+
import {openExtensionActionPage} from './lib/browser-launch.mjs';
|
|
7
|
+
import {createApiAspect} from '@tomflow/chatloop-trace';
|
|
8
|
+
import {createOrderedApiObservationSender,createObservationDrain} from './lib/api-observation-queue.mjs';
|
|
9
|
+
const observationSender=createOrderedApiObservationSender(record=>
|
|
10
|
+
ipc.nativeApiObservation(record));
|
|
11
|
+
const INTERNAL_DRAIN=Symbol.for('chat-loop.telemetry.drain.internal');
|
|
12
|
+
const apiAspect=createApiAspect('@tomflow/chatloop-extension',{
|
|
13
|
+
sink:record=>{
|
|
14
|
+
// The sink uses the private raw IPC transport, not the exported Native
|
|
15
|
+
// callable. Public nativeHostApi/nativeApiObservation calls therefore
|
|
16
|
+
// remain observable without re-entering their own AOP wrappers.
|
|
17
|
+
return observationSender.send({
|
|
18
|
+
callId:record.callId,traceId:record.traceId,spanId:record.spanId,
|
|
19
|
+
...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
|
|
20
|
+
apiName:'extension.'+record.surface+'.'+record.api,
|
|
21
|
+
phase:record.phase,
|
|
22
|
+
...(record.durationMs!==null?{durationMs:record.durationMs}:{}),
|
|
23
|
+
...(record.errorCode?{errorCode:record.errorCode}:{})
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
const drainTelemetry=createObservationDrain(apiAspect,observationSender);
|
|
28
|
+
import * as bridge from './lib/bridge.mjs';
|
|
29
|
+
import * as session from './lib/session-file.mjs';
|
|
30
|
+
import * as binding from './lib/context-binding.mjs';
|
|
31
|
+
import * as ipc from './lib/context-ipc.mjs';
|
|
32
|
+
import * as evidence from './lib/owner-evidence.mjs';
|
|
33
|
+
|
|
34
|
+
bridge.configureBridgeActions(actionCapabilities,apiAspect.current);
|
|
35
|
+
binding.configureContextBinding({configFile:bridge.configFile});
|
|
36
|
+
evidence.configureOwnerEvidence({
|
|
37
|
+
readSession:session.readSession,sessionPath:session.sessionPath,
|
|
38
|
+
cliPath:()=>fileURLToPath(new URL('./bin/cli.mjs',import.meta.url))
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Bounded provider contract for Context's reviewed orphan fence.
|
|
42
|
+
export const verifyOrphanOwnerIdle=apiAspect.observe(
|
|
43
|
+
'verifyOrphanOwnerIdle',evidence.verifyOrphanOwnerIdle);
|
|
44
|
+
|
|
45
|
+
// Internal entrypoint contracts, not a second npm subpath.
|
|
46
|
+
export const extensionCliApi=apiAspect.observe('extensionCliApi',
|
|
47
|
+
()=>apiAspect.methods(Object.freeze({
|
|
48
|
+
[INTERNAL_DRAIN]:drainTelemetry,
|
|
49
|
+
ACTIONS:bridge.ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME:bridge.HOST_NAME,
|
|
50
|
+
configFile:bridge.configFile,prepare:bridge.prepare,
|
|
51
|
+
readResult:bridge.readResult,privateDir:bridge.privateDir,
|
|
52
|
+
validateExtensionId:bridge.validateExtensionId,
|
|
53
|
+
openExtensionActionPage
|
|
54
|
+
}), 'extensionCliApi','cli'));
|
|
55
|
+
export const nativeHostApi=apiAspect.observe('nativeHostApi',
|
|
56
|
+
()=>apiAspect.methods(Object.freeze({
|
|
57
|
+
[INTERNAL_DRAIN]:drainTelemetry,
|
|
58
|
+
readRequest:bridge.readRequest,finish:bridge.finish,
|
|
59
|
+
readSession:session.readSession,writeSession:session.writeSession,
|
|
60
|
+
registeredContext:binding.registeredContext,
|
|
61
|
+
nativeContextControl:ipc.nativeContextControl,
|
|
62
|
+
// One named, non-authoritative span for each Native messaging operation.
|
|
63
|
+
observeNativeOperation:(op,perform,parent=null)=>{
|
|
64
|
+
if(typeof perform!=='function')throw TypeError('NATIVE_OPERATION_REQUIRED');
|
|
65
|
+
const name=typeof op==='string'&&/^[a-z][a-z0-9-]{0,60}$/.test(op)
|
|
66
|
+
?op:'invalid';
|
|
67
|
+
return apiAspect.observe('native.op.'+name,perform,'native',
|
|
68
|
+
parent?{parent}:{})();
|
|
69
|
+
},
|
|
70
|
+
nativeApiObservation:ipc.nativeApiObservation
|
|
71
|
+
}), 'nativeHostApi','native'));
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// One CLI interpretation rule for every statically declared browser Action.
|
|
2
|
+
// Only the three reviewed owner-control kinds can request privileged intent.
|
|
3
|
+
export function matchExtensionAction(catalog,argv){
|
|
4
|
+
if(!Array.isArray(argv)||argv[0]!=='extension')return null;
|
|
5
|
+
const input=argv.slice(1);
|
|
6
|
+
for(const cap of catalog){
|
|
7
|
+
if(!Array.isArray(cap.cli))continue;
|
|
8
|
+
const route=cap.cli;
|
|
9
|
+
if(input.length===route.length+1&&cap.kind==='owner-clean'
|
|
10
|
+
&&input.slice(0,route.length).join(' ')===route.join(' ')
|
|
11
|
+
&&/^[1-9][0-9]*$/.test(input.at(-1))
|
|
12
|
+
&&Number.isSafeInteger(Number(input.at(-1))))
|
|
13
|
+
return {id:cap.id,intent:{tabId:Number(input.at(-1))}};
|
|
14
|
+
if(input.length===route.length&&input.join(' ')===route.join(' '))
|
|
15
|
+
return {id:cap.id,needsIntent:['owner-intent','owner-start'].includes(cap.kind)};
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Keep each API span ordered at the existing single Supervisor writer.
|
|
2
|
+
// Telemetry is best-effort: it neither changes nor retries the business call.
|
|
3
|
+
// Concurrent spans are allowed; BEGIN and terminal of one call never race.
|
|
4
|
+
export function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2048}={}){
|
|
5
|
+
if(typeof deliver!=='function'||!Number.isInteger(parallel)||parallel<1||
|
|
6
|
+
!Number.isInteger(capacity)||capacity<2)throw TypeError('OBSERVATION_SENDER_INVALID');
|
|
7
|
+
const waiting=[],active=new Set();
|
|
8
|
+
const health={submitted:0,confirmed:0,dropped:0,failed:0,lastFailureCode:null};
|
|
9
|
+
let running=0,scheduled=false;
|
|
10
|
+
function pump(){
|
|
11
|
+
scheduled=false;
|
|
12
|
+
while(running<parallel){
|
|
13
|
+
const position=waiting.findIndex(({record})=>!active.has(record.callId));
|
|
14
|
+
if(position<0)return;
|
|
15
|
+
const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
|
|
16
|
+
running++;active.add(id);
|
|
17
|
+
let success=false;
|
|
18
|
+
Promise.resolve().then(()=>deliver(record)).then(result=>{
|
|
19
|
+
success=result!==false;
|
|
20
|
+
if(success)health.confirmed++;
|
|
21
|
+
else{health.failed++;health.lastFailureCode='OBSERVATION_REJECTED'}
|
|
22
|
+
},error=>{
|
|
23
|
+
health.failed++;
|
|
24
|
+
health.lastFailureCode=/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')
|
|
25
|
+
?error.code:'OBSERVATION_TRANSPORT_FAILED';
|
|
26
|
+
}).finally(()=>{
|
|
27
|
+
// Keep later terminal evidence even when BEGIN transport failed:
|
|
28
|
+
// an orphan terminal is an auditable gap, not an invisible call.
|
|
29
|
+
active.delete(id);running--;resolve(success);schedule();
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function schedule(){
|
|
34
|
+
if(scheduled)return;
|
|
35
|
+
scheduled=true;queueMicrotask(pump);
|
|
36
|
+
}
|
|
37
|
+
function send(record){
|
|
38
|
+
health.submitted++;
|
|
39
|
+
if(waiting.length>=capacity){
|
|
40
|
+
health.dropped++;
|
|
41
|
+
health.lastFailureCode='OBSERVATION_QUEUE_FULL';
|
|
42
|
+
return Promise.resolve(false);
|
|
43
|
+
}
|
|
44
|
+
return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
|
|
45
|
+
}
|
|
46
|
+
return Object.freeze({send,
|
|
47
|
+
health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// One bounded CLI/Native process-exit gate, after the business reply.
|
|
51
|
+
// The Trace AOP queue and this transport have separate async backlogs.
|
|
52
|
+
// Never count "queue empty" as "Writer accepted the records".
|
|
53
|
+
export function createObservationDrain(aspect,sender){
|
|
54
|
+
if(typeof aspect?.drain!=='function'||typeof aspect?.health!=='function'
|
|
55
|
+
||typeof sender?.health!=='function')throw TypeError('OBSERVATION_DRAIN_INVALID');
|
|
56
|
+
return async function drain(timeoutMs=4200){
|
|
57
|
+
const budget=Number.isSafeInteger(timeoutMs)
|
|
58
|
+
?Math.max(0,Math.min(timeoutMs,6000)):4200;
|
|
59
|
+
const deadline=Date.now()+budget;
|
|
60
|
+
let state;
|
|
61
|
+
do{
|
|
62
|
+
const remaining=Math.max(1,deadline-Date.now());
|
|
63
|
+
await aspect.drain(Math.min(750,remaining));
|
|
64
|
+
const a=aspect.health(),s=sender.health();
|
|
65
|
+
state={pending:a.pending+s.pending,inFlight:a.inFlight+s.inFlight,
|
|
66
|
+
dropped:a.dropped+s.dropped,failed:a.sinkFailures+s.failed,
|
|
67
|
+
submitted:s.submitted,confirmed:s.confirmed,
|
|
68
|
+
lastFailureCode:s.lastFailureCode};
|
|
69
|
+
if(state.pending===0&&state.inFlight===0)break;
|
|
70
|
+
}while(Date.now()<deadline);
|
|
71
|
+
return Object.freeze({...state,status:state.pending||state.inFlight
|
|
72
|
+
?'TIMEOUT':state.dropped||state.failed?'LOG_GAP':'OK'});
|
|
73
|
+
};
|
|
74
|
+
}
|