@steerable/agent-shell 0.12.7 → 0.13.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/dist/auth/credentials.d.ts +83 -0
- package/dist/auth/credentials.js +426 -0
- package/dist/auth/index.d.ts +33 -9
- package/dist/auth/index.js +85 -0
- package/dist/host/external-pack-loader.d.ts +40 -0
- package/dist/host/external-pack-loader.js +247 -0
- package/dist/host/http-routes.d.ts +6 -2
- package/dist/host/http-routes.js +5 -2
- package/dist/host/pack-assembly.d.ts +9 -1
- package/dist/host/runtime.js +54 -1
- package/dist/local-backend/coreloop-stream.d.ts +4 -0
- package/dist/local-backend/coreloop-stream.js +4 -0
- package/dist/local-backend/fact-chain.d.ts +38 -0
- package/dist/local-backend/fact-chain.js +145 -0
- package/dist/local-backend/router.d.ts +3 -1
- package/dist/local-backend/router.js +329 -35
- package/dist/local-backend/state-reconcile.d.ts +42 -0
- package/dist/local-backend/state-reconcile.js +81 -0
- package/dist/local-backend/title-refresh.d.ts +39 -0
- package/dist/local-backend/title-refresh.js +80 -0
- package/dist/local-backend/turn-security-context.d.ts +42 -0
- package/dist/local-backend/turn-security-context.js +62 -0
- package/dist/local-backend/ui-surface.d.ts +75 -0
- package/dist/local-backend/ui-surface.js +368 -0
- package/dist/local-executor.d.ts +3 -0
- package/dist/local-executor.js +40 -1
- package/dist/memory/authoring-candidates.d.ts +26 -0
- package/dist/memory/authoring-candidates.js +73 -0
- package/dist/memory/injector.d.ts +34 -0
- package/dist/memory/injector.js +111 -0
- package/dist/memory/routes.d.ts +16 -0
- package/dist/memory/routes.js +146 -0
- package/dist/memory/store.d.ts +176 -0
- package/dist/memory/store.js +623 -0
- package/dist/memory/tools.d.ts +83 -0
- package/dist/memory/tools.js +143 -0
- package/dist/present-files.d.ts +25 -1
- package/dist/present-files.js +170 -2
- package/dist/scenario/applications.d.ts +52 -0
- package/dist/scenario/applications.js +143 -0
- package/dist/scenario/pack.d.ts +1 -1
- package/dist/security/policy-digest.d.ts +28 -0
- package/dist/security/policy-digest.js +104 -0
- package/dist/server/http-server.js +23 -6
- package/dist/sidecar/boot.d.ts +1 -0
- package/dist/sidecar/boot.js +2 -0
- package/dist/sidecar/rejected-before-effect.d.ts +22 -0
- package/dist/sidecar/rejected-before-effect.js +63 -0
- package/dist/sidecar/reverse-approval.d.ts +2 -0
- package/dist/sidecar/reverse-approval.js +28 -5
- package/dist/sidecar/reverse-tools.d.ts +3 -0
- package/dist/sidecar/reverse-tools.js +129 -17
- package/dist/sidecar/types.d.ts +6 -0
- package/dist/storage/fde-fallback.d.ts +4 -0
- package/dist/storage/fde-fallback.js +354 -0
- package/dist/storage/fde-types.d.ts +215 -0
- package/dist/storage/fde-types.js +1 -0
- package/dist/storage/index.d.ts +113 -1
- package/dist/storage/index.js +797 -0
- package/dist/storage/insights-redact.d.ts +4 -1
- package/dist/storage/insights-redact.js +6 -1
- package/dist/storage/process-locks.d.ts +1 -1
- package/dist/storage/process-locks.js +1 -1
- package/dist/storage/scoped-store.d.ts +3 -1
- package/dist/tool-presentation.js +20 -0
- package/dist/tool-router.d.ts +20 -1
- package/dist/tool-router.js +76 -12
- package/package.json +5 -5
|
@@ -4,7 +4,7 @@ import { ToolRouter } from '../tool-router.js';
|
|
|
4
4
|
import { type ResolvedAsk } from '../sidecar/reverse-ask-user.js';
|
|
5
5
|
import type { TaskService } from './task-service.js';
|
|
6
6
|
import { type PackBackendBinaryResponse } from './pack-backend-routes.js';
|
|
7
|
-
import { type Principal } from '../auth/index.js';
|
|
7
|
+
import { type OriginChannel, type Principal } from '../auth/index.js';
|
|
8
8
|
export interface LocalBackendRequest {
|
|
9
9
|
method: string;
|
|
10
10
|
path: string;
|
|
@@ -13,6 +13,8 @@ export interface LocalBackendRequest {
|
|
|
13
13
|
headers?: Record<string, string | string[] | undefined>;
|
|
14
14
|
/** Authenticated identity supplied by the BS HTTP layer. */
|
|
15
15
|
principal?: Principal;
|
|
16
|
+
/** Originating channel ('desktop' | 'web' | 'cli' | 'im' | 'webhook'). */
|
|
17
|
+
originChannel?: OriginChannel;
|
|
16
18
|
}
|
|
17
19
|
export interface LocalBackendResponse<T = unknown> {
|
|
18
20
|
status: number;
|
|
@@ -62,7 +62,14 @@ import { invokePackHttpRoute } from '../host/http-routes.js';
|
|
|
62
62
|
import { installProductCli } from '../cli-install.js';
|
|
63
63
|
import { collectTurnFiles } from './turn-files.js';
|
|
64
64
|
import { resolveMentionedPaths } from './mentioned-paths.js';
|
|
65
|
-
import { getAuthProvider } from '../auth/index.js';
|
|
65
|
+
import { LOCAL_DEFAULT_PRINCIPAL, getAuthProvider, parseOriginChannel, resolvePublicBootstrap, } from '../auth/index.js';
|
|
66
|
+
import { CredentialAccessError, defaultCredentialBroker, } from '../auth/credentials.js';
|
|
67
|
+
import { listRegisteredAgentProfiles, listRegisteredApplications, resetActiveApplication, resolveActiveApplication, setActiveApplication, } from '../scenario/applications.js';
|
|
68
|
+
import { beginTurnSecurityContext, endTurnSecurityContext, getTurnSecurityContext, } from './turn-security-context.js';
|
|
69
|
+
import { ensurePhase9Store } from '../storage/fde-fallback.js';
|
|
70
|
+
import { dispatchUiSurfaceAction, refreshPersistedUiSurface, renderAndPersistUiSurface, } from './ui-surface.js';
|
|
71
|
+
import { assembleFactChainGraph } from './fact-chain.js';
|
|
72
|
+
import { handleMemoryHttpRoute } from '../memory/routes.js';
|
|
66
73
|
function stringRecord(value) {
|
|
67
74
|
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
68
75
|
return {};
|
|
@@ -372,6 +379,7 @@ export class LocalBackendRouter {
|
|
|
372
379
|
this.resolveStore = options.resolveStore ?? (() => options.store);
|
|
373
380
|
this.broadcast = options.broadcast ?? null;
|
|
374
381
|
this.taskService = options.taskService ?? null;
|
|
382
|
+
this.toolRouter.setPhase9Store?.(options.store);
|
|
375
383
|
const goals = this.toolRouter.goals?.();
|
|
376
384
|
goals?.onChange((chatId, goal) => {
|
|
377
385
|
this.broadcast?.('goal-changed', { chatId, goal });
|
|
@@ -406,6 +414,179 @@ export class LocalBackendRouter {
|
|
|
406
414
|
const { method } = request;
|
|
407
415
|
const url = new URL(request.path, 'http://local.backend');
|
|
408
416
|
const pathname = url.pathname;
|
|
417
|
+
if (pathname.startsWith('/api/v2/memory')) {
|
|
418
|
+
const memRes = await handleMemoryHttpRoute({
|
|
419
|
+
method,
|
|
420
|
+
pathname,
|
|
421
|
+
searchParams: url.searchParams,
|
|
422
|
+
body: this.toRecord(request.body),
|
|
423
|
+
store: this.store,
|
|
424
|
+
principal: request.principal,
|
|
425
|
+
});
|
|
426
|
+
if (memRes)
|
|
427
|
+
return memRes;
|
|
428
|
+
}
|
|
429
|
+
const reconciliationsMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/reconciliations$/);
|
|
430
|
+
if (reconciliationsMatch && method === 'GET') {
|
|
431
|
+
const chatId = decodeURIComponent(reconciliationsMatch[1]);
|
|
432
|
+
const chat = await this.store.getChat(chatId);
|
|
433
|
+
if (!chat)
|
|
434
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
435
|
+
const includeResolved = url.searchParams.get('includeResolved') === '1';
|
|
436
|
+
const reconciliations = await ensurePhase9Store(this.store).listPendingReconciliations(chatId, { includeResolved });
|
|
437
|
+
return { status: 200, data: { reconciliations } };
|
|
438
|
+
}
|
|
439
|
+
const reconcileMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/reconcile$/);
|
|
440
|
+
if (reconcileMatch && method === 'POST') {
|
|
441
|
+
const chatId = decodeURIComponent(reconcileMatch[1]);
|
|
442
|
+
const chat = await this.store.getChat(chatId);
|
|
443
|
+
if (!chat)
|
|
444
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
445
|
+
const payload = this.toRecord(request.body);
|
|
446
|
+
const reconciliationId = String(payload.reconciliationId ?? '').trim();
|
|
447
|
+
const rawInput = String(payload.resolution ?? payload.status ?? '').trim();
|
|
448
|
+
const resolutionMap = {
|
|
449
|
+
confirmed_succeeded: 'confirmed_executed',
|
|
450
|
+
confirmed_executed: 'confirmed_executed',
|
|
451
|
+
resolved_committed: 'confirmed_executed',
|
|
452
|
+
confirmed_not_executed: 'confirmed_not_executed',
|
|
453
|
+
resolved_not_committed: 'confirmed_not_executed',
|
|
454
|
+
};
|
|
455
|
+
const normalizedStatus = resolutionMap[rawInput];
|
|
456
|
+
if (!reconciliationId || !normalizedStatus) {
|
|
457
|
+
return {
|
|
458
|
+
status: 400,
|
|
459
|
+
data: {
|
|
460
|
+
detail: 'reconciliationId and resolution (confirmed_succeeded | confirmed_not_executed) are required',
|
|
461
|
+
},
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const note = typeof payload.note === 'string' && payload.note.trim() ? payload.note.trim() : null;
|
|
465
|
+
const principal = request.principal ?? LOCAL_DEFAULT_PRINCIPAL;
|
|
466
|
+
const updated = await ensurePhase9Store(this.store).resolvePendingReconciliation({
|
|
467
|
+
chatId,
|
|
468
|
+
reconciliationId,
|
|
469
|
+
status: normalizedStatus,
|
|
470
|
+
resolutionNote: note,
|
|
471
|
+
resolvedBy: principal.id,
|
|
472
|
+
});
|
|
473
|
+
if (!updated) {
|
|
474
|
+
return { status: 404, data: { detail: 'reconciliation not found' } };
|
|
475
|
+
}
|
|
476
|
+
const ledgerSummary = normalizedStatus === 'confirmed_executed'
|
|
477
|
+
? `[Reconciliation ${updated.id}] Human operator (${principal.id}) confirmed that "${updated.toolName}" SUCCEEDED externally${note ? `: ${note}` : ''}. Do NOT re-execute "${updated.toolName}" for the same intent.`
|
|
478
|
+
: `[Reconciliation ${updated.id}] Human operator (${principal.id}) confirmed that "${updated.toolName}" DID NOT execute externally${note ? `: ${note}` : ''}. Lock released; automatic retry is NOT triggered until requested.`;
|
|
479
|
+
await this.store.addMessage(chatId, 'system', ledgerSummary);
|
|
480
|
+
this.broadcast?.('reconciliation:updated', { chatId, reconciliation: updated });
|
|
481
|
+
return { status: 200, data: { reconciliation: updated, ledgerNote: ledgerSummary } };
|
|
482
|
+
}
|
|
483
|
+
const surfacesListMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/surfaces$/);
|
|
484
|
+
if (surfacesListMatch) {
|
|
485
|
+
const chatId = decodeURIComponent(surfacesListMatch[1]);
|
|
486
|
+
if (!await this.store.getChat(chatId)) {
|
|
487
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
488
|
+
}
|
|
489
|
+
if (method === 'GET') {
|
|
490
|
+
const rows = await ensurePhase9Store(this.store).listChatUiSurfaces(chatId);
|
|
491
|
+
const surfaces = rows.map((r) => ({
|
|
492
|
+
...(r.state.rawPayload && typeof r.state.rawPayload === 'object'
|
|
493
|
+
? r.state.rawPayload
|
|
494
|
+
: {}),
|
|
495
|
+
surfaceId: r.surfaceId,
|
|
496
|
+
revision: r.revision,
|
|
497
|
+
resolvedData: r.state.resolvedData ?? {},
|
|
498
|
+
sourceHashes: r.state.sourceHashes ?? {},
|
|
499
|
+
}));
|
|
500
|
+
return { status: 200, data: { surfaces } };
|
|
501
|
+
}
|
|
502
|
+
if (method === 'POST') {
|
|
503
|
+
const surface = await renderAndPersistUiSurface({
|
|
504
|
+
store: this.store,
|
|
505
|
+
chatId,
|
|
506
|
+
principal: request.principal,
|
|
507
|
+
raw: this.toRecord(request.body),
|
|
508
|
+
});
|
|
509
|
+
this.broadcast?.('ui_surface:updated', { chatId, surface });
|
|
510
|
+
return { status: 200, data: { surface } };
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
const surfaceRefreshMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/surfaces\/([^/]+)\/refresh$/);
|
|
514
|
+
if (surfaceRefreshMatch && method === 'GET') {
|
|
515
|
+
const chatId = decodeURIComponent(surfaceRefreshMatch[1]);
|
|
516
|
+
const surfaceId = decodeURIComponent(surfaceRefreshMatch[2]);
|
|
517
|
+
if (!await this.store.getChat(chatId)) {
|
|
518
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
519
|
+
}
|
|
520
|
+
const surface = await refreshPersistedUiSurface({
|
|
521
|
+
store: this.store,
|
|
522
|
+
chatId,
|
|
523
|
+
surfaceId,
|
|
524
|
+
principal: request.principal,
|
|
525
|
+
});
|
|
526
|
+
if (!surface)
|
|
527
|
+
return { status: 404, data: { detail: 'surface not found' } };
|
|
528
|
+
return { status: 200, data: { surface } };
|
|
529
|
+
}
|
|
530
|
+
const surfaceActionMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/surfaces\/([^/]+)\/actions$/);
|
|
531
|
+
if (surfaceActionMatch && method === 'POST') {
|
|
532
|
+
const chatId = decodeURIComponent(surfaceActionMatch[1]);
|
|
533
|
+
const surfaceId = decodeURIComponent(surfaceActionMatch[2]);
|
|
534
|
+
if (!await this.store.getChat(chatId)) {
|
|
535
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
536
|
+
}
|
|
537
|
+
return await dispatchUiSurfaceAction({
|
|
538
|
+
store: this.store,
|
|
539
|
+
toolRouter: this.toolRouter,
|
|
540
|
+
chatId,
|
|
541
|
+
surfaceId,
|
|
542
|
+
principal: request.principal,
|
|
543
|
+
originChannel: request.originChannel,
|
|
544
|
+
body: this.toRecord(request.body),
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
const factChainMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/fact-chain$/);
|
|
548
|
+
if (factChainMatch && method === 'GET') {
|
|
549
|
+
const chatId = decodeURIComponent(factChainMatch[1]);
|
|
550
|
+
if (!await this.store.getChat(chatId)) {
|
|
551
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
552
|
+
}
|
|
553
|
+
const rawKind = url.searchParams.get('targetKind') ?? 'message';
|
|
554
|
+
const targetKind = rawKind === 'tool' || rawKind === 'deliverable' ? rawKind : 'message';
|
|
555
|
+
const targetId = url.searchParams.get('targetId') ?? '';
|
|
556
|
+
const graph = await assembleFactChainGraph({
|
|
557
|
+
store: this.store,
|
|
558
|
+
chatId,
|
|
559
|
+
targetKind,
|
|
560
|
+
targetId,
|
|
561
|
+
});
|
|
562
|
+
return { status: 200, data: { graph } };
|
|
563
|
+
}
|
|
564
|
+
const deliverablesListMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/deliverables$/);
|
|
565
|
+
if (deliverablesListMatch && method === 'GET') {
|
|
566
|
+
const chatId = decodeURIComponent(deliverablesListMatch[1]);
|
|
567
|
+
if (!await this.store.getChat(chatId)) {
|
|
568
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
569
|
+
}
|
|
570
|
+
const deliverables = await ensurePhase9Store(this.store).listChatDeliverables(chatId);
|
|
571
|
+
return { status: 200, data: { deliverables } };
|
|
572
|
+
}
|
|
573
|
+
const deliverableSnapshotMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/deliverables\/([^/]+)\/snapshot$/);
|
|
574
|
+
if (deliverableSnapshotMatch && method === 'GET') {
|
|
575
|
+
const chatId = decodeURIComponent(deliverableSnapshotMatch[1]);
|
|
576
|
+
const deliverableId = decodeURIComponent(deliverableSnapshotMatch[2]);
|
|
577
|
+
const deliverables = await ensurePhase9Store(this.store).listChatDeliverables(chatId);
|
|
578
|
+
const deliv = deliverables.find((d) => d.id === deliverableId);
|
|
579
|
+
if (!deliv || !deliv.reportPath) {
|
|
580
|
+
return { status: 404, data: { detail: 'deliverable snapshot not found' } };
|
|
581
|
+
}
|
|
582
|
+
return {
|
|
583
|
+
kind: 'file',
|
|
584
|
+
status: 200,
|
|
585
|
+
filePath: deliv.reportPath,
|
|
586
|
+
contentType: deliv.mimeType || 'application/octet-stream',
|
|
587
|
+
fileName: deliv.fileName,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
409
590
|
const goalMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/goal$/);
|
|
410
591
|
if (goalMatch) {
|
|
411
592
|
const chatId = goalMatch[1];
|
|
@@ -478,6 +659,12 @@ export class LocalBackendRouter {
|
|
|
478
659
|
data: success ? { success: true } : { detail: 'loop not found' },
|
|
479
660
|
};
|
|
480
661
|
}
|
|
662
|
+
if (method === 'GET' && pathname === '/api/v2/auth/bootstrap') {
|
|
663
|
+
const data = await resolvePublicBootstrap(request.headers ?? {}, {
|
|
664
|
+
...(url.searchParams.get('safe') === '1' ? { safeMode: true } : {}),
|
|
665
|
+
});
|
|
666
|
+
return { status: 200, data };
|
|
667
|
+
}
|
|
481
668
|
if (method === 'GET' && pathname === '/api/v2/auth/me') {
|
|
482
669
|
const authProvider = getAuthProvider();
|
|
483
670
|
if (authProvider) {
|
|
@@ -491,6 +678,70 @@ export class LocalBackendRouter {
|
|
|
491
678
|
}
|
|
492
679
|
return { status: 200, data: buildLocalApiUser() };
|
|
493
680
|
}
|
|
681
|
+
const effectivePrincipal = Object.freeze({
|
|
682
|
+
...(request.principal ?? LOCAL_DEFAULT_PRINCIPAL),
|
|
683
|
+
});
|
|
684
|
+
const effectiveOriginChannel = parseOriginChannel(request.originChannel ?? request.headers?.['x-steerable-origin-channel'], 'web');
|
|
685
|
+
if (pathname === '/api/v2/applications/active') {
|
|
686
|
+
if (method === 'GET') {
|
|
687
|
+
const application = await resolveActiveApplication(this.store, {
|
|
688
|
+
safeMode: url.searchParams.get('safe') === '1',
|
|
689
|
+
});
|
|
690
|
+
return {
|
|
691
|
+
status: 200,
|
|
692
|
+
data: {
|
|
693
|
+
application,
|
|
694
|
+
available: listRegisteredApplications(),
|
|
695
|
+
profiles: listRegisteredAgentProfiles(),
|
|
696
|
+
},
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
if (method === 'POST') {
|
|
700
|
+
const payload = this.toRecord(request.body);
|
|
701
|
+
const appId = String(payload.applicationId ?? 'default').trim() || 'default';
|
|
702
|
+
try {
|
|
703
|
+
const application = await setActiveApplication(this.store, appId);
|
|
704
|
+
return { status: 200, data: { application } };
|
|
705
|
+
}
|
|
706
|
+
catch (err) {
|
|
707
|
+
return {
|
|
708
|
+
status: 400,
|
|
709
|
+
data: { detail: err instanceof Error ? err.message : String(err) },
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return this.notFound('Not found');
|
|
714
|
+
}
|
|
715
|
+
if (method === 'POST' && pathname === '/api/v2/applications/reset') {
|
|
716
|
+
const application = await resetActiveApplication(this.store);
|
|
717
|
+
return { status: 200, data: { application } };
|
|
718
|
+
}
|
|
719
|
+
if (pathname === '/api/v2/credentials' && method === 'GET') {
|
|
720
|
+
const items = await defaultCredentialBroker.listMetadata(this.store, effectivePrincipal);
|
|
721
|
+
return { status: 200, data: { items } };
|
|
722
|
+
}
|
|
723
|
+
const credMatch = pathname.match(/^\/api\/v2\/credentials\/([^/]+)$/);
|
|
724
|
+
if (credMatch) {
|
|
725
|
+
const sourceId = decodeURIComponent(credMatch[1]);
|
|
726
|
+
try {
|
|
727
|
+
if (method === 'PUT' || method === 'POST') {
|
|
728
|
+
const payload = this.toRecord(request.body);
|
|
729
|
+
const item = await defaultCredentialBroker.setCredential(this.store, effectivePrincipal, sourceId, payload);
|
|
730
|
+
return { status: 200, data: { item } };
|
|
731
|
+
}
|
|
732
|
+
if (method === 'DELETE') {
|
|
733
|
+
const deleted = await defaultCredentialBroker.deleteCredential(this.store, effectivePrincipal, sourceId);
|
|
734
|
+
return { status: 200, data: { deleted } };
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
catch (err) {
|
|
738
|
+
if (err instanceof CredentialAccessError) {
|
|
739
|
+
return { status: err.status, data: { detail: err.message } };
|
|
740
|
+
}
|
|
741
|
+
throw err;
|
|
742
|
+
}
|
|
743
|
+
return this.notFound('Not found');
|
|
744
|
+
}
|
|
494
745
|
if (pathname === '/api/v2/portable/config' ||
|
|
495
746
|
pathname === '/api/v2/portable/preview' ||
|
|
496
747
|
pathname === '/api/v2/portable/chats' ||
|
|
@@ -2401,10 +2652,16 @@ export class LocalBackendRouter {
|
|
|
2401
2652
|
params: packMatch.params,
|
|
2402
2653
|
query: url.searchParams,
|
|
2403
2654
|
body: request.body,
|
|
2655
|
+
principal: effectivePrincipal,
|
|
2656
|
+
originChannel: effectiveOriginChannel,
|
|
2404
2657
|
...(request.headers ? { headers: request.headers } : {}),
|
|
2405
2658
|
});
|
|
2406
2659
|
}
|
|
2407
|
-
const packHttp = await invokePackHttpRoute(method, pathname, request.body
|
|
2660
|
+
const packHttp = await invokePackHttpRoute(method, pathname, request.body, {
|
|
2661
|
+
principal: effectivePrincipal,
|
|
2662
|
+
originChannel: effectiveOriginChannel,
|
|
2663
|
+
query: Object.fromEntries(url.searchParams.entries()),
|
|
2664
|
+
});
|
|
2408
2665
|
if (packHttp)
|
|
2409
2666
|
return packHttp;
|
|
2410
2667
|
return this.fallbackResponse(method, pathname);
|
|
@@ -2624,6 +2881,15 @@ export class LocalBackendRouter {
|
|
|
2624
2881
|
});
|
|
2625
2882
|
const turnEntry = { abort: turnAbort, done: turnDone };
|
|
2626
2883
|
this.activeTurnRuns.set(chatId, turnEntry);
|
|
2884
|
+
const streamOriginChannel = parseOriginChannel(request.originChannel ??
|
|
2885
|
+
request.headers?.['x-steerable-origin-channel'] ??
|
|
2886
|
+
payload.originChannel, 'web');
|
|
2887
|
+
const turnSec = beginTurnSecurityContext({
|
|
2888
|
+
chatId,
|
|
2889
|
+
principal: request.principal ?? LOCAL_DEFAULT_PRINCIPAL,
|
|
2890
|
+
originChannel: streamOriginChannel,
|
|
2891
|
+
store: this.store,
|
|
2892
|
+
});
|
|
2627
2893
|
try {
|
|
2628
2894
|
return await this.withChatWriteLock(chatId, emit, async (emit) => {
|
|
2629
2895
|
// W7-1: resume=true(仅 send 路由)续跑 durable record 里被中断的 turn,
|
|
@@ -2932,6 +3198,7 @@ export class LocalBackendRouter {
|
|
|
2932
3198
|
});
|
|
2933
3199
|
}
|
|
2934
3200
|
finally {
|
|
3201
|
+
endTurnSecurityContext(chatId, turnSec);
|
|
2935
3202
|
if (this.activeTurnRuns.get(chatId) === turnEntry) {
|
|
2936
3203
|
this.activeTurnRuns.delete(chatId);
|
|
2937
3204
|
}
|
|
@@ -4142,7 +4409,22 @@ export class LocalBackendRouter {
|
|
|
4142
4409
|
},
|
|
4143
4410
|
execSandbox,
|
|
4144
4411
|
approval: approval
|
|
4145
|
-
? {
|
|
4412
|
+
? {
|
|
4413
|
+
...approval,
|
|
4414
|
+
writableRoots: turnFileRoots,
|
|
4415
|
+
pathBase: workspaceRoot,
|
|
4416
|
+
pendingReconciliations: await (async () => {
|
|
4417
|
+
const allRecs = await ensurePhase9Store(this.store).listPendingReconciliations(chatId, { includeResolved: true });
|
|
4418
|
+
const blocking = {};
|
|
4419
|
+
for (const rec of allRecs) {
|
|
4420
|
+
if ((rec.status === 'pending' || rec.status === 'confirmed_executed') &&
|
|
4421
|
+
!(rec.toolName in blocking)) {
|
|
4422
|
+
blocking[rec.toolName] = rec.id;
|
|
4423
|
+
}
|
|
4424
|
+
}
|
|
4425
|
+
return blocking;
|
|
4426
|
+
})(),
|
|
4427
|
+
}
|
|
4146
4428
|
: undefined,
|
|
4147
4429
|
// delegate-on-pool 统一:模型的多代理面收敛为单工具
|
|
4148
4430
|
// delegate_subagent(默认开)。内置画像集(explore/research/coder)
|
|
@@ -4489,28 +4771,36 @@ export class LocalBackendRouter {
|
|
|
4489
4771
|
// settled — the crash would then look like a normal stopped turn and
|
|
4490
4772
|
// "continue last reply" would never be offered. The record stays on the
|
|
4491
4773
|
// user turn, which is what the resume path replays.
|
|
4774
|
+
const activeSec = getTurnSecurityContext(chatId);
|
|
4775
|
+
const safeAssistantText = activeSec?.redactor.hasSecrets
|
|
4776
|
+
? activeSec.redactor.redactString(assistantText)
|
|
4777
|
+
: assistantText;
|
|
4778
|
+
const rawAssistantMeta = {
|
|
4779
|
+
completionStatus,
|
|
4780
|
+
completionReason,
|
|
4781
|
+
executedActions,
|
|
4782
|
+
timeline,
|
|
4783
|
+
mode: chatMode,
|
|
4784
|
+
coreloop: true,
|
|
4785
|
+
traceId: outcomeTraceId,
|
|
4786
|
+
...(parentAgentId ? { agentId: parentAgentId } : {}),
|
|
4787
|
+
...(children.length > 0 ? { orchestrationChildEvents: children } : {}),
|
|
4788
|
+
...(durationMs != null ? { durationMs } : {}),
|
|
4789
|
+
...(autoContinuations > 0 ? { autoContinuations } : {}),
|
|
4790
|
+
...(turnFiles.length > 0 ? { turnFiles } : {}),
|
|
4791
|
+
// R6: the turn's bill, kept on the row so a replayed message shows
|
|
4792
|
+
// the same figures the live turn did — the child rows only carry
|
|
4793
|
+
// their own slice, and the per-turn total is not derivable from
|
|
4794
|
+
// them (the parent's own spend is not in any child).
|
|
4795
|
+
...(turnUsage ? { usage: turnUsage } : {}),
|
|
4796
|
+
...(failureInfo ? { failure: failureInfo } : {}),
|
|
4797
|
+
};
|
|
4798
|
+
const safeAssistantMeta = activeSec?.redactor.hasSecrets
|
|
4799
|
+
? activeSec.redactor.redactUnknown(rawAssistantMeta)
|
|
4800
|
+
: rawAssistantMeta;
|
|
4492
4801
|
const assistant = sidecarLost
|
|
4493
4802
|
? null
|
|
4494
|
-
: await this.store.addMessage(chatId, 'assistant',
|
|
4495
|
-
completionStatus,
|
|
4496
|
-
completionReason,
|
|
4497
|
-
executedActions,
|
|
4498
|
-
timeline,
|
|
4499
|
-
mode: chatMode,
|
|
4500
|
-
coreloop: true,
|
|
4501
|
-
traceId: outcomeTraceId,
|
|
4502
|
-
...(parentAgentId ? { agentId: parentAgentId } : {}),
|
|
4503
|
-
...(children.length > 0 ? { orchestrationChildEvents: children } : {}),
|
|
4504
|
-
...(durationMs != null ? { durationMs } : {}),
|
|
4505
|
-
...(autoContinuations > 0 ? { autoContinuations } : {}),
|
|
4506
|
-
...(turnFiles.length > 0 ? { turnFiles } : {}),
|
|
4507
|
-
// R6: the turn's bill, kept on the row so a replayed message shows
|
|
4508
|
-
// the same figures the live turn did — the child rows only carry
|
|
4509
|
-
// their own slice, and the per-turn total is not derivable from
|
|
4510
|
-
// them (the parent's own spend is not in any child).
|
|
4511
|
-
...(turnUsage ? { usage: turnUsage } : {}),
|
|
4512
|
-
...(failureInfo ? { failure: failureInfo } : {}),
|
|
4513
|
-
}));
|
|
4803
|
+
: await this.store.addMessage(chatId, 'assistant', safeAssistantText, JSON.stringify(safeAssistantMeta));
|
|
4514
4804
|
if (!sidecarLost) {
|
|
4515
4805
|
try {
|
|
4516
4806
|
await recordInsightTurn(this.store, {
|
|
@@ -4564,6 +4854,21 @@ export class LocalBackendRouter {
|
|
|
4564
4854
|
const durationMs = typeof sidecarTrace.durationMs === 'number'
|
|
4565
4855
|
? sidecarTrace.durationMs
|
|
4566
4856
|
: null;
|
|
4857
|
+
const rawTracePayload = {
|
|
4858
|
+
coreloop: true,
|
|
4859
|
+
trace: sidecarTrace,
|
|
4860
|
+
spans: fetched.spans ?? [],
|
|
4861
|
+
events: fetched.events ?? [],
|
|
4862
|
+
...(fetched.eventsTruncated
|
|
4863
|
+
? {
|
|
4864
|
+
eventsTruncated: true,
|
|
4865
|
+
eventsTotal: fetched.eventsTotal,
|
|
4866
|
+
}
|
|
4867
|
+
: {}),
|
|
4868
|
+
};
|
|
4869
|
+
const safeTracePayload = activeSec?.redactor.hasSecrets
|
|
4870
|
+
? activeSec.redactor.redactUnknown(rawTracePayload)
|
|
4871
|
+
: rawTracePayload;
|
|
4567
4872
|
await this.store.saveTrace({
|
|
4568
4873
|
id: traceId,
|
|
4569
4874
|
chatId,
|
|
@@ -4573,18 +4878,7 @@ export class LocalBackendRouter {
|
|
|
4573
4878
|
startedAtMs: durationMs != null ? Date.now() - durationMs : Date.now(),
|
|
4574
4879
|
durationMs,
|
|
4575
4880
|
status: passStatus,
|
|
4576
|
-
payload:
|
|
4577
|
-
coreloop: true,
|
|
4578
|
-
trace: sidecarTrace,
|
|
4579
|
-
spans: fetched.spans ?? [],
|
|
4580
|
-
events: fetched.events ?? [],
|
|
4581
|
-
...(fetched.eventsTruncated
|
|
4582
|
-
? {
|
|
4583
|
-
eventsTruncated: true,
|
|
4584
|
-
eventsTotal: fetched.eventsTotal,
|
|
4585
|
-
}
|
|
4586
|
-
: {}),
|
|
4587
|
-
},
|
|
4881
|
+
payload: safeTracePayload,
|
|
4588
4882
|
});
|
|
4589
4883
|
}
|
|
4590
4884
|
catch (err) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* State Ownership Projection Reconciliation & Pin Invariants (R2-1).
|
|
3
|
+
*
|
|
4
|
+
* Implements the rules documented in `docs/spec/state-ownership.md`:
|
|
5
|
+
* 1. Sidecar `sessions.db` is authoritative for turn history (`LedgerTurnEntry[]`);
|
|
6
|
+
* host `chat_messages` is a projection that backfills missing entries on
|
|
7
|
+
* reconnect without duplicating already-projected turns.
|
|
8
|
+
* 2. Session `Pin` bindings (`workspaceRoot`, `agentId`, `applicationId`) are
|
|
9
|
+
* captured at session creation and never drift when global defaults change.
|
|
10
|
+
*/
|
|
11
|
+
import type { ScopedStore } from '../storage/scoped-store.js';
|
|
12
|
+
export interface LedgerHistoryItem {
|
|
13
|
+
readonly ledgerSeq: number;
|
|
14
|
+
readonly role: 'user' | 'assistant' | 'system';
|
|
15
|
+
readonly content: string;
|
|
16
|
+
readonly metadata?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
export interface PinnedSessionSpec {
|
|
19
|
+
readonly workspaceRoot: string | null;
|
|
20
|
+
readonly agentId: string;
|
|
21
|
+
readonly applicationId: string;
|
|
22
|
+
readonly pinnedAt: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Reconciles host `chat_messages` projection against authoritative sidecar
|
|
26
|
+
* ledger items (`sessions.db`). Missing items are appended in `ledgerSeq`
|
|
27
|
+
* order with `ledgerSeq` recorded in `message_metadata`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function reconcileChatProjectionFromLedger(store: ScopedStore, chatId: string, ledgerItems: readonly LedgerHistoryItem[]): Promise<{
|
|
30
|
+
backfilledCount: number;
|
|
31
|
+
totalProjected: number;
|
|
32
|
+
}>;
|
|
33
|
+
/**
|
|
34
|
+
* Captures or reads the immutable `PinnedSessionSpec` for `chatId` so subsequent
|
|
35
|
+
* changes to global default agent or active application never mutate an existing
|
|
36
|
+
* session's bound environment (`Pin` category in `state-ownership.md`).
|
|
37
|
+
*/
|
|
38
|
+
export declare function ensurePinnedSessionSpec(store: ScopedStore, chatId: string, globalDefaults: {
|
|
39
|
+
readonly workspaceRoot?: string | null;
|
|
40
|
+
readonly defaultAgentId: string;
|
|
41
|
+
readonly activeApplicationId: string;
|
|
42
|
+
}): Promise<PinnedSessionSpec>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reconciles host `chat_messages` projection against authoritative sidecar
|
|
3
|
+
* ledger items (`sessions.db`). Missing items are appended in `ledgerSeq`
|
|
4
|
+
* order with `ledgerSeq` recorded in `message_metadata`.
|
|
5
|
+
*/
|
|
6
|
+
export async function reconcileChatProjectionFromLedger(store, chatId, ledgerItems) {
|
|
7
|
+
const existing = await store.listMessages(chatId);
|
|
8
|
+
const seenLedgerSeqs = new Set();
|
|
9
|
+
const existingUserAssistantPairs = new Set();
|
|
10
|
+
for (const msg of existing) {
|
|
11
|
+
if (msg.messageMetadata) {
|
|
12
|
+
try {
|
|
13
|
+
const parsed = JSON.parse(msg.messageMetadata);
|
|
14
|
+
if (typeof parsed.ledgerSeq === 'number') {
|
|
15
|
+
seenLedgerSeqs.add(parsed.ledgerSeq);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// Ignore malformed legacy metadata
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
existingUserAssistantPairs.add(`${msg.role}\u0000${msg.content}`);
|
|
23
|
+
}
|
|
24
|
+
const sorted = [...ledgerItems].sort((a, b) => a.ledgerSeq - b.ledgerSeq);
|
|
25
|
+
let backfilledCount = 0;
|
|
26
|
+
for (const item of sorted) {
|
|
27
|
+
if (seenLedgerSeqs.has(item.ledgerSeq))
|
|
28
|
+
continue;
|
|
29
|
+
// Avoid duplicating pre-existing messages written before crash without ledgerSeq
|
|
30
|
+
if (seenLedgerSeqs.size === 0 &&
|
|
31
|
+
existingUserAssistantPairs.has(`${item.role}\u0000${item.content}`)) {
|
|
32
|
+
existingUserAssistantPairs.delete(`${item.role}\u0000${item.content}`);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const mergedMeta = {
|
|
36
|
+
...(item.metadata ?? {}),
|
|
37
|
+
ledgerSeq: item.ledgerSeq,
|
|
38
|
+
reconciledFromLedger: true,
|
|
39
|
+
};
|
|
40
|
+
await store.addMessage(chatId, item.role, item.content, JSON.stringify(mergedMeta));
|
|
41
|
+
seenLedgerSeqs.add(item.ledgerSeq);
|
|
42
|
+
backfilledCount += 1;
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
backfilledCount,
|
|
46
|
+
totalProjected: existing.length + backfilledCount,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Captures or reads the immutable `PinnedSessionSpec` for `chatId` so subsequent
|
|
51
|
+
* changes to global default agent or active application never mutate an existing
|
|
52
|
+
* session's bound environment (`Pin` category in `state-ownership.md`).
|
|
53
|
+
*/
|
|
54
|
+
export async function ensurePinnedSessionSpec(store, chatId, globalDefaults) {
|
|
55
|
+
const key = `chat_pin:${chatId}`;
|
|
56
|
+
if (typeof store.getCustomSetting === 'function') {
|
|
57
|
+
const raw = await store.getCustomSetting(key);
|
|
58
|
+
if (raw) {
|
|
59
|
+
try {
|
|
60
|
+
const parsed = JSON.parse(raw);
|
|
61
|
+
if (parsed && typeof parsed.agentId === 'string' && typeof parsed.applicationId === 'string') {
|
|
62
|
+
return Object.freeze(parsed);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// Re-pin if corrupted
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const chat = await store.getChat(chatId);
|
|
71
|
+
const pinned = Object.freeze({
|
|
72
|
+
workspaceRoot: globalDefaults.workspaceRoot ?? null,
|
|
73
|
+
agentId: chat?.agentId ?? globalDefaults.defaultAgentId,
|
|
74
|
+
applicationId: globalDefaults.activeApplicationId,
|
|
75
|
+
pinnedAt: new Date().toISOString(),
|
|
76
|
+
});
|
|
77
|
+
if (typeof store.setCustomSetting === 'function') {
|
|
78
|
+
await store.setCustomSetting(key, JSON.stringify(pinned));
|
|
79
|
+
}
|
|
80
|
+
return pinned;
|
|
81
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background title drift refresh via controlled `SideCallPort` guardrails (Phase 9 R7-3).
|
|
3
|
+
*
|
|
4
|
+
* Strictly preserves Phase 1 `title_source` ownership:
|
|
5
|
+
* - Whenever `chat.titleSource === 'user'` (manually renamed by user), returns
|
|
6
|
+
* immediately with ZERO sidecall invocations and NEVER overwrites the title.
|
|
7
|
+
* - For `chat.titleSource === 'auto'`, checks every `intervalAssistantTurns` (default 6)
|
|
8
|
+
* using scrubbed `2,000` head + `8,000` tail context and a `15s` hard timeout.
|
|
9
|
+
*/
|
|
10
|
+
import { SecretRedactor } from '../auth/credentials.js';
|
|
11
|
+
import type { ScopedStore } from '../storage/scoped-store.js';
|
|
12
|
+
export declare const TITLE_REFRESH_HEAD_CHARS = 2000;
|
|
13
|
+
export declare const TITLE_REFRESH_TAIL_CHARS = 8000;
|
|
14
|
+
export declare const TITLE_REFRESH_TIMEOUT_MS = 15000;
|
|
15
|
+
export declare const TITLE_REFRESH_TURN_INTERVAL = 6;
|
|
16
|
+
export interface TitleDriftDecision {
|
|
17
|
+
readonly drifted: boolean;
|
|
18
|
+
readonly newTitle?: string;
|
|
19
|
+
}
|
|
20
|
+
export type TitleDriftEvaluator = (input: {
|
|
21
|
+
readonly caller: 'sidecall:title_refresh';
|
|
22
|
+
readonly currentTitle: string;
|
|
23
|
+
readonly scrubbedHead: string;
|
|
24
|
+
readonly scrubbedTail: string;
|
|
25
|
+
readonly signal: AbortSignal;
|
|
26
|
+
}) => Promise<TitleDriftDecision>;
|
|
27
|
+
export declare function maybeRefreshDriftedChatTitle(options: {
|
|
28
|
+
readonly store: ScopedStore;
|
|
29
|
+
readonly chatId: string;
|
|
30
|
+
readonly evaluateDrift: TitleDriftEvaluator;
|
|
31
|
+
readonly redactor?: SecretRedactor;
|
|
32
|
+
readonly parentSignal?: AbortSignal;
|
|
33
|
+
readonly intervalAssistantTurns?: number;
|
|
34
|
+
readonly timeoutMs?: number;
|
|
35
|
+
}): Promise<{
|
|
36
|
+
readonly updated: boolean;
|
|
37
|
+
readonly skippedReason?: 'chat_not_found' | 'user_locked_title' | 'below_interval' | 'no_drift' | 'degraded';
|
|
38
|
+
readonly title?: string;
|
|
39
|
+
}>;
|