@tomflow/chatloop-tools 0.4.33 → 0.9.0
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 +117 -127
- package/bin/cli.mjs +48 -38
- package/bin/supervisor.mjs +4 -0
- package/index.mjs +238 -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 +12 -1
- package/lib/trace-observation.mjs +118 -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 -1615
- 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
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
import {readFileSync} from 'node:fs';
|
|
2
|
-
export const CONTEXT_PACKAGE_VERSION=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
3
|
-
// Opt-in ContextService MCP adapter. Never a browser Owner or an admin endpoint.
|
|
4
|
-
// Importing this module is safe on the published Node >=20 legacy runtime.
|
|
5
|
-
const ID='^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$';
|
|
6
|
-
const scopeError=code=>Object.assign(new Error(code),{code});
|
|
7
|
-
// A grant is an atomic permission statement, not a bag of best-effort tokens.
|
|
8
|
-
// Do not silently drop malformed entries or normalize duplicate grants.
|
|
9
|
-
// Reused by the SDK CLI, Context Core, MCP Gateway, and Native binding.
|
|
10
|
-
export function parseContextAllowedProjects(raw){
|
|
11
|
-
if(typeof raw!=='string'||raw.trim()==='')
|
|
12
|
-
throw scopeError('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
|
|
13
|
-
const entries=raw.split(',').map(x=>x.trim());
|
|
14
|
-
if(entries.some(x=>!new RegExp(ID).test(x))||
|
|
15
|
-
new Set(entries).size!==entries.length)
|
|
16
|
-
throw scopeError('CONTEXT_PROJECT_SCOPE_INVALID');
|
|
17
|
-
return new Set(entries);
|
|
18
|
-
}
|
|
19
|
-
const req=(operation,required,optional=[])=>({
|
|
20
|
-
type:'object',required:['operation',...required],additionalProperties:false,
|
|
21
|
-
properties:Object.fromEntries([['operation',{const:operation}],...required.map(k=>[k,fields[k]]),
|
|
22
|
-
...optional.map(k=>[k,fields[k]])])
|
|
23
|
-
});
|
|
24
|
-
const fields={
|
|
25
|
-
projectId:{type:'string',pattern:ID},taskId:{type:'string',pattern:ID},
|
|
26
|
-
materialId:{type:'string',pattern:ID},
|
|
27
|
-
title:{type:'string',minLength:1,maxLength:200},objective:{type:'string',maxLength:10000},
|
|
28
|
-
sharedContext:{type:'object'},context:{type:'object'},patch:{type:'object'},
|
|
29
|
-
expectedStoreEpoch:{type:'string',minLength:10,maxLength:64},
|
|
30
|
-
expectedProjectRevision:{type:'integer',minimum:1},
|
|
31
|
-
expectedTaskRevision:{type:'integer',minimum:1},
|
|
32
|
-
expectedBindingRevision:{type:'integer',minimum:0},
|
|
33
|
-
expectedApprovalRevision:{type:'integer',minimum:1},
|
|
34
|
-
writeRequestId:{type:'string',minLength:8,maxLength:128},
|
|
35
|
-
documentId:{type:'string',pattern:ID},version:{type:'integer',minimum:1},
|
|
36
|
-
kind:{enum:['R','P','INSTRUCTIONS','HISTORY','LEGACY_EVIDENCE','REFERENCE']},
|
|
37
|
-
body:{type:'string',minLength:1,maxLength:4194304},
|
|
38
|
-
provenance:{enum:['USER_AUTHORED','LEGACY_UNVERIFIED']},
|
|
39
|
-
sourcePath:{type:'string',minLength:1,maxLength:4096},
|
|
40
|
-
requirementRef:{type:'object',additionalProperties:false,
|
|
41
|
-
required:['documentId','version','contentHash'],
|
|
42
|
-
properties:{documentId:{type:'string',pattern:ID},version:{type:'integer',minimum:1},
|
|
43
|
-
contentHash:{type:'string',pattern:'^[a-f0-9]{64}$'}}},
|
|
44
|
-
contentHash:{type:'string',pattern:'^[a-f0-9]{64}$'},
|
|
45
|
-
limit:{type:'integer',minimum:1,maximum:100},
|
|
46
|
-
cursor:{type:'string',pattern:ID},
|
|
47
|
-
issueId:{type:'string',minLength:8,maxLength:64},
|
|
48
|
-
decision:{enum:['APPROVE','REJECT','REQUEST_CHANGE','CUSTOM','ACCEPT']},
|
|
49
|
-
outcome:{enum:['CANCELLED','FAILED','REJECTED']},
|
|
50
|
-
reason:{const:'REPAIR_SAME_SCOPE'},
|
|
51
|
-
purpose:{enum:['NEW_EXECUTION','REPAIR_SAME_SCOPE']},
|
|
52
|
-
impact:{enum:['NO_SCOPE_IMPACT','R_AND_P_REAPPROVAL']},
|
|
53
|
-
reviewEvidenceRef:{type:'string',minLength:8,maxLength:4096},
|
|
54
|
-
effectRef:{type:'string',minLength:1,maxLength:256},
|
|
55
|
-
resolutionEvidenceRef:{type:'string',minLength:8,maxLength:4096},
|
|
56
|
-
sourceRef:{type:'string',minLength:8,maxLength:256},
|
|
57
|
-
deliveryRef:{type:'string',minLength:8,maxLength:4096},
|
|
58
|
-
comment:{type:'string',maxLength:2000},
|
|
59
|
-
artifactId:{type:'string',minLength:8,maxLength:128},
|
|
60
|
-
locator:{type:'string',minLength:1,maxLength:4096},
|
|
61
|
-
role:{type:'string',pattern:'^[a-z][a-z0-9_-]{0,63}$'},
|
|
62
|
-
retention:{enum:['RETAINED','EXTERNAL','EPHEMERAL']},
|
|
63
|
-
sourceRole:{const:'user'},
|
|
64
|
-
userTurn:{type:'string',minLength:8,maxLength:256},
|
|
65
|
-
presentedAssistantRef:{type:'string',minLength:8,maxLength:256},
|
|
66
|
-
checkpointId:{type:'string',minLength:8,maxLength:64},
|
|
67
|
-
storeEpoch:{type:'string',minLength:10,maxLength:64},
|
|
68
|
-
maxBytes:{type:'integer',minimum:16384,maximum:262144},
|
|
69
|
-
runRef:{type:'string',minLength:8,maxLength:256},
|
|
70
|
-
runCredential:{type:'string',pattern:'^[0-9a-f]{64}$'},
|
|
71
|
-
evidenceRefs:{type:'array',maxItems:200,items:{type:'object'}},
|
|
72
|
-
unknownEffects:{type:'array',maxItems:200,items:{type:'object'}}
|
|
73
|
-
};
|
|
74
|
-
const w=['expectedStoreEpoch','writeRequestId'];
|
|
75
|
-
fields.group={type:'string',minLength:1,maxLength:64};
|
|
76
|
-
fields.methodId={type:'string',minLength:3,maxLength:128};
|
|
77
|
-
fields.workspaceRoots={type:'array',minItems:1,maxItems:16,items:{type:'string',maxLength:4096}};
|
|
78
|
-
|
|
79
|
-
const readDefs=[
|
|
80
|
-
['project.list',[],['limit','cursor']],['project.get',['projectId'],[]],
|
|
81
|
-
['project.authority',['projectId'],[]],
|
|
82
|
-
['project.registryAuthority',['projectId'],[]],
|
|
83
|
-
['project.material.list',['projectId'],[]],
|
|
84
|
-
['project.material.get',['projectId','materialId','version'],[]],
|
|
85
|
-
['task.list',['projectId'],['limit','cursor']],['task.get',['projectId','taskId'],[]],
|
|
86
|
-
['document.get',['projectId','taskId','documentId','version'],[]],
|
|
87
|
-
['document.list',['projectId','taskId'],[]],
|
|
88
|
-
['evidence.list',['projectId','taskId'],[]],
|
|
89
|
-
['context.history',['projectId','taskId'],[]],
|
|
90
|
-
['context.resume',['projectId','taskId','checkpointId'],['maxBytes']],
|
|
91
|
-
['context.request.status',['projectId','storeEpoch','writeRequestId'],[]]
|
|
92
|
-
];
|
|
93
|
-
const mutateDefs=[
|
|
94
|
-
['project.create',['projectId','title',...w],['sharedContext']],
|
|
95
|
-
['project.material.put',['projectId','materialId','version','kind','body',
|
|
96
|
-
'expectedProjectRevision',...w],['sourcePath','contentHash','provenance']],
|
|
97
|
-
['project.patch',['projectId','expectedProjectRevision','sharedContext',...w],[]],
|
|
98
|
-
['project.archive',['projectId','expectedProjectRevision',...w],[]],
|
|
99
|
-
['task.create',['projectId','taskId','title',...w],['objective','context']],
|
|
100
|
-
['task.archive',['projectId','taskId','expectedTaskRevision',...w],[]],
|
|
101
|
-
['task.reopen',['projectId','taskId','expectedTaskRevision','reason','userTurn',...w],[]],
|
|
102
|
-
['task.reviewProjectRules',['projectId','taskId','expectedTaskRevision',
|
|
103
|
-
'expectedProjectRevision','impact','reviewEvidenceRef',...w],[]],
|
|
104
|
-
['task.accept',['projectId','taskId','expectedTaskRevision','decision','userTurn',...w],['comment']],
|
|
105
|
-
['task.complete',['projectId','taskId','expectedTaskRevision','expectedBindingRevision',
|
|
106
|
-
'runRef','runCredential','deliveryRef',...w],[]],
|
|
107
|
-
['task.patch',['projectId','taskId','expectedTaskRevision','patch',...w],
|
|
108
|
-
['expectedBindingRevision','runRef','runCredential']],
|
|
109
|
-
['document.createDraft',['projectId','taskId','documentId','version','kind','body',
|
|
110
|
-
'expectedTaskRevision',...w],['requirementRef']],
|
|
111
|
-
['presentation.resolve',['projectId','taskId','issueId','outcome','sourceRef',
|
|
112
|
-
'expectedTaskRevision',...w],[]],
|
|
113
|
-
['document.prepareIssue',['projectId','taskId','documentId','version','contentHash',
|
|
114
|
-
'expectedTaskRevision',...w],[]],
|
|
115
|
-
['approval.observe',['projectId','taskId','issueId','decision','sourceRole','userTurn',
|
|
116
|
-
'presentedAssistantRef','expectedTaskRevision',...w],[]],
|
|
117
|
-
['approval.revoke',['projectId','taskId','expectedTaskRevision','expectedApprovalRevision',...w],[]],
|
|
118
|
-
['evidence.attach',['projectId','taskId','expectedTaskRevision','locator',
|
|
119
|
-
'role',...w],['contentHash','retention','expectedBindingRevision','runRef','runCredential']],
|
|
120
|
-
['evidence.detach',['projectId','taskId','expectedTaskRevision','artifactId',
|
|
121
|
-
...w],['expectedBindingRevision','runRef','runCredential']],
|
|
122
|
-
['start.reserve',['projectId','taskId','expectedTaskRevision',
|
|
123
|
-
'expectedApprovalRevision',...w],['purpose']],
|
|
124
|
-
['context.patch',['projectId','taskId','expectedTaskRevision','expectedBindingRevision',
|
|
125
|
-
'runRef','runCredential','patch',...w],[]],
|
|
126
|
-
['context.unknown.resolve',['projectId','taskId','expectedTaskRevision',
|
|
127
|
-
'expectedBindingRevision','runRef','runCredential','effectRef','resolutionEvidenceRef',...w],[]],
|
|
128
|
-
['context.checkpoint',['projectId','taskId','expectedTaskRevision','expectedBindingRevision',
|
|
129
|
-
'runRef','runCredential',...w],['evidenceRefs','unknownEffects']]
|
|
130
|
-
];
|
|
131
|
-
|
|
132
|
-
// This catalog is the single source for SDK, CLI and ChatGPT MCP descriptions.
|
|
133
|
-
export const CONTEXT_CONTRACT='chat-loop.context-sdk.v1';
|
|
134
|
-
readDefs.push(
|
|
135
|
-
['sdk.methods.list',[],['group']],
|
|
136
|
-
['sdk.methods.describe',['methodId'],[]],
|
|
137
|
-
['project.resolve',['workspaceRoots'],[]],
|
|
138
|
-
['project.open',['projectId'],[]],
|
|
139
|
-
['context.open',['projectId'],[]],
|
|
140
|
-
['task.open',['projectId','taskId'],[]]
|
|
141
|
-
);
|
|
142
|
-
const READ_DESC={
|
|
143
|
-
'sdk.methods.list':'Discover available SDK methods by group without reading project data.',
|
|
144
|
-
'sdk.methods.describe':'Read the exact input schema, semantics and failure conditions of one method.',
|
|
145
|
-
'project.resolve':'Find authorized projects matching confirmed workspace roots; never guesses identity.',
|
|
146
|
-
'project.open':'Open an authorized project summary, current instruction reference and task candidates.',
|
|
147
|
-
'context.open':'Open the level-one project Context summary without loading historical documents.',
|
|
148
|
-
'task.open':'Load one chosen task current state and versioned recovery references.',
|
|
149
|
-
'project.list':'List authorized Project identities. Use limit (1–100) and optional last-visible Project cursor for bounded pages; omit pagination arguments for the legacy array.',
|
|
150
|
-
'project.get':'Read the selected project identity and shared context.',
|
|
151
|
-
'project.authority':'Check whether a project is actually managed and writable.',
|
|
152
|
-
'project.registryAuthority':'Read the exact legacy Registry physical source authority; independent of business write eligibility.',
|
|
153
|
-
'project.material.list':'List versioned project materials without returning full bodies.',
|
|
154
|
-
'project.material.get':'Read exact reviewed project Instructions or historical material by version.',
|
|
155
|
-
'task.list':'List authorized tasks of a selected project; supply limit (1–100) and optional last-visible task cursor for bounded keyset pages. Without pagination arguments, returns the legacy array.',
|
|
156
|
-
'task.get':'Read exact task state, revisions, progress and blocker details.',
|
|
157
|
-
'document.get':'Read an immutable R/P document at a precise version.',
|
|
158
|
-
'document.list':'List versioned R/P documents of a task.',
|
|
159
|
-
'evidence.list':'List task evidence references and verification state.',
|
|
160
|
-
'context.history':'Read versioned history and receipts for a task.',
|
|
161
|
-
'context.resume':'Read one verified checkpoint snapshot; does not grant Browser Owner.',
|
|
162
|
-
'context.request.status':'Check an unknown write using its original durable writeRequestId.'
|
|
163
|
-
};
|
|
164
|
-
const WRITE_DESC={
|
|
165
|
-
'project.create':'Legacy unified-Store only: add a project to an initialized authorized Store; per-project databases require operator project init.',
|
|
166
|
-
'project.material.put':'Write one immutable project material version.',
|
|
167
|
-
'project.patch':'Change project context and explicit current Instructions reference with CAS.',
|
|
168
|
-
'project.archive':'Archive an authorized project after checking active tasks.',
|
|
169
|
-
'task.create':'Create a project-scoped task with an initial DRAFT state.',
|
|
170
|
-
'task.patch':'Patch permitted Task fields with revision and run-holder checks.',
|
|
171
|
-
'task.archive':'Archive an authorized task without bypassing active run restrictions.',
|
|
172
|
-
'task.reopen':'Reopen a delivered task only for authorized same-scope repair.',
|
|
173
|
-
'task.reviewProjectRules':'Adopt verified new project rules or require R/P reapproval.',
|
|
174
|
-
'task.accept':'Record actual user delivery acceptance decision.',
|
|
175
|
-
'task.complete':'Commit machine delivery outcome under current run-binding authorization.',
|
|
176
|
-
'document.createDraft':'Create immutable R/P draft version linked to a task.',
|
|
177
|
-
'document.prepareIssue':'Record intent to present a precise R/P version.',
|
|
178
|
-
'presentation.resolve':'Resolve an uncompleted R/P presentation attempt with evidence.',
|
|
179
|
-
'approval.observe':'Record soft evidence of a real user decision on a displayed R/P version.',
|
|
180
|
-
'approval.revoke':'Invalidate earlier approvals at the correct task revision.',
|
|
181
|
-
'evidence.attach':'Attach a verified external evidence reference to one task.',
|
|
182
|
-
'evidence.detach':'Detach a task evidence reference with CAS and permission checks.',
|
|
183
|
-
'start.reserve':'Reserve a short-lived start lease after both effective R/P approvals.',
|
|
184
|
-
'context.patch':'Write active-run progress under the current holder and revisions.',
|
|
185
|
-
'context.unknown.resolve':'Resolve a known unknown side effect only with matching evidence.',
|
|
186
|
-
'context.checkpoint':'Create a durable business checkpoint, not Browser Owner permission.'
|
|
187
|
-
};
|
|
188
|
-
const groupOf=op=>op.split('.')[0];
|
|
189
|
-
export const methodDefinitions=[
|
|
190
|
-
...readDefs.map(([id,required,optional])=>({id,group:groupOf(id),mode:'read',
|
|
191
|
-
description:READ_DESC[id]||'Read '+id.replaceAll('.',' ')+' from authorized Context.',
|
|
192
|
-
inputSchema:req(id,required,optional)})),
|
|
193
|
-
...mutateDefs.map(([id,required,optional])=>({id,group:groupOf(id),mode:'write',
|
|
194
|
-
description:WRITE_DESC[id]||'Write '+id.replaceAll('.',' ')+' to authorized Context.',
|
|
195
|
-
inputSchema:req(id,required,optional)}))
|
|
196
|
-
];
|
|
197
|
-
export const methodById=new Map(methodDefinitions.map(m=>[m.id,m]));
|
|
198
|
-
export function listMethods(group){
|
|
199
|
-
return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,methods:methodDefinitions
|
|
200
|
-
.filter(m=>!group||m.group===group)
|
|
201
|
-
.map(({id,group,mode,description})=>({methodId:id,group,mode,description}))};
|
|
202
|
-
}
|
|
203
|
-
export function describeMethod(methodId){
|
|
204
|
-
const m=methodById.get(methodId);
|
|
205
|
-
if(!m)throw Object.assign(new Error('METHOD_NOT_FOUND'),{code:'METHOD_NOT_FOUND'});
|
|
206
|
-
return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,methodId:m.id,group:m.group,mode:m.mode,
|
|
207
|
-
description:m.description,inputSchema:m.inputSchema,
|
|
208
|
-
outputContract:'JSON value, immutable hashes and explicit revision/authority where applicable',
|
|
209
|
-
errorContract:'typed error code; unknown write outcome requires original requestId receipt lookup'};
|
|
210
|
-
}
|
|
211
|
-
export const contextGatewayTools=[
|
|
212
|
-
{name:'chat_loop_context_get',
|
|
213
|
-
description:'Context SDK READ. First use sdk.methods.list, then sdk.methods.describe to discover authorized Project/Task/Document/Checkpoint operations; read project summary before expanding detail.',
|
|
214
|
-
inputSchema:{oneOf:readDefs.map(([id,required,optional])=>req(id,required,optional))},
|
|
215
|
-
annotations:{readOnlyHint:true}},
|
|
216
|
-
{name:'chat_loop_context_mutate',
|
|
217
|
-
description:'Context SDK WRITE. First inspect current version and method Schema; use expectedStoreEpoch, revisions and unique writeRequestId. No internal Native run controls.',
|
|
218
|
-
inputSchema:{oneOf:mutateDefs.map(([id,required,optional])=>req(id,required,optional))},
|
|
219
|
-
annotations:{readOnlyHint:false}}
|
|
220
|
-
];
|
|
221
|
-
export function validateContextCall(name,args){
|
|
222
|
-
const defs=name==='chat_loop_context_get'?readDefs:
|
|
223
|
-
name==='chat_loop_context_mutate'?mutateDefs:null;
|
|
224
|
-
if(!defs)throw Object.assign(new Error('UNKNOWN_TOOL'),{code:'UNKNOWN_TOOL'});
|
|
225
|
-
if(!args||typeof args!=='object'||Array.isArray(args))
|
|
226
|
-
throw Object.assign(new Error('INVALID_ARGUMENT'),{code:'INVALID_ARGUMENT'});
|
|
227
|
-
const op=defs.find(([id])=>id===args.operation);
|
|
228
|
-
if(!op)throw Object.assign(new Error('UNSUPPORTED_CONTEXT_OPERATION'),{code:'UNSUPPORTED_CONTEXT_OPERATION'});
|
|
229
|
-
const [,required,optional]=op;
|
|
230
|
-
if(required.some(k=>!Object.hasOwn(args,k))||
|
|
231
|
-
Object.keys(args).some(k=>k!=='operation'&&!required.includes(k)&&!optional.includes(k)))
|
|
232
|
-
throw Object.assign(new Error('INVALID_ARGUMENT'),{code:'INVALID_ARGUMENT'});
|
|
233
|
-
for(const key of [...required,...optional]){
|
|
234
|
-
if(Object.hasOwn(args,key)&&!matchesSchema(args[key],fields[key]))
|
|
235
|
-
throw Object.assign(new Error('INVALID_ARGUMENT'),{code:'INVALID_ARGUMENT'});
|
|
236
|
-
}
|
|
237
|
-
return methodById.get(args.operation);
|
|
238
|
-
}
|
|
239
|
-
// Validate nested and top-level inputs from the *same* schema exposed to MCP.
|
|
240
|
-
// Open-ended domain objects (patch/context/evidence) remain validated by Core.
|
|
241
|
-
function matchesSchema(value,spec){
|
|
242
|
-
if(spec.const!==undefined&&value!==spec.const)return false;
|
|
243
|
-
if(spec.enum&&!spec.enum.includes(value))return false;
|
|
244
|
-
if(spec.type==='string')
|
|
245
|
-
return typeof value==='string'&&value.length>=(spec.minLength??0)
|
|
246
|
-
&&value.length<=(spec.maxLength??Infinity)
|
|
247
|
-
&&(!spec.pattern||new RegExp(spec.pattern).test(value));
|
|
248
|
-
if(spec.type==='integer')
|
|
249
|
-
return Number.isSafeInteger(value)&&(spec.minimum===undefined||value>=spec.minimum)
|
|
250
|
-
&&(spec.maximum===undefined||value<=spec.maximum);
|
|
251
|
-
if(spec.type==='array')
|
|
252
|
-
return Array.isArray(value)&&value.length>=(spec.minItems??0)
|
|
253
|
-
&&value.length<=(spec.maxItems??Infinity)
|
|
254
|
-
&&value.every(x=>!spec.items||matchesSchema(x,spec.items));
|
|
255
|
-
if(spec.type==='object'){
|
|
256
|
-
if(!value||typeof value!=='object'||Array.isArray(value))return false;
|
|
257
|
-
if(spec.required?.some(k=>!Object.hasOwn(value,k)))return false;
|
|
258
|
-
if(spec.additionalProperties===false&&Object.keys(value).some(k=>!Object.hasOwn(spec.properties??{},k)))
|
|
259
|
-
return false;
|
|
260
|
-
return Object.entries(spec.properties??{}).every(([key,child])=>
|
|
261
|
-
!Object.hasOwn(value,key)||matchesSchema(value[key],child));
|
|
262
|
-
}
|
|
263
|
-
return true;
|
|
264
|
-
}
|
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
// Authorized Context SDK dispatcher. No Browser Owner and no internal run controls.
|
|
2
|
-
import {DatabaseSync} from 'node:sqlite';
|
|
3
|
-
import {existsSync,lstatSync,realpathSync} from 'node:fs';
|
|
4
|
-
import {homedir} from 'node:os';
|
|
5
|
-
import {isAbsolute,join,resolve} from 'node:path';
|
|
6
|
-
import {openContextProtocol} from './context-protocol.mjs';
|
|
7
|
-
import {CONTEXT_CONTRACT,validateContextCall,listMethods,describeMethod,
|
|
8
|
-
parseContextAllowedProjects} from './methods.mjs';
|
|
9
|
-
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
10
|
-
const fail=code=>Object.assign(new Error(code),{code});
|
|
11
|
-
export const contextRoot=()=>resolve(process.env.CHAT_LOOP_CONTEXT_ROOT||join(homedir(),'.chat-loop','context'));
|
|
12
|
-
export const allowedProjects=()=>parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
|
|
13
|
-
function projectDatabase(projectId){
|
|
14
|
-
if(!ID.test(projectId||''))throw fail('INVALID_SCOPE');
|
|
15
|
-
// Never silently keep routing to an old shared Store when a per-Project
|
|
16
|
-
// root was configured for cutover. Two data roots are not a valid mode.
|
|
17
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB&&process.env.CHAT_LOOP_CONTEXT_ROOT)
|
|
18
|
-
throw fail('CONTEXT_SOURCE_AMBIGUOUS');
|
|
19
|
-
const explicit=process.env.CHAT_LOOP_CONTEXT_DB;
|
|
20
|
-
if(explicit){
|
|
21
|
-
if(!isAbsolute(explicit))throw fail('CONTEXT_DB_NOT_ABSOLUTE');
|
|
22
|
-
return explicit; // Explicit legacy Store is a separately verified transition mode.
|
|
23
|
-
}
|
|
24
|
-
const root=contextRoot();
|
|
25
|
-
if(existsSync(root)){
|
|
26
|
-
const st=lstatSync(root);
|
|
27
|
-
if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077))throw fail('CONTEXT_ROOT_UNTRUSTED');
|
|
28
|
-
}
|
|
29
|
-
const dir=join(root,projectId);
|
|
30
|
-
if(existsSync(dir)){
|
|
31
|
-
const st=lstatSync(dir);
|
|
32
|
-
if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077))throw fail('PROJECT_DIRECTORY_UNTRUSTED');
|
|
33
|
-
}
|
|
34
|
-
return join(dir,'context.sqlite');
|
|
35
|
-
}
|
|
36
|
-
// Real read-only SQLite discovery: never initializes a missing database or turns WAL on.
|
|
37
|
-
function projectMeta(projectId){
|
|
38
|
-
const file=projectDatabase(projectId);
|
|
39
|
-
if(!existsSync(file))return null;
|
|
40
|
-
const st=lstatSync(file);
|
|
41
|
-
if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077))throw fail('STORE_FILE_UNTRUSTED');
|
|
42
|
-
const db=new DatabaseSync(file,{readOnly:true,timeout:3500});
|
|
43
|
-
try{
|
|
44
|
-
db.exec('PRAGMA query_only=ON');
|
|
45
|
-
if(!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'").get())
|
|
46
|
-
throw fail('STORE_SCHEMA_UNKNOWN');
|
|
47
|
-
const schema=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
|
|
48
|
-
if(schema!=='6')throw fail('STORE_SCHEMA_MISMATCH');
|
|
49
|
-
const r=db.prepare('SELECT project_id,title,project_revision,shared_context_json,archived FROM projects WHERE project_id=?').get(projectId);
|
|
50
|
-
if(!r)throw fail('PROJECT_IDENTITY_MISMATCH');
|
|
51
|
-
if(!process.env.CHAT_LOOP_CONTEXT_DB){
|
|
52
|
-
const others=db.prepare('SELECT project_id FROM projects WHERE project_id<>?').all(projectId);
|
|
53
|
-
if(others.length)throw fail('PROJECT_IDENTITY_MISMATCH');
|
|
54
|
-
}
|
|
55
|
-
const sharedContext=JSON.parse(r.shared_context_json);
|
|
56
|
-
return {projectId,title:r.title,projectRevision:r.project_revision,
|
|
57
|
-
sharedContext,workspaceRefs:Array.isArray(sharedContext.workspaceRefs)?
|
|
58
|
-
sharedContext.workspaceRefs:[],archived:!!r.archived};
|
|
59
|
-
}finally{db.close()}
|
|
60
|
-
}
|
|
61
|
-
// Shared, security-reviewed Project identity resolver for the private Native
|
|
62
|
-
// adapter. It must never create a Store or resolve a different Project's DB.
|
|
63
|
-
export function resolveVerifiedProjectDatabase(projectId){
|
|
64
|
-
if(!projectMeta(projectId))throw fail('STORE_MISSING');
|
|
65
|
-
return projectDatabase(projectId);
|
|
66
|
-
}
|
|
67
|
-
function resolveProjects(a,allowed){
|
|
68
|
-
if(!Array.isArray(a.workspaceRoots)||!a.workspaceRoots.length)throw fail('WORKSPACE_REQUIRED');
|
|
69
|
-
const roots=a.workspaceRoots.map(s=>{
|
|
70
|
-
if(typeof s!=='string'||!isAbsolute(s))throw fail('WORKSPACE_INVALID');
|
|
71
|
-
try{return realpathSync(s)}catch{throw fail('WORKSPACE_UNVERIFIED')}
|
|
72
|
-
});
|
|
73
|
-
const matches=[];
|
|
74
|
-
for(const id of allowed){
|
|
75
|
-
const meta=projectMeta(id);
|
|
76
|
-
if(!meta||meta.archived)continue;
|
|
77
|
-
const registered=meta.workspaceRefs.filter(x=>typeof x==='string'&&isAbsolute(x));
|
|
78
|
-
const resolved=registered.map(x=>{try{return realpathSync(x)}catch{return null}});
|
|
79
|
-
const matchingRoots=roots.filter(x=>resolved.includes(x));
|
|
80
|
-
if(matchingRoots.length){
|
|
81
|
-
const {sharedContext,...publicMeta}=meta;
|
|
82
|
-
matches.push({...publicMeta,matchingRoots});
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return {candidates:matches,ambiguous:matches.length!==1};
|
|
86
|
-
}
|
|
87
|
-
async function runContextOperation(args){
|
|
88
|
-
const methodId=args?.operation;
|
|
89
|
-
const method=validateContextCall('chat_loop_context_get',args);
|
|
90
|
-
if(method.id==='sdk.methods.list')return listMethods(args.group);
|
|
91
|
-
if(method.id==='sdk.methods.describe')return describeMethod(args.methodId);
|
|
92
|
-
const allowed=allowedProjects();
|
|
93
|
-
if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
|
|
94
|
-
if(methodId==='project.resolve')return resolveProjects(args,allowed);
|
|
95
|
-
if(methodId==='project.list'){
|
|
96
|
-
if(!process.env.CHAT_LOOP_CONTEXT_DB){
|
|
97
|
-
const publicProject=meta=>({
|
|
98
|
-
projectId:meta.projectId,title:meta.title,
|
|
99
|
-
projectRevision:meta.projectRevision,sharedContext:meta.sharedContext,
|
|
100
|
-
archived:meta.archived
|
|
101
|
-
});
|
|
102
|
-
// Preserve the old array shape unless the caller explicitly pages.
|
|
103
|
-
if(args.limit===undefined&&args.cursor===undefined)
|
|
104
|
-
return [...allowed].map(projectMeta).filter(Boolean).map(publicProject);
|
|
105
|
-
const limit=args.limit??30,cursor=args.cursor??null;
|
|
106
|
-
if(cursor!==null&&(!allowed.has(cursor)||!projectMeta(cursor)))
|
|
107
|
-
throw fail('PROJECT_CURSOR_INVALID');
|
|
108
|
-
const entries=[];
|
|
109
|
-
for(const id of [...allowed].sort()){
|
|
110
|
-
if(cursor!==null&&id<=cursor)continue;
|
|
111
|
-
const meta=projectMeta(id);
|
|
112
|
-
if(!meta)continue;
|
|
113
|
-
entries.push(publicProject(meta));
|
|
114
|
-
if(entries.length>limit)break;
|
|
115
|
-
}
|
|
116
|
-
const incomplete=entries.length>limit,projects=entries.slice(0,limit);
|
|
117
|
-
return {projects,incomplete,nextCursor:incomplete?projects.at(-1).projectId:null,limit};
|
|
118
|
-
}
|
|
119
|
-
const db=openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
|
|
120
|
-
readOnly:true,principalId:'private-mcp',
|
|
121
|
-
authorizeData:(_type,projectId)=>allowed.has(projectId),
|
|
122
|
-
authorizeInternal:()=>false});
|
|
123
|
-
try{return db.projectList({limit:args.limit,cursor:args.cursor})}finally{db.close()}
|
|
124
|
-
}
|
|
125
|
-
if(args.projectId!==undefined&&!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
126
|
-
if(!args.projectId)throw fail('PROJECT_ID_REQUIRED');
|
|
127
|
-
return executeDb(args,allowed,method.mode);
|
|
128
|
-
}
|
|
129
|
-
export async function dispatchContextCall(name,args){
|
|
130
|
-
const method=validateContextCall(name,args);
|
|
131
|
-
if(method.mode==='read')return runContextOperation(args);
|
|
132
|
-
const allowed=allowedProjects();
|
|
133
|
-
if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
|
|
134
|
-
if(!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
135
|
-
// A model-authorized business patch is NOT permission to bind a new workspace.
|
|
136
|
-
// Keep binding violations distinct even when generic project creation is disabled.
|
|
137
|
-
if(method.id==='project.patch' && Object.hasOwn(args.sharedContext,'workspaceRefs'))
|
|
138
|
-
throw fail('WORKSPACE_REBIND_REQUIRES_OPERATOR');
|
|
139
|
-
if(method.id==='project.create' && args.sharedContext &&
|
|
140
|
-
Object.hasOwn(args.sharedContext,'workspaceRefs'))
|
|
141
|
-
throw fail('WORKSPACE_BIND_REQUIRES_OPERATOR');
|
|
142
|
-
// Per-project SQLite is created ONLY via the local operator's validated init.
|
|
143
|
-
// Never allow a generic MCP mutation to add a second Project into that file.
|
|
144
|
-
if(method.id==='project.create'&&!process.env.CHAT_LOOP_CONTEXT_DB)
|
|
145
|
-
throw fail('PROJECT_CREATE_OPERATOR_ONLY');
|
|
146
|
-
return executeDb(args,allowed,method.mode);
|
|
147
|
-
}
|
|
148
|
-
function executeDb(a,allowed,mode){
|
|
149
|
-
if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
|
|
150
|
-
// A read or ordinary write must never create a project directory or SQLite.
|
|
151
|
-
// Only explicit operator project init may create a previously absent Store.
|
|
152
|
-
const file=projectDatabase(a.projectId);
|
|
153
|
-
if(!existsSync(file))throw fail('STORE_MISSING');
|
|
154
|
-
// project.list/resolve already verify this; ordinary get/mutate must too.
|
|
155
|
-
// Read-only identity check precedes any writable SQLite open and rules out
|
|
156
|
-
// a copied/renamed or multi-Project database under the wrong directory.
|
|
157
|
-
if(!process.env.CHAT_LOOP_CONTEXT_DB)projectMeta(a.projectId);
|
|
158
|
-
const db=openContextProtocol(file,{
|
|
159
|
-
readOnly:mode==='read',
|
|
160
|
-
principalId:'private-mcp',authorizeData:(_type,projectId)=>allowed.has(projectId),
|
|
161
|
-
authorizeInternal:()=>false
|
|
162
|
-
});
|
|
163
|
-
try{
|
|
164
|
-
if(mode==='write'&&a.operation!=='project.create'){
|
|
165
|
-
if(!db.projectBusinessAuthority(a.projectId).writable)
|
|
166
|
-
throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
|
|
167
|
-
}
|
|
168
|
-
if(a.operation==='project.open'||a.operation==='context.open'){
|
|
169
|
-
const {project,authority,tasks,taskCount,storeEpoch}=db.projectSnapshot(a.projectId);
|
|
170
|
-
return {contractVersion:CONTEXT_CONTRACT,project,authority,storeEpoch,
|
|
171
|
-
taskCount,tasks,incomplete:taskCount>tasks.length,
|
|
172
|
-
nextOperation:taskCount>tasks.length?'task.list':null};
|
|
173
|
-
}
|
|
174
|
-
if(a.operation==='task.open'){
|
|
175
|
-
const {project,authority,task,storeEpoch}=db.projectSnapshot(a.projectId,a.taskId);
|
|
176
|
-
return {contractVersion:CONTEXT_CONTRACT,task,storeEpoch,
|
|
177
|
-
projectRevision:project.projectRevision,authority};
|
|
178
|
-
}
|
|
179
|
-
switch(a.operation){
|
|
180
|
-
case 'project.list':return db.projectList();
|
|
181
|
-
case 'project.get':return db.projectGet(a.projectId);
|
|
182
|
-
case 'project.authority':return db.projectBusinessAuthority(a.projectId);
|
|
183
|
-
case 'project.registryAuthority':return db.registryAuthority(a.projectId);
|
|
184
|
-
case 'project.material.list':return db.projectMaterialList(a.projectId);
|
|
185
|
-
case 'project.material.get':return db.projectMaterialGet(a.projectId,a.materialId,a.version);
|
|
186
|
-
case 'project.material.put':return db.projectMaterialPut(a);
|
|
187
|
-
case 'project.create':return db.projectCreate(a);
|
|
188
|
-
case 'project.patch':return db.projectPatch(a);
|
|
189
|
-
case 'project.archive':return db.projectArchive(a);
|
|
190
|
-
case 'task.list':return db.taskList(a.projectId,{limit:a.limit,cursor:a.cursor});
|
|
191
|
-
case 'task.get':return db.get(a.projectId,a.taskId);
|
|
192
|
-
case 'task.create':return db.taskCreate(a);
|
|
193
|
-
case 'task.patch':return db.taskPatch(a);
|
|
194
|
-
case 'task.archive':return db.taskArchive(a);
|
|
195
|
-
case 'task.reopen':return db.taskReopen(a);
|
|
196
|
-
case 'task.reviewProjectRules':return db.taskReviewProjectRules(a);
|
|
197
|
-
case 'task.accept':return db.taskAccept(a);
|
|
198
|
-
case 'task.complete':return db.taskComplete(a);
|
|
199
|
-
case 'document.get':return db.documentGet(a.projectId,a.taskId,a.documentId,a.version);
|
|
200
|
-
case 'document.list':return db.documentList(a.projectId,a.taskId);
|
|
201
|
-
case 'document.createDraft':return db.documentCreate(a);
|
|
202
|
-
case 'document.prepareIssue':return db.prepareIssue(a);
|
|
203
|
-
case 'presentation.resolve':return db.presentationResolve(a);
|
|
204
|
-
case 'approval.observe':return db.observeApproval(a);
|
|
205
|
-
case 'approval.revoke':return db.revokeApproval(a);
|
|
206
|
-
case 'start.reserve':return db.reserve(a);
|
|
207
|
-
case 'evidence.list':return db.evidenceList(a.projectId,a.taskId);
|
|
208
|
-
case 'evidence.attach':return db.evidenceAttach(a);
|
|
209
|
-
case 'evidence.detach':return db.evidenceDetach(a);
|
|
210
|
-
case 'context.history':return db.history(a.projectId,a.taskId);
|
|
211
|
-
case 'context.patch':return db.patch(a);
|
|
212
|
-
case 'context.unknown.resolve':return db.resolveUnknownEffect(a);
|
|
213
|
-
case 'context.checkpoint':return db.checkpoint(a);
|
|
214
|
-
case 'context.resume':return db.resume(a.projectId,a.taskId,a.checkpointId,a.maxBytes);
|
|
215
|
-
case 'context.request.status':return db.requestStatus(a);
|
|
216
|
-
default:throw Error('UNSUPPORTED_CONTEXT_OPERATION');
|
|
217
|
-
}
|
|
218
|
-
}finally{db.close()}
|
|
219
|
-
}
|