@tomflow/chatloop-tools 0.9.62 → 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 +29 -10
  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 +3 -13
  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 -83
  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
@@ -1,71 +0,0 @@
1
- // Sole npm SDK entry: all private module dependencies are composed here.
2
- // Node-native Worker entrypoints consume these APIs, never lib/* paths.
3
- import {fileURLToPath} from 'node:url';
4
- import {actionCapabilities} from './actions.generated.mjs';
5
- import {matchExtensionAction} from './lib/action-routing.mjs';
6
- import {openExtensionActionPage} from './lib/browser-launch.mjs';
7
- import {createApiAspect} from '@tomflow/chatloop-trace';
8
- import {createOrderedApiObservationSender,createObservationDrain} from './lib/api-observation-queue.mjs';
9
- const observationSender=createOrderedApiObservationSender(record=>
10
- ipc.nativeApiObservation(record));
11
- const INTERNAL_DRAIN=Symbol.for('chat-loop.telemetry.drain.internal');
12
- const apiAspect=createApiAspect('@tomflow/chatloop-extension',{
13
- sink:record=>{
14
- // The sink uses the private raw IPC transport, not the exported Native
15
- // callable. Public nativeHostApi/nativeApiObservation calls therefore
16
- // remain observable without re-entering their own AOP wrappers.
17
- return observationSender.send({
18
- callId:record.callId,traceId:record.traceId,spanId:record.spanId,
19
- ...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
20
- apiName:'extension.'+record.surface+'.'+record.api,
21
- phase:record.phase,
22
- ...(record.durationMs!==null?{durationMs:record.durationMs}:{}),
23
- ...(record.errorCode?{errorCode:record.errorCode}:{})
24
- });
25
- }
26
- });
27
- const drainTelemetry=createObservationDrain(apiAspect,observationSender);
28
- import * as bridge from './lib/bridge.mjs';
29
- import * as session from './lib/session-file.mjs';
30
- import * as binding from './lib/context-binding.mjs';
31
- import * as ipc from './lib/context-ipc.mjs';
32
- import * as evidence from './lib/owner-evidence.mjs';
33
-
34
- bridge.configureBridgeActions(actionCapabilities,apiAspect.current);
35
- binding.configureContextBinding({configFile:bridge.configFile});
36
- evidence.configureOwnerEvidence({
37
- readSession:session.readSession,sessionPath:session.sessionPath,
38
- cliPath:()=>fileURLToPath(new URL('./bin/cli.mjs',import.meta.url))
39
- });
40
-
41
- // Bounded provider contract for Context's reviewed orphan fence.
42
- export const verifyOrphanOwnerIdle=apiAspect.observe(
43
- 'verifyOrphanOwnerIdle',evidence.verifyOrphanOwnerIdle);
44
-
45
- // Internal entrypoint contracts, not a second npm subpath.
46
- export const extensionCliApi=apiAspect.observe('extensionCliApi',
47
- ()=>apiAspect.methods(Object.freeze({
48
- [INTERNAL_DRAIN]:drainTelemetry,
49
- ACTIONS:bridge.ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME:bridge.HOST_NAME,
50
- configFile:bridge.configFile,prepare:bridge.prepare,
51
- readResult:bridge.readResult,privateDir:bridge.privateDir,
52
- validateExtensionId:bridge.validateExtensionId,
53
- openExtensionActionPage
54
- }), 'extensionCliApi','cli'));
55
- export const nativeHostApi=apiAspect.observe('nativeHostApi',
56
- ()=>apiAspect.methods(Object.freeze({
57
- [INTERNAL_DRAIN]:drainTelemetry,
58
- readRequest:bridge.readRequest,finish:bridge.finish,
59
- readSession:session.readSession,writeSession:session.writeSession,
60
- registeredContext:binding.registeredContext,
61
- nativeContextControl:ipc.nativeContextControl,
62
- // One named, non-authoritative span for each Native messaging operation.
63
- observeNativeOperation:(op,perform,parent=null)=>{
64
- if(typeof perform!=='function')throw TypeError('NATIVE_OPERATION_REQUIRED');
65
- const name=typeof op==='string'&&/^[a-z][a-z0-9-]{0,60}$/.test(op)
66
- ?op:'invalid';
67
- return apiAspect.observe('native.op.'+name,perform,'native',
68
- parent?{parent}:{})();
69
- },
70
- nativeApiObservation:ipc.nativeApiObservation
71
- }), 'nativeHostApi','native'));
@@ -1,19 +0,0 @@
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
- }
@@ -1,82 +0,0 @@
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
- }
@@ -1,303 +0,0 @@
1
- import {randomUUID} from 'node:crypto';
2
- import {existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync} from 'node:fs';
3
- import {homedir, tmpdir} from 'node:os';
4
- import {join} from 'node:path';
5
-
6
- export const HOST_NAME = 'com.tomflow.chatloop.extension';
7
- export let ACTIONS=Object.freeze([]);
8
- let readApiParent=()=>null;
9
- const API_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;
10
- const validParent=p=>p&&API_UUID.test(p.traceId||'')&&API_UUID.test(p.spanId||'');
11
- export function configureBridgeActions(actions,parentReader=()=>null){
12
- if(ACTIONS.length)throw Error('EXTENSION_ACTIONS_ALREADY_CONFIGURED');
13
- if(!Array.isArray(actions)||!actions.length||
14
- actions.some(action=>typeof action?.id!=='string'))
15
- throw Error('EXTENSION_ACTIONS_INVALID');
16
- ACTIONS=Object.freeze(actions.map(action=>action.id));
17
- if(typeof parentReader!=='function')throw Error('EXTENSION_TRACE_PORT_INVALID');
18
- readApiParent=parentReader;
19
- }
20
- const ID = /^[a-f0-9]{32}$/;
21
- const MAX_TEXT = 8 * 1024 * 1024;
22
- const MAX_PNG = 24 * 1024 * 1024;
23
- const TTL_MS = 20 * 60 * 1000;
24
- const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
25
- function pathEntryExists(path){
26
- try{lstatSync(path);return true}
27
- catch(error){if(error.code==='ENOENT')return false;throw error}
28
- }
29
- export const configFile = () => join(homedir(), '.chat-loop', 'extension', 'config.json');
30
- // The CLI and Chrome Native Host have independent environments. A fixed
31
- // v2 namespace also fences unresolved requests from the former TMPDIR-based
32
- // transport: never scan, migrate or replay those records.
33
- export const tempRoot = () => {
34
- const base=process.platform==='darwin'?'/private/tmp':process.platform==='linux'?'/tmp':tmpdir();
35
- if(process.platform!=='win32'){
36
- const st=lstatSync(base);
37
- if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==0
38
- ||!(st.mode&0o1000)||!(st.mode&0o002))
39
- throw Object.assign(Error('Untrusted IPC temp root'),{code:'UNTRUSTED_STATE'});
40
- }
41
- return join(base,'chatloop-extension-v2-'+(process.getuid?.()??process.env.USERNAME??'user'));
42
- };
43
- export function privateDir(path) {
44
- mkdirSync(path, {recursive:true, mode:0o700});
45
- const st=lstatSync(path);
46
- if(!st.isDirectory() || st.isSymbolicLink() || (process.getuid && st.uid!==process.getuid())
47
- || (process.platform!=='win32' && (st.mode&0o077)))
48
- throw Object.assign(Error('Untrusted extension state directory'),{code:'UNTRUSTED_STATE'});
49
- return path;
50
- }
51
- // Both request and reply are private IPC records; never trust a symlink or
52
- // a file with broader permissions merely because its directory is private.
53
- function privateRecord(file,code){
54
- const st=lstatSync(file);
55
- if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
56
- ||(process.platform!=='win32'&&(st.mode&0o077)))
57
- throw Object.assign(Error('Untrusted extension record'),{code});
58
- }
59
- export function requestDir(id) {
60
- if(typeof id!=='string'||!ID.test(id))throw Object.assign(Error('Invalid request ID'),{code:'INVALID_REQUEST_ID'});
61
- return join(tempRoot(),id);
62
- }
63
- function validateIntent(action, intent) {
64
- if(action==='session'){
65
- const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
66
- const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
67
- const keys=['operation','projectId','taskId','sessionId','generation',
68
- 'expectedNativeUpdatedAt','expectedTaskRevision',
69
- 'expectedBindingRevision','contextStoreEpoch','confirmed'];
70
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
71
- ||Object.keys(intent).length!==keys.length
72
- ||keys.some(k=>!Object.hasOwn(intent,k))
73
- ||intent.operation!=='cancel'||intent.confirmed!==true
74
- ||!ID.test(intent.projectId||'')||!ID.test(intent.taskId||'')
75
- ||!UUID.test(intent.sessionId||'')
76
- ||!Number.isSafeInteger(intent.generation)||intent.generation<0
77
- ||!Number.isSafeInteger(intent.expectedNativeUpdatedAt)
78
- ||intent.expectedNativeUpdatedAt<=0
79
- ||!Number.isSafeInteger(intent.expectedTaskRevision)
80
- ||intent.expectedTaskRevision<1
81
- ||!Number.isSafeInteger(intent.expectedBindingRevision)
82
- ||intent.expectedBindingRevision<1
83
- ||typeof intent.contextStoreEpoch!=='string'
84
- ||intent.contextStoreEpoch.length<10||intent.contextStoreEpoch.length>128)
85
- throw Object.assign(Error('Exact session cancellation required'),
86
- {code:'INVALID_SESSION_INTENT'});
87
- return {...intent};
88
- }
89
- if(action==='entry_test'){
90
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
91
- ||Object.keys(intent).some(k=>!['prompt','appId','testOnly','confirmed','recoverTestAt','recoverExactDraft','verifyChatUrl'].includes(k))
92
- ||typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
93
- ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)
94
- ||typeof intent.appId!=='string'||!/^asdk_app_[a-z0-9]{20,64}$/.test(intent.appId)
95
- ||intent.testOnly!==true||intent.confirmed!==true
96
- ||(intent.verifyChatUrl!==undefined&&(
97
- typeof intent.verifyChatUrl!=='string'
98
- ||!/^https:\/\/chatgpt\.com\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.verifyChatUrl)
99
- ||intent.recoverTestAt!==undefined||intent.recoverExactDraft!==undefined))
100
- ||(intent.recoverTestAt!==undefined&&intent.recoverTestAt!==true)
101
- ||(intent.recoverExactDraft!==undefined
102
- &&(typeof intent.recoverExactDraft!=='string'
103
- ||!intent.recoverExactDraft.trim()
104
- ||intent.recoverExactDraft.length>4000)))
105
- throw Object.assign(Error('Explicit test-only entry intent required'),{code:'INVALID_ENTRY_TEST_INTENT'});
106
- return {prompt:intent.prompt,appId:intent.appId,testOnly:true,confirmed:true,
107
- ...(intent.recoverTestAt?{recoverTestAt:true}:{}),
108
- ...(intent.recoverExactDraft?{recoverExactDraft:intent.recoverExactDraft}:{}),
109
- ...(intent.verifyChatUrl?{verifyChatUrl:intent.verifyChatUrl}:{})};
110
- }
111
- if(action==='start'){
112
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
113
- ||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision'].includes(k))
114
- ||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.projectId||'')
115
- ||(intent.taskId!==undefined && !(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.taskId))
116
- ||(intent.purpose!==undefined && (intent.purpose!=='REPAIR_SAME_SCOPE'
117
- ||intent.mode!=='adopt'||!intent.taskId||!intent.contextLeaseRef))
118
- ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
119
- .some(k=>Object.hasOwn(intent,k))
120
- &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
121
- ||intent.contextLeaseRef.length<8
122
- ||typeof intent.contextStoreEpoch!=='string'||intent.contextStoreEpoch.length<10
123
- ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
124
- ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
125
- // Public Extension CLI must not bypass the managed Context Start lease.
126
- ||(intent.mode==='adopt'&&!Object.hasOwn(intent,'contextLeaseRef'))
127
- ||intent.confirmed!==true || (intent.mode!==undefined && intent.mode!=='adopt')
128
- || (intent.replaceBlockedSessionId!==undefined
129
- && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId))
130
- ||(intent.chatUrl!==undefined
131
- && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'||!CHAT_URL.test(intent.chatUrl)))
132
- ||(intent.mode==='adopt'
133
- ? Object.hasOwn(intent,'prompt')
134
- : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
135
- ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)))
136
- throw Object.assign(Error('Explicit confirmed task and project required'),{code:'INVALID_START_INTENT'});
137
- return {projectId:intent.projectId,confirmed:true,
138
- ...(intent.taskId?{taskId:intent.taskId}:{}),
139
- ...(intent.purpose?{purpose:intent.purpose}:{}),
140
- ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
141
- contextStoreEpoch:intent.contextStoreEpoch,
142
- contextTaskRevision:intent.contextTaskRevision,
143
- contextApprovalRevision:intent.contextApprovalRevision}:{}),
144
- ...(intent.mode==='adopt'?{mode:'adopt',...(intent.chatUrl?{chatUrl:intent.chatUrl}:{})}:{prompt:intent.prompt}),
145
- ...(intent.replaceBlockedSessionId?{replaceBlockedSessionId:intent.replaceBlockedSessionId}:{})};
146
- }
147
- if(action==='clean'){
148
- if(!intent || typeof intent!=='object' || Array.isArray(intent)
149
- || Object.keys(intent).length!==1 || !Number.isSafeInteger(intent.tabId)
150
- || intent.tabId<1)
151
- throw Object.assign(Error('Clean requires an exact tabId'),{code:'INVALID_CLEAN_TARGET'});
152
- return {tabId:intent.tabId};
153
- }
154
- if(!['continue','handoff'].includes(action)) {
155
- if(intent!==undefined)throw Object.assign(Error('Unexpected intent'),{code:'INVALID_INTENT'});
156
- return null;
157
- }
158
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
159
- || typeof intent.turnToken!=='string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(intent.turnToken))
160
- throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
161
- // Query is read-only and uses the same formal Action page; no seventh Action.
162
- if(Object.hasOwn(intent,'intentId')||intent.lookup===true){
163
- const latest=intent.lookup===true;
164
- if(Object.keys(intent).some(k=>k!=='turnToken'&&k!==(latest?'lookup':'intentId'))
165
- ||latest&&Object.hasOwn(intent,'intentId')
166
- ||!latest&&(typeof intent.intentId!=='string'||!/^[a-f0-9]{32}$/.test(intent.intentId)))
167
- throw Object.assign(Error('Invalid intent query'),{code:'INVALID_INTENT'});
168
- return latest?{turnToken:intent.turnToken,lookup:true}
169
- :{turnToken:intent.turnToken,intentId:intent.intentId};
170
- }
171
- if(Object.keys(intent).some(k=>k!=='turnToken'&&(action==='continue'?k!=='nextPrompt':k!=='reason')))
172
- throw Object.assign(Error('Invalid model intent'),{code:'INVALID_INTENT'});
173
- if(action==='continue' && (typeof intent.nextPrompt!=='string'
174
- || !intent.nextPrompt.trim() || intent.nextPrompt.length>4000
175
- || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.nextPrompt)))
176
- throw Object.assign(Error('Invalid continuation text'),{code:'INVALID_INTENT'});
177
- if(action==='handoff' && intent.reason!==undefined
178
- && (typeof intent.reason!=='string'||intent.reason.length>400
179
- || /[\x00-\x1f]/.test(intent.reason)))
180
- throw Object.assign(Error('Invalid handoff reason'),{code:'INVALID_INTENT'});
181
- return action==='continue' ? {turnToken:intent.turnToken,nextPrompt:intent.nextPrompt}
182
- : {turnToken:intent.turnToken,reason:intent.reason||''};
183
- }
184
- export function prepare(action,intent) {
185
- if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown extension action'),{code:'UNKNOWN_ACTION'});
186
- const validated=validateIntent(action,intent);
187
- privateDir(tempRoot());
188
- cleanup();
189
- const id=randomUUID().replaceAll('-',''), nonce=randomUUID().replaceAll('-',''), at=Date.now();
190
- const dir=privateDir(requestDir(id));
191
- // This private request is the already-authorized CLI → Native transport.
192
- // Correlation is soft: never promote it to a capability or Owner proof.
193
- let traceParent=null;
194
- try{const current=readApiParent();if(validParent(current))traceParent=current}catch{}
195
- writeFileSync(join(dir,'request.json'), JSON.stringify({id,nonce,action,at,expiresAt:at+TTL_MS,...(traceParent?{traceParent}:{}),...(validated ? {intent:validated} : {})}),
196
- {flag:'wx',mode:0o600});
197
- return {id,nonce,action,dir};
198
- }
199
- export function readRequest(id) {
200
- const dir=requestDir(id);
201
- if(!pathEntryExists(dir))throw Object.assign(Error('No request'),{code:'NO_REQUEST'});
202
- privateDir(dir);
203
- const p=join(dir,'request.json');
204
- privateRecord(p,'UNTRUSTED_REQUEST');
205
- const r=JSON.parse(readFileSync(p,'utf8'));
206
- if(r.id!==id||!ACTIONS.includes(r.action)||Date.now()>r.expiresAt)
207
- throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
208
- if(['continue','handoff','clean','start','entry_test'].includes(r.action))validateIntent(r.action,r.intent);
209
- if(r.traceParent!==undefined&&!validParent(r.traceParent))delete r.traceParent;
210
- return r;
211
- }
212
- export function finish({id,nonce,action,status,payload='',code=null}) {
213
- const r=readRequest(id);
214
- if(nonce!==r.nonce||action!==r.action)throw Object.assign(Error('Request mismatch'),{code:'REQUEST_MISMATCH'});
215
- if(status!=='OK'&&status!=='FAILED')throw Object.assign(Error('Invalid status'),{code:'INVALID_RESULT'});
216
- const dir=requestDir(id);
217
- const resultPath=join(dir,'result.json');
218
- if(pathEntryExists(resultPath))throw Object.assign(Error('Duplicate result'),{code:'ALREADY_FINISHED'});
219
- let bytes=0,mimeType=null,filename=null;
220
- if(status==='OK'){
221
- if(typeof payload!=='string')throw Object.assign(Error('Invalid payload'),{code:'INVALID_PAYLOAD'});
222
- let buf;
223
- if(action==='chat_screenshot'){
224
- if(!/^[A-Za-z0-9+/]*={0,2}$/.test(payload))throw Object.assign(Error('Invalid PNG encoding'),{code:'INVALID_PNG'});
225
- buf=Buffer.from(payload,'base64');
226
- if(buf.subarray(0,8).toString('hex')!=='89504e470d0a1a0a')throw Object.assign(Error('Invalid PNG signature'),{code:'INVALID_PNG'});
227
- mimeType='image/png';filename='result.png';
228
- if(buf.length>MAX_PNG)throw Object.assign(Error('PNG too large'),{code:'RESULT_TOO_LARGE'});
229
- }else{
230
- buf=Buffer.from(payload,'utf8');
231
- if(buf.length>MAX_TEXT)throw Object.assign(Error('Text too large'),{code:'RESULT_TOO_LARGE'});
232
- mimeType=action==='chat_dom'?'text/html':'text/plain';
233
- filename=action==='reload'?null:action==='chat_dom'?'result.html':'result.txt';
234
- }
235
- bytes=buf.length;
236
- if(filename)writeFileSync(join(dir,filename),buf,{flag:'wx',mode:0o600});
237
- }
238
- const failureCode=typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
239
- ?code:'ACTION_FAILED';
240
- const rec={id,action,status,code:status==='FAILED'?failureCode:null,
241
- path:filename?join(dir,filename):null,bytes,mimeType,at:Date.now(),
242
- verified:action!=='reload'};
243
- writeFileSync(resultPath+'.tmp',JSON.stringify(rec),{flag:'wx',mode:0o600});
244
- renameSync(resultPath+'.tmp',resultPath);
245
- return rec;
246
- }
247
- export function readResult(id) {
248
- const dir=requestDir(id),p=join(dir,'result.json');
249
- if(!pathEntryExists(p))return null;
250
- privateDir(dir);
251
- privateRecord(p,'UNTRUSTED_RESULT');
252
- let rec;
253
- try{rec=JSON.parse(readFileSync(p,'utf8'))}catch{
254
- throw Object.assign(Error('Untrusted result'),{code:'UNTRUSTED_RESULT'});
255
- }
256
- const request=readRequest(id);
257
- const expectedFile=request.action==='reload'?null:
258
- request.action==='chat_screenshot'?'result.png':
259
- request.action==='chat_dom'?'result.html':'result.txt';
260
- const expectedMime=request.action==='chat_screenshot'?'image/png':
261
- request.action==='chat_dom'?'text/html':'text/plain';
262
- const invalid=()=>Object.assign(Error('Untrusted result'),{code:'UNTRUSTED_RESULT'});
263
- if(!rec||typeof rec!=='object'||Array.isArray(rec)
264
- ||Object.keys(rec).some(k=>!['id','action','status','code','path',
265
- 'bytes','mimeType','at','verified'].includes(k))
266
- ||rec.id!==id||rec.action!==request.action
267
- ||!['OK','FAILED'].includes(rec.status)
268
- ||rec.verified!==(request.action!=='reload')
269
- ||!Number.isSafeInteger(rec.at)||rec.at<request.at||rec.at>request.expiresAt
270
- ||!Number.isSafeInteger(rec.bytes)||rec.bytes<0
271
- ||(rec.status==='FAILED'
272
- ?rec.path!==null||rec.mimeType!==null||rec.bytes!==0
273
- ||typeof rec.code!=='string'||!/^[A-Z][A-Z0-9_]{1,95}$/.test(rec.code)
274
- :rec.code!==null||rec.mimeType!==expectedMime
275
- ||rec.path!==(expectedFile?join(dir,expectedFile):null)
276
- ||rec.bytes>(request.action==='chat_screenshot'?MAX_PNG:MAX_TEXT)))
277
- throw invalid();
278
- if(rec.status==='OK'&&expectedFile){
279
- try{
280
- privateRecord(rec.path,'UNTRUSTED_RESULT');
281
- if(lstatSync(rec.path).size!==rec.bytes)throw invalid();
282
- }catch{throw invalid()}
283
- }
284
- return rec;
285
- }
286
- export function cleanup(){
287
- const root=tempRoot();
288
- if(!existsSync(root))return;
289
- privateDir(root);
290
- for(const f of readdirSync(root)){
291
- if(!ID.test(f))continue;
292
- const p=join(root,f);
293
- try{
294
- const st=lstatSync(p);
295
- if(st.isDirectory()&&!st.isSymbolicLink()&&Date.now()-st.mtimeMs>TTL_MS)
296
- rmSync(p,{recursive:true,force:true});
297
- }catch{}
298
- }
299
- }
300
- export function validateExtensionId(id) {
301
- if(!/^[a-p]{32}$/.test(id||''))throw Object.assign(Error('Invalid Chrome extension ID'),{code:'INVALID_EXTENSION_ID'});
302
- return id;
303
- }
@@ -1,83 +0,0 @@
1
- import {spawnSync} from 'node:child_process';
2
-
3
- // Open a formal extension Action page in the existing Chrome window that owns
4
- // the ChatGPT conversation. "open -a Google Chrome <url>" chooses the last
5
- // active *profile*, which can be a different profile without this extension.
6
- // This script does not read or modify a Chat tab; it creates only an Action tab.
7
- // Ambiguous ownership fails closed rather than sending an Action elsewhere.
8
- const OPEN_IN_CHAT_WINDOW = `on run argv
9
- set destination to item 1 of argv
10
- tell application "Google Chrome"
11
- set candidateIds to {}
12
- repeat with w in windows
13
- set hasChat to false
14
- repeat with t in tabs of w
15
- try
16
- if (URL of t) starts with "https://chatgpt.com/" then set hasChat to true
17
- end try
18
- end repeat
19
- if hasChat then set end of candidateIds to id of w
20
- end repeat
21
- if (count of candidateIds) is not 1 then error "CHATGPT_WINDOW_AMBIGUOUS_OR_ABSENT" number 103
22
- set ownWindow to window id (item 1 of candidateIds)
23
- make new tab at end of tabs of ownWindow with properties {URL:destination}
24
- return "WINDOW=" & (id of ownWindow)
25
- end tell
26
- end run`;
27
-
28
- // Entry TEST_ONLY may bootstrap a normal Chat when there is no existing
29
- // ChatGPT tab. In that case require exactly one Chrome window containing the
30
- // explicitly verified Chat Loop extension details page. Never select a random
31
- // Chrome window or another profile, and never create a Chat tab here.
32
- const OPEN_TEST_ENTRY_WINDOW = `on run argv
33
- set destination to item 1 of argv
34
- set managerURL to item 2 of argv
35
- tell application "Google Chrome"
36
- set chatWindowIds to {}
37
- repeat with w in windows
38
- set hasChat to false
39
- repeat with t in tabs of w
40
- try
41
- if (URL of t) starts with "https://chatgpt.com/" then set hasChat to true
42
- end try
43
- end repeat
44
- if hasChat then set end of chatWindowIds to id of w
45
- end repeat
46
- if (count of chatWindowIds) is 1 then
47
- set ownWindow to window id (item 1 of chatWindowIds)
48
- else
49
- if (count of chatWindowIds) is not 0 then error "CHATGPT_WINDOW_AMBIGUOUS" number 103
50
- set managerWindowIds to {}
51
- repeat with w in windows
52
- set hasManager to false
53
- repeat with t in tabs of w
54
- try
55
- if (URL of t) is managerURL then set hasManager to true
56
- end try
57
- end repeat
58
- if hasManager then set end of managerWindowIds to id of w
59
- end repeat
60
- if (count of managerWindowIds) is not 1 then error "ENTRY_TEST_WINDOW_UNVERIFIED" number 103
61
- set ownWindow to window id (item 1 of managerWindowIds)
62
- end if
63
- make new tab at end of tabs of ownWindow with properties {URL:destination}
64
- return "WINDOW=" & (id of ownWindow)
65
- end tell
66
- end run`;
67
-
68
- export function openExtensionActionPage(url,{platform=process.platform,spawn=spawnSync}={}){
69
- if(platform!=='darwin')
70
- throw Object.assign(Error('Browser launcher not yet verified on this OS'),
71
- {code:'BROWSER_LAUNCH_UNSUPPORTED'});
72
- if(!/^chrome-extension:\/\/[a-p]{32}\/[a-z_]+\.html\?requestId=[a-f0-9]{32}$/.test(url))
73
- throw Object.assign(Error('Untrusted Extension Action URL'),{code:'INVALID_ACTION_URL'});
74
- const entry=url.match(/^chrome-extension:\/\/([a-p]{32})\/entry_test\.html\?requestId=[a-f0-9]{32}$/);
75
- const launchArgs=entry
76
- ?['-e',OPEN_TEST_ENTRY_WINDOW,url,'chrome://extensions/?id='+entry[1]]
77
- :['-e',OPEN_IN_CHAT_WINDOW,url];
78
- const receipt=spawn('osascript',launchArgs,{encoding:'utf8',timeout:7000});
79
- if(receipt.error||receipt.status!==0||!/\bWINDOW=\d+\b/.test(receipt.stdout||''))
80
- throw Object.assign(Error('Existing ChatGPT Chrome window unavailable or ambiguous'),
81
- {code:'CHROME_TARGET_WINDOW_UNVERIFIED'});
82
- return {status:'OPENED',windowVerified:true};
83
- }
@@ -1,45 +0,0 @@
1
- // Read only operator-owned references from the existing Extension configuration.
2
- // The files retain the task/approval truth; this index never grants execution.
3
- import {existsSync,lstatSync,readFileSync,realpathSync} from 'node:fs';
4
- import {dirname,isAbsolute} from 'node:path';
5
- let configFile;
6
- export function configureContextBinding(api){
7
- if(configFile)throw Error('EXTENSION_MODULE_ALREADY_COMPOSED');
8
- if(typeof api?.configFile!=='function')throw Error('EXTENSION_PORT_MISSING:configFile');
9
- configFile=api.configFile;
10
- }
11
- const invalid=()=>Object.assign(Error('CONTEXT_BINDING_UNVERIFIED'),{code:'CONTEXT_BINDING_UNVERIFIED'});
12
- const trusted=(p,directory=false)=>{
13
- const s=lstatSync(p);
14
- if(s.isSymbolicLink()||(directory?!s.isDirectory():!s.isFile())
15
- ||process.getuid&&s.uid!==process.getuid()
16
- ||process.platform!=='win32'&&(s.mode&0o077))throw invalid();
17
- return s;
18
- };
19
- const pathValue=(value,directory=false)=>{
20
- if(typeof value!=='string'||!isAbsolute(value)||value.length>2048||/[\x00-\x1f]/.test(value))
21
- throw invalid();
22
- const s=lstatSync(realpathSync(value));
23
- if(directory?!s.isDirectory():!s.isFile())throw invalid();
24
- return value;
25
- };
26
- export function registeredContext(projectId){
27
- const file=configFile();
28
- if(!existsSync(file))return null;
29
- try{
30
- trusted(dirname(file),true);
31
- if(trusted(file).size>65536)throw invalid();
32
- const config=JSON.parse(readFileSync(file,'utf8')),entry=config.projectContext;
33
- if(entry===undefined||entry?.projectId!==projectId)return null;
34
- if(!entry||Array.isArray(entry)||typeof entry!=='object'
35
- ||Object.keys(entry).some(k=>!['projectId','sourceRoots','contextPath','taskDocPath','approvalDocPath'].includes(k))
36
- ||!Array.isArray(entry.sourceRoots)||entry.sourceRoots.length<1||entry.sourceRoots.length>8)
37
- throw invalid();
38
- const result={projectId,sourceRoots:entry.sourceRoots.map(p=>pathValue(p,true)),
39
- contextPath:pathValue(entry.contextPath),
40
- ...(entry.taskDocPath!==undefined?{taskDocPath:pathValue(entry.taskDocPath)}:{}),
41
- ...(entry.approvalDocPath!==undefined?{approvalDocPath:pathValue(entry.approvalDocPath)}:{})};
42
- if(JSON.stringify(result).length>8192)throw invalid();
43
- return result;
44
- }catch(error){throw invalid();}
45
- }