@tomflow/chatloop-tools 0.9.64 → 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 (175) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +296 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  45. package/node_modules/@tomflow/chatloop-context/package.json +38 -0
  46. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  47. package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
  48. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
  49. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  126. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  127. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  128. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  129. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  130. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  131. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  132. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  133. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  134. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  135. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
  136. package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
  137. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
  138. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
  139. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
  140. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
  141. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  142. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
  143. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
  144. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  145. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  146. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  147. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  148. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  149. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  150. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  151. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  152. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  153. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  154. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
  155. package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
  156. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
  157. package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
  158. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  159. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  160. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  161. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  162. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  163. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
  164. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
  165. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
  166. package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
  167. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  168. package/node_modules/ps-list/index.d.ts +76 -0
  169. package/node_modules/ps-list/index.js +366 -0
  170. package/node_modules/ps-list/license +9 -0
  171. package/node_modules/ps-list/package.json +44 -0
  172. package/node_modules/ps-list/readme.md +56 -0
  173. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  174. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  175. package/package.json +12 -4
@@ -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,205 @@
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
+ // Previous extension versions may have persisted a confirmed first send
27
+ // before recording whether its Context bind completed. Do not downgrade
28
+ // such an Owner to unmanaged execution on Worker restart or upgrade.
29
+ if(previous.contextLeaseRef&&!previous.contextManaged){
30
+ await saveRun({...previous,phase:'BLOCKED',
31
+ reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'});
32
+ return {status:'BLOCKED',code:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
33
+ }
34
+ // A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
35
+ // assistant must be the exact already-handled question from this Owner, with
36
+ // no intervening user messages. This keeps the old identity boundary
37
+ // without adding a WAITING_USER phase or a second communication channel.
38
+ const humanReply=["PENDING_CONFIRMATION_DOM","ADOPTED_IDLE_BASELINE"].includes(previous.reason)
39
+ && message.userKey!==previous.newUserKey
40
+ && previous.userKey && previous.assistantKey
41
+ && message.userKey!==previous.userKey
42
+ && message.priorAssistantKey===previous.assistantKey
43
+ && message.priorAssistantUserKey===previous.userKey
44
+ && message.directReplyAfterPriorAssistant===true;
45
+ if (message.userKey !== previous.newUserKey && !humanReply) {
46
+ await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
47
+ return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
48
+ }
49
+ const confirmation=await currentConfirmation(tabId,message.page,
50
+ message.userKey,message.assistantKey);
51
+ if (message.pendingConfirmation===true || confirmation===true) {
52
+ // The current assistant still has an unanswered confirmation widget.
53
+ // Do not open a Continue/Handoff Action, even after its old deadline.
54
+ const held=settleModelIntent({...previous,phase:"WAITING_REPLY",
55
+ userKey:message.userKey,assistantKey:message.assistantKey,
56
+ reason:"PENDING_CONFIRMATION_DOM"},
57
+ "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
58
+ await saveRun(held);
59
+ return {status:"IGNORED",code:"PENDING_CONFIRMATION_DOM"};
60
+ }
61
+ if (confirmation===null) {
62
+ await saveRun({...previous,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
63
+ return {status:"BLOCKED",code:"CONFIRMATION_DOM_UNVERIFIED"};
64
+ }
65
+ let replyText = message.replyText;
66
+ let status = workerApi.parseStatus(replyText);
67
+ if (status === "UNKNOWN") {
68
+ const recovery = await recheckUnknownTurn(message, previous, tabId);
69
+ if (recovery) {status = recovery.status; replyText = recovery.replyText;}
70
+ }
71
+ const now = Date.now();
72
+ // Keep the same clock throughout one Chat. A successful Handoff resets it.
73
+ const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
74
+ && message.startedAt <= now ? message.startedAt : now;
75
+ const startedAt = previous?.phase === "WAITING_REPLY"
76
+ ? previous.startedAt || now : initial;
77
+ const timeExpired = now >= startedAt + windowMsOf(previous);
78
+ // Deadline intent can be persisted by the timer even while a Turn RUNS.
79
+ // The decision below still waits for the observer's complete Turn proof.
80
+ const queued = !humanReply && previous?.modelIntent?.page===message.page
81
+ && previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
82
+ // Existing DONE/BLOCKED, deadline and page-error policies still win.
83
+ // A queued model request only changes a still-eligible CONTINUE Turn.
84
+ let nextAction = status === "HANDOFF" ? "UNSUPPORTED_MODEL_HANDOFF"
85
+ : (previous?.handoffPending || timeExpired) && status === "CONTINUE"
86
+ ? "HANDOFF" : status === "CONTINUE" && queued
87
+ ? queued.action : status;
88
+ if (nextAction !== "CONTINUE" && nextAction !== "HANDOFF") {
89
+ if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
90
+ const terminal={...previous, phase:status==="DONE"?"DONE":"BLOCKED",
91
+ reason:status,userKey:message.userKey,assistantKey:message.assistantKey};
92
+ if(status==="DONE"&&previous.contextManaged&&previous.taskId){
93
+ // Check the actual Context delivery BEFORE publishing a durable DONE.
94
+ // A model's machine marker alone is never a committed Task outcome.
95
+ const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
96
+ op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
97
+ const fact=observed?.result;
98
+ if(observed?.status!=="OK"||fact?.executionOutcome!=="DONE"
99
+ ||!fact.deliveryRef
100
+ ||fact.runRef!==previous.sessionId+":"+previous.taskId+":"+(previous.generation||0)){
101
+ await saveRun({...terminal,phase:"BLOCKED",
102
+ reason:"CONTEXT_TERMINAL_NOT_COMMITTED",contextTerminalFence:"UNVERIFIED"});
103
+ return {status:"BLOCKED",code:"CONTEXT_TERMINAL_NOT_COMMITTED"};
104
+ }
105
+ // The signed Native fence requires phase DONE; keep a durable
106
+ // PENDING marker that denies IDLE/Start until the fence is verified.
107
+ await saveRun({...terminal,contextTerminalFence:"PENDING"});
108
+ const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
109
+ op:"context-control",command:"run.fence.terminal",
110
+ args:{expectedStoreEpoch:previous.contextManaged.storeEpoch,
111
+ writeRequestId:"terminal:"+previous.sessionId+":"+(previous.generation||0),
112
+ expectedTaskRevision:fact.taskRevision,
113
+ expectedBindingRevision:fact.bindingRevision}
114
+ }).catch(()=>null);
115
+ if(fenced?.status!=="OK"||fenced.result?.status!=="TERMINAL_FENCED"){
116
+ // Native DONE cannot regress to BLOCKED. Leave that truthful
117
+ // projection in place, but never treat it as released write rights.
118
+ await saveRun({...terminal,reason:"CONTEXT_TERMINAL_FENCE_UNVERIFIED",
119
+ contextTerminalFence:"UNVERIFIED"});
120
+ return {status:"BLOCKED",code:"CONTEXT_TERMINAL_FENCE_UNVERIFIED"};
121
+ }
122
+ await saveRun({...terminal,contextTerminalFence:"CONFIRMED"});
123
+ }else await saveRun(terminal);
124
+ }
125
+ return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
126
+ ? "MODEL_HANDOFF_DISABLED" : status};
127
+ }
128
+ // Recheck at the last new-authorization boundary, even if a periodic or
129
+ // one-shot alarm was delayed while the Worker handled completion evidence.
130
+ const newlyDue = Date.now() >= startedAt + windowMsOf(previous);
131
+ if (nextAction === "CONTINUE" && newlyDue) nextAction = "HANDOFF";
132
+ const token = crypto.randomUUID();
133
+ const run = {...(previous?.sessionId ? {sessionId: previous.sessionId,
134
+ projectId: previous.projectId,...(previous.taskId?{taskId:previous.taskId}:{}),
135
+ ...(previous.contextManaged?{contextManaged:previous.contextManaged}:{}),
136
+ generation: previous.generation || 0} : {}),
137
+ tabId, page: message.page, userKey: message.userKey,
138
+ assistantKey: message.assistantKey, phase: "RESERVED", token,
139
+ action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
140
+ // Preserve the last recovered message across normal progress: a repair
141
+ // acknowledgement cannot replay that same failed Turn.
142
+ ...(previous?.recoveryAttempts ? {recoveryAttempts:previous.recoveryAttempts,
143
+ ...(previous.recoveryProtocol?{recoveryProtocol:previous.recoveryProtocol}:{}),
144
+ ...(previous.recoverySourceAssistantKey?{recoverySourceAssistantKey:previous.recoverySourceAssistantKey}:{})} : {}),
145
+ // Preserve an explicitly configured window through every Continue and
146
+ // Handoff. Otherwise the clock silently falls back to the default
147
+ // after the first completed Turn, breaking the persisted deadline.
148
+ ...(Number.isSafeInteger(previous?.windowMs) && previous.windowMs > 0
149
+ ? {windowMs:previous.windowMs} : {}),
150
+ ...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
151
+ ...((previous?.handoffPending || newlyDue) ? {
152
+ handoffPending: true,
153
+ handoffPendingAt: previous?.handoffPendingAt || Date.now()} : {}),
154
+ // A completed Turn is a successful recovery and clears the consecutive error-Handoff guard.
155
+ errorHandoffCount: 0,
156
+ // A timed Handoff uses an Action-local read-only snapshot. Do not keep
157
+ // the entire conversation in storage or embed it in the Action URL.
158
+ handoffMode: nextAction === "HANDOFF" ? "TIMED" : null,
159
+ ...(status==="CONTINUE" && queued
160
+ && (queued.action===nextAction
161
+ ||queued.action==="CONTINUE"&&nextAction==="HANDOFF")
162
+ ? {modelIntent:queued} : {})};
163
+ // Deadline wins, but the queued continuation is retained as a *proposal*
164
+ // in the bounded Handoff packet instead of silently losing task progress.
165
+ const overridden=queued?.action==="CONTINUE"&&nextAction==="HANDOFF";
166
+ const recorded=queued?updateModelReceipt(run,queued.id,{
167
+ status:overridden?"OVERRIDDEN_BY_DEADLINE":"RESERVED",
168
+ actualAction:nextAction,
169
+ reason:overridden?"OVERRIDDEN_BY_DEADLINE":null,
170
+ checkpointForwarded:false}):run;
171
+ // Durable before opening an Action; an uncertain outcome must never be retried.
172
+ await saveRun(recorded);
173
+ try {
174
+ const url = chrome.runtime.getURL(nextAction === "HANDOFF" ? "handoff.html" : "continue.html")
175
+ + "?tabId=" + tabId + "&token=" + encodeURIComponent(token);
176
+ const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
177
+ return {status: "QUEUED", actionTabId: actionTab.id};
178
+ } catch (error) {
179
+ await saveRun({...recorded, phase: "BLOCKED", reason: "ACTION_PAGE_CREATE_FAILED"});
180
+ return {status: "BLOCKED", code: safeWorkerErrorCode(error,"ACTION_PAGE_CREATE_FAILED")};
181
+ }
182
+ }
183
+ // Recover ONLY an interrupted pre-send reservation from the old Worker
184
+ // implementation: Chrome said RESERVED, native still said BLOCKED, so no
185
+ // ACTION_TAKE/PENDING/DOM click could have occurred. Invalidate that token
186
+ // through the same authorized scheduler, never by editing the disk file.
187
+ async function repairUncommittedBlockedRecovery(){
188
+ const run=await readRun();
189
+ if(run?.phase!=="RESERVED"
190
+ ||run.recoveryMode!=="TOOL_PREFLIGHT_REPAIRED"
191
+ ||run.recoveryAttempts!==1 || run.recoveryProtocol || !run.sessionId
192
+ ||!Number.isInteger(run.manualActionTabId))
193
+ return run;
194
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
195
+ {op:"session-read"}).catch(()=>null);
196
+ if(disk?.status!=="OK"
197
+ ||!matchesNativeProjection(sessionProjection({...run,phase:"BLOCKED"}),disk.session))
198
+ return run;
199
+ const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
200
+ for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
201
+ "manualActionTabId","actionPendingAt","resourceToken"])
202
+ delete restored[field];
203
+ await saveRun(restored);
204
+ return restored;
205
+ }
@@ -0,0 +1,78 @@
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 ownerLedger from './lib/owner-ledger.mjs';
31
+ import {createScopedNativeControl} from './lib/scoped-native-control.mjs';
32
+ import * as binding from './lib/context-binding.mjs';
33
+ import * as ipc from './lib/context-ipc.mjs';
34
+ import * as evidence from './lib/owner-evidence.mjs';
35
+
36
+ bridge.configureBridgeActions(actionCapabilities,apiAspect.current);
37
+ binding.configureContextBinding({configFile:bridge.configFile});
38
+ evidence.configureOwnerEvidence({
39
+ readSession:session.readSession,sessionPath:session.sessionPath,
40
+ cliPath:()=>fileURLToPath(new URL('./bin/cli.mjs',import.meta.url))
41
+ });
42
+
43
+ // Bounded provider contract for Context's reviewed orphan fence.
44
+ export const verifyOrphanOwnerIdle=apiAspect.observe(
45
+ 'verifyOrphanOwnerIdle',evidence.verifyOrphanOwnerIdle);
46
+
47
+ // Internal entrypoint contracts, not a second npm subpath.
48
+ export const extensionCliApi=apiAspect.observe('extensionCliApi',
49
+ ()=>apiAspect.methods(Object.freeze({
50
+ [INTERNAL_DRAIN]:drainTelemetry,
51
+ ACTIONS:bridge.ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME:bridge.HOST_NAME,
52
+ configFile:bridge.configFile,prepare:bridge.prepare,
53
+ readResult:bridge.readResult,privateDir:bridge.privateDir,
54
+ validateExtensionId:bridge.validateExtensionId,
55
+ openExtensionActionPage
56
+ }), 'extensionCliApi','cli'));
57
+ export const nativeHostApi=apiAspect.observe('nativeHostApi',
58
+ ()=>apiAspect.methods(Object.freeze({
59
+ [INTERNAL_DRAIN]:drainTelemetry,
60
+ readRequest:bridge.readRequest,finish:bridge.finish,
61
+ readSession:session.readSession,writeSession:session.writeSession,
62
+ handleScopedNativeMessage:createScopedNativeControl({
63
+ readRequest:bridge.readRequest,readScopedOwner:ownerLedger.readOwnerLedgerTask,
64
+ writeScopedOwner:ownerLedger.writeOwnerLedgerSession,
65
+ retireScopedOwner:ownerLedger.retireOwnerLedgerTerminal,
66
+ nativeContextControl:ipc.nativeContextControl}),
67
+ registeredContext:binding.registeredContext,
68
+ nativeContextControl:ipc.nativeContextControl,
69
+ // One named, non-authoritative span for each Native messaging operation.
70
+ observeNativeOperation:(op,perform,parent=null)=>{
71
+ if(typeof perform!=='function')throw TypeError('NATIVE_OPERATION_REQUIRED');
72
+ const name=typeof op==='string'&&/^[a-z][a-z0-9-]{0,60}$/.test(op)
73
+ ?op:'invalid';
74
+ return apiAspect.observe('native.op.'+name,perform,'native',
75
+ parent?{parent}:{})();
76
+ },
77
+ nativeApiObservation:ipc.nativeApiObservation
78
+ }), 'nativeHostApi','native'));
@@ -0,0 +1,19 @@
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','owner-session',
16
+ 'entry-test'].includes(cap.kind)};
17
+ }
18
+ return null;
19
+ }
@@ -0,0 +1,82 @@
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(({callId})=>!active.has(callId));
14
+ if(position<0)return;
15
+ const [{record,callId,resolve}]=waiting.splice(position,1),id=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
+ // A malformed telemetry record must not throw later inside an unhandled
40
+ // queueMicrotask or mutate its ordering key after being queued.
41
+ let callId;
42
+ try{callId=record?.callId}catch{}
43
+ if(typeof callId!=='string'||!callId||callId.length>128){
44
+ health.dropped++;health.lastFailureCode='OBSERVATION_INVALID';
45
+ return Promise.resolve(false);
46
+ }
47
+ if(waiting.length>=capacity){
48
+ health.dropped++;
49
+ health.lastFailureCode='OBSERVATION_QUEUE_FULL';
50
+ return Promise.resolve(false);
51
+ }
52
+ return new Promise(resolve=>{waiting.push({record,callId,resolve});schedule()});
53
+ }
54
+ return Object.freeze({send,
55
+ health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
56
+ }
57
+
58
+ // One bounded CLI/Native process-exit gate, after the business reply.
59
+ // The Trace AOP queue and this transport have separate async backlogs.
60
+ // Never count "queue empty" as "Writer accepted the records".
61
+ export function createObservationDrain(aspect,sender){
62
+ if(typeof aspect?.drain!=='function'||typeof aspect?.health!=='function'
63
+ ||typeof sender?.health!=='function')throw TypeError('OBSERVATION_DRAIN_INVALID');
64
+ return async function drain(timeoutMs=4200){
65
+ const budget=Number.isSafeInteger(timeoutMs)
66
+ ?Math.max(0,Math.min(timeoutMs,6000)):4200;
67
+ const deadline=Date.now()+budget;
68
+ let state;
69
+ do{
70
+ const remaining=Math.max(1,deadline-Date.now());
71
+ await aspect.drain(Math.min(750,remaining));
72
+ const a=aspect.health(),s=sender.health();
73
+ state={pending:a.pending+s.pending,inFlight:a.inFlight+s.inFlight,
74
+ dropped:a.dropped+s.dropped,failed:a.sinkFailures+s.failed,
75
+ submitted:s.submitted,confirmed:s.confirmed,
76
+ lastFailureCode:s.lastFailureCode};
77
+ if(state.pending===0&&state.inFlight===0)break;
78
+ }while(Date.now()<deadline);
79
+ return Object.freeze({...state,status:state.pending||state.inFlight
80
+ ?'TIMEOUT':state.dropped||state.failed?'LOG_GAP':'OK'});
81
+ };
82
+ }