@tomflow/chatloop-context 0.1.5 → 0.6.1
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 +240 -271
- package/bin/cli.mjs +25 -270
- package/capabilities/approval.mjs +151 -0
- package/capabilities/context.mjs +376 -0
- package/capabilities/document.mjs +266 -0
- package/capabilities/evidence.mjs +134 -0
- package/capabilities/presentation.mjs +82 -0
- package/capabilities/project.mjs +349 -0
- package/capabilities/sdk.mjs +72 -0
- package/capabilities/start.mjs +73 -0
- package/capabilities/task.mjs +507 -0
- package/capabilities.generated.mjs +11 -0
- package/docs/interfaces.md +182 -0
- package/docs/operator-and-migration.md +277 -0
- package/index.mjs +236 -0
- package/lib/api-aspect.mjs +190 -0
- package/lib/api-log.mjs +161 -0
- package/lib/approval-policy.mjs +24 -0
- package/lib/capability-catalog.generated.json +1989 -0
- package/lib/capability-router.mjs +67 -0
- package/lib/cli-commands.mjs +280 -0
- package/lib/context-cli.mjs +16 -19
- package/lib/context-migration.mjs +17 -9
- package/lib/core/context.mjs +115 -0
- package/lib/core/evidence.mjs +51 -0
- package/lib/core/health.mjs +55 -0
- package/lib/core/migration.mjs +262 -0
- package/lib/core/project.mjs +246 -0
- package/lib/core/review.mjs +147 -0
- package/lib/core/run.mjs +343 -0
- package/lib/core/store.mjs +391 -0
- package/lib/core/task.mjs +166 -0
- package/lib/line-review.mjs +13 -0
- package/lib/methods.mjs +49 -202
- package/lib/operations.mjs +33 -145
- package/lib/orphan-operator.mjs +17 -51
- package/lib/process-inventory.mjs +20 -0
- package/lib/project-branch.mjs +312 -0
- package/lib/project-diagnostic.mjs +26 -328
- package/lib/project-guards.mjs +19 -0
- package/lib/project-store.mjs +115 -0
- package/lib/trusted-run.mjs +86 -0
- package/lib/workspace-operator.mjs +12 -2
- package/package.json +32 -14
- package/scripts/build-capabilities.mjs +114 -0
- package/lib/context-protocol.mjs +0 -1687
package/index.mjs
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// The ONLY JavaScript package entry. Roles are explicit; importing it does
|
|
2
|
+
// not open a Store, authorize a Principal, or grant an execution capability.
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {capabilities} from './capabilities.generated.mjs';
|
|
5
|
+
import {createCapabilityRouter} from './lib/capability-router.mjs';
|
|
6
|
+
import {auditFunction,auditMethods,subscribeContextApiLog,
|
|
7
|
+
configureApiLogCorrelation} from './lib/api-log.mjs';
|
|
8
|
+
import {currentApiTrace,withApiTraceParent} from './lib/api-aspect.mjs';
|
|
9
|
+
configureApiLogCorrelation({current:currentApiTrace,withParent:withApiTraceParent});
|
|
10
|
+
export {subscribeContextApiLog};
|
|
11
|
+
import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,methodById,methodDefinitions,
|
|
12
|
+
contextGatewayTools,validateContextCall,parseContextAllowedProjects,
|
|
13
|
+
listMethods,describeMethod} from './lib/methods.mjs';
|
|
14
|
+
|
|
15
|
+
export {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION};
|
|
16
|
+
|
|
17
|
+
// Public MCP adapter contract: metadata, validation, and the npm-installed
|
|
18
|
+
// CLI command. The adapter cannot select a private module path itself.
|
|
19
|
+
export const contextGateway=auditMethods(Object.freeze({
|
|
20
|
+
tools:contextGatewayTools,
|
|
21
|
+
validate:validateContextCall,
|
|
22
|
+
allowedProjects:parseContextAllowedProjects,
|
|
23
|
+
cliPath:fileURLToPath(new URL('./bin/cli.mjs',import.meta.url))
|
|
24
|
+
}),{
|
|
25
|
+
validate:([name,args])=>({api:'gateway.validate',surface:'gateway',mode:'read',
|
|
26
|
+
projectRef:args?.projectId,taskRef:args?.taskId}),
|
|
27
|
+
allowedProjects:()=>({api:'gateway.allowed_projects',surface:'gateway',mode:'read'})
|
|
28
|
+
});
|
|
29
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
30
|
+
const runtimeRequired=()=>{
|
|
31
|
+
if(Number(process.versions.node.split('.')[0])<24)
|
|
32
|
+
throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// Two public package entrypoints, one SDK composition root here.
|
|
36
|
+
// Private modules only declare typed named capabilities; they never import one
|
|
37
|
+
// another, nor reverse-import this facade (which would create ESM cycles).
|
|
38
|
+
// Lazy tiers keep privileged operator code out of ordinary business requests.
|
|
39
|
+
let sdkPromise,operatorPromise,trustedPromise;
|
|
40
|
+
function sdkRuntime(){
|
|
41
|
+
if(!sdkPromise)sdkPromise=(async()=>{
|
|
42
|
+
const [
|
|
43
|
+
core,health,migrationCore,projectCore,taskCore,reviewCore,
|
|
44
|
+
evidenceCore,contextCore,runCore,migration,policy,methods,
|
|
45
|
+
projectStore,operations,lineReview
|
|
46
|
+
]=await Promise.all([
|
|
47
|
+
import('./lib/core/store.mjs'),import('./lib/core/health.mjs'),
|
|
48
|
+
import('./lib/core/migration.mjs'),import('./lib/core/project.mjs'),
|
|
49
|
+
import('./lib/core/task.mjs'),import('./lib/core/review.mjs'),
|
|
50
|
+
import('./lib/core/evidence.mjs'),import('./lib/core/context.mjs'),
|
|
51
|
+
import('./lib/core/run.mjs'),import('./lib/context-migration.mjs'),
|
|
52
|
+
import('./lib/approval-policy.mjs'),import('./lib/methods.mjs'),
|
|
53
|
+
import('./lib/project-store.mjs'),import('./lib/operations.mjs'),
|
|
54
|
+
import('./lib/line-review.mjs')
|
|
55
|
+
]);
|
|
56
|
+
migration.configureMigrationSource({
|
|
57
|
+
reviewPreservedLines:lineReview.reviewPreservedLines
|
|
58
|
+
});
|
|
59
|
+
core.configureCore({
|
|
60
|
+
createHealthMethods:health.createHealthMethods,
|
|
61
|
+
createMigrationMethods:migrationCore.createMigrationMethods,
|
|
62
|
+
createProjectMethods:projectCore.createProjectMethods,
|
|
63
|
+
createTaskMethods:taskCore.createTaskMethods,
|
|
64
|
+
createReviewMethods:reviewCore.createReviewMethods,
|
|
65
|
+
createEvidenceMethods:evidenceCore.createEvidenceMethods,
|
|
66
|
+
createContextMethods:contextCore.createContextMethods,
|
|
67
|
+
createRunMethods:runCore.createRunMethods,
|
|
68
|
+
verifySourceUnit:migration.verifySourceUnit,
|
|
69
|
+
inspectRegistryReferenceForReview:migration.inspectRegistryReferenceForReview,
|
|
70
|
+
hasApprovedPlan:policy.hasApprovedPlan,
|
|
71
|
+
hasRequirementApproval:policy.hasRequirementApproval
|
|
72
|
+
});
|
|
73
|
+
projectStore.configureProjectStore({
|
|
74
|
+
parseContextAllowedProjects:methods.parseContextAllowedProjects
|
|
75
|
+
});
|
|
76
|
+
operations.configureOperations({
|
|
77
|
+
capabilityRouter:createCapabilityRouter(methodDefinitions,capabilities),
|
|
78
|
+
openContextProtocol:core.openContextProtocol,
|
|
79
|
+
CONTEXT_CONTRACT:methods.CONTEXT_CONTRACT,
|
|
80
|
+
validateContextCall:methods.validateContextCall,
|
|
81
|
+
listMethods:methods.listMethods,describeMethod:methods.describeMethod,
|
|
82
|
+
projectDatabase:projectStore.projectDatabase,
|
|
83
|
+
projectMeta:projectStore.projectMeta,
|
|
84
|
+
verifiedStoreFile:projectStore.verifiedStoreFile,
|
|
85
|
+
resolveProjects:projectStore.resolveProjects,
|
|
86
|
+
allowedProjects:projectStore.allowedProjects
|
|
87
|
+
});
|
|
88
|
+
return Object.freeze({core,migration,methods,operations,projectStore,lineReview});
|
|
89
|
+
})();
|
|
90
|
+
return sdkPromise;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function operatorRuntime(){
|
|
94
|
+
if(!operatorPromise)operatorPromise=(async()=>{
|
|
95
|
+
const sdk=await sdkRuntime();
|
|
96
|
+
const {core,migration,methods,operations,projectStore,lineReview}=sdk;
|
|
97
|
+
const [inventory,workspace,branch,diagnostic,orphan,admin,guards,commands]=
|
|
98
|
+
await Promise.all([
|
|
99
|
+
import('./lib/process-inventory.mjs'),
|
|
100
|
+
import('./lib/workspace-operator.mjs'),
|
|
101
|
+
import('./lib/project-branch.mjs'),
|
|
102
|
+
import('./lib/project-diagnostic.mjs'),
|
|
103
|
+
import('./lib/orphan-operator.mjs'),
|
|
104
|
+
import('./lib/context-cli.mjs'),
|
|
105
|
+
import('./lib/project-guards.mjs'),
|
|
106
|
+
import('./lib/cli-commands.mjs')
|
|
107
|
+
]);
|
|
108
|
+
admin.configureContextAdmin({
|
|
109
|
+
activeLegacyWriters:inventory.activeLegacyWriters,
|
|
110
|
+
openContextProtocol:core.openContextProtocol,
|
|
111
|
+
parseContextAllowedProjects:methods.parseContextAllowedProjects,
|
|
112
|
+
scanSourceUnit:migration.scanSourceUnit,
|
|
113
|
+
saveShadowManifest:migration.saveShadowManifest,
|
|
114
|
+
readShadowManifest:migration.readShadowManifest,
|
|
115
|
+
verifyShadowManifest:migration.verifyShadowManifest,
|
|
116
|
+
backupContextDb:migration.backupContextDb,
|
|
117
|
+
createRecoveryManifest:migration.createRecoveryManifest,
|
|
118
|
+
restoreBackupToDiagnosticBranch:migration.restoreBackupToDiagnosticBranch
|
|
119
|
+
});
|
|
120
|
+
workspace.configureWorkspaceOperator({
|
|
121
|
+
openContextProtocol:core.openContextProtocol,
|
|
122
|
+
contextRoot:projectStore.contextRoot,
|
|
123
|
+
allowedProjects:projectStore.allowedProjects,
|
|
124
|
+
dispatchContextCall:operations.dispatchContextCall
|
|
125
|
+
});
|
|
126
|
+
branch.configureProjectBranch({
|
|
127
|
+
knownWriterInventory:inventory.knownWriterInventory,
|
|
128
|
+
openContextProtocol:core.openContextProtocol,
|
|
129
|
+
backupContextDb:migration.backupContextDb,
|
|
130
|
+
verifySourceUnit:migration.verifySourceUnit,
|
|
131
|
+
scanSourceUnit:migration.scanSourceUnit,
|
|
132
|
+
ID:guards.ID,ensure:guards.ensure,
|
|
133
|
+
privateFile:guards.privateFile,privateRoot:guards.privateRoot
|
|
134
|
+
});
|
|
135
|
+
diagnostic.configureProjectDiagnostic({
|
|
136
|
+
projectBranch:branch,
|
|
137
|
+
openContextProtocol:core.openContextProtocol,
|
|
138
|
+
verifySourceUnit:migration.verifySourceUnit,
|
|
139
|
+
scanSourceUnit:migration.scanSourceUnit,
|
|
140
|
+
reviewPreservedLines:lineReview.reviewPreservedLines,
|
|
141
|
+
ID:guards.ID,ensure:guards.ensure,privateFile:guards.privateFile
|
|
142
|
+
});
|
|
143
|
+
orphan.configureOrphanOperator({
|
|
144
|
+
openContextProtocol:core.openContextProtocol,
|
|
145
|
+
contextRoot:projectStore.contextRoot,
|
|
146
|
+
allowedProjects:projectStore.allowedProjects,
|
|
147
|
+
confirmWorkspaceOperator:workspace.confirmWorkspaceOperator
|
|
148
|
+
});
|
|
149
|
+
commands.configureCliCommands({
|
|
150
|
+
openContextProtocol:core.openContextProtocol,
|
|
151
|
+
contextRoot:projectStore.contextRoot,
|
|
152
|
+
allowedProjects:projectStore.allowedProjects,
|
|
153
|
+
verifySourceUnit:migration.verifySourceUnit,
|
|
154
|
+
createProjectDiagnosticBranch:diagnostic.createProjectDiagnosticBranch,
|
|
155
|
+
createManagedProjectBranch:diagnostic.createManagedProjectBranch,
|
|
156
|
+
fenceLegacyProjectStore:diagnostic.fenceLegacyProjectStore,
|
|
157
|
+
auditLegacyProjectSources:diagnostic.auditLegacyProjectSources,
|
|
158
|
+
inspectLegacyRegistryReference:diagnostic.inspectLegacyRegistryReference,
|
|
159
|
+
activeLegacyWriters:inventory.activeLegacyWriters,
|
|
160
|
+
fenceOrphanRunOperator:orphan.fenceOrphanRunOperator,
|
|
161
|
+
canonicalWorkspaceRefs:workspace.canonicalWorkspaceRefs,
|
|
162
|
+
confirmWorkspaceOperator:workspace.confirmWorkspaceOperator,
|
|
163
|
+
assertWorkspaceUnclaimed:workspace.assertWorkspaceUnclaimed,
|
|
164
|
+
withWorkspaceRegistryLock:workspace.withWorkspaceRegistryLock,
|
|
165
|
+
rebindProjectWorkspaces:workspace.rebindProjectWorkspaces,
|
|
166
|
+
readOperatorWorkspaceReceipt:workspace.readOperatorWorkspaceReceipt,
|
|
167
|
+
runContextCli:admin.runContextCli,
|
|
168
|
+
requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION
|
|
169
|
+
});
|
|
170
|
+
return Object.freeze({...sdk,inventory,workspace,branch,diagnostic,
|
|
171
|
+
orphan,admin,guards,commands});
|
|
172
|
+
})();
|
|
173
|
+
return operatorPromise;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function trustedRuntime(){
|
|
177
|
+
if(!trustedPromise)trustedPromise=(async()=>{
|
|
178
|
+
const {core,projectStore}=await sdkRuntime();
|
|
179
|
+
const trusted=await import('./lib/trusted-run.mjs');
|
|
180
|
+
trusted.configureTrustedRun({
|
|
181
|
+
openContextProtocol:core.openContextProtocol,
|
|
182
|
+
allowedProjects:projectStore.allowedProjects,
|
|
183
|
+
resolveVerifiedProjectDatabase:projectStore.resolveVerifiedProjectDatabase
|
|
184
|
+
});
|
|
185
|
+
return Object.freeze({execute:trusted.executeTrustedRun});
|
|
186
|
+
})();
|
|
187
|
+
return trustedPromise;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Implementation stays free of observability; the exported callable is a Proxy.
|
|
191
|
+
async function requestContextCore(args){
|
|
192
|
+
const method=methodById.get(args?.operation);
|
|
193
|
+
const tool=method?.mode==='write'?'chat_loop_context_mutate':'chat_loop_context_get';
|
|
194
|
+
validateContextCall(tool,args);
|
|
195
|
+
if(method.id==='sdk.methods.list')return listMethods(args.group,args.view);
|
|
196
|
+
if(method.id==='sdk.methods.describe')return describeMethod(args.methodId);
|
|
197
|
+
runtimeRequired();
|
|
198
|
+
const {operations}=await sdkRuntime();
|
|
199
|
+
return operations.dispatchContextCall(tool,args);
|
|
200
|
+
}
|
|
201
|
+
export const requestContext=auditFunction(requestContextCore,([args])=>{
|
|
202
|
+
const method=methodById.get(args?.operation);
|
|
203
|
+
return {api:method?.id??'request.invalid',surface:'sdk',
|
|
204
|
+
mode:method?.mode??'unknown',projectRef:args?.projectId,taskRef:args?.taskId};
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// Each nested operation is intercepted without modifying the trusted runtime.
|
|
208
|
+
async function loadTrustedRuntimeCore(){
|
|
209
|
+
runtimeRequired();
|
|
210
|
+
const instance=await trustedRuntime();
|
|
211
|
+
return auditMethods(instance,{
|
|
212
|
+
execute:([command,args])=>({
|
|
213
|
+
api:typeof command==='string'&&/^[a-z][a-z0-9.-]{1,69}$/.test(command)
|
|
214
|
+
?'trusted.'+command:'trusted.invalid',
|
|
215
|
+
surface:'trusted',mode:'internal',projectRef:args?.projectId,taskRef:args?.taskId
|
|
216
|
+
})
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
export const loadTrustedRuntime=auditFunction(loadTrustedRuntimeCore,
|
|
220
|
+
()=>({api:'sdk.load_trusted',surface:'sdk',mode:'internal'}));
|
|
221
|
+
|
|
222
|
+
// Only the single public CLI callable is exposed; the internals stay private.
|
|
223
|
+
async function loadLocalOperatorCore(){
|
|
224
|
+
runtimeRequired();
|
|
225
|
+
const {commands}=await operatorRuntime();
|
|
226
|
+
return auditMethods(Object.freeze({
|
|
227
|
+
runLocalCliCommand:commands.runLocalCliCommand
|
|
228
|
+
}),{
|
|
229
|
+
runLocalCliCommand:()=>({
|
|
230
|
+
// Only the public callable name, not CLI tokens, may enter logs.
|
|
231
|
+
api:'operator.runLocalCliCommand',surface:'operator',mode:'operator'
|
|
232
|
+
})
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
export const loadLocalOperator=auditFunction(loadLocalOperatorCore,
|
|
236
|
+
()=>({api:'sdk.load_operator',surface:'sdk',mode:'operator'}));
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// Canonical AOP observer, generated into independently installable npm packages and MV3.
|
|
2
|
+
// Soft evidence only: no parameters, results, URLs, secrets or model content.
|
|
3
|
+
const SAFE=/^[a-zA-Z][a-zA-Z0-9_.:-]{0,126}$/;
|
|
4
|
+
const PACKAGE=/^@[a-z0-9][a-z0-9._-]{0,45}\/[a-z0-9][a-z0-9._-]{0,80}$/;
|
|
5
|
+
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
6
|
+
const safe=(s,fallback='api.unknown')=>typeof s==='string'&&SAFE.test(s)?s:fallback;
|
|
7
|
+
const code=e=>typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
|
|
8
|
+
?e.code:'API_FAILED';
|
|
9
|
+
const uid=()=>{
|
|
10
|
+
try{return globalThis.crypto.randomUUID()}catch{
|
|
11
|
+
const hex='0123456789abcdef',h=n=>Array.from({length:n},
|
|
12
|
+
()=>hex[Math.floor(Math.random()*16)]).join('');
|
|
13
|
+
return h(8)+'-'+h(4)+'-4'+h(3)+'-a'+h(3)+'-'+h(12);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
const schedule=typeof setImmediate==='function'?setImmediate:fn=>setTimeout(fn,0);
|
|
17
|
+
const clock=()=>typeof performance!=='undefined'&&typeof performance.now==='function'
|
|
18
|
+
?performance.now():Date.now();
|
|
19
|
+
const MAX_PENDING=4096,MAX_BATCH=128;
|
|
20
|
+
const CONTEXT_KEY=Symbol.for('chat-loop.observation.async-context.v1');
|
|
21
|
+
// Process-local correlation only, never an authorization or plugin registry.
|
|
22
|
+
const contextStore=()=>{
|
|
23
|
+
if(typeof process==='undefined'||typeof process.getBuiltinModule!=='function')return null;
|
|
24
|
+
try{
|
|
25
|
+
if(!process[CONTEXT_KEY]){
|
|
26
|
+
const {AsyncLocalStorage}=process.getBuiltinModule('node:async_hooks');
|
|
27
|
+
Object.defineProperty(process,CONTEXT_KEY,{
|
|
28
|
+
value:new AsyncLocalStorage(),enumerable:false,configurable:false
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return process[CONTEXT_KEY];
|
|
32
|
+
}catch{return null}
|
|
33
|
+
};
|
|
34
|
+
const validParent=v=>v&&UUID.test(v.traceId||'')&&UUID.test(v.spanId||'');
|
|
35
|
+
export function currentApiTrace(){
|
|
36
|
+
try{
|
|
37
|
+
const local=contextStore()?.getStore();
|
|
38
|
+
if(validParent(local))return {traceId:local.traceId,spanId:local.spanId};
|
|
39
|
+
// Child-process context is sanitized correlation metadata, not trust.
|
|
40
|
+
const value=typeof process!=='undefined'?process.env?.CHAT_LOOP_API_PARENT:null;
|
|
41
|
+
if(typeof value!=='string'||value.length>180)return null;
|
|
42
|
+
const parsed=JSON.parse(value);
|
|
43
|
+
return validParent(parsed)?{traceId:parsed.traceId,spanId:parsed.spanId}:null;
|
|
44
|
+
}catch{return null}
|
|
45
|
+
}
|
|
46
|
+
export function withApiTraceParent(parent,fn){
|
|
47
|
+
if(typeof fn!=='function')throw TypeError('API_TRACE_CALLBACK_REQUIRED');
|
|
48
|
+
if(!validParent(parent))throw TypeError('API_TRACE_PARENT_INVALID');
|
|
49
|
+
const storage=contextStore();
|
|
50
|
+
return storage?storage.run({traceId:parent.traceId,spanId:parent.spanId},fn):fn();
|
|
51
|
+
}
|
|
52
|
+
export function createApiAspect(packageName,{sink}={}){
|
|
53
|
+
const packageId=typeof packageName==='string'&&PACKAGE.test(packageName)
|
|
54
|
+
?packageName:'unknown';
|
|
55
|
+
const queue=[],listeners=new Set(),
|
|
56
|
+
stats={emitted:0,delivered:0,dropped:0,sinkFailures:0};
|
|
57
|
+
let scheduled=false;
|
|
58
|
+
const output=typeof sink==='function'?sink:record=>{
|
|
59
|
+
if(listeners.size){
|
|
60
|
+
for(const listener of [...listeners]){
|
|
61
|
+
try{
|
|
62
|
+
const result=listener(record);
|
|
63
|
+
if(result&&typeof result.then==='function')
|
|
64
|
+
Promise.resolve(result).catch(()=>{stats.sinkFailures++});
|
|
65
|
+
}catch{stats.sinkFailures++}
|
|
66
|
+
}
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if(typeof process==='undefined'||!process.stderr?.write||
|
|
70
|
+
process.env.CHAT_LOOP_API_LOG_STDERR==='0')return;
|
|
71
|
+
process.stderr.write('CHAT_LOOP_API_LOG '+JSON.stringify(record)+'\n');
|
|
72
|
+
};
|
|
73
|
+
const flush=()=>{
|
|
74
|
+
scheduled=false;
|
|
75
|
+
for(let i=0;i<MAX_BATCH&&queue.length;i++){
|
|
76
|
+
const item=queue.shift();
|
|
77
|
+
try{
|
|
78
|
+
const result=output(item);
|
|
79
|
+
stats.delivered++;
|
|
80
|
+
if(result&&typeof result.then==='function')
|
|
81
|
+
Promise.resolve(result).catch(()=>{stats.sinkFailures++});
|
|
82
|
+
}catch{stats.sinkFailures++}
|
|
83
|
+
}
|
|
84
|
+
if(queue.length){scheduled=true;schedule(flush)}
|
|
85
|
+
};
|
|
86
|
+
const emit=event=>{
|
|
87
|
+
try{
|
|
88
|
+
if(queue.length>=MAX_PENDING){stats.dropped++;return}
|
|
89
|
+
queue.push(Object.freeze(event));stats.emitted++;
|
|
90
|
+
if(!scheduled){scheduled=true;schedule(flush)}
|
|
91
|
+
}catch{stats.dropped++}
|
|
92
|
+
};
|
|
93
|
+
function observe(name,fn,surface='sdk',options={}){
|
|
94
|
+
if(typeof fn!=='function')throw TypeError('API_ASPECT_TARGET_REQUIRED');
|
|
95
|
+
const api=safe(name),layer=safe(surface,'sdk');
|
|
96
|
+
return new Proxy(fn,{
|
|
97
|
+
get(target,key,receiver){
|
|
98
|
+
if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
|
|
99
|
+
return Reflect.get(target,key,receiver);
|
|
100
|
+
},
|
|
101
|
+
apply(target,thisArg,args){
|
|
102
|
+
let started,base;
|
|
103
|
+
try{
|
|
104
|
+
// MCP requests are fresh user operations, not children of a
|
|
105
|
+
// long-lived CLI/server bootstrap event listener registration.
|
|
106
|
+
// Browser callbacks lack Node AsyncLocalStorage; a narrowly scoped
|
|
107
|
+
// explicit parent links the async reply to its actual dispatch span.
|
|
108
|
+
const explicit=validParent(options?.parent)?options.parent:null;
|
|
109
|
+
const callId=uid(),parent=explicit||(layer==='mcp'?null:currentApiTrace());
|
|
110
|
+
started=clock();
|
|
111
|
+
base={contract:'chat-loop.api-call.v1',package:packageId,
|
|
112
|
+
api,surface:layer,callId,
|
|
113
|
+
traceId:parent?.traceId||callId,spanId:callId,
|
|
114
|
+
parentSpanId:parent?.spanId||null};
|
|
115
|
+
}catch{/* Never fail a target due to tracing. */}
|
|
116
|
+
const mark=(phase,error)=>{
|
|
117
|
+
if(!base)return;
|
|
118
|
+
try{
|
|
119
|
+
emit({...base,phase,time:new Date().toISOString(),
|
|
120
|
+
durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(clock()-started)),
|
|
121
|
+
errorCode:phase==='FAILED'?code(error):null});
|
|
122
|
+
}catch{/* Non-authoritative telemetry. */}
|
|
123
|
+
};
|
|
124
|
+
mark('BEGIN');
|
|
125
|
+
// Only sanitized correlation IDs may cross from the AOP boundary into
|
|
126
|
+
// the hosting callback. A faulty observer must never affect the call.
|
|
127
|
+
if(base&&typeof options?.onBegin==='function'){
|
|
128
|
+
try{options.onBegin(Object.freeze({traceId:base.traceId,spanId:base.spanId}));}
|
|
129
|
+
catch{stats.sinkFailures++}
|
|
130
|
+
}
|
|
131
|
+
const execute=()=>Reflect.apply(target,thisArg,args);
|
|
132
|
+
let result;
|
|
133
|
+
try{
|
|
134
|
+
const storage=base?contextStore():null;
|
|
135
|
+
result=storage?storage.run({traceId:base.traceId,spanId:base.spanId},execute)
|
|
136
|
+
:execute();
|
|
137
|
+
}catch(e){mark('FAILED',e);throw e}
|
|
138
|
+
const failed=value=>{
|
|
139
|
+
try{return (layer==='mcp'&&value?.isError===true)
|
|
140
|
+
||(layer==='browser'&&api.startsWith('browser.dispatch.')&&value===false)}
|
|
141
|
+
catch{stats.sinkFailures++;return false}
|
|
142
|
+
};
|
|
143
|
+
const failureCode=()=>({code:layer==='browser'
|
|
144
|
+
?'BROWSER_MESSAGE_UNHANDLED':'MCP_TOOL_ERROR'});
|
|
145
|
+
// Do not assimilate arbitrary user thenables for telemetry: invoking
|
|
146
|
+
// their then() could cause a second business side effect. Observe native
|
|
147
|
+
// Promises only, otherwise record the synchronous return boundary.
|
|
148
|
+
let nativePromise=false;
|
|
149
|
+
try{nativePromise=result instanceof Promise}catch{stats.sinkFailures++}
|
|
150
|
+
if(nativePromise){
|
|
151
|
+
// Preserve the exact native Promise object and rejection semantics.
|
|
152
|
+
try{Promise.resolve(result).then(
|
|
153
|
+
value=>{
|
|
154
|
+
const isError=failed(value);
|
|
155
|
+
mark(isError?'FAILED':'OK',
|
|
156
|
+
isError?failureCode():undefined);
|
|
157
|
+
},
|
|
158
|
+
error=>mark('FAILED',error)
|
|
159
|
+
).catch(()=>{stats.sinkFailures++});}
|
|
160
|
+
catch{stats.sinkFailures++}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
const isError=failed(result);
|
|
164
|
+
mark(isError?'FAILED':'OK',
|
|
165
|
+
isError?failureCode():undefined);
|
|
166
|
+
return result;
|
|
167
|
+
}});
|
|
168
|
+
}
|
|
169
|
+
function methods(instance,prefix,surface='sdk'){
|
|
170
|
+
if(!instance||typeof instance!=='object')return instance;
|
|
171
|
+
const facade={...instance},cache=new Map();
|
|
172
|
+
return new Proxy(facade,{
|
|
173
|
+
get(object,key,receiver){
|
|
174
|
+
const v=Reflect.get(object,key,receiver);
|
|
175
|
+
if(typeof v!=='function'||typeof key!=='string')return v;
|
|
176
|
+
if(!cache.has(key))cache.set(key,observe(prefix+'.'+key,v,surface));
|
|
177
|
+
return cache.get(key);
|
|
178
|
+
},
|
|
179
|
+
set(){return false},defineProperty(){return false},deleteProperty(){return false}
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
const subscribe=observe('subscribeApiLog',listener=>{
|
|
183
|
+
if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
|
|
184
|
+
listeners.add(listener);
|
|
185
|
+
return ()=>listeners.delete(listener);
|
|
186
|
+
},'internal');
|
|
187
|
+
return Object.freeze({observe,methods,subscribe,
|
|
188
|
+
health:()=>Object.freeze({...stats,pending:queue.length}),
|
|
189
|
+
current:currentApiTrace,withParent:withApiTraceParent});
|
|
190
|
+
}
|
package/lib/api-log.mjs
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// Context public AOP boundary. No domain implementation imports this module.
|
|
2
|
+
// Proxy preserves call arguments, this, sync/async return and thrown errors.
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
// The npm root injects the generated observation context port. Private
|
|
5
|
+
// modules never import another private module, even for optional telemetry.
|
|
6
|
+
let currentApiTrace=()=>null,withApiTraceParent=(_parent,execute)=>execute();
|
|
7
|
+
export function configureApiLogCorrelation({current,withParent}){
|
|
8
|
+
if(typeof current!=='function'||typeof withParent!=='function')
|
|
9
|
+
throw TypeError('API_LOG_CORRELATION_PORT_INVALID');
|
|
10
|
+
currentApiTrace=current;
|
|
11
|
+
withApiTraceParent=withParent;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const API_LOG_CONTRACT='chat-loop.context-api-log.v1';
|
|
15
|
+
const API=/^[a-z][A-Za-z0-9._-]{1,89}$/;
|
|
16
|
+
const PROJECT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
17
|
+
const TASK=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
18
|
+
const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
|
|
19
|
+
const listeners=new Set();
|
|
20
|
+
// Registration begins before its own subscriber exists. Keep only this
|
|
21
|
+
// single, sanitized, synchronous bootstrap span for that new subscriber.
|
|
22
|
+
let recentSubscribeBegin=null;
|
|
23
|
+
const safeName=name=>typeof name==='string'&&API.test(name)?name:'api.invalid';
|
|
24
|
+
const safeProject=value=>typeof value==='string'&&PROJECT.test(value)?value:null;
|
|
25
|
+
const safeTask=value=>typeof value==='string'&&TASK.test(value)?value:null;
|
|
26
|
+
const safeCode=error=>typeof error?.code==='string'&&CODE.test(error.code)
|
|
27
|
+
?error.code:'CONTEXT_FAILED';
|
|
28
|
+
|
|
29
|
+
// The sole sink subscription (Tools may route to its existing Supervisor).
|
|
30
|
+
function subscribe(listener){
|
|
31
|
+
if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
|
|
32
|
+
listeners.add(listener);
|
|
33
|
+
// Deliver the BEGIN of this subscribe API call to its newly added
|
|
34
|
+
// listener. Other, pre-existing listeners already received it through
|
|
35
|
+
// the ordinary queue; the new listener must not see an orphan OK.
|
|
36
|
+
const active=currentApiTrace();
|
|
37
|
+
const begin=recentSubscribeBegin;
|
|
38
|
+
if(begin&&begin.spanId===active?.spanId){
|
|
39
|
+
recentSubscribeBegin=null;
|
|
40
|
+
if(pendingEvents.length<MAX_AUDIT_PENDING){
|
|
41
|
+
pendingEvents.push({safe:begin,targets:[listener],stderr:false});
|
|
42
|
+
if(!scheduled){scheduled=true;setImmediate(drainAudit)}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return auditFunction(()=>listeners.delete(listener),
|
|
46
|
+
()=>({api:'sdk.unsubscribe_log',mode:'internal'}));
|
|
47
|
+
}
|
|
48
|
+
export const subscribeContextApiLog=auditFunction(subscribe,
|
|
49
|
+
()=>({api:'sdk.subscribe_log',mode:'internal'}));
|
|
50
|
+
|
|
51
|
+
// Audit is a bounded asynchronous side channel, not part of the API's
|
|
52
|
+
// execution stack. Observers never run while the business call is executing;
|
|
53
|
+
// a slow observer cannot postpone an already available API result. Saturation
|
|
54
|
+
// drops telemetry, never business calls or authoritative receipts.
|
|
55
|
+
const MAX_AUDIT_PENDING=4096;
|
|
56
|
+
const AUDIT_BATCH_SIZE=128;
|
|
57
|
+
const pendingEvents=[];
|
|
58
|
+
let scheduled=false;
|
|
59
|
+
function drainAudit(){
|
|
60
|
+
scheduled=false;
|
|
61
|
+
for(let i=0;i<AUDIT_BATCH_SIZE&&pendingEvents.length;i++){
|
|
62
|
+
const {safe,targets,stderr}=pendingEvents.shift();
|
|
63
|
+
if(stderr){
|
|
64
|
+
try{process.stderr.write('CHAT_LOOP_CONTEXT_API_LOG '+JSON.stringify(safe)+'\n')}
|
|
65
|
+
catch{/* stderr is not an authority. */}
|
|
66
|
+
}
|
|
67
|
+
for(const listener of targets){
|
|
68
|
+
try{
|
|
69
|
+
const pending=listener(safe);
|
|
70
|
+
if(pending&&typeof pending.then==='function')
|
|
71
|
+
Promise.resolve(pending).catch(()=>{});
|
|
72
|
+
}catch{/* A broken observation sink cannot alter business semantics. */}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if(pendingEvents.length){scheduled=true;setImmediate(drainAudit)}
|
|
76
|
+
}
|
|
77
|
+
function emit(event){
|
|
78
|
+
if(pendingEvents.length>=MAX_AUDIT_PENDING)return;
|
|
79
|
+
const safe=Object.freeze(event);
|
|
80
|
+
if(safe.api==='sdk.subscribe_log'&&safe.phase==='BEGIN')
|
|
81
|
+
recentSubscribeBegin=safe;
|
|
82
|
+
const stderr=process.env.CHAT_LOOP_CONTEXT_API_LOG_STDERR==='1';
|
|
83
|
+
const targets=[...listeners];
|
|
84
|
+
if(!stderr&&!targets.length)return;
|
|
85
|
+
pendingEvents.push({safe,targets,stderr});
|
|
86
|
+
if(!scheduled){scheduled=true;setImmediate(drainAudit)}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function observe({api,mode='read',surface='sdk',projectRef=null,taskRef=null},execute){
|
|
90
|
+
const callId=randomUUID(),started=performance.now(),parent=currentApiTrace();
|
|
91
|
+
const base={contract:API_LOG_CONTRACT,callId,
|
|
92
|
+
traceId:parent?.traceId||callId,spanId:callId,parentSpanId:parent?.spanId||null,
|
|
93
|
+
api:safeName(api),
|
|
94
|
+
surface,mode,projectRef:safeProject(projectRef),taskRef:safeTask(taskRef)};
|
|
95
|
+
const record=(phase,error)=>emit({
|
|
96
|
+
...base,phase,time:new Date().toISOString(),
|
|
97
|
+
durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(performance.now()-started)),
|
|
98
|
+
errorCode:phase==='FAILED'?safeCode(error):null
|
|
99
|
+
});
|
|
100
|
+
record('BEGIN');
|
|
101
|
+
try{
|
|
102
|
+
const value=withApiTraceParent({traceId:base.traceId,spanId:callId},execute);
|
|
103
|
+
// Unknown thenables must not be invoked twice by the audit observer.
|
|
104
|
+
// A real Promise can be observed without changing its identity.
|
|
105
|
+
let nativePromise=false;
|
|
106
|
+
try{nativePromise=value instanceof Promise}catch{/* observer-only test */}
|
|
107
|
+
if(nativePromise){
|
|
108
|
+
// Preserve the original Promise/thenable identity and rejection.
|
|
109
|
+
try{Promise.resolve(value).then(
|
|
110
|
+
()=>record('OK'),error=>record('FAILED',error)
|
|
111
|
+
).catch(()=>{});}catch{/* logging must never replace the result */}
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
record('OK');return value;
|
|
115
|
+
}catch(error){
|
|
116
|
+
record('FAILED',error);
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// One reusable interception implementation, not per-operation logging code.
|
|
122
|
+
// describe(args) is private metadata extraction, never receives control of
|
|
123
|
+
// the original argument array or function execution.
|
|
124
|
+
export function auditFunction(target,describe){
|
|
125
|
+
if(typeof target!=='function')throw TypeError('API_TARGET_REQUIRED');
|
|
126
|
+
return new Proxy(target,{
|
|
127
|
+
get(fn,key,receiver){
|
|
128
|
+
if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
|
|
129
|
+
return Reflect.get(fn,key,receiver);
|
|
130
|
+
},
|
|
131
|
+
apply(fn,thisArg,args){
|
|
132
|
+
let detail;
|
|
133
|
+
try{detail=describe(args)??{}}catch{detail={api:'api.invalid',mode:'unknown'}}
|
|
134
|
+
return observe(detail,()=>Reflect.apply(fn,thisArg,args));
|
|
135
|
+
}});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Lazily proxy selected callable properties, without changing object keys,
|
|
139
|
+
// descriptors, non-function fields or the implementation's own method body.
|
|
140
|
+
export function auditMethods(target,descriptors){
|
|
141
|
+
// JS Proxy cannot override a frozen target's non-configurable data method.
|
|
142
|
+
// Proxy a private shallow facade, with the same keys and immutable behavior.
|
|
143
|
+
// Capability addition must not silently bypass its observation metadata.
|
|
144
|
+
for(const [key,descriptor] of Object.entries(
|
|
145
|
+
Object.getOwnPropertyDescriptors(target)))
|
|
146
|
+
if(typeof descriptor.value==='function'&&!Object.hasOwn(descriptors,key))
|
|
147
|
+
throw TypeError('API_AUDIT_DESCRIPTOR_MISSING:'+key);
|
|
148
|
+
const facade={...target},cached=new Map();
|
|
149
|
+
return new Proxy(facade,{
|
|
150
|
+
set(){return false},
|
|
151
|
+
defineProperty(){return false},
|
|
152
|
+
deleteProperty(){return false},
|
|
153
|
+
get(object,key,receiver){
|
|
154
|
+
const value=Reflect.get(object,key,receiver);
|
|
155
|
+
if(typeof value!=='function'||!Object.hasOwn(descriptors,key))return value;
|
|
156
|
+
if(!cached.has(key))
|
|
157
|
+
cached.set(key,auditFunction(value,descriptors[key]));
|
|
158
|
+
return cached.get(key);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Context owns business approval policy. No SQLite, browser, MCP or Session state.
|
|
2
|
+
// V1 is intentionally the two genuine R->P soft user Turns already in production.
|
|
3
|
+
// A new strong approval requires an explicitly versioned policy and migrations,
|
|
4
|
+
// not changing a count scattered through Run/Permit transactions.
|
|
5
|
+
export const APPROVAL_POLICY_V1=Object.freeze({
|
|
6
|
+
id:'chat-loop.approval.r-p.v1',
|
|
7
|
+
requiredKinds:Object.freeze(['R','P'])
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
const fromUser=a=>Boolean(a&&typeof a==='object'
|
|
11
|
+
&&(a.sourceRole===undefined||a.sourceRole==='user')
|
|
12
|
+
&&typeof a.userTurn==='string'&&a.userTurn.length>0);
|
|
13
|
+
|
|
14
|
+
export function hasRequirementApproval(records){
|
|
15
|
+
return Array.isArray(records)&&records.length===1
|
|
16
|
+
&&records[0]?.kind==='R'&&fromUser(records[0]);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function hasApprovedPlan(records){
|
|
20
|
+
return Array.isArray(records)&&records.length===2
|
|
21
|
+
&&records[0]?.kind==='R'&&records[1]?.kind==='P'
|
|
22
|
+
&&fromUser(records[0])&&fromUser(records[1])
|
|
23
|
+
&&records[0].userTurn!==records[1].userTurn;
|
|
24
|
+
}
|