@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,142 @@
1
+ // This module declares ports; index.mjs is the only dependency assembler.
2
+ // No implementation module imports another implementation module.
3
+ let openContextProtocol, allowedProjects, resolveVerifiedProjectDatabase;
4
+ let connected=false;
5
+ export function configureTrustedRun(capabilities){
6
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
7
+ for(const name of ['openContextProtocol', 'allowedProjects', 'resolveVerifiedProjectDatabase']){
8
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
9
+ }
10
+ ({openContextProtocol, allowedProjects, resolveVerifiedProjectDatabase}=capabilities);
11
+ connected=true;
12
+ }
13
+
14
+ // Trusted Native run domain facade: one validated operation, no raw SQLite
15
+ // handle, path resolver, credential generator or arbitrary Core method export.
16
+ // The caller must first verify the signed Supervisor IPC and Native projection.
17
+ // This package still enforces the Project grant, domain command list, and CAS.
18
+ const fail=code=>Object.assign(new Error(code),{code});
19
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
20
+ const supported=new Set(['permit.consume','run.bind.initial','run.fence',
21
+ 'run.bind.handoff','run.restore-same-owner',
22
+ 'run.restore-fenced-handoff','run.fence.terminal',
23
+ 'run.credential.rotate','run.fence.cancel','run.terminalStatus',
24
+ 'run.reopenStatus','run.snapshot','permit.status',
25
+ 'run.idleStartPermitStatus']);
26
+
27
+ export function executeTrustedRun(command,args,native){
28
+ assert(supported.has(command)&&args&&typeof args==='object'
29
+ &&!Array.isArray(args)&&native&&typeof native==='object',
30
+ 'CONTEXT_COMMAND_INVALID');
31
+ assert(!['principal','role','internalAuthorized','ownerCommitted',
32
+ 'nativeCommitted'].some(k=>Object.hasOwn(args,k)),
33
+ 'CLIENT_AUTH_FIELD_FORBIDDEN');
34
+ const startRecovery=command==='run.terminalStatus'&&Object.hasOwn(args,'startRecoveryLeaseRef');
35
+ const handoffProbe=Object.hasOwn(args,'expectedHandoffAttemptId');
36
+ if(handoffProbe)assert(command==='run.terminalStatus'
37
+ &&!startRecovery&&(native.phase==='PENDING'
38
+ ||native.phase==='BLOCKED'&&native.activeChatId!==null
39
+ &&Number.isSafeInteger(native.revision)&&native.revision>=2)
40
+ &&typeof args.expectedHandoffAttemptId==='string'
41
+ &&/^[a-f0-9]{32}$/.test(args.expectedHandoffAttemptId),
42
+ 'HANDOFF_STATUS_PROBE_DENIED');
43
+ if(startRecovery)assert(native.phase==='BLOCKED'&&native.generation===0
44
+ &&native.activeChatId===null&&native.activeChatUrl===null
45
+ &&typeof args.startRecoveryLeaseRef==='string'
46
+ &&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(args.startRecoveryLeaseRef),
47
+ 'START_RECOVERY_NATIVE_UNVERIFIED');
48
+ // A signed V2 Task Status can read an exact pre-Adopt Owner whose Chat
49
+ // has not been claimed yet. V1 has no Native revision; this exception
50
+ // is read-only, generation zero and cannot authorize a START permit.
51
+ const preAdoptStatus=command==='run.terminalStatus'
52
+ &&Number.isSafeInteger(native.revision)&&native.revision>=1
53
+ &&native.generation===0
54
+ &&['STARTING','RESERVED','PENDING'].includes(native.phase)
55
+ &&native.activeChatId===null&&native.activeChatUrl===null;
56
+ assert(native.projectId===args.projectId && native.taskId===args.taskId
57
+ && native.sessionId===args.sessionId
58
+ && native.generation===args.generation
59
+ && native.activeChatId===args.activeChatId
60
+ && (native.activeChatId!==null || command==='permit.consume'&&args.kind==='START'
61
+ ||startRecovery||preAdoptStatus),
62
+ 'CONTEXT_NATIVE_BINDING_MISMATCH');
63
+ const allowed=allowedProjects();
64
+ assert(allowed.has(native.projectId),'PROJECT_ACCESS_DENIED');
65
+ if(command==='run.fence'){
66
+ assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
67
+ assert(args.targetGeneration===native.generation+1,'TARGET_GENERATION_MISMATCH');
68
+ }
69
+ if(['run.fence','run.fence.terminal','run.bind.initial','run.bind.handoff',
70
+ 'run.credential.rotate','run.fence.cancel'].includes(command))
71
+ assert(args.runRef===native.sessionId+':'+native.taskId+':'+native.generation,
72
+ 'RUN_REF_MISMATCH');
73
+ if(command==='permit.consume')
74
+ assert(args.kind==='RECOVER_HANDOFF'
75
+ ?native.phase==='BLOCKED'&&native.activeChatId!==null
76
+ &&Number.isSafeInteger(native.revision)&&native.revision>=2
77
+ :['RESERVED','PENDING'].includes(native.phase)
78
+ ||['CONTINUE','HANDOFF'].includes(args.kind)
79
+ &&native.phase==='WAITING_REPLY'
80
+ &&Number.isSafeInteger(native.revision)&&native.revision>=1,
81
+ 'NATIVE_PHASE_MISMATCH');
82
+ if(['run.bind.initial','run.bind.handoff'].includes(command))
83
+ assert(native.phase==='WAITING_REPLY','NATIVE_PHASE_MISMATCH');
84
+ if(command==='run.credential.rotate')
85
+ assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
86
+ if(command==='run.fence.cancel')
87
+ assert(native.phase==='BLOCKED'&&args.reason==='USER_CANCELLED',
88
+ 'CANCEL_NATIVE_NOT_BLOCKED');
89
+ if(command==='run.restore-same-owner')
90
+ assert(native.phase==='RESERVED','NATIVE_PHASE_MISMATCH');
91
+ if(command==='run.restore-fenced-handoff')
92
+ assert(native.phase==='BLOCKED'&&native.activeChatId!==null
93
+ &&Number.isSafeInteger(native.revision)&&native.revision>=2,
94
+ 'NATIVE_RECOVERY_NOT_FENCED');
95
+ if(command==='run.fence.terminal')
96
+ assert(native.phase==='DONE'
97
+ ||native.phase==='WAITING_REPLY'
98
+ &&Number.isSafeInteger(native.revision)&&native.revision>=1,
99
+ 'NATIVE_PHASE_MISMATCH');
100
+ if(command==='run.reopenStatus')
101
+ assert(native.phase==='DONE','NATIVE_PHASE_MISMATCH');
102
+
103
+ const file=resolveVerifiedProjectDatabase(args.projectId);
104
+ const db=openContextProtocol(file,{principalId:'native-controlled',
105
+ authorizeData:(_access,p)=>allowed.has(p),authorizeInternal:()=>true});
106
+ try{
107
+ if((startRecovery||!['run.terminalStatus','run.reopenStatus','run.snapshot',
108
+ 'permit.status','run.idleStartPermitStatus'].includes(command))
109
+ &&!db.projectBusinessAuthority(args.projectId).writable)
110
+ throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
111
+ switch(command){
112
+ case 'run.terminalStatus':return db.terminalStatus(args.projectId,args.taskId,
113
+ startRecovery?args.startRecoveryLeaseRef:null,
114
+ handoffProbe?args.expectedHandoffAttemptId:null);
115
+ case 'run.reopenStatus':return db.reopenStatus(args.projectId,args.taskId);
116
+ case 'run.snapshot':return db.latestCheckpoint(args.projectId,args.taskId);
117
+ case 'permit.status':return db.permitStatus(
118
+ args.projectId,args.taskId,args.actionToken);
119
+ case 'run.idleStartPermitStatus':return db.idleStartPermitStatus(
120
+ args.projectId,args.taskId,args.startActionToken);
121
+ case 'permit.consume':return db.consumePermit(args);
122
+ case 'run.credential.rotate':return db.rotateCredential(args);
123
+ case 'run.bind.initial':return db.bindInitial({...args,ownerCommitted:true});
124
+ case 'run.fence':return db.fence(args);
125
+ case 'run.fence.cancel':return db.fenceCancelledIdle(args);
126
+ case 'run.fence.terminal':return db.fenceTerminal(args);
127
+ case 'run.bind.handoff':
128
+ return db.bindHandoff({...args,ownerCommitted:true,nativeCommitted:true});
129
+ case 'run.restore-fenced-handoff':
130
+ return db.restoreFencedHandoff({...args,
131
+ sourceRunRef:native.sessionId+':'+native.taskId+':'+native.generation});
132
+ case 'run.restore-same-owner':
133
+ assert(args.sendState==='NOT_SENT'
134
+ &&typeof args.recoveryActionToken==='string',
135
+ 'SEND_NOT_PROVEN_ABSENT');
136
+ return db.restoreSameOwner({...args,
137
+ sourceRunRef:native.sessionId+':'+native.taskId+':'+native.generation,
138
+ oldActionTokenRevoked:true,workerRestored:true,
139
+ nativeRestored:true,ownerStillSame:true});
140
+ }
141
+ }finally{db.close()}
142
+ }
@@ -0,0 +1,169 @@
1
+ // Operator-only Workspace ownership. Never imported by ordinary MCP.
2
+ import {createHash} from 'node:crypto';
3
+ import {readdirSync,lstatSync,realpathSync,existsSync,mkdirSync,rmdirSync} from 'node:fs';
4
+ import {isAbsolute,join,relative,sep} from 'node:path';
5
+ import {createInterface} from 'node:readline/promises';
6
+ // This module declares ports; index.mjs is the only dependency assembler.
7
+ // No implementation module imports another implementation module.
8
+ let openContextProtocol, contextRoot, dispatchContextCall, allowedProjects;
9
+ let connected=false;
10
+ export function configureWorkspaceOperator(capabilities){
11
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
12
+ for(const name of ['openContextProtocol', 'contextRoot', 'dispatchContextCall', 'allowedProjects']){
13
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
14
+ }
15
+ ({openContextProtocol, contextRoot, dispatchContextCall, allowedProjects}=capabilities);
16
+ connected=true;
17
+ }
18
+
19
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
20
+ const fail=code=>Object.assign(new Error(code),{code});
21
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
22
+ const overlap=(a,b)=>a===b||[relative(a,b),relative(b,a)]
23
+ .some(r=>r!==''&&r!=='..'&&!r.startsWith('..'+sep)&&!isAbsolute(r));
24
+ const trustedDir=path=>{
25
+ const s=lstatSync(path);
26
+ assert(s.isDirectory()&&!s.isSymbolicLink()&&!(s.mode&0o077)
27
+ &&(!process.getuid||s.uid===process.getuid()),'CONTEXT_ROOT_UNTRUSTED');
28
+ };
29
+ export function canonicalWorkspaceRefs(paths,{allowEmpty=false}={}){
30
+ assert(Array.isArray(paths)&&paths.length<=16&&(allowEmpty||paths.length>0),
31
+ 'WORKSPACE_BINDING_INVALID');
32
+ const refs=paths.map(path=>{
33
+ assert(typeof path==='string'&&path.length<=4096&&isAbsolute(path),
34
+ 'WORKSPACE_INVALID');
35
+ let real,st;
36
+ try{st=lstatSync(path);real=realpathSync(path)}
37
+ catch{throw fail('WORKSPACE_UNVERIFIED')}
38
+ assert(st.isDirectory()&&!st.isSymbolicLink(),'WORKSPACE_SYMLINK_REJECTED');
39
+ return real;
40
+ });
41
+ for(let i=0;i<refs.length;i++)for(let j=0;j<i;j++)
42
+ assert(!overlap(refs[i],refs[j]),'WORKSPACE_SCOPE_OVERLAP');
43
+ return refs;
44
+ }
45
+ export function confirmationPhrase(action,projectId,revision,refs){
46
+ const hash=createHash('sha256').update(JSON.stringify(
47
+ {action,projectId,revision,refs})).digest('hex').slice(0,12);
48
+ return 'CONFIRM '+action+' '+projectId+' '+hash;
49
+ }
50
+ export async function confirmWorkspaceOperator(action,projectId,revision,refs){
51
+ if(!process.stdin.isTTY||!process.stderr.isTTY)throw fail('OPERATOR_TTY_REQUIRED');
52
+ const phrase=confirmationPhrase(action,projectId,revision,refs);
53
+ const rl=createInterface({input:process.stdin,output:process.stderr,terminal:true});
54
+ try{
55
+ process.stderr.write('Local operator approval only. Project: '+projectId+
56
+ '\nAction: '+action+'\nReviewed paths:\n'+
57
+ (refs.length?refs.map(x=>' '+x).join('\n'):' (clear all)')+'\n');
58
+ const answer=await rl.question('Type '+phrase+' to authorize: ');
59
+ assert(answer===phrase,'OPERATOR_CONFIRMATION_MISMATCH');
60
+ }finally{rl.close()}
61
+ }
62
+ export function withWorkspaceRegistryLock(root,fn){
63
+ trustedDir(root);
64
+ const lock=join(root,'.project-register.lock');
65
+ try{mkdirSync(lock,{mode:0o700})}catch{throw fail('PROJECT_REGISTRY_BUSY')}
66
+ // Async backups must retain the same global lock through atomic publication.
67
+ let deferred=false;
68
+ try{
69
+ const result=fn();
70
+ if(result&&typeof result.then==='function'){
71
+ deferred=true;
72
+ return result.finally(()=>rmdirSync(lock));
73
+ }
74
+ return result;
75
+ }finally{if(!deferred)rmdirSync(lock)}
76
+ }
77
+ // Scan all physical project directories, not just the current MCP grant.
78
+ // An ungranted Project can still own the same Workspace. Do not auto-pick.
79
+ export function assertWorkspaceUnclaimed(root,projectId,refs){
80
+ for(const dir of readdirSync(root,{withFileTypes:true})){
81
+ if(!ID.test(dir.name)||dir.name===projectId)continue;
82
+ assert(dir.isDirectory()&&!dir.isSymbolicLink(),'PROJECT_DIRECTORY_UNTRUSTED');
83
+ const file=join(root,dir.name,'context.sqlite');
84
+ assert(existsSync(file),'PROJECT_IDENTITY_UNVERIFIED');
85
+ const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
86
+ authorizeData:()=>true});
87
+ let list;
88
+ try{list=db.projectList()}finally{db.close()}
89
+ assert(list.length===1&&list[0].projectId===dir.name,'PROJECT_IDENTITY_MISMATCH');
90
+ for(const existing of list[0].sharedContext?.workspaceRefs??[]){
91
+ assert(typeof existing==='string'&&isAbsolute(existing),'WORKSPACE_BINDING_INVALID');
92
+ let canonical;
93
+ try{canonical=realpathSync(existing)}catch{canonical=existing}
94
+ for(const current of refs)
95
+ assert(!overlap(canonical,current),'WORKSPACE_OWNERSHIP_CONFLICT');
96
+ }
97
+ }
98
+ }
99
+ export async function rebindProjectWorkspaces({
100
+ projectId,expectedProjectRevision,expectedStoreEpoch,writeRequestId,workspaces
101
+ }){
102
+ assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
103
+ assert(ID.test(projectId||'')&&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
104
+ assert(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
105
+ 'PROJECT_REVISION_REQUIRED');
106
+ assert(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
107
+ 'STORE_EPOCH_REQUIRED');
108
+ assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&
109
+ writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
110
+ const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:true});
111
+ const root=contextRoot();
112
+ trustedDir(root);
113
+ // First pass has no write side effects. Confirmation is bound to exact refs.
114
+ const before=await dispatchContextCall('chat_loop_context_get',
115
+ {operation:'project.open',projectId});
116
+ assert(before.project.projectRevision===expectedProjectRevision,
117
+ 'PROJECT_VERSION_CONFLICT');
118
+ assert(before.storeEpoch===expectedStoreEpoch,'STALE_EPOCH');
119
+ assert(!before.project.archived,'PROJECT_ARCHIVED');
120
+ assert(before.authority.writable===true,'PROJECT_CUTOVER_NOT_VERIFIED');
121
+ await confirmWorkspaceOperator('BIND',projectId,expectedProjectRevision,refs);
122
+ return withWorkspaceRegistryLock(root,()=>{
123
+ // Re-read under the *same* global lock as project register; Core CAS
124
+ // protects concurrent business writes that do not take this lock.
125
+ assertWorkspaceUnclaimed(root,projectId,refs);
126
+ const current=canonicalWorkspaceRefs(workspaces,{allowEmpty:true});
127
+ assert(JSON.stringify(current)===JSON.stringify(refs),'WORKSPACE_CHANGED');
128
+ const file=join(root,projectId,'context.sqlite');
129
+ const db=openContextProtocol(file,{principalId:'local-operator',
130
+ authorizeData:(_mode,p)=>p===projectId,
131
+ authorizeAdmin:(op,p)=>op==='project.bind'&&p===projectId});
132
+ try{
133
+ const ids=db.projectList();
134
+ assert(ids.length===1&&ids[0].projectId===projectId,
135
+ 'PROJECT_IDENTITY_MISMATCH');
136
+ assert(db.projectBusinessAuthority(projectId).writable===true,
137
+ 'PROJECT_CUTOVER_NOT_VERIFIED');
138
+ const receipt=db.projectPatch({projectId,expectedProjectRevision,
139
+ expectedStoreEpoch,writeRequestId,sharedContext:{workspaceRefs:refs}});
140
+ const after=db.projectGet(projectId);
141
+ assert(after.projectRevision===receipt.projectRevision&&
142
+ JSON.stringify(after.sharedContext.workspaceRefs)===JSON.stringify(refs),
143
+ 'WORKSPACE_RECEIPT_UNVERIFIED');
144
+ return {...receipt,projectId,workspaceRefs:refs,storeEpoch:expectedStoreEpoch,
145
+ writeRequestId};
146
+ }finally{db.close()}
147
+ });
148
+ }
149
+
150
+ // Read-only recovery for an operator write whose CLI result was lost.
151
+ // Receipt uses the SAME local-operator principal, not the model MCP principal.
152
+ export async function readOperatorWorkspaceReceipt({projectId,storeEpoch,writeRequestId}){
153
+ assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
154
+ assert(ID.test(projectId||'')&&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
155
+ assert(typeof storeEpoch==='string'&&storeEpoch.length>=10,'STORE_EPOCH_REQUIRED');
156
+ assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&
157
+ writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
158
+ const opened=await dispatchContextCall('chat_loop_context_get',
159
+ {operation:'project.open',projectId});
160
+ assert(opened.storeEpoch===storeEpoch,'STALE_EPOCH');
161
+ const file=join(contextRoot(),projectId,'context.sqlite');
162
+ const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
163
+ authorizeData:(_mode,p)=>p===projectId});
164
+ try{
165
+ return {projectId,storeEpoch,writeRequestId,
166
+ receipt:db.requestStatus({projectId,storeEpoch,writeRequestId}),
167
+ project:db.projectGet(projectId)};
168
+ }finally{db.close()}
169
+ }
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@tomflow/chatloop-context",
3
+ "version": "0.6.32",
4
+ "type": "module",
5
+ "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "engines": {
10
+ "node": ">=24"
11
+ },
12
+ "bin": {
13
+ "chatloop-context": "./bin/cli.mjs"
14
+ },
15
+ "exports": {
16
+ ".": "./index.mjs"
17
+ },
18
+ "files": [
19
+ "index.mjs",
20
+ "capabilities.generated.mjs",
21
+ "capabilities/",
22
+ "lib/",
23
+ "bin/",
24
+ "scripts/",
25
+ "README.md",
26
+ "docs/"
27
+ ],
28
+ "scripts": {
29
+ "build:capabilities": "node ./scripts/build-capabilities.mjs",
30
+ "build:capabilities:check": "node ./scripts/build-capabilities.mjs --check",
31
+ "prepack": "node ./scripts/build-capabilities.mjs --check"
32
+ },
33
+ "dependencies": {
34
+ "ps-list": "9.0.0",
35
+ "@tomflow/chatloop-extension": "0.4.34",
36
+ "@tomflow/chatloop-trace": "0.4.6"
37
+ }
38
+ }
@@ -0,0 +1,114 @@
1
+ // Deterministic, build-time Context capability composition.
2
+ // Source of truth: capabilities/<id>.mjs. Runtime never scans directories.
3
+ import {readdirSync,readFileSync,writeFileSync} from 'node:fs';
4
+ import {dirname,join,resolve} from 'node:path';
5
+ import {fileURLToPath,pathToFileURL} from 'node:url';
6
+ import {createHash} from 'node:crypto';
7
+
8
+ const ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
9
+ const ID=/^[a-z][a-z0-9-]{0,63}$/;
10
+ const METHOD=/^[a-z][a-z0-9-]*\.[a-zA-Z0-9._-]+$/;
11
+ const ADAPTERS=new Set(['sdk.methods.list','sdk.methods.describe','project.resolve',
12
+ 'project.list','project.open','task.open']);
13
+ const failure=code=>Object.assign(Error(code),{code});
14
+ const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
15
+
16
+ export async function compileCapabilities(sourceDir=join(ROOT,'capabilities')){
17
+ const files=readdirSync(sourceDir).filter(s=>s.endsWith('.mjs')).sort();
18
+ if(!files.length)throw failure('CAPABILITY_EMPTY');
19
+ const caps=[],seenIds=new Set(),seenMethods=new Set();
20
+ for(const name of files){
21
+ if(!/^[a-z][a-z0-9-]*\.mjs$/.test(name))throw failure('CAPABILITY_FILENAME_INVALID');
22
+ const path=resolve(sourceDir,name);
23
+ const fingerprint=createHash('sha256').update(readFileSync(path)).digest('hex');
24
+ const {capability:c}=await import(pathToFileURL(path).href+'?sha256='+fingerprint);
25
+ if(!object(c)||!ID.test(c.id)||name!==c.id+'.mjs'||seenIds.has(c.id)
26
+ ||!Number.isSafeInteger(c.version)||c.version<1
27
+ ||typeof c.purpose!=='string'||!c.purpose.length
28
+ ||typeof c.startWith!=='string'||!Array.isArray(c.methods)||!c.methods.length)
29
+ throw failure('CAPABILITY_DECLARATION_INVALID');
30
+ seenIds.add(c.id);
31
+ for(const m of c.methods){
32
+ if(!object(m)||!METHOD.test(m.id)||m.group!==c.id
33
+ ||!m.id.startsWith(c.id+'.')||seenMethods.has(m.id)
34
+ ||(m.order!==undefined&&(!Number.isSafeInteger(m.order)||m.order<0))
35
+ ||!['read','write'].includes(m.mode)||typeof m.description!=='string'
36
+ ||!object(m.inputSchema)||m.inputSchema.type!=='object'
37
+ ||m.inputSchema.additionalProperties!==false
38
+ ||!Array.isArray(m.inputSchema.required)
39
+ ||!m.inputSchema.required.includes('operation')
40
+ ||!object(m.inputSchema.properties)
41
+ ||m.inputSchema.properties.operation?.const!==m.id
42
+ ||m.inputSchema.required.some(k=>!Object.hasOwn(m.inputSchema.properties,k))
43
+ ||!object(m.route))throw failure('CAPABILITY_METHOD_INVALID');
44
+ seenMethods.add(m.id);
45
+ if(m.route.kind==='adapter'){
46
+ if(!ADAPTERS.has(m.id)||m.route.name!==m.id)
47
+ throw failure('CAPABILITY_ADAPTER_NOT_ALLOWED');
48
+ }else if(m.route.kind==='core'){
49
+ if(!/^[a-zA-Z][a-zA-Z0-9]*$/.test(m.route.method)
50
+ ||!Array.isArray(m.route.params)
51
+ ||m.route.params.some(p=>!(typeof p==='string'||
52
+ object(p)&&Object.keys(p).length===1&&object(p.$object))))
53
+ throw failure('CAPABILITY_CORE_ROUTE_INVALID');
54
+ }else if(m.route.kind==='module'){
55
+ // Unreviewed custom business writes must not bypass Core's CAS/receipt.
56
+ // A new writer must first acquire an explicitly reviewed receipt port.
57
+ if(m.mode!=='read'||!m.inputSchema.required.includes('projectId')
58
+ ||typeof c.execute!=='function')
59
+ throw failure('CAPABILITY_CUSTOM_PERMISSION_INVALID');
60
+ }else throw failure('CAPABILITY_ROUTE_INVALID');
61
+ }
62
+ if(!c.methods.some(m=>m.id===c.startWith))
63
+ throw failure('CAPABILITY_START_METHOD_INVALID');
64
+ caps.push(c);
65
+ }
66
+ const flattened=caps.flatMap(c=>c.methods);
67
+ const explicitOrders=flattened.filter(m=>m.order!==undefined).map(m=>m.order);
68
+ if(new Set(explicitOrders).size!==explicitOrders.length)
69
+ throw failure('CAPABILITY_METHOD_ORDER_DUPLICATE');
70
+ // Existing APIs retain their published presentation order. New capability
71
+ // methods need no global position: the compiler deterministically appends
72
+ // them by ID, so adding a group never edits another group's declarations.
73
+ let nextOrder=Math.max(-1,...explicitOrders)+1;
74
+ const assigned=new Map(flattened.filter(m=>m.order===undefined)
75
+ .sort((a,b)=>a.id.localeCompare(b.id))
76
+ .map(m=>[m.id,nextOrder++]));
77
+ const methods=flattened.map(m=>{
78
+ const {id,group,mode,description,inputSchema,route,lifecycle}=m;
79
+ return {id,group,mode,description,inputSchema,route,
80
+ order:m.order??assigned.get(id),...(lifecycle?{lifecycle}:{})};
81
+ }).sort((a,b)=>a.order-b.order);
82
+ const groups=caps.map(c=>({
83
+ id:c.id,purpose:c.purpose,startWith:c.startWith,
84
+ order:Math.min(...methods.filter(m=>m.group===c.id).map(m=>m.order))
85
+ })).sort((a,b)=>a.order-b.order);
86
+ const json=JSON.stringify({groups,methods},null,2)+'\n';
87
+ const imports=files.map((file,i)=>
88
+ "import {capability as c"+i+"} from './capabilities/"+file+"';").join('\n');
89
+ const js='// GENERATED from capabilities/*.mjs. Do not edit.\n'+
90
+ imports+'\nexport const capabilities=Object.freeze(['+
91
+ files.map((_,i)=>'c'+i).join(',')+']);\n';
92
+ return {json,js,groups,methods};
93
+ }
94
+
95
+ async function main(){
96
+ const {json,js,methods}=await compileCapabilities();
97
+ const targets=[
98
+ [join(ROOT,'lib/capability-catalog.generated.json'),json],
99
+ [join(ROOT,'capabilities.generated.mjs'),js]
100
+ ];
101
+ if(process.argv.includes('--check')){
102
+ for(const [file,expected] of targets){
103
+ let actual;try{actual=readFileSync(file,'utf8')}catch{}
104
+ if(actual!==expected)throw failure('CAPABILITY_BUILD_STALE:'+file);
105
+ }
106
+ if(process.env.npm_lifecycle_event!=='prepack')
107
+ console.log('CAPABILITIES_CURRENT '+methods.length);
108
+ }else{
109
+ for(const [file,value] of targets)writeFileSync(file,value);
110
+ console.log('CAPABILITIES_BUILT '+methods.length);
111
+ }
112
+ }
113
+ if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
114
+ await main();