@tomflow/chatloop-tools 0.9.63 → 0.9.64

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 (154) 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/package.json +2 -12
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -89
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
package/README.md CHANGED
@@ -57,6 +57,18 @@ Usage: chatloop-tools start [desktop-commander|tunnel]
57
57
  Start all enabled tools or one.
58
58
  ```
59
59
 
60
+ ## Task-first MCP/CLI adapter contract (source-only, NOT_RUN)
61
+
62
+ No additional Gateway, npm export or model-directed browser sender is introduced. The same `extension` MCP Provider has **optional** `taskFirst:true` in the existing `start`, `continue`, `handoff` and `session` schemas, and optional exact `projectId+taskId` in `status`. The provider/CLI validates shape and forwards the signed private Action request to the **same** Extension Worker; neither Provider nor Supervisor selects the latest Task, consumes Context Permits or sends to Chat.
63
+
64
+ - `start`: `taskFirst:true,mode:'adopt',confirmed:true` plus an existing original Chat URL, exact TaskKey and Context `start.reserve` lease/epoch/Task/approval revisions; never a first-message send or replacement of another Task.
65
+ - `continue` / `handoff`: `taskFirst:true` and one previously issued Turn Token. Query `intentId` or `lookup:true` is read-only, not a replay permission. QUEUED/PENDING/SEND_BEGIN/UNKNOWN are not proof of a successful Chat send.
66
+ - `status`: no arguments retains legacy V1 status; only both `projectId` and `taskId` select the new read-only Native/Context Task projection. No partial/fuzzy/latest Task selector.
67
+ - `session`: `operation:cancel` 保持原 `taskFirst:true` 或 V1 的精确取消字段与门禁,只允许没有附加 Permit 的空闲原 Chat Adopt;Context 在同事务核 Start-only Permit 历史。`operation:recover-handoff` 则必须为 `taskFirst:true`,带精确 `projectId/taskId/sessionId/generation/expectedNativeRevision/originalAttemptId` 和 `confirmed:true`;MCP Schema/Provider 均与 Cancel 分支隔离,已有 `session` CLI 固定版本继续调用原 Action,且必须在 `session.html` 由真实用户点击后才进入 Worker。恢复仅针对已证明 `NOT_SENT` 的原 Handoff,绝不创建 Chat 或发送。
68
+ - The authenticated Native and Context receivers independently verify the source, current Task/session/generation/Chat, Project ACL and CAS. Supplied `taskFirst` or a plausible URL is never owner authority. Supervisor now also requires the exact private 0600 `owner-registry.lock` kernel-cutover marker before trusting a V2 Native Owner as Context write authority; absent/old/unknown markers stay `NATIVE_OWNER_LOCK_CUTOVER_UNVERIFIED` instead of silently trusting an O_EXCL-only ledger. V1 read-only status keeps its legacy identity checks. Current source includes a strict same-home Session directory guard to avoid Supervisor and Native verifying different Ledgers.
69
+ - These source declarations impact `providers.generated.mjs`, package pin/lock data and distributed Chrome/Native code. **Generators, tests, builds, npm publish, installation and E2E were deliberately NOT_RUN**. The current installed Gateway cannot be claimed to expose this schema until publication and deployment prove it.
70
+ - The Gateway's optional Continue/Handoff Trace correlation now validates returned `projectId` and `taskId` against the same canonical TaskKey character set as the Extension/Context owner contract. A colon-containing task ID is not silently promoted as a trusted correlation label; absent or invalid optional labels do not authorize or cancel a browser Action. This is source-only and unverified at runtime.
71
+
60
72
  ## Capability composition
61
73
 
62
74
  `providers/<id>.mjs` owns each MCP Provider's tool names, schemas,
@@ -65,7 +77,7 @@ activation condition, scoped call adapter and optional CLI commands.
65
77
  The seven built-in Providers are:
66
78
 
67
79
  - `desktop`: allowlisted Desktop Commander tools and isolated fixtures
68
- - `extension`: nine scoped actions delegated to the official Extension CLI, currently resolved through npm `@latest` per invocation (a mutable dist-tag, not a pinned runtime/Chrome version); the received CLI contract must be verified independently. Timeout, missing/invalid CLI identity, and malformed action results return `EXTENSION_RESULT_UNKNOWN`, never a safe-to-retry send failure; the actual Chrome-loaded Owner/version still require separate verification
80
+ - `extension`: nine scoped actions delegated to the official Extension CLI. Legacy V1 actions retain their original resolution policy; **Task-first** `start/continue/handoff` with `taskFirst:true`, and exact-Task `status` are now routed to the fixed Extension version declared by Context (no `@latest` downgrade). Task-first `start` requires real approved original-Chat Adopt + Context lease, `continue/handoff` require original `turnToken`, and `status` requires an explicit `projectId/taskId`; `session cancel` uses a separate exact Native revision; `session recover-handoff` additionally requires an original Handoff attempt, a new signed request and a real Action-page click. Neither is implicit. This is an **unreleased source contract**, not proof the pinned npm package or Chrome extension already supports it. Timeout, missing CLI identity, malformed receipts or mismatched installed version remain `UNKNOWN/BLOCKED` and must never cause a second send. Native Ledger directory must match the canonical session directory outside isolated fixtures; source-only changes have not been tested, installed or published.
69
81
  - `runtime`: exact-request receipt lookup without replay
70
82
  - `context`: independent Context SDK read/write schemas and fixed CLI
71
83
  - `trace`: Project-scoped diagnosis and SOFT stage observations; an independent `api_system` lookup can correlate an individual Form/Document App using its opaque `traceRef` returned by Prepare/Show. App kind remains `UNVERIFIED` when no matching event is found. Diagnosis separates `writerHealth` (Supervisor Writer status) from `gatewayHealth` (including process-wide App observation loss); loss counters appear under `globalObservationWarnings` and are never assigned to a particular Project/Form/Document as an invented `gap`. Missing actual App parent API spans remain scoped gaps. A rendered but unsubmitted Form has no submit event to expect. Source event timestamps remain ISO UTC; operator reports must label their display timezone. These are soft API/UI observations, not authenticated clicks, user-message identity or business approvals.
package/index.mjs CHANGED
@@ -14,7 +14,7 @@ import {probeLocalWriteCapability,trustedSystemTempRoot} from './lib/local-write
14
14
  let auditPort=null;
15
15
  const auditBacklog=[];
16
16
  let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
17
- let auditLastLossCode=null,mcpAudit=null;
17
+ let auditLastLossCode=null,auditLastLossApi=null,auditLastLossPhase=null,mcpAudit=null;
18
18
  let formObservationLost=0,documentObservationLost=0;
19
19
  const OBSERVER_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
20
20
  const localError=code=>Object.assign(Error(code),{code});
@@ -34,8 +34,8 @@ async function drainAudit(){
34
34
  }catch(error){
35
35
  if(['ENOENT','ECONNREFUSED'].includes(error?.code)&&
36
36
  auditNoOwnerRetries++<MAX_NO_OWNER_RETRIES)break;
37
- auditBacklog.shift(); // unknown telemetry is dropped, not retried
38
- auditLost++;
37
+ const lost=auditBacklog.shift(); // unknown telemetry is dropped, never replayed
38
+ auditLastLossApi=lost?.api||'UNVERIFIED'; auditLastLossPhase=lost?.phase||'UNVERIFIED'; auditLost++;
39
39
  auditLastLossCode=/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')?error.code:
40
40
  'TRACE_AUDIT_SINK_FAILED';
41
41
  auditNoOwnerRetries=0;
@@ -54,7 +54,8 @@ async function drainAudit(){
54
54
  }
55
55
  const recordApi=event=>{
56
56
  if(auditBacklog.length>=MAX_AUDIT_BACKLOG){
57
- auditLost++;auditLastLossCode='TRACE_AUDIT_BACKLOG_OVERFLOW';return;
57
+ auditLost++;auditLastLossCode='TRACE_AUDIT_BACKLOG_OVERFLOW';
58
+ auditLastLossApi=event?.api||'UNVERIFIED';auditLastLossPhase=event?.phase||'UNVERIFIED';return;
58
59
  }
59
60
  auditBacklog.push(event);
60
61
  if(auditPort){
@@ -63,8 +64,7 @@ const recordApi=event=>{
63
64
  }
64
65
  };
65
66
  const apiAspect=createApiAspect('@tomflow/chatloop-tools',{sink:recordApi});
66
- // A short-lived CLI may finish producing its reply before its soft audit queue
67
- // is delivered. Drain only *after* that reply; never delay an API or replay it.
67
+ // Short-lived CLIs drain soft audit after replying; never delay or replay business calls.
68
68
  async function drainCliTelemetry(timeoutMs=300){
69
69
  const deadline=Date.now()+Math.max(0,Math.min(timeoutMs,750));
70
70
  // The MCP AOP's separate queue must also drain before EOF exits.
@@ -190,7 +190,7 @@ async function runtime(){
190
190
  writerStatus:result.traceHealth.status,
191
191
  formObservationLost,documentObservationLost,
192
192
  apiObservationLost:auditLost,
193
- ...(auditLost?{apiObservationLastErrorCode:auditLastLossCode}:{})};
193
+ ...(auditLost?{apiObservationLastErrorCode:auditLastLossCode,apiObservationLastApi:auditLastLossApi,apiObservationLastPhase:auditLastLossPhase}:{})};
194
194
  if((formObservationLost>0||documentObservationLost>0||auditLost>0)
195
195
  &&health.status==='OK')health.status='TRACE_DEGRADED';
196
196
  return {...result,traceHealth:health};
@@ -5,6 +5,7 @@ import {existsSync,lstatSync,readFileSync} from 'node:fs';
5
5
  import {homedir} from 'node:os';
6
6
  import {join,dirname} from 'node:path';
7
7
  import {loadTrustedRuntime} from '@tomflow/chatloop-context';
8
+ import {assertLegacyContextOwnerOnly,verifyScopedNativeOwner} from './native-owner-v2.mjs';
8
9
  // All internal dependencies are supplied as API contracts by index.mjs.
9
10
  // Private modules never import or resolve another private implementation.
10
11
  let verifyContextEnvelope;
@@ -21,10 +22,19 @@ export function configureContextControlRun(ports){
21
22
  const fail=code=>Object.assign(new Error(code),{code});
22
23
  const assert=(ok,code)=>{if(!ok)throw fail(code)};
23
24
  const supported=new Set(['permit.consume','run.bind.initial','run.fence',
24
- 'run.bind.handoff','run.restore-same-owner','run.fence.terminal',
25
- 'run.credential.rotate','run.fence.cancel','run.terminalStatus','run.reopenStatus','run.snapshot']);
26
- const sessionPath=()=>join(process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR||
27
- join(homedir(),'.chat-loop','session'),'active-session.json');
25
+ 'run.bind.handoff','run.restore-same-owner',
26
+ 'run.restore-fenced-handoff','run.fence.terminal',
27
+ 'run.credential.rotate','run.fence.cancel','run.terminalStatus',
28
+ 'run.reopenStatus','run.snapshot','permit.status',
29
+ 'run.idleStartPermitStatus']);
30
+ const sessionPath=()=>{
31
+ const canonical=join(homedir(),'.chat-loop','session');
32
+ const configured=process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR;
33
+ if(configured&&configured!==canonical
34
+ &&process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1')
35
+ throw fail('NATIVE_SESSION_DIRECTORY_MISMATCH');
36
+ return join(configured||canonical,'active-session.json');
37
+ };
28
38
  function readNativePointer(){
29
39
  const file=sessionPath();
30
40
  assert(existsSync(file),'NATIVE_SESSION_MISSING');
@@ -45,11 +55,19 @@ export async function handleContextControl(message){
45
55
  throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
46
56
  const payload=verifyContextEnvelope(message);
47
57
  const {command,args}=payload;
58
+ assert(Object.keys(payload).every(k=>['command','args','ownerProofV2'].includes(k)),
59
+ 'CONTEXT_CONTROL_ENVELOPE_INVALID');
48
60
  assert(supported.has(command)&&args&&typeof args==='object'&&!Array.isArray(args),
49
61
  'CONTEXT_COMMAND_INVALID');
50
62
  assert(!['principal','role','internalAuthorized'].some(k=>Object.hasOwn(args,k)),
51
63
  'CLIENT_AUTH_FIELD_FORBIDDEN');
52
- const native=readNativePointer();
64
+ // Signed v2 requests must name the exact owner revision; never derive
65
+ // Task identity from the most-recent global V1 pointer.
66
+ // No Chrome V2 caller is enabled until Native/Worker routing is verified.
67
+ const scoped=Object.hasOwn(payload,'ownerProofV2');
68
+ if(!scoped)assertLegacyContextOwnerOnly();
69
+ const native=scoped?verifyScopedNativeOwner(payload.ownerProofV2)
70
+ :readNativePointer();
53
71
  const runtime=await loadTrustedRuntime();
54
72
  return runtime.execute(command,args,native);
55
73
  }
@@ -36,6 +36,7 @@ const NPX_COMMAND=process.platform==='win32'?'npx.cmd':'npx';
36
36
  const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
37
37
  const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
38
38
  const CHAT_ID=/^[0-9a-f-]{12,}$/i;
39
+ const TASK_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
39
40
  // Match the existing Context child-CLI correlation boundary. Never inherit
40
41
  // an unverified stale parent from the supervisor process environment.
41
42
  function childApiEnvironment(){
@@ -56,10 +57,16 @@ function childApiEnvironment(){
56
57
  }catch{delete env.CHAT_LOOP_API_PARENT}
57
58
  return env;
58
59
  }
59
- export const extensionInvocation=name=>{
60
+ export const extensionInvocation=(name,args={})=>{
60
61
  const command=extensionCommand(name);
61
62
  if(!command)return null;
62
- const packageSpec=name==='session'
63
+ const versionPinned=name==='session'
64
+ ||name==='status'&&args.projectId
65
+ ||['start','continue','handoff'].includes(name)
66
+ &&args.taskFirst===true;
67
+ // Task-first is a versioned cross-package contract, never a mutable
68
+ // @latest CLI that could silently downgrade to the global V1 sender.
69
+ const packageSpec=versionPinned
63
70
  ?'@tomflow/chatloop-extension@'+sessionExtensionPin:EXTENSION_PACKAGE;
64
71
  return {executable:NPX_COMMAND,
65
72
  args:['--yes','--package='+packageSpec,'chatloop-extension',...command]};
@@ -97,15 +104,17 @@ export async function forwardExtensionAction(name,args={}) {
97
104
  ||proof.writeReadVerified!==true||proof.cleaned!==true)
98
105
  return fail('START_LOCAL_PREFLIGHT_BLOCKED');
99
106
  }
100
- const invocation=extensionInvocation(name);
107
+ const invocation=extensionInvocation(name,args);
101
108
  if(!invocation)return fail('EXTENSION_PROVIDER_UNTRUSTED');
102
109
  const control=isControlTool(name);
110
+ const scopedStatus=name==='status'
111
+ &&typeof args.projectId==='string'&&typeof args.taskId==='string';
103
112
  if(name==='clean')invocation.args.push(String(args.tabId));
104
113
  const fixedTemp=name==='start'?trustedTempRoot():null;
105
114
  const env=childApiEnvironment();
106
115
  if(fixedTemp)for(const key of ['TMPDIR','TMP','TEMP'])env[key]=fixedTemp;
107
116
  const response=await new Promise(resolve=>{
108
- const child=spawn(invocation.executable,invocation.args,{stdio:[control?'pipe':'ignore','pipe','pipe'],
117
+ const child=spawn(invocation.executable,invocation.args,{stdio:[control||scopedStatus?'pipe':'ignore','pipe','pipe'],
109
118
  cwd:fixedTemp||tmpdir(),windowsHide:true,env});
110
119
  let stdout='',stdoutBytes=0,finished=false,closed=false,tailTimer=null;
111
120
  const settle=(value,receiptCompleted=false)=>{
@@ -148,7 +157,7 @@ export async function forwardExtensionAction(name,args={}) {
148
157
  // Decode UTF-8 incrementally, and accept the completed RESULT frame
149
158
  // without holding the MCP tool response for the CLI's audit tail.
150
159
  child.stdout.setEncoding('utf8');
151
- if(control){
160
+ if(control||scopedStatus){
152
161
  child.stdin.on('error',()=>{});
153
162
  child.stdin.end(JSON.stringify(args));
154
163
  }
@@ -228,11 +237,11 @@ export function formatExtensionResult(name,response) {
228
237
  // Only verified, bounded identifiers can cross into the optional Trace
229
238
  // correlation contract. Missing identifiers are unverified.
230
239
  const correlated=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(proof.sessionId||'')
231
- &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(proof.projectId||'')
240
+ &&TASK_ID.test(proof.projectId||'')
232
241
  &&Number.isSafeInteger(proof.generation)&&proof.generation>=0;
233
242
  const traceRef=correlated?{sessionId:proof.sessionId,
234
243
  projectId:proof.projectId,generation:proof.generation,
235
- ...(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(proof.taskId||'')
244
+ ...(TASK_ID.test(proof.taskId||'')
236
245
  ?{taskId:proof.taskId}:{})}:{};
237
246
  if(proof.status==='STATUS'){
238
247
  if(typeof proof.phase!=='string')return fail('INVALID_MODEL_INTENT_REPLY');
@@ -0,0 +1,128 @@
1
+ // Supervisor-only, read-only projection check. Not an Owner authority.
2
+ import {lstatSync,readFileSync} from 'node:fs';
3
+ import {homedir} from 'node:os';
4
+ import {join,dirname} from 'node:path';
5
+
6
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
8
+ const CHAT=/^[0-9a-f-]{12,}$/i;
9
+ const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
10
+ const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY',
11
+ 'DONE','BLOCKED','CANCELLED']);
12
+ const fail=code=>Object.assign(Error(code),{code});
13
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
14
+ const paths=()=>{
15
+ const canonical=join(homedir(),'.chat-loop','session');
16
+ const configured=process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR;
17
+ // The Chrome Native Host resolves Owner from the account HOME; an
18
+ // independently configured Supervisor directory must not authenticate
19
+ // a different Ledger as the same browser. Test fixtures are isolated.
20
+ if(configured&&configured!==canonical
21
+ &&process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1')
22
+ throw fail('NATIVE_SESSION_DIRECTORY_MISMATCH');
23
+ const dir=configured||canonical;
24
+ return {dir,file:join(dir,'owner-ledger-v2.json'),
25
+ legacy:join(dir,'active-session.json'),
26
+ lock:join(dir,'owner-registry.lock')};
27
+ };
28
+ function entry(path){
29
+ try{return lstatSync(path)}catch(e){
30
+ if(e.code==='ENOENT')return null;
31
+ throw fail('NATIVE_OWNER_STORAGE_UNVERIFIED');
32
+ }
33
+ }
34
+ function privateDir(dir){
35
+ const st=entry(dir);
36
+ if(st)assert(st.isDirectory()&&!st.isSymbolicLink()&&
37
+ (!process.getuid||st.uid===process.getuid())&&
38
+ (process.platform==='win32'||(st.mode&0o077)===0),
39
+ 'NATIVE_OWNER_STORAGE_UNTRUSTED');
40
+ return Boolean(st);
41
+ }
42
+ function privateData(file){
43
+ if(!privateDir(dirname(file)))return null;
44
+ const st=entry(file);
45
+ if(!st)return null;
46
+ assert(st.isFile()&&!st.isSymbolicLink()&&st.size<=128*1024&&
47
+ (!process.getuid||st.uid===process.getuid())&&
48
+ (process.platform==='win32'||(st.mode&0o077)===0),
49
+ 'NATIVE_OWNER_STORAGE_UNTRUSTED');
50
+ try{return JSON.parse(readFileSync(file,'utf8'))}
51
+ catch{throw fail('NATIVE_OWNER_STORAGE_CORRUPT')}
52
+ }
53
+ function ledger(){
54
+ const data=privateData(paths().file);
55
+ if(!data)return null;
56
+ assert(data.schemaVersion===2&&Number.isSafeInteger(data.ledgerRevision)
57
+ &&data.ledgerRevision>=0&&data.sessions&&
58
+ typeof data.sessions==='object'&&!Array.isArray(data.sessions)&&
59
+ Object.keys(data.sessions).length<=64,'NATIVE_OWNER_LEDGER_INVALID');
60
+ const active=new Set(),sessionIds=new Set();
61
+ for(const [key,s] of Object.entries(data.sessions)){
62
+ assert(s&&typeof s==='object'&&ID.test(s.projectId||'')
63
+ &&ID.test(s.taskId||'')&&UUID.test(s.sessionId||'')
64
+ &&key===JSON.stringify([s.projectId,s.taskId])
65
+ &&Number.isSafeInteger(s.revision)&&s.revision>=1
66
+ &&Number.isSafeInteger(s.generation)&&s.generation>=0
67
+ &&Number.isSafeInteger(s.updatedAt)&&s.updatedAt>0
68
+ &&PHASE.has(s.phase)
69
+ &&(s.activeChatId===null&&s.activeChatUrl===null
70
+ ||typeof s.activeChatId==='string'&&CHAT.test(s.activeChatId)
71
+ &&typeof s.activeChatUrl==='string'&&CHAT_URL.test(s.activeChatUrl)
72
+ &&s.activeChatUrl.endsWith('/'+s.activeChatId))
73
+ &&(s.phase!=='WAITING_REPLY'||s.activeChatId!==null)
74
+ ,'NATIVE_OWNER_LEDGER_INVALID');
75
+ const sessionKey=s.sessionId.toLowerCase();
76
+ assert(!sessionIds.has(sessionKey),'NATIVE_OWNER_DUPLICATE_SESSION');
77
+ sessionIds.add(sessionKey);
78
+ if(s.phase!=='DONE'&&s.phase!=='CANCELLED'&&s.activeChatId){
79
+ const claim=s.activeChatId.toLowerCase();
80
+ assert(!active.has(claim),'NATIVE_OWNER_DUPLICATE_CHAT');
81
+ active.add(claim);
82
+ }
83
+ }
84
+ return data;
85
+ }
86
+ function assertKernelLockCutover(){
87
+ // The new Native V1/V2 writers only operate under this persistent
88
+ // marker plus Darwin lockf. An older O_EXCL-only Native ledger must not
89
+ // be promoted into a new scoped Context write authority by Supervisor.
90
+ const file=paths().lock,st=entry(file);
91
+ assert(st?.isFile()&&!st.isSymbolicLink()
92
+ &&st.size===Buffer.byteLength('CHAT_LOOP_OWNER_KERNEL_LOCK_V1\n')
93
+ &&(st.mode&0o077)===0
94
+ &&(!process.getuid||st.uid===process.getuid()),
95
+ 'NATIVE_OWNER_LOCK_CUTOVER_UNVERIFIED');
96
+ assert(readFileSync(file,'utf8')==='CHAT_LOOP_OWNER_KERNEL_LOCK_V1\n',
97
+ 'NATIVE_OWNER_LOCK_CUTOVER_UNVERIFIED');
98
+ }
99
+ function legacyInactive(){
100
+ const old=privateData(paths().legacy);
101
+ assert(!old||old.phase==='DONE'||old.phase==='CANCELLED',
102
+ 'NATIVE_LEGACY_OWNER_ACTIVE');
103
+ }
104
+ export function assertLegacyContextOwnerOnly(){
105
+ const data=ledger();
106
+ assert(!data||Object.values(data.sessions)
107
+ .every(s=>s.phase==='DONE'||s.phase==='CANCELLED'),
108
+ 'NATIVE_SCOPED_OWNER_ACTIVE');
109
+ }
110
+ export function verifyScopedNativeOwner(proof){
111
+ assert(proof&&typeof proof==='object'&&!Array.isArray(proof)&&
112
+ Object.keys(proof).length===7&&
113
+ ID.test(proof.projectId||'')&&ID.test(proof.taskId||'')
114
+ &&UUID.test(proof.sessionId||'')
115
+ &&Number.isSafeInteger(proof.generation)&&proof.generation>=0
116
+ &&Number.isSafeInteger(proof.revision)&&proof.revision>=1
117
+ &&PHASE.has(proof.phase)
118
+ &&(proof.activeChatId===null||
119
+ typeof proof.activeChatId==='string'&&CHAT.test(proof.activeChatId)),
120
+ 'NATIVE_SCOPED_PROOF_INVALID');
121
+ assertKernelLockCutover();
122
+ legacyInactive();
123
+ const current=ledger()?.sessions[JSON.stringify([proof.projectId,proof.taskId])];
124
+ assert(current&&['projectId','taskId','sessionId','generation',
125
+ 'revision','phase','activeChatId'].every(k=>current[k]===proof[k]),
126
+ 'NATIVE_SCOPED_PROOF_STALE');
127
+ return current;
128
+ }
@@ -25,8 +25,26 @@ export async function verifyTunnelConnection(p,verified,ports={}){
25
25
  ||!existsSync(healthFile))
26
26
  throw Object.assign(Error('NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'),{
27
27
  code:'NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'});
28
+ // A freshly started Tunnel can establish remote control-plane polling
29
+ // after the local readyz comes up. Keep the exact PID and all three hard
30
+ // checks; allow bounded warmup rather than treating the first 30 failures
31
+ // as terminal. The explicit wait port is used only by isolated fixtures.
32
+ const maxAttempts=60;
33
+ const wait=ports.wait??(ms=>new Promise(resolve=>setTimeout(resolve,ms)));
34
+ const safeStatus=value=>{
35
+ let status=value;
36
+ if(typeof value==='string'){
37
+ try{status=JSON.parse(value.trim())}catch{return null}
38
+ }
39
+ if(!status||typeof status!=='object'||Array.isArray(status))return null;
40
+ // Never return raw health JSON; it can contain URLs or credentials.
41
+ return {result:status.result==='ok'?'ok':'not_ready',
42
+ healthz:status.healthz?.ok===true,
43
+ readyz:status.readyz?.ok===true,
44
+ controlPlanePoll:status.control_plane_poll?.ok===true};
45
+ };
28
46
  let last;
29
- for(let attempt=0;attempt<30;attempt++){
47
+ for(let attempt=0;attempt<maxAttempts;attempt++){
30
48
  try{
31
49
  const output=await run(binary,['health','--url-file',healthFile,
32
50
  '--pid',String(tunnel.pid),'--require-control-plane-poll','--json'],
@@ -35,12 +53,18 @@ export async function verifyTunnelConnection(p,verified,ports={}){
35
53
  if(result.result==='ok'&&result.healthz?.ok===true
36
54
  &&result.readyz?.ok===true&&result.control_plane_poll?.ok===true)
37
55
  return {result:'ok',pid:tunnel.pid,controlPlanePoll:true};
38
- last=result;
39
- }catch(error){last={code:error.code||'TUNNEL_HEALTH_FAILED'};}
40
- await new Promise(resolve=>setTimeout(resolve,500));
56
+ last=safeStatus(result)||{code:'TUNNEL_PROBE_UNVERIFIED'};
57
+ }catch(error){
58
+ last={code:/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')
59
+ ?error.code:'TUNNEL_HEALTH_FAILED',
60
+ ...(Number.isSafeInteger(error?.status)?{exitCode:error.status}:{}),
61
+ ...(safeStatus(error?.stdout)||{})};
62
+ }
63
+ if(attempt+1<maxAttempts)await wait(500);
41
64
  }
42
65
  throw Object.assign(Error('NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY'),{
43
- code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',tunnelStatus:last});
66
+ code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',
67
+ attempts:maxAttempts,tunnelStatus:last});
44
68
  }
45
69
  export async function verifyMcpTools(p,ports={}){
46
70
  const {runtimeLaunchEnv}=ports;
@@ -234,7 +234,9 @@ export async function runTraceDiagnose(args){
234
234
  if(health?.apiObservationLost>0){
235
235
  globalWarnings.push('MCP_API_TRACE_OBSERVATION_LOSS');
236
236
  result.globalApiObservationLoss={count:health.apiObservationLost,
237
- lastErrorCode:health.apiObservationLastErrorCode||'UNVERIFIED'};
237
+ lastErrorCode:health.apiObservationLastErrorCode||'UNVERIFIED',
238
+ lastApi:health.apiObservationLastApi||'UNVERIFIED',
239
+ lastPhase:health.apiObservationLastPhase||'UNVERIFIED'};
238
240
  }
239
241
  if(globalWarnings.length)result.globalObservationWarnings=globalWarnings;
240
242
  if(result.writerHealth==='TRACE_DEGRADED'){
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.63",
6
+ "version": "0.9.64",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -22,29 +22,19 @@
22
22
  ],
23
23
  "scripts": {
24
24
  "doctor": "node ./bin/cli.mjs doctor",
25
- "test": "node --test ./test/*.test.mjs",
26
25
  "build:providers": "node ./scripts/build-providers.mjs",
27
26
  "build:providers:check": "node ./scripts/build-providers.mjs --check",
28
27
  "build:form": "node ./scripts/build-form-app.mjs",
29
28
  "build:form:check": "node ./scripts/build-form-app.mjs --check",
30
29
  "build:document": "node ./scripts/build-document-app.mjs",
31
30
  "build:document:check": "node ./scripts/build-document-app.mjs --check",
32
- "pretest": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check",
33
31
  "prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check"
34
32
  },
35
33
  "dependencies": {
36
34
  "@tomflow/chatloop-context": "0.6.26",
37
35
  "@tomflow/chatloop-trace": "0.4.6",
38
- "@wonderwhy-er/desktop-commander": "0.2.44",
39
- "ps-list": "9.0.0",
40
- "@tomflow/chatloop-extension": "0.4.34"
36
+ "@wonderwhy-er/desktop-commander": "0.2.44"
41
37
  },
42
- "bundleDependencies": [
43
- "@tomflow/chatloop-context",
44
- "@tomflow/chatloop-trace",
45
- "ps-list",
46
- "@tomflow/chatloop-extension"
47
- ],
48
38
  "engines": {
49
39
  "node": ">=24"
50
40
  },
@@ -18,27 +18,33 @@ const endpoints=[
18
18
  [['extension','clean'],extensionTool('clean','Clear composer text in one exact verified ChatGPT tab; never sends.',false,
19
19
  {tabId:{type:'integer',minimum:1}},['tabId'])],
20
20
  [['extension','reload'],extensionTool('reload','Request reload of Chat Loop Extension; final health is unverified.',false)],
21
- [['extension','status'],extensionTool('status','Read the unique current Mac Chrome Web Chat Owner; never starts or sends.',true)],
21
+ [['extension','status'],extensionTool('status',
22
+ 'Read legacy Owner with no selector, or one exact authorized Task Owner with projectId+taskId; never starts or sends.',true,
23
+ {projectId:{type:'string',pattern:PROJECT_ID.source},
24
+ taskId:{type:'string',pattern:PROJECT_ID.source}})],
22
25
  [['extension','session'],extensionTool('session',
23
- 'Exact Context-managed idle Adopt cancellation. User authorization required; no delivery or Chat send. Refuses live work, unknown effects and identity drift.',false,
24
- {operation:{type:'string',enum:['cancel']},
26
+ 'Exact idle Adopt cancellation, or separately confirmed recovery of a fenced unsent Handoff in the original Task/Chat. Recovery requires a real click in the signed session Action; neither operation sends a Chat message.',false,
27
+ {operation:{type:'string',enum:['cancel','recover-handoff']},
25
28
  projectId:{type:'string',pattern:PROJECT_ID.source},
26
29
  taskId:{type:'string',pattern:PROJECT_ID.source},
27
30
  sessionId:{type:'string',pattern:REPLACE_SESSION.source},
28
31
  generation:{type:'integer',minimum:0},
29
32
  expectedNativeUpdatedAt:{type:'integer',minimum:1},
33
+ expectedNativeRevision:{type:'integer',minimum:1},
34
+ originalAttemptId:{type:'string',pattern:INTENT_ID.source},
35
+ taskFirst:{type:'boolean',const:true},
30
36
  expectedTaskRevision:{type:'integer',minimum:1},
31
37
  expectedBindingRevision:{type:'integer',minimum:1},
32
38
  contextStoreEpoch:{type:'string',minLength:10,maxLength:128},
33
39
  confirmed:{const:true}},
34
- ['operation','projectId','taskId','sessionId','generation',
35
- 'expectedNativeUpdatedAt','expectedTaskRevision','expectedBindingRevision',
36
- 'contextStoreEpoch','confirmed'])],
40
+ ['operation','projectId','taskId','sessionId','generation','confirmed'])],
37
41
  [['extension','start'],extensionTool('start',
38
42
  'Controlled execution ONLY: in Stage 03, mode=adopt requires a fresh Context start.reserve lease (taskId, contextLeaseRef, store epoch and revisions); Native validates the real R/P-approved original Chat without resending. The prompt-based branch creates a machine-owned execution session and requires the model status protocol; it is NOT a native @ Chat Loop user entry or Stage 01/02 testing mechanism. For TEST_ONLY native @ App entry, use the separate Extension entry test action, not Start.',false,
39
43
  {projectId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
40
44
  taskId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
41
45
  purpose:{type:'string',enum:['REPAIR_SAME_SCOPE']},
46
+ taskFirst:{type:'boolean',const:true,
47
+ description:'Task-first isolated original-Chat Adopt; no new message.'},
42
48
  contextLeaseRef:{type:'string',minLength:8,maxLength:128},
43
49
  contextStoreEpoch:{type:'string',minLength:10,maxLength:128},
44
50
  contextTaskRevision:{type:'integer',minimum:1},
@@ -49,10 +55,14 @@ const endpoints=[
49
55
  replaceBlockedSessionId:{type:'string',pattern:REPLACE_SESSION.source}},
50
56
  ['projectId','confirmed'])],
51
57
  [['extension','continue'],extensionTool('continue','Submit next-turn text with turnToken and nextPrompt; alternatively query its final status with turnToken and intentId. Only the Extension can send after Turn completion.',false,
52
- {turnToken:{type:'string',pattern:TURN_TOKEN.source},nextPrompt:{type:'string',minLength:1,maxLength:4000,pattern:'\\S'},
58
+ {turnToken:{type:'string',pattern:TURN_TOKEN.source},
59
+ taskFirst:{type:'boolean',const:true},
60
+ nextPrompt:{type:'string',minLength:1,maxLength:4000,pattern:'\\S'},
53
61
  intentId:{type:'string',pattern:INTENT_ID.source},lookup:{type:'boolean'}},['turnToken'])],
54
62
  [['extension','handoff'],extensionTool('handoff','Submit an early Handoff with turnToken and optional reason; alternatively query receipt with turnToken and intentId. Extension still owns the timing and send.',false,
55
- {turnToken:{type:'string',pattern:TURN_TOKEN.source},reason:{type:'string',maxLength:400},
63
+ {turnToken:{type:'string',pattern:TURN_TOKEN.source},
64
+ taskFirst:{type:'boolean',const:true},
65
+ reason:{type:'string',maxLength:400},
56
66
  intentId:{type:'string',pattern:INTENT_ID.source},lookup:{type:'boolean'}},['turnToken'])],
57
67
  ];
58
68
  export const extensionTools=endpoints.map(([,tool])=>tool);
@@ -70,11 +80,33 @@ export function validExtensionArgs(name,args){
70
80
  if(name==='clean'){
71
81
  if(Object.keys(args).length!==1||!Number.isSafeInteger(args.tabId)||args.tabId<1)
72
82
  return false;
83
+ }else if(name==='status'){
84
+ if(Object.keys(args).length!==0
85
+ &&!(Object.keys(args).length===2
86
+ &&PROJECT_ID.test(args.projectId||'')
87
+ &&PROJECT_ID.test(args.taskId||'')))return false;
73
88
  }else if(!control && Object.keys(args).length)return false;
74
89
  if(name==='session'){
90
+ if(args.operation==='recover-handoff'){
91
+ const keys=['operation','projectId','taskId','sessionId',
92
+ 'generation','expectedNativeRevision','originalAttemptId',
93
+ 'confirmed','taskFirst'];
94
+ return Object.keys(args).length===keys.length
95
+ &&keys.every(k=>Object.hasOwn(args,k))
96
+ &&PROJECT_ID.test(args.projectId||'')
97
+ &&PROJECT_ID.test(args.taskId||'')
98
+ &&REPLACE_SESSION.test(args.sessionId||'')
99
+ &&Number.isSafeInteger(args.generation)&&args.generation>=0
100
+ &&Number.isSafeInteger(args.expectedNativeRevision)
101
+ &&args.expectedNativeRevision>=2
102
+ &&INTENT_ID.test(args.originalAttemptId||'')
103
+ &&args.confirmed===true&&args.taskFirst===true;
104
+ }
105
+ const scoped=args.taskFirst===true;
75
106
  const k=['operation','projectId','taskId','sessionId','generation',
76
- 'expectedNativeUpdatedAt','expectedTaskRevision',
77
- 'expectedBindingRevision','contextStoreEpoch','confirmed'];
107
+ scoped?'expectedNativeRevision':'expectedNativeUpdatedAt',
108
+ 'expectedTaskRevision','expectedBindingRevision',
109
+ 'contextStoreEpoch','confirmed',...(scoped?['taskFirst']:[])];
78
110
  if(Object.keys(args).length!==k.length
79
111
  ||k.some(key=>!Object.hasOwn(args,key))
80
112
  ||args.operation!=='cancel'||args.confirmed!==true
@@ -82,8 +114,11 @@ export function validExtensionArgs(name,args){
82
114
  ||!PROJECT_ID.test(args.taskId||'')
83
115
  ||!REPLACE_SESSION.test(args.sessionId||'')
84
116
  ||!Number.isSafeInteger(args.generation)||args.generation<0
85
- ||!Number.isSafeInteger(args.expectedNativeUpdatedAt)
86
- ||args.expectedNativeUpdatedAt<=0
117
+ ||(scoped
118
+ ?!Number.isSafeInteger(args.expectedNativeRevision)
119
+ ||args.expectedNativeRevision<1
120
+ :!Number.isSafeInteger(args.expectedNativeUpdatedAt)
121
+ ||args.expectedNativeUpdatedAt<=0)
87
122
  ||!Number.isSafeInteger(args.expectedTaskRevision)
88
123
  ||args.expectedTaskRevision<1
89
124
  ||!Number.isSafeInteger(args.expectedBindingRevision)
@@ -105,6 +140,10 @@ export function validExtensionArgs(name,args){
105
140
  ||!Number.isSafeInteger(args.contextTaskRevision)||args.contextTaskRevision<1
106
141
  ||!Number.isSafeInteger(args.contextApprovalRevision)||args.contextApprovalRevision<1))
107
142
  ||args.confirmed!==true
143
+ ||(args.taskFirst!==undefined
144
+ &&(args.taskFirst!==true||args.mode!=='adopt'
145
+ ||!args.taskId||!args.chatUrl||!args.contextLeaseRef
146
+ ||args.purpose!==undefined||args.replaceBlockedSessionId!==undefined))
108
147
  // A managed original-Chat Adopt must carry a Context start.reserve lease.
109
148
  // The exact lease/approval is checked by Native permit.consume, not here.
110
149
  ||(args.mode==='adopt'&&!Object.hasOwn(args,'contextLeaseRef'))
@@ -119,25 +158,29 @@ export function validExtensionArgs(name,args){
119
158
  return false;
120
159
  }
121
160
  if(control&&!['start','session'].includes(name)){
122
- if(typeof args.turnToken!=='string'||!TURN_TOKEN.test(args.turnToken))
161
+ if(typeof args.turnToken!=='string'||!TURN_TOKEN.test(args.turnToken)
162
+ ||args.taskFirst!==undefined&&args.taskFirst!==true)
123
163
  return false;
164
+ const v2=args.taskFirst===true;
124
165
  const hasId=Object.hasOwn(args,'intentId');
125
166
  const hasLookup=Object.hasOwn(args,'lookup');
126
167
  // Receipt query and newest-receipt lookup are mutually exclusive.
127
168
  if(hasId||hasLookup){
128
- if(hasId===hasLookup||Object.keys(args).length!==2)return false;
169
+ if(hasId===hasLookup||Object.keys(args).length!==(v2?3:2))return false;
129
170
  return hasId
130
171
  ? typeof args.intentId==='string'&&INTENT_ID.test(args.intentId)
131
172
  : args.lookup===true;
132
173
  }
133
174
  if(name==='continue'){
134
- return Object.keys(args).length===2
175
+ return Object.keys(args).length===(v2?3:2)
135
176
  && typeof args.nextPrompt==='string' && !!args.nextPrompt.trim()
136
177
  && args.nextPrompt.length<=4000
137
178
  && !/[\x00-\x1f]/.test(args.nextPrompt.replaceAll('\n',''));
138
179
  }
139
180
  // Handoff only needs the bound token; its short reason is optional.
140
- return (Object.keys(args).length===1||Object.hasOwn(args,'reason'))
181
+ return (Object.keys(args).length===(v2?2:1)
182
+ ||Object.hasOwn(args,'reason')
183
+ &&Object.keys(args).length===(v2?3:2))
141
184
  && (args.reason===undefined || (typeof args.reason==='string'
142
185
  && args.reason.length<=400 && !/[\x00-\x1f]/.test(args.reason)));
143
186
  }