@tomflow/chatloop-tools 0.9.20 → 0.9.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/node_modules/@tomflow/chatloop-context/README.md +240 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +40 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
- package/package.json +10 -2
|
@@ -0,0 +1,86 @@
|
|
|
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','run.fence.terminal',
|
|
22
|
+
'run.credential.rotate','run.terminalStatus','run.reopenStatus','run.snapshot']);
|
|
23
|
+
|
|
24
|
+
export function executeTrustedRun(command,args,native){
|
|
25
|
+
assert(supported.has(command)&&args&&typeof args==='object'
|
|
26
|
+
&&!Array.isArray(args)&&native&&typeof native==='object',
|
|
27
|
+
'CONTEXT_COMMAND_INVALID');
|
|
28
|
+
assert(!['principal','role','internalAuthorized','ownerCommitted',
|
|
29
|
+
'nativeCommitted'].some(k=>Object.hasOwn(args,k)),
|
|
30
|
+
'CLIENT_AUTH_FIELD_FORBIDDEN');
|
|
31
|
+
assert(native.projectId===args.projectId && native.taskId===args.taskId
|
|
32
|
+
&& native.sessionId===args.sessionId
|
|
33
|
+
&& native.generation===args.generation
|
|
34
|
+
&& native.activeChatId===args.activeChatId
|
|
35
|
+
&& (native.activeChatId!==null || command==='permit.consume'&&args.kind==='START'),
|
|
36
|
+
'CONTEXT_NATIVE_BINDING_MISMATCH');
|
|
37
|
+
const allowed=allowedProjects();
|
|
38
|
+
assert(allowed.has(native.projectId),'PROJECT_ACCESS_DENIED');
|
|
39
|
+
if(command==='run.fence'){
|
|
40
|
+
assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
|
|
41
|
+
assert(args.targetGeneration===native.generation+1,'TARGET_GENERATION_MISMATCH');
|
|
42
|
+
}
|
|
43
|
+
if(['run.fence','run.fence.terminal','run.bind.initial','run.bind.handoff',
|
|
44
|
+
'run.credential.rotate'].includes(command))
|
|
45
|
+
assert(args.runRef===native.sessionId+':'+native.taskId+':'+native.generation,
|
|
46
|
+
'RUN_REF_MISMATCH');
|
|
47
|
+
if(command==='permit.consume')
|
|
48
|
+
assert(['RESERVED','PENDING'].includes(native.phase),'NATIVE_PHASE_MISMATCH');
|
|
49
|
+
if(['run.bind.initial','run.bind.handoff'].includes(command))
|
|
50
|
+
assert(native.phase==='WAITING_REPLY','NATIVE_PHASE_MISMATCH');
|
|
51
|
+
if(command==='run.credential.rotate')
|
|
52
|
+
assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
|
|
53
|
+
if(command==='run.restore-same-owner')
|
|
54
|
+
assert(native.phase==='RESERVED','NATIVE_PHASE_MISMATCH');
|
|
55
|
+
if(command==='run.fence.terminal'||command==='run.reopenStatus')
|
|
56
|
+
assert(native.phase==='DONE','NATIVE_PHASE_MISMATCH');
|
|
57
|
+
|
|
58
|
+
const file=resolveVerifiedProjectDatabase(args.projectId);
|
|
59
|
+
const db=openContextProtocol(file,{principalId:'native-controlled',
|
|
60
|
+
authorizeData:(_access,p)=>allowed.has(p),authorizeInternal:()=>true});
|
|
61
|
+
try{
|
|
62
|
+
if(!['run.terminalStatus','run.reopenStatus','run.snapshot'].includes(command)
|
|
63
|
+
&&!db.projectBusinessAuthority(args.projectId).writable)
|
|
64
|
+
throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
|
|
65
|
+
switch(command){
|
|
66
|
+
case 'run.terminalStatus':return db.terminalStatus(args.projectId,args.taskId);
|
|
67
|
+
case 'run.reopenStatus':return db.reopenStatus(args.projectId,args.taskId);
|
|
68
|
+
case 'run.snapshot':return db.latestCheckpoint(args.projectId,args.taskId);
|
|
69
|
+
case 'permit.consume':return db.consumePermit(args);
|
|
70
|
+
case 'run.credential.rotate':return db.rotateCredential(args);
|
|
71
|
+
case 'run.bind.initial':return db.bindInitial({...args,ownerCommitted:true});
|
|
72
|
+
case 'run.fence':return db.fence(args);
|
|
73
|
+
case 'run.fence.terminal':return db.fenceTerminal(args);
|
|
74
|
+
case 'run.bind.handoff':
|
|
75
|
+
return db.bindHandoff({...args,ownerCommitted:true,nativeCommitted:true});
|
|
76
|
+
case 'run.restore-same-owner':
|
|
77
|
+
assert(args.sendState==='NOT_SENT'
|
|
78
|
+
&&typeof args.recoveryActionToken==='string',
|
|
79
|
+
'SEND_NOT_PROVEN_ABSENT');
|
|
80
|
+
return db.restoreSameOwner({...args,
|
|
81
|
+
sourceRunRef:native.sessionId+':'+native.taskId+':'+native.generation,
|
|
82
|
+
oldActionTokenRevoked:true,workerRestored:true,
|
|
83
|
+
nativeRestored:true,ownerStillSame:true});
|
|
84
|
+
}
|
|
85
|
+
}finally{db.close()}
|
|
86
|
+
}
|
|
@@ -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,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tomflow/chatloop-context",
|
|
3
|
+
"version": "0.6.11",
|
|
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
|
+
"test": "node --test ./test/*.test.mjs",
|
|
30
|
+
"build:capabilities": "node ./scripts/build-capabilities.mjs",
|
|
31
|
+
"build:capabilities:check": "node ./scripts/build-capabilities.mjs --check",
|
|
32
|
+
"prepack": "node ./scripts/build-capabilities.mjs --check",
|
|
33
|
+
"pretest": "node ./scripts/build-capabilities.mjs --check"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"ps-list": "9.0.0",
|
|
37
|
+
"@tomflow/chatloop-extension": "0.4.11",
|
|
38
|
+
"@tomflow/chatloop-trace": "0.4.4"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -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();
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# @tomflow/chatloop-extension
|
|
2
|
+
|
|
3
|
+
Chrome MV3 companion for Chat Loop. **Browser Worker is the only Chrome Owner and
|
|
4
|
+
send authority**; Native Messaging is a guarded persistence/IPC boundary,
|
|
5
|
+
not a second browser executor.
|
|
6
|
+
|
|
7
|
+
## Runtime entrypoints
|
|
8
|
+
|
|
9
|
+
- `index.mjs`: npm SDK with `verifyOrphanOwnerIdle`, `extensionCliApi`,
|
|
10
|
+
`nativeHostApi` — the only three exported functions.
|
|
11
|
+
- `bin/cli.mjs`: the `chatloop-extension` CLI (`npx` after publishing).
|
|
12
|
+
- `bin/native-host.mjs`: private Chrome Native Messaging Host process.
|
|
13
|
+
- `extension/background.js`: MV3 Worker and unique Browser Owner.
|
|
14
|
+
- `extension/actions/*.js`: Action executors; browser APIs are not Node SDKs.
|
|
15
|
+
|
|
16
|
+
## API invocation logging
|
|
17
|
+
|
|
18
|
+
The public npm SDK, CLI and Native Host functions use a generated, bounded,
|
|
19
|
+
non-blocking API observation slice. The MV3 Worker's formal message dispatch
|
|
20
|
+
records only the allowlisted message type, not payloads or chat text. It
|
|
21
|
+
forwards a separate, best-effort Native observation into the **existing
|
|
22
|
+
Supervisor Trace** when available; an unavailable Native Host or Supervisor
|
|
23
|
+
can drop these observations but cannot change Owner or action receipts.
|
|
24
|
+
Remotely exposed Extension MCP calls are recorded independently by the Tools
|
|
25
|
+
Gateway's single API observation port. No second log service is created.
|
|
26
|
+
Logging cannot authorize sending, change Owner or retry an UNKNOWN action.
|
|
27
|
+
|
|
28
|
+
## Build-time Action capabilities
|
|
29
|
+
|
|
30
|
+
Each `capabilities/<id>.mjs` owns an Action's name, CLI route, page,
|
|
31
|
+
execution kind, result type and local deadline. No separate API catalog is
|
|
32
|
+
maintained. `npm run build:actions` generates both:
|
|
33
|
+
|
|
34
|
+
- `actions.generated.mjs` — Node CLI/Native SDK action catalog.
|
|
35
|
+
- `extension/loop/action-catalog.generated.js` — browser-only Eye map.
|
|
36
|
+
|
|
37
|
+
New **read-only Eye** actions can declare an additional `chat_*` name,
|
|
38
|
+
their own CLI route, and either the existing `text` or `dom` read mode.
|
|
39
|
+
The builder creates their isolated Action HTML, which uses the same
|
|
40
|
+
`actions/common.js` target/Owner/Native receipt checks and the shared
|
|
41
|
+
`actions/read-mode.js` executor. No existing Action or central CLI/Worker
|
|
42
|
+
dispatch switch needs modification. The builder refuses duplicate names,
|
|
43
|
+
privileged type changes, invalid read modes, missing assets and stale output.
|
|
44
|
+
|
|
45
|
+
**A declaration does not grant sending authority.** Start, Continue, Handoff,
|
|
46
|
+
Clean, Status, screenshot and reload keep their reviewed, explicit Worker
|
|
47
|
+
handlers and existing trust boundaries. New send/Owner/Native mutation
|
|
48
|
+
requires a separate authorized security review and implementation; it cannot
|
|
49
|
+
be enabled by dropping in a capability file. Browser read actions never
|
|
50
|
+
clear an unknown send result or adopt a different Chat Owner.
|
|
51
|
+
|
|
52
|
+
### Validation
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
npm run build:actions
|
|
56
|
+
npm run build:actions:check
|
|
57
|
+
npm test
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Workspace `npm run check` and npm `pretest`/`prepack` also verify generated
|
|
61
|
+
catalogs. `test/capability-composition.test.mjs` proves isolated addition and
|
|
62
|
+
removal of an Eye action and rejects privileged or duplicate declarations.
|
|
63
|
+
The package build and Chrome manifest versions must match.
|
|
64
|
+
|
|
65
|
+
## CLI
|
|
66
|
+
|
|
67
|
+
```text
|
|
68
|
+
Usage: chatloop-extension <command> [options]
|
|
69
|
+
Commands: capabilities, host, extension
|
|
70
|
+
Run: chatloop-extension <command> --help
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
Usage: chatloop-extension extension <command>
|
|
75
|
+
Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start
|
|
76
|
+
Run: chatloop-extension extension <command> --help
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
For the installed command list, run `chatloop-extension extension --help`.
|
|
80
|
+
|
|
81
|
+
`extension start` requires the real approved intent; `mode=adopt` does not
|
|
82
|
+
re-send. Continue/Handoff only register intents with one Turn token and never
|
|
83
|
+
silently send or repeat. Clean needs an exact verified tab ID, and Status
|
|
84
|
+
is read-only. IPC messages are one-shot and have durable identity checks.
|
|
85
|
+
|
|
86
|
+
This package's source version is read from its own `package.json`. Installed
|
|
87
|
+
Tools/Context consumers may pin a different Extension version; updating
|
|
88
|
+
their dependencies is a separate release task. Source tests do not prove
|
|
89
|
+
npm publication, Chrome reload, Native Host installation or Stage 03 E2E.
|
|
90
|
+
Inspect real installed versions, Owner and authoritative receipts first.
|
|
91
|
+
|
|
92
|
+
Product-level Extension/Context documents live in the source repository,
|
|
93
|
+
**not in this published npm package**. Its runtime API and security contract
|
|
94
|
+
are described above without requiring that repository.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// GENERATED by scripts/build-actions.mjs — do not edit.
|
|
2
|
+
import {capability as a0} from './capabilities/chat_text.mjs';
|
|
3
|
+
import {capability as a1} from './capabilities/chat_dom.mjs';
|
|
4
|
+
import {capability as a2} from './capabilities/chat_screenshot.mjs';
|
|
5
|
+
import {capability as a3} from './capabilities/reload.mjs';
|
|
6
|
+
import {capability as a4} from './capabilities/continue.mjs';
|
|
7
|
+
import {capability as a5} from './capabilities/handoff.mjs';
|
|
8
|
+
import {capability as a6} from './capabilities/clean.mjs';
|
|
9
|
+
import {capability as a7} from './capabilities/status.mjs';
|
|
10
|
+
import {capability as a8} from './capabilities/start.mjs';
|
|
11
|
+
export const actionCapabilities=Object.freeze([a0,a1,a2,a3,a4,a5,a6,a7,a8]);
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// CLI is owned by the Extension package; local-tools delegates, never implements actions.
|
|
3
|
+
import {existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync} from 'node:fs';
|
|
4
|
+
import {homedir} from 'node:os';
|
|
5
|
+
import {dirname,join,resolve} from 'node:path';
|
|
6
|
+
import {fileURLToPath} from 'node:url';
|
|
7
|
+
import {extensionCliApi} from '../index.mjs';
|
|
8
|
+
const cliContract=extensionCliApi();
|
|
9
|
+
const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId,openExtensionActionPage}=cliContract;
|
|
10
|
+
const actionById=new Map(actionCapabilities.map(cap=>[cap.id,cap]));
|
|
11
|
+
const actionHelp=actionCapabilities.map(cap=>cap.cli.join(' ')+
|
|
12
|
+
(cap.kind==='owner-clean'?' <tab-id>':'')).join(' | ');
|
|
13
|
+
const contract='chat-loop.extension-cli.v1';
|
|
14
|
+
const providerVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
15
|
+
const HELP={
|
|
16
|
+
'': 'Usage: chatloop-extension <command> [options]\nCommands: capabilities, host, extension\nRun: chatloop-extension <command> --help',
|
|
17
|
+
host: 'Usage: chatloop-extension host install <extension-id>\nRegisters the local Chrome Native Messaging Host (macOS).',
|
|
18
|
+
extension: 'Usage: chatloop-extension extension <command>\nCommands: '+actionHelp+'\nRun: chatloop-extension extension <command> --help',
|
|
19
|
+
'extension clean':'Usage: chatloop-extension extension clean <tab-id>\nClear only the verified ChatGPT composer. Never send or close a Chat.\nMachine Clean requires the exact tab id of a terminal Chat Loop Owner; popup Clean requires a user-selected ChatGPT tab.',
|
|
20
|
+
'extension continue':'Usage: chatloop-extension extension continue (JSON intent on stdin)\nSubmit next-turn text or query receipt; does not send directly.',
|
|
21
|
+
'extension handoff':'Usage: chatloop-extension extension handoff (JSON intent on stdin)\nRequest early handoff or query receipt; does not transfer directly.',
|
|
22
|
+
'extension status':'Usage: chatloop-extension extension status\nRead-only, verified active Web Chat status.',
|
|
23
|
+
'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart a new task with prompt, or use mode=adopt (no prompt) to bind the only R/P-approved existing Chat without sending.'
|
|
24
|
+
};
|
|
25
|
+
function helpFor(args){
|
|
26
|
+
if(args.length===1&&['-h','--help','help'].includes(args[0]))return HELP[''];
|
|
27
|
+
if(args.at(-1)==='--help'||args.at(-1)==='-h'){
|
|
28
|
+
const section=args.slice(0,-1).join(' ');
|
|
29
|
+
return HELP[section] || (section.startsWith('extension chat ')
|
|
30
|
+
? 'Usage: chatloop-extension '+section+'\nRead the current uniquely verified Chat Owner.'
|
|
31
|
+
: section==='extension reload'?'Usage: chatloop-extension extension reload\nRequest extension reload; final health is unverified.'
|
|
32
|
+
: null);
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
|
38
|
+
const emit=(event,command,fields={})=>process.stdout.write(JSON.stringify({contract,providerVersion,event,command,...fields})+'\n');
|
|
39
|
+
const quoted=s=>"'"+s.replaceAll("'","'\\''")+"'";
|
|
40
|
+
function installHost(extensionId) {
|
|
41
|
+
validateExtensionId(extensionId);
|
|
42
|
+
if(process.platform!=='darwin')throw Object.assign(Error('Native Host registration not verified on this OS'),{code:'HOST_INSTALL_UNSUPPORTED'});
|
|
43
|
+
const conf=configFile();privateDir(dirname(conf));
|
|
44
|
+
const node=process.execPath,script=fileURLToPath(new URL('./native-host.mjs',import.meta.url));
|
|
45
|
+
const runner=join(dirname(conf),'native-host.sh');
|
|
46
|
+
writeFileSync(runner,'#!/bin/sh\nexec '+quoted(node)+' '+quoted(script)+' "$@"\n',{mode:0o700});
|
|
47
|
+
chmodSync(runner,0o700);
|
|
48
|
+
const hostDir=join(homedir(),'Library','Application Support','Google','Chrome','NativeMessagingHosts');
|
|
49
|
+
mkdirSync(hostDir,{recursive:true});
|
|
50
|
+
const manifest={name:HOST_NAME,description:'Private Chat Loop Extension Native Messaging Host',
|
|
51
|
+
path:runner,type:'stdio',allowed_origins:['chrome-extension://'+extensionId+'/']};
|
|
52
|
+
const manifestPath=join(hostDir,HOST_NAME+'.json');
|
|
53
|
+
writeFileSync(manifestPath,JSON.stringify(manifest,null,2)+'\n',{mode:0o600});
|
|
54
|
+
writeFileSync(conf,JSON.stringify({extensionId,host:HOST_NAME,at:Date.now()},null,2)+'\n',{mode:0o600});
|
|
55
|
+
return {status:'INSTALLED',extensionId,manifestPath};
|
|
56
|
+
}
|
|
57
|
+
function configuration() {
|
|
58
|
+
if(!existsSync(configFile()))throw Object.assign(Error('Run host install <extension-id> first'),{code:'HOST_NOT_CONFIGURED'});
|
|
59
|
+
const config=JSON.parse(readFileSync(configFile(),'utf8'));
|
|
60
|
+
validateExtensionId(config.extensionId);
|
|
61
|
+
return config;
|
|
62
|
+
}
|
|
63
|
+
function openAction(url) {
|
|
64
|
+
return openExtensionActionPage(url);
|
|
65
|
+
}
|
|
66
|
+
async function executeAction(action,intent) {
|
|
67
|
+
if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
|
|
68
|
+
const config=configuration(),req=prepare(action,intent);
|
|
69
|
+
const descriptor=actionById.get(action);
|
|
70
|
+
const page=descriptor?.page;
|
|
71
|
+
if(!page)throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
|
|
72
|
+
const url='chrome-extension://'+config.extensionId+'/'+page+'?requestId='+req.id;
|
|
73
|
+
openAction(url);
|
|
74
|
+
const until=Date.now()+descriptor.waitMs;
|
|
75
|
+
while(Date.now()<until){
|
|
76
|
+
const result=readResult(req.id);
|
|
77
|
+
if(result){
|
|
78
|
+
if(result.status!=='OK')throw Object.assign(Error(result.code||'ACTION_FAILED'),{code:result.code||'ACTION_FAILED'});
|
|
79
|
+
if(!result.verified) return {...result,status:'ACCEPTED_UNVERIFIED'};
|
|
80
|
+
// The temp file is the canonical artifact. Returning small text is a CLI convenience.
|
|
81
|
+
if(descriptor.textResult){
|
|
82
|
+
const contents=readFileSync(result.path,'utf8');
|
|
83
|
+
return {...result,content:contents.length<=500000?contents:undefined,
|
|
84
|
+
truncated:contents.length>500000};
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
await wait(100);
|
|
89
|
+
}
|
|
90
|
+
throw Object.assign(Error('No verified Extension Action result; do not retry blindly'),{code:'RESULT_TIMEOUT'});
|
|
91
|
+
}
|
|
92
|
+
async function readIntent() {
|
|
93
|
+
// Only for model control tools. Read a bounded stdin payload; never embed text in URL/argv.
|
|
94
|
+
if(process.stdin.isTTY)throw Object.assign(Error('JSON intent required on stdin'),{code:'INVALID_INTENT'});
|
|
95
|
+
let body='';
|
|
96
|
+
process.stdin.setEncoding('utf8'); // JSON intent may span UTF-8 chunks.
|
|
97
|
+
for await(const chunk of process.stdin){
|
|
98
|
+
body+=chunk;
|
|
99
|
+
if(body.length>6000)throw Object.assign(Error('Model intent too large'),{code:'INVALID_INTENT'});
|
|
100
|
+
}
|
|
101
|
+
try {return JSON.parse(body);}catch{
|
|
102
|
+
throw Object.assign(Error('Invalid JSON intent'),{code:'INVALID_INTENT'});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function execute(argv) {
|
|
106
|
+
const cmd=argv.join(' ');
|
|
107
|
+
if(argv.length===0||cmd==='capabilities'){
|
|
108
|
+
return {implemented:['capabilities','host install <extension-id>',
|
|
109
|
+
...actionCapabilities.map(cap=>'extension '+cap.cli.join(' ')+
|
|
110
|
+
(cap.kind==='owner-clean'?' <tab-id>':
|
|
111
|
+
['owner-intent','owner-start'].includes(cap.kind)?' (JSON on stdin)':''))],
|
|
112
|
+
available:existsSync(configFile()),hostConfigured:existsSync(configFile())};
|
|
113
|
+
}
|
|
114
|
+
if(argv[0]==='host'&&argv[1]==='install'&&argv.length===3)return installHost(argv[2]);
|
|
115
|
+
const route=matchExtensionAction(actionCapabilities,argv);
|
|
116
|
+
if(route)return executeAction(route.id,route.needsIntent
|
|
117
|
+
?await readIntent():route.intent);
|
|
118
|
+
throw Object.assign(Error('Unknown command'),{code:'INVALID_ARGUMENT'});
|
|
119
|
+
}
|
|
120
|
+
const args=process.argv.slice(2),command=args.join(' ')||'capabilities';
|
|
121
|
+
const help=helpFor(args);
|
|
122
|
+
if(help!==null){
|
|
123
|
+
process.stdout.write(help+'\n');
|
|
124
|
+
}else{
|
|
125
|
+
emit('STARTED',command);
|
|
126
|
+
try{
|
|
127
|
+
const data=await execute(args);
|
|
128
|
+
emit('RESULT',command,{ok:true,value:data});
|
|
129
|
+
}catch(e){
|
|
130
|
+
emit('RESULT',command,{ok:false,error:{code:e.code||'UNKNOWN_RESULT',message:e.message}});
|
|
131
|
+
process.exitCode=1;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// After the CLI reply is produced, allow bounded observation delivery.
|
|
135
|
+
// This never changes its result or retries its business side effect.
|
|
136
|
+
const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
|
|
137
|
+
if(audit?.status!=='OK'){
|
|
138
|
+
// Sanitized counters only; the already-emitted RESULT is authoritative.
|
|
139
|
+
process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
|
|
140
|
+
component:'extension.cli',...audit})+'\n');
|
|
141
|
+
}
|