@tomflow/chatloop-tools 0.4.34 → 0.9.4
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/README.md +120 -127
- package/bin/cli.mjs +48 -38
- package/bin/supervisor.mjs +4 -0
- package/index.mjs +269 -0
- package/lib/adapters/fixture.mjs +3 -2
- package/lib/adapters/index.mjs +14 -5
- package/lib/adapters/mcp-child.mjs +29 -7
- package/lib/adapters/tunnel.mjs +25 -7
- package/lib/api-aspect.mjs +190 -0
- package/lib/cli-command-router.mjs +34 -0
- package/lib/context-control-auth.mjs +12 -1
- package/lib/context-control-run.mjs +17 -79
- package/lib/context-gateway.mjs +108 -15
- package/lib/control.mjs +3 -2
- package/lib/extension-cli-contract.mjs +22 -0
- package/lib/extension-proxy.mjs +48 -19
- package/lib/gateway.mjs +46 -176
- package/lib/mcp-tool-router.mjs +60 -0
- package/lib/release-owner-preflight.mjs +41 -0
- package/lib/release.mjs +94 -49
- package/lib/{supervisor.mjs → supervisor-runtime.mjs} +143 -80
- package/lib/trace-gateway.mjs +25 -7
- package/lib/trace-observation.mjs +123 -0
- package/lib/tunnel.mjs +17 -29
- package/package.json +20 -14
- package/providers/context.mjs +20 -0
- package/providers/desktop.mjs +80 -0
- package/{lib/extension-contract.mjs → providers/extension.mjs} +36 -0
- package/providers/runtime.mjs +32 -0
- package/providers/trace.mjs +25 -0
- package/providers.generated.mjs +8 -0
- package/scripts/build-providers.mjs +69 -0
- package/lib/context-cli.mjs +0 -2
- package/lib/context-migration.mjs +0 -2
- package/lib/context-protocol.mjs +0 -2
- package/lib/task-registry-managed.mjs +0 -38
- package/lib/task-registry.mjs +0 -221
- package/node_modules/@tomflow/chatloop-context/README.md +0 -271
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -273
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -301
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -272
- package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +0 -1617
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -264
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -219
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -455
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -159
- package/node_modules/@tomflow/chatloop-context/package.json +0 -21
- package/node_modules/@tomflow/chatloop-trace/README.md +0 -13
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -259
- package/node_modules/@tomflow/chatloop-trace/package.json +0 -11
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Owned Desktop Commander/fixture MCP tools: one allowlist, one call path.
|
|
2
|
+
import {readFileSync} from 'node:fs';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
const allowedDesktopTools=new Set([
|
|
5
|
+
'get_config','read_file','read_multiple_files','write_file','write_pdf',
|
|
6
|
+
'create_directory','list_directory','move_file','start_search',
|
|
7
|
+
'get_more_search_results','stop_search','list_searches','get_file_info',
|
|
8
|
+
'edit_block','start_process','read_process_output','interact_with_process',
|
|
9
|
+
'force_terminate','list_sessions','list_processes','kill_process'
|
|
10
|
+
]);
|
|
11
|
+
// The vendor descriptions contain long onboarding instructions and even
|
|
12
|
+
// directives to start unnecessary REPLs. Keep the exact vendor inputSchema,
|
|
13
|
+
// but describe the supported API succinctly at this single MCP boundary.
|
|
14
|
+
const desktopDescriptions={
|
|
15
|
+
read_file:'Read a file or URL (text, images, PDF, DOCX, spreadsheets). Use absolute path and optional offset/length to limit output; respect allowed directories.',
|
|
16
|
+
read_multiple_files:'Read several authorized absolute file paths in one request. Returns each result with its source path.',
|
|
17
|
+
write_file:'Create/replace or append to a file. mode is rewrite or append; prefer small chunks. Check the existing file and user authorization before overwriting.',
|
|
18
|
+
write_pdf:'Create or modify a PDF with markdown/operations. Use a new outputPath for modifications; never silently overwrite the original.',
|
|
19
|
+
list_directory:'List files and folders under an authorized absolute path; depth limits recursion and output.',
|
|
20
|
+
start_search:'Search filenames (searchType=files) or file contents (searchType=content) from an authorized root. Returns a session for paginated results.',
|
|
21
|
+
get_more_search_results:'Get additional results from an existing search session using sessionId and pagination.',
|
|
22
|
+
edit_block:'Apply an exact targeted edit; pass file_path and old_string/new_string for text, or range/content for spreadsheets. Refuse ambiguous replacements.',
|
|
23
|
+
start_process:'Run CLI commands through the MCP process, never launch macOS Terminal/iTerm apps. A PID is not completion; read its output.',
|
|
24
|
+
read_process_output:'Read output of an already-started PID with optional offset/length/timeout_ms. Does not start the command again.',
|
|
25
|
+
interact_with_process:'Send input to an existing interactive PID and obtain output. Do not repeat commands with unknown side effects.',
|
|
26
|
+
get_config:'Read Desktop Commander configuration/allowed directories for diagnosis; does not grant or change permissions.'
|
|
27
|
+
};
|
|
28
|
+
const desktopTools=JSON.parse(readFileSync(
|
|
29
|
+
new URL('../lib/desktop-commander-tools.json',import.meta.url),'utf8'))
|
|
30
|
+
.filter(t=>allowedDesktopTools.has(t.name))
|
|
31
|
+
.map(t=>({...t,description:desktopDescriptions[t.name]||t.description.trim()}));
|
|
32
|
+
|
|
33
|
+
const fixtureTool={name:'ping',description:'Inert lifecycle test health check',
|
|
34
|
+
inputSchema:{type:'object',properties:{},additionalProperties:false}};
|
|
35
|
+
const toolsFor=t=>t.kind==='mcp-child'?desktopTools:t.kind==='fixture'?[fixtureTool]:[];
|
|
36
|
+
const prefix=id=>id.replaceAll('-','_')+'__';
|
|
37
|
+
const fail=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
38
|
+
export const provider=Object.freeze({
|
|
39
|
+
id:'desktop',order:0,
|
|
40
|
+
names:[...desktopTools.map(t=>'desktop_commander__'+t.name),
|
|
41
|
+
'mock_alpha__ping','mock_beta__ping'],
|
|
42
|
+
create({control,release,terminal}){
|
|
43
|
+
const registry=control.registry;
|
|
44
|
+
const active=()=>registry().filter(t=>t.enabled).flatMap(t=>
|
|
45
|
+
toolsFor(t).map(({_meta,...tool})=>({
|
|
46
|
+
tool:{...tool,name:prefix(t.id)+tool.name},
|
|
47
|
+
toolId:t.id,localName:tool.name
|
|
48
|
+
})));
|
|
49
|
+
return Object.freeze({
|
|
50
|
+
tools:()=>active().map(x=>x.tool),
|
|
51
|
+
async call(name,args){
|
|
52
|
+
const route=active().find(x=>x.tool.name===name);
|
|
53
|
+
if(!route)return fail('UNKNOWN_TOOL');
|
|
54
|
+
// No-argument MCP calls are equivalent to an empty arguments object.
|
|
55
|
+
args=args??{};
|
|
56
|
+
if(typeof args!=='object'||Array.isArray(args))
|
|
57
|
+
return fail('INVALID_ARGUMENT');
|
|
58
|
+
if(route.toolId==='desktop-commander'&&
|
|
59
|
+
terminal.isGraphicalTerminalCommand(route.localName,args))
|
|
60
|
+
return fail('GUI_TERMINAL_LAUNCH_PROHIBITED');
|
|
61
|
+
if(!process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR&&
|
|
62
|
+
!process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&release.runtimeNeedsUpgrade())
|
|
63
|
+
return fail('RUNTIME_UPGRADE_REQUIRED');
|
|
64
|
+
try{
|
|
65
|
+
const deadlineMs=control.toolCallDeadlineMs(args),requestId=randomUUID();
|
|
66
|
+
const res=await control.talk({contract:control.CONTRACT,requestId,
|
|
67
|
+
action:'call',scope:'tool',toolId:route.toolId,
|
|
68
|
+
name:route.localName,args,deadlineMs},deadlineMs+2000);
|
|
69
|
+
if(res.status!=='OK')return fail(res.error?.code==='TIMEOUT'
|
|
70
|
+
?'OPERATION_UNCONFIRMED:'+requestId
|
|
71
|
+
:res.error?.code||'TOOL_UNAVAILABLE');
|
|
72
|
+
return res.result;
|
|
73
|
+
}catch(e){
|
|
74
|
+
return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
|
|
75
|
+
?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
});
|
|
@@ -104,3 +104,39 @@ export function validExtensionArgs(name,args){
|
|
|
104
104
|
}
|
|
105
105
|
return true;
|
|
106
106
|
}
|
|
107
|
+
|
|
108
|
+
// Extension remains the sole Browser Owner. This provider delegates to its
|
|
109
|
+
// pinned CLI and never sends a ChatGPT message from the Gateway itself.
|
|
110
|
+
|
|
111
|
+
const fail=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
112
|
+
const prefix='chat_loop_extension__';
|
|
113
|
+
export const provider=Object.freeze({
|
|
114
|
+
id:'extension',order:1,
|
|
115
|
+
names:extensionTools.map(tool=>prefix+tool.name),
|
|
116
|
+
create({extension}){
|
|
117
|
+
const enabled=()=>process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1';
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
tools:()=>enabled()?extensionTools.map(tool=>({...tool,name:prefix+tool.name})):[],
|
|
120
|
+
async call(name,args){
|
|
121
|
+
if(!enabled())return fail('UNKNOWN_TOOL');
|
|
122
|
+
const original=name.slice(prefix.length);
|
|
123
|
+
if(!extensionTools.some(tool=>tool.name===original))
|
|
124
|
+
return fail('UNKNOWN_TOOL');
|
|
125
|
+
try{
|
|
126
|
+
const result=await extension.forwardExtensionAction(original,args??{});
|
|
127
|
+
// Telemetry is an independent best-effort side channel. A slow or
|
|
128
|
+
// failing observer must never replace a verified Extension receipt
|
|
129
|
+
// or hold up the caller after the action has already completed.
|
|
130
|
+
setImmediate(()=>{
|
|
131
|
+
try{
|
|
132
|
+
void Promise.resolve(extension.observeExtensionResult(
|
|
133
|
+
original,args??{},result)).catch(()=>{});
|
|
134
|
+
}catch{/* Logging never changes action status or retry safety. */}
|
|
135
|
+
});
|
|
136
|
+
return result;
|
|
137
|
+
}catch(e){return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
|
|
138
|
+
?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE')}
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Receipt lookup is a read-only lookup of the original request; never replay.
|
|
2
|
+
import {randomUUID} from 'node:crypto';
|
|
3
|
+
const requestIdPattern=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
4
|
+
const tool={name:'chat_loop_runtime__operation_status',
|
|
5
|
+
description:'Read a previously timed-out MCP request receipt without replaying its side effects.',
|
|
6
|
+
inputSchema:{type:'object',required:['requestId'],additionalProperties:false,
|
|
7
|
+
properties:{requestId:{type:'string',pattern:requestIdPattern.source}}}};
|
|
8
|
+
const fail=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
9
|
+
export const provider=Object.freeze({
|
|
10
|
+
id:'runtime',order:2,names:[tool.name],
|
|
11
|
+
create({control}){
|
|
12
|
+
return Object.freeze({
|
|
13
|
+
tools:()=>[tool],
|
|
14
|
+
async call(name,args){
|
|
15
|
+
if(name!==tool.name)return fail('UNKNOWN_TOOL');
|
|
16
|
+
if(!args||typeof args!=='object'||Array.isArray(args)
|
|
17
|
+
||Object.keys(args).length!==1
|
|
18
|
+
||typeof args.requestId!=='string'
|
|
19
|
+
||!requestIdPattern.test(args.requestId))return fail('INVALID_ARGUMENT');
|
|
20
|
+
try{
|
|
21
|
+
const res=await control.talk({
|
|
22
|
+
contract:control.CONTRACT,action:'receipt',requestId:randomUUID(),
|
|
23
|
+
targetRequestId:args.requestId},4000);
|
|
24
|
+
return res.status==='OK'&&res.operation
|
|
25
|
+
?{content:[{type:'text',text:JSON.stringify({operation:res.operation})}]}
|
|
26
|
+
:fail('RECEIPT_UNAVAILABLE');
|
|
27
|
+
}catch(e){return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
|
|
28
|
+
?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE')}
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Trace observes but never grants business write rights or Browser Owner.
|
|
2
|
+
import {traceDiagnoseTool,traceStageTool} from '../lib/trace-gateway.mjs';
|
|
3
|
+
const names=[traceDiagnoseTool.name,traceStageTool.name];
|
|
4
|
+
const fail=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
5
|
+
export const provider=Object.freeze({
|
|
6
|
+
id:'trace',order:4,names,
|
|
7
|
+
create({trace}){
|
|
8
|
+
return Object.freeze({
|
|
9
|
+
tools:()=>trace.traceGatewayEnabled()?[traceDiagnoseTool,traceStageTool]:[],
|
|
10
|
+
async call(name,args){
|
|
11
|
+
if(!trace.traceGatewayEnabled())return fail('UNKNOWN_TOOL');
|
|
12
|
+
try{
|
|
13
|
+
const result=name===traceStageTool.name
|
|
14
|
+
?await trace.runTraceStage(args)
|
|
15
|
+
:name===traceDiagnoseTool.name
|
|
16
|
+
?await trace.runTraceDiagnose(args)
|
|
17
|
+
:null;
|
|
18
|
+
if(result===null)return fail('UNKNOWN_TOOL');
|
|
19
|
+
return {content:[{type:'text',text:JSON.stringify(result)}]};
|
|
20
|
+
}catch(e){return fail(e.code||(
|
|
21
|
+
name===traceStageTool.name?'TRACE_STAGE_FAILED':'TRACE_DIAGNOSE_FAILED'))}
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// GENERATED by scripts/build-providers.mjs — never edit.
|
|
2
|
+
import {provider as p0} from './providers/desktop.mjs';
|
|
3
|
+
import {provider as p1} from './providers/extension.mjs';
|
|
4
|
+
import {provider as p2} from './providers/runtime.mjs';
|
|
5
|
+
import {provider as p3} from './providers/context.mjs';
|
|
6
|
+
import {provider as p4} from './providers/trace.mjs';
|
|
7
|
+
export const providerDefinitions=Object.freeze([p0,p1,p2,p3,p4]);
|
|
8
|
+
export const providerFiles=Object.freeze(["providers/desktop.mjs","providers/extension.mjs","providers/runtime.mjs","providers/context.mjs","providers/trace.mjs"]);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Deterministic build-time provider assembly. Never runtime-directory-scan.
|
|
2
|
+
import {readFileSync,readdirSync,writeFileSync} from 'node:fs';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {dirname,join,resolve} from 'node:path';
|
|
5
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
6
|
+
import {RESERVED_CLI_COMMANDS} from '../lib/cli-command-router.mjs';
|
|
7
|
+
const root=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
8
|
+
const fail=code=>Object.assign(Error(code),{code});
|
|
9
|
+
export async function compileMcpProviders(source=join(root,'providers')){
|
|
10
|
+
const files=readdirSync(source).filter(n=>n.endsWith('.mjs')).sort();
|
|
11
|
+
if(!files.length)throw fail('MCP_PROVIDERS_EMPTY');
|
|
12
|
+
const ids=new Set(),names=new Set(),commands=new Set(RESERVED_CLI_COMMANDS),records=[];
|
|
13
|
+
for(const name of files){
|
|
14
|
+
if(!/^[a-z][a-z0-9-]*\.mjs$/.test(name))throw fail('MCP_PROVIDER_FILENAME_INVALID');
|
|
15
|
+
const file=resolve(source,name);
|
|
16
|
+
const hash=createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
17
|
+
const {provider:p}=await import(pathToFileURL(file).href+'?sha256='+hash);
|
|
18
|
+
if(!p||p.id!==name.slice(0,-4)||ids.has(p.id)
|
|
19
|
+
||!Array.isArray(p.names)||!Array.isArray(p.commands??[])
|
|
20
|
+
||(p.names.length>0&&typeof p.create!=='function')
|
|
21
|
+
||(p.create!==undefined&&typeof p.create!=='function')
|
|
22
|
+
||!(p.names.length||(p.commands??[]).length)
|
|
23
|
+
||p.order!==undefined&&(!Number.isSafeInteger(p.order)||p.order<0))
|
|
24
|
+
throw fail('MCP_PROVIDER_DECLARATION_INVALID');
|
|
25
|
+
ids.add(p.id);
|
|
26
|
+
for(const tool of p.names){
|
|
27
|
+
if(typeof tool!=='string'||!/^[a-z][a-z0-9_]*$/.test(tool)
|
|
28
|
+
||names.has(tool))throw fail('MCP_PROVIDER_TOOL_CONFLICT');
|
|
29
|
+
names.add(tool);
|
|
30
|
+
}
|
|
31
|
+
for(const cmd of p.commands??[]){
|
|
32
|
+
if(!cmd||typeof cmd.name!=='string'
|
|
33
|
+
||!/^[a-z][a-z0-9-]*$/.test(cmd.name)||commands.has(cmd.name)
|
|
34
|
+
||typeof cmd.help!=='string'||!cmd.help.length
|
|
35
|
+
||typeof cmd.run!=='function')throw fail('CLI_COMMAND_CONFLICT');
|
|
36
|
+
commands.add(cmd.name);
|
|
37
|
+
}
|
|
38
|
+
records.push({name,id:p.id,order:p.order});
|
|
39
|
+
}
|
|
40
|
+
const existing=records.filter(x=>x.order!==undefined).map(x=>x.order);
|
|
41
|
+
if(new Set(existing).size!==existing.length)
|
|
42
|
+
throw fail('MCP_PROVIDER_ORDER_CONFLICT');
|
|
43
|
+
let next=Math.max(-1,...existing)+1;
|
|
44
|
+
for(const item of records.filter(x=>x.order===undefined).sort((a,b)=>a.name.localeCompare(b.name)))
|
|
45
|
+
item.order=next++;
|
|
46
|
+
records.sort((a,b)=>a.order-b.order);
|
|
47
|
+
const imports=records.map((item,i)=>
|
|
48
|
+
"import {provider as p"+i+"} from './providers/"+item.name+"';").join('\n');
|
|
49
|
+
return '// GENERATED by scripts/build-providers.mjs — never edit.\n'+imports+
|
|
50
|
+
'\nexport const providerDefinitions=Object.freeze(['+
|
|
51
|
+
records.map((_,i)=>'p'+i).join(',')+']);\n'+
|
|
52
|
+
'export const providerFiles=Object.freeze('+JSON.stringify(
|
|
53
|
+
records.map(item=>'providers/'+item.name))+');\n';
|
|
54
|
+
}
|
|
55
|
+
async function main(){
|
|
56
|
+
const expected=await compileMcpProviders();
|
|
57
|
+
const path=join(root,'providers.generated.mjs');
|
|
58
|
+
if(process.argv.includes('--check')){
|
|
59
|
+
let actual;try{actual=readFileSync(path,'utf8')}catch{}
|
|
60
|
+
if(actual!==expected)throw fail('MCP_PROVIDER_BUILD_STALE');
|
|
61
|
+
if(process.env.npm_lifecycle_event!=='prepack')
|
|
62
|
+
console.log('MCP_PROVIDERS_CURRENT');
|
|
63
|
+
}else{
|
|
64
|
+
writeFileSync(path,expected);
|
|
65
|
+
console.log('MCP_PROVIDERS_BUILT');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
|
|
69
|
+
await main();
|
package/lib/context-cli.mjs
DELETED
package/lib/context-protocol.mjs
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
// Legacy MCP registry compatibility: once the exact physical Registry source
|
|
2
|
-
// is MANAGED_RW, it can never create a second JSON write authority.
|
|
3
|
-
// New edits go through ContextService with epoch + idempotent CAS.
|
|
4
|
-
import {existsSync,lstatSync,readFileSync} from 'node:fs';
|
|
5
|
-
import {createHash} from 'node:crypto';
|
|
6
|
-
const error=code=>Object.assign(new Error(code),{code});
|
|
7
|
-
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
8
|
-
const state=(path,expectedHash)=>{
|
|
9
|
-
try{
|
|
10
|
-
const st=lstatSync(path);
|
|
11
|
-
if(!st.isFile()||st.isSymbolicLink()||st.size>512*1024)
|
|
12
|
-
return 'UNVERIFIED';
|
|
13
|
-
const actual=sha(readFileSync(path));
|
|
14
|
-
return actual===expectedHash?'PRESENT':'CHANGED';
|
|
15
|
-
}catch(e){return e.code==='ENOENT'?'MISSING':'UNVERIFIED'}
|
|
16
|
-
};
|
|
17
|
-
const snapshot=task=>{
|
|
18
|
-
const c=task.currentContext;
|
|
19
|
-
return {taskId:task.taskId,projectId:task.projectId,title:c.title,
|
|
20
|
-
taskDocPath:c.taskDocPath,parentTaskId:c.parentTaskId??null,
|
|
21
|
-
revision:task.taskRevision,taskDocumentState:state(c.taskDocPath,c.taskDocumentHash),
|
|
22
|
-
documents:(c.legacyDocuments??[]).map(x=>({...x,sourceStatus:'UNVERIFIED'})),
|
|
23
|
-
migrated:true,sourceOfTruth:'ContextService'};
|
|
24
|
-
};
|
|
25
|
-
export function managedTaskRegistry(db,args){
|
|
26
|
-
if(args.action==='list'){
|
|
27
|
-
return {tasks:db.taskList(args.projectId).filter(t=>t.currentContext?.taskDocPath)
|
|
28
|
-
.map(snapshot)};
|
|
29
|
-
}
|
|
30
|
-
if(args.action==='get'){
|
|
31
|
-
const t=db.get(args.projectId,args.taskId);
|
|
32
|
-
if(!t.currentContext?.taskDocPath)throw error('REGISTRY_NOT_MIGRATED_TASK');
|
|
33
|
-
return snapshot(t);
|
|
34
|
-
}
|
|
35
|
-
// Old calls lack expectedStoreEpoch, writeRequestId, and scoped run cred.
|
|
36
|
-
// A successful JSON write would create two authorities. Never do it.
|
|
37
|
-
throw error('REGISTRY_MANAGED_USE_CONTEXT_MUTATE');
|
|
38
|
-
}
|
package/lib/task-registry.mjs
DELETED
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
// Task identity + document references only. No workflow/approval/Chrome state.
|
|
2
|
-
import {randomUUID} from 'node:crypto';
|
|
3
|
-
import {closeSync,existsSync,openSync,readFileSync,realpathSync,lstatSync,mkdirSync,
|
|
4
|
-
renameSync,unlinkSync,writeFileSync} from 'node:fs';
|
|
5
|
-
import {relative,isAbsolute,join,sep} from 'node:path';
|
|
6
|
-
import {ensurePrivateDir,paths} from './control.mjs';
|
|
7
|
-
|
|
8
|
-
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
9
|
-
const goodId=value=>ID.test(value||'')&&!['__proto__','constructor','prototype'].includes(value);
|
|
10
|
-
const ROLE=/^[a-z][a-z0-9_-]{0,63}$/;
|
|
11
|
-
const error=code=>Object.assign(new Error(code),{code});
|
|
12
|
-
const validText=(v,max=200)=>typeof v==='string'&&v.length>0&&v.length<=max
|
|
13
|
-
&&v.trim()===v&&!/[\x00-\x1f]/.test(v);
|
|
14
|
-
const rootOf=p=>{
|
|
15
|
-
if(typeof p!=='string'||!isAbsolute(p))throw error('INVALID_PROJECT_ROOT');
|
|
16
|
-
const st=lstatSync(p);
|
|
17
|
-
if(!st.isDirectory()||st.isSymbolicLink())throw error('INVALID_PROJECT_ROOT');
|
|
18
|
-
return realpathSync(p);
|
|
19
|
-
};
|
|
20
|
-
const authorized=(roots,p)=>{
|
|
21
|
-
if(typeof p!=='string'||!isAbsolute(p)||p.length>4096||/[\x00-\x1f]/.test(p))
|
|
22
|
-
throw error('INVALID_DOCUMENT_PATH');
|
|
23
|
-
let st,real;
|
|
24
|
-
try{st=lstatSync(p);real=realpathSync(p);}catch{throw error('DOCUMENT_MISSING');}
|
|
25
|
-
if(!st.isFile()||st.isSymbolicLink())throw error('DOCUMENT_UNTRUSTED');
|
|
26
|
-
if(!roots.some(root=>{
|
|
27
|
-
const rel=relative(root,real);
|
|
28
|
-
return rel!==''&&rel!=='..'&&!rel.startsWith('..'+sep)&&!isAbsolute(rel);
|
|
29
|
-
}))throw error('DOCUMENT_OUTSIDE_PROJECT');
|
|
30
|
-
return real;
|
|
31
|
-
};
|
|
32
|
-
const taskDoc=(roots,path,taskId)=>{
|
|
33
|
-
const real=authorized(roots,path),st=lstatSync(real);
|
|
34
|
-
if(st.size>512*1024)throw error('TASK_DOCUMENT_TOO_LARGE');
|
|
35
|
-
const text=readFileSync(real,'utf8');
|
|
36
|
-
const ids=[...text.matchAll(/^\s*(?:[-*]\s*)?taskId\s*[::]\s*["'\x60]?([a-zA-Z0-9][a-zA-Z0-9._-]*)/gmi)].map(m=>m[1]);
|
|
37
|
-
if(ids.length!==1||ids[0]!==taskId)throw error('TASK_DOCUMENT_ID_MISMATCH');
|
|
38
|
-
return real;
|
|
39
|
-
};
|
|
40
|
-
const filePath=()=>join(paths().dir,'task-registry.v1.json');
|
|
41
|
-
const initial=()=>({schemaVersion:1,projects:Object.create(null)});
|
|
42
|
-
const ownedFile=file=>{
|
|
43
|
-
const st=lstatSync(file);
|
|
44
|
-
if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
|
|
45
|
-
||process.platform!=='win32'&&(st.mode&0o077))throw error('REGISTRY_UNTRUSTED');
|
|
46
|
-
if(st.size>4*1024*1024)throw error('REGISTRY_TOO_LARGE');
|
|
47
|
-
};
|
|
48
|
-
function load(){
|
|
49
|
-
ensurePrivateDir();
|
|
50
|
-
const file=filePath();
|
|
51
|
-
if(!existsSync(file))return initial();
|
|
52
|
-
ownedFile(file);
|
|
53
|
-
let state;
|
|
54
|
-
try{state=JSON.parse(readFileSync(file,'utf8'));}catch{throw error('REGISTRY_CORRUPT');}
|
|
55
|
-
if(state?.schemaVersion!==1||!state.projects||Array.isArray(state.projects)
|
|
56
|
-
||typeof state.projects!=='object')throw error('REGISTRY_SCHEMA_MISMATCH');
|
|
57
|
-
return state;
|
|
58
|
-
}
|
|
59
|
-
function withMutation(fn){
|
|
60
|
-
ensurePrivateDir();
|
|
61
|
-
const file=filePath(),lock=file+'.lock';
|
|
62
|
-
let fd;
|
|
63
|
-
try{fd=openSync(lock,'wx',0o600);}
|
|
64
|
-
catch{throw error('REGISTRY_BUSY');}
|
|
65
|
-
try{
|
|
66
|
-
const state=load();
|
|
67
|
-
const result=fn(state);
|
|
68
|
-
if(result.changed){
|
|
69
|
-
const temp=file+'.'+randomUUID()+'.tmp';
|
|
70
|
-
try{
|
|
71
|
-
writeFileSync(temp,JSON.stringify(state,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
72
|
-
renameSync(temp,file);
|
|
73
|
-
}finally{if(existsSync(temp))unlinkSync(temp);}
|
|
74
|
-
}
|
|
75
|
-
return result.value;
|
|
76
|
-
}finally{closeSync(fd);unlinkSync(lock);}
|
|
77
|
-
}
|
|
78
|
-
const fields=(args,allow)=>{
|
|
79
|
-
if(!args||typeof args!=='object'||Array.isArray(args)
|
|
80
|
-
||Object.keys(args).some(k=>!allow.includes(k)))throw error('INVALID_ARGUMENT');
|
|
81
|
-
};
|
|
82
|
-
const project=(state,projectId)=>{
|
|
83
|
-
if(!goodId(projectId))throw error('INVALID_PROJECT_ID');
|
|
84
|
-
const value=Object.hasOwn(state.projects,projectId)?state.projects[projectId]:null;
|
|
85
|
-
if(!value)throw error('PROJECT_NOT_REGISTERED');
|
|
86
|
-
return value;
|
|
87
|
-
};
|
|
88
|
-
const task=(state,projectId,taskId)=>{
|
|
89
|
-
if(!goodId(taskId))throw error('INVALID_TASK_ID');
|
|
90
|
-
const p=project(state,projectId);
|
|
91
|
-
if(!Object.hasOwn(p.tasks,taskId))throw error('TASK_NOT_FOUND');
|
|
92
|
-
return {p,t:p.tasks[taskId]};
|
|
93
|
-
};
|
|
94
|
-
const roots=p=>[p.projectRoot,...(p.contextRoot?[p.contextRoot]:[])];
|
|
95
|
-
const pathState=(r,path,id=null)=>{
|
|
96
|
-
try{id?taskDoc(r,path,id):authorized(r,path);return 'PRESENT';}
|
|
97
|
-
catch(e){return e.code==='DOCUMENT_MISSING'?'MISSING':'UNVERIFIED';}
|
|
98
|
-
};
|
|
99
|
-
const snapshot=(p,t)=>({
|
|
100
|
-
taskId:t.taskId,projectId:t.projectId,title:t.title,
|
|
101
|
-
taskDocPath:t.taskDocPath,parentTaskId:t.parentTaskId,revision:t.revision,
|
|
102
|
-
taskDocumentState:pathState(roots(p),t.taskDocPath,t.taskId),
|
|
103
|
-
documents:t.documents.map(d=>({...d,sourceStatus:pathState(roots(p),d.sourcePath)}))
|
|
104
|
-
});
|
|
105
|
-
export const taskRegistryTool={
|
|
106
|
-
name:'chat_loop_task_registry',
|
|
107
|
-
description:'Register and locate explicitly scoped long-lived tasks and their real files; no workflow/status/approval or browser authority. Actions: register/get/list/link/unlink/update. Register requires task document containing exact taskId; update/unlink require revision.',
|
|
108
|
-
inputSchema:{type:'object',additionalProperties:false,
|
|
109
|
-
properties:{
|
|
110
|
-
action:{type:'string',enum:['register','get','list','link','unlink','update']},
|
|
111
|
-
projectId:{type:'string',minLength:1,maxLength:128},
|
|
112
|
-
taskId:{type:'string',minLength:1,maxLength:128},
|
|
113
|
-
projectRoot:{type:'string',description:'Explicit verified absolute source root, only on register'},
|
|
114
|
-
contextRoot:{type:'string',description:'Optional independent authorized Context directory, only on first registration'},
|
|
115
|
-
title:{type:'string',maxLength:200},
|
|
116
|
-
taskDocPath:{type:'string'},
|
|
117
|
-
parentTaskId:{type:'string'},
|
|
118
|
-
sourcePath:{type:'string'},
|
|
119
|
-
role:{type:'string',description:'Document kind (e.g. requirement, plan, test, report)'},
|
|
120
|
-
versionRef:{type:'string',description:'Optional source version pointer, not approval'},
|
|
121
|
-
expectedRevision:{type:'integer',minimum:1}
|
|
122
|
-
},required:['action','projectId']}
|
|
123
|
-
};
|
|
124
|
-
export function runTaskRegistry(args){
|
|
125
|
-
const action=args?.action;
|
|
126
|
-
if(!['register','get','list','link','unlink','update'].includes(action))
|
|
127
|
-
throw error('INVALID_ACTION');
|
|
128
|
-
if(action==='register'){
|
|
129
|
-
fields(args,['action','projectId','taskId','projectRoot','contextRoot','title','taskDocPath','parentTaskId']);
|
|
130
|
-
if(!goodId(args.projectId)||!goodId(args.taskId)
|
|
131
|
-
||!validText(args.title)||!validText(args.taskDocPath,4096))
|
|
132
|
-
throw error('INVALID_ARGUMENT');
|
|
133
|
-
const base=rootOf(args.projectRoot),ctx=args.contextRoot===undefined?null:rootOf(args.contextRoot);
|
|
134
|
-
const doc=taskDoc([base,...(ctx?[ctx]:[])],args.taskDocPath,args.taskId);
|
|
135
|
-
return withMutation(state=>{
|
|
136
|
-
let p=Object.hasOwn(state.projects,args.projectId)?state.projects[args.projectId]:null;
|
|
137
|
-
if(p&&(p.projectRoot!==base||p.contextRoot!==ctx))throw error('PROJECT_BINDING_CONFLICT');
|
|
138
|
-
if(!p){
|
|
139
|
-
p={projectRoot:base,contextRoot:ctx,tasks:Object.create(null)};
|
|
140
|
-
state.projects[args.projectId]=p;
|
|
141
|
-
}
|
|
142
|
-
const parent=args.parentTaskId??null;
|
|
143
|
-
if(parent!==null){
|
|
144
|
-
if(!goodId(parent)||parent===args.taskId)throw error('INVALID_PARENT');
|
|
145
|
-
if(!Object.hasOwn(p.tasks,parent))throw error('PARENT_NOT_FOUND');
|
|
146
|
-
}
|
|
147
|
-
const existing=Object.hasOwn(p.tasks,args.taskId)?p.tasks[args.taskId]:null;
|
|
148
|
-
if(existing){
|
|
149
|
-
if(existing.taskDocPath!==doc||existing.title!==args.title||existing.parentTaskId!==parent)
|
|
150
|
-
throw error('TASK_ID_CONFLICT');
|
|
151
|
-
return {changed:false,value:snapshot(p,existing)};
|
|
152
|
-
}
|
|
153
|
-
const entry={projectId:args.projectId,taskId:args.taskId,title:args.title,
|
|
154
|
-
taskDocPath:doc,parentTaskId:parent,revision:1,documents:[]};
|
|
155
|
-
p.tasks[args.taskId]=entry;
|
|
156
|
-
return {changed:true,value:snapshot(p,entry)};
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
if(action==='list'){
|
|
160
|
-
fields(args,['action','projectId']);
|
|
161
|
-
const p=project(load(),args.projectId);
|
|
162
|
-
return {tasks:Object.values(p.tasks).map(t=>snapshot(p,t))};
|
|
163
|
-
}
|
|
164
|
-
if(action==='get'){
|
|
165
|
-
fields(args,['action','projectId','taskId']);
|
|
166
|
-
const {p,t}=task(load(),args.projectId,args.taskId);
|
|
167
|
-
return snapshot(p,t);
|
|
168
|
-
}
|
|
169
|
-
if(action==='link'||action==='unlink'){
|
|
170
|
-
fields(args,['action','projectId','taskId','sourcePath','role',
|
|
171
|
-
...(action==='link'?['versionRef']:['expectedRevision'])]);
|
|
172
|
-
if(!validText(args.sourcePath,4096)||!ROLE.test(args.role??'related')
|
|
173
|
-
||action==='link'&&args.versionRef!==undefined&&!validText(args.versionRef,128))
|
|
174
|
-
throw error('INVALID_ARGUMENT');
|
|
175
|
-
return withMutation(state=>{
|
|
176
|
-
const {p,t}=task(state,args.projectId,args.taskId),role=args.role??'related';
|
|
177
|
-
let real;
|
|
178
|
-
if(action==='link')real=authorized(roots(p),args.sourcePath);
|
|
179
|
-
else{
|
|
180
|
-
// A removed/moved source is still detachable by its previously registered path.
|
|
181
|
-
if(typeof args.sourcePath!=='string'||!isAbsolute(args.sourcePath))throw error('INVALID_DOCUMENT_PATH');
|
|
182
|
-
real=args.sourcePath;
|
|
183
|
-
}
|
|
184
|
-
const ix=t.documents.findIndex(d=>d.sourcePath===real&&d.role===role);
|
|
185
|
-
if(action==='link'){
|
|
186
|
-
const versionRef=args.versionRef??null;
|
|
187
|
-
if(ix>=0){
|
|
188
|
-
if(t.documents[ix].versionRef!==versionRef)throw error('DOCUMENT_REF_CONFLICT');
|
|
189
|
-
return {changed:false,value:snapshot(p,t)};
|
|
190
|
-
}
|
|
191
|
-
t.documents.push({sourcePath:real,role,versionRef});
|
|
192
|
-
}else{
|
|
193
|
-
if(!Number.isSafeInteger(args.expectedRevision)||args.expectedRevision!==t.revision)
|
|
194
|
-
throw error('REVISION_CONFLICT');
|
|
195
|
-
if(ix<0)throw error('DOCUMENT_REF_NOT_FOUND');
|
|
196
|
-
t.documents.splice(ix,1);
|
|
197
|
-
}
|
|
198
|
-
t.revision++;
|
|
199
|
-
return {changed:true,value:snapshot(p,t)};
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
fields(args,['action','projectId','taskId','expectedRevision','title','taskDocPath']);
|
|
203
|
-
if(!Number.isSafeInteger(args.expectedRevision)
|
|
204
|
-
||args.title===undefined&&args.taskDocPath===undefined
|
|
205
|
-
||args.title!==undefined&&!validText(args.title)
|
|
206
|
-
||args.taskDocPath!==undefined&&!validText(args.taskDocPath,4096))
|
|
207
|
-
throw error('INVALID_ARGUMENT');
|
|
208
|
-
return withMutation(state=>{
|
|
209
|
-
const {p,t}=task(state,args.projectId,args.taskId);
|
|
210
|
-
if(t.revision!==args.expectedRevision)throw error('REVISION_CONFLICT');
|
|
211
|
-
const path=args.taskDocPath===undefined?t.taskDocPath
|
|
212
|
-
:taskDoc(roots(p),args.taskDocPath,t.taskId);
|
|
213
|
-
const title=args.title??t.title;
|
|
214
|
-
if(t.taskDocPath===path&&t.title===title)
|
|
215
|
-
return {changed:false,value:snapshot(p,t)};
|
|
216
|
-
t.taskDocPath=path;
|
|
217
|
-
t.title=title;
|
|
218
|
-
t.revision++;
|
|
219
|
-
return {changed:true,value:snapshot(p,t)};
|
|
220
|
-
});
|
|
221
|
-
}
|