@steerable/agent-shell 0.12.8 → 0.14.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/dist/attachments/image-normalizer.d.ts +39 -0
- package/dist/attachments/image-normalizer.js +131 -0
- 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/image-attachment.js +10 -5
- 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 +602 -45
- 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 +38 -0
- package/dist/memory/injector.js +122 -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/raster-image.d.ts +7 -1
- package/dist/raster-image.js +34 -0
- 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/index.d.ts +1 -1
- 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 +146 -18
- package/dist/sidecar/supervisor.d.ts +31 -1
- package/dist/sidecar/supervisor.js +47 -0
- package/dist/sidecar/types.d.ts +72 -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/reliability-summary.d.ts +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
|
@@ -5,6 +5,7 @@ import { readFile, realpath, stat } from 'node:fs/promises';
|
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import { getLocale, tFor } from '../i18n.js';
|
|
8
|
+
import { classifyErrorMessage } from '@steerable/agent-protocol';
|
|
8
9
|
import { getAppRootDir, getUserDataDir, shellOpenPath } from '../runtime.js';
|
|
9
10
|
import { acquireChatWriteLock, ChatBusyError, } from '../storage/process-locks.js';
|
|
10
11
|
import { llmService, getSidecarSupervisor, whenSidecarSupervisor } from '../llm/index.js';
|
|
@@ -62,7 +63,15 @@ import { invokePackHttpRoute } from '../host/http-routes.js';
|
|
|
62
63
|
import { installProductCli } from '../cli-install.js';
|
|
63
64
|
import { collectTurnFiles } from './turn-files.js';
|
|
64
65
|
import { resolveMentionedPaths } from './mentioned-paths.js';
|
|
65
|
-
import { getAuthProvider } from '../auth/index.js';
|
|
66
|
+
import { LOCAL_DEFAULT_PRINCIPAL, getAuthProvider, parseOriginChannel, resolvePublicBootstrap, } from '../auth/index.js';
|
|
67
|
+
import { CredentialAccessError, defaultCredentialBroker, } from '../auth/credentials.js';
|
|
68
|
+
import { listRegisteredAgentProfiles, listRegisteredApplications, resetActiveApplication, resolveActiveApplication, setActiveApplication, } from '../scenario/applications.js';
|
|
69
|
+
import { beginTurnSecurityContext, endTurnSecurityContext, getTurnSecurityContext, } from './turn-security-context.js';
|
|
70
|
+
import { ensurePhase9Store } from '../storage/fde-fallback.js';
|
|
71
|
+
import { dispatchUiSurfaceAction, refreshPersistedUiSurface, renderAndPersistUiSurface, } from './ui-surface.js';
|
|
72
|
+
import { assembleFactChainGraph } from './fact-chain.js';
|
|
73
|
+
import { bumpSessionCompactionEpoch, getSessionCompactionEpoch, } from '../memory/injector.js';
|
|
74
|
+
import { handleMemoryHttpRoute } from '../memory/routes.js';
|
|
66
75
|
function stringRecord(value) {
|
|
67
76
|
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
68
77
|
return {};
|
|
@@ -372,6 +381,7 @@ export class LocalBackendRouter {
|
|
|
372
381
|
this.resolveStore = options.resolveStore ?? (() => options.store);
|
|
373
382
|
this.broadcast = options.broadcast ?? null;
|
|
374
383
|
this.taskService = options.taskService ?? null;
|
|
384
|
+
this.toolRouter.setPhase9Store?.(options.store);
|
|
375
385
|
const goals = this.toolRouter.goals?.();
|
|
376
386
|
goals?.onChange((chatId, goal) => {
|
|
377
387
|
this.broadcast?.('goal-changed', { chatId, goal });
|
|
@@ -406,6 +416,179 @@ export class LocalBackendRouter {
|
|
|
406
416
|
const { method } = request;
|
|
407
417
|
const url = new URL(request.path, 'http://local.backend');
|
|
408
418
|
const pathname = url.pathname;
|
|
419
|
+
if (pathname.startsWith('/api/v2/memory')) {
|
|
420
|
+
const memRes = await handleMemoryHttpRoute({
|
|
421
|
+
method,
|
|
422
|
+
pathname,
|
|
423
|
+
searchParams: url.searchParams,
|
|
424
|
+
body: this.toRecord(request.body),
|
|
425
|
+
store: this.store,
|
|
426
|
+
principal: request.principal,
|
|
427
|
+
});
|
|
428
|
+
if (memRes)
|
|
429
|
+
return memRes;
|
|
430
|
+
}
|
|
431
|
+
const reconciliationsMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/reconciliations$/);
|
|
432
|
+
if (reconciliationsMatch && method === 'GET') {
|
|
433
|
+
const chatId = decodeURIComponent(reconciliationsMatch[1]);
|
|
434
|
+
const chat = await this.store.getChat(chatId);
|
|
435
|
+
if (!chat)
|
|
436
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
437
|
+
const includeResolved = url.searchParams.get('includeResolved') === '1';
|
|
438
|
+
const reconciliations = await ensurePhase9Store(this.store).listPendingReconciliations(chatId, { includeResolved });
|
|
439
|
+
return { status: 200, data: { reconciliations } };
|
|
440
|
+
}
|
|
441
|
+
const reconcileMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/reconcile$/);
|
|
442
|
+
if (reconcileMatch && method === 'POST') {
|
|
443
|
+
const chatId = decodeURIComponent(reconcileMatch[1]);
|
|
444
|
+
const chat = await this.store.getChat(chatId);
|
|
445
|
+
if (!chat)
|
|
446
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
447
|
+
const payload = this.toRecord(request.body);
|
|
448
|
+
const reconciliationId = String(payload.reconciliationId ?? '').trim();
|
|
449
|
+
const rawInput = String(payload.resolution ?? payload.status ?? '').trim();
|
|
450
|
+
const resolutionMap = {
|
|
451
|
+
confirmed_succeeded: 'confirmed_executed',
|
|
452
|
+
confirmed_executed: 'confirmed_executed',
|
|
453
|
+
resolved_committed: 'confirmed_executed',
|
|
454
|
+
confirmed_not_executed: 'confirmed_not_executed',
|
|
455
|
+
resolved_not_committed: 'confirmed_not_executed',
|
|
456
|
+
};
|
|
457
|
+
const normalizedStatus = resolutionMap[rawInput];
|
|
458
|
+
if (!reconciliationId || !normalizedStatus) {
|
|
459
|
+
return {
|
|
460
|
+
status: 400,
|
|
461
|
+
data: {
|
|
462
|
+
detail: 'reconciliationId and resolution (confirmed_succeeded | confirmed_not_executed) are required',
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
const note = typeof payload.note === 'string' && payload.note.trim() ? payload.note.trim() : null;
|
|
467
|
+
const principal = request.principal ?? LOCAL_DEFAULT_PRINCIPAL;
|
|
468
|
+
const updated = await ensurePhase9Store(this.store).resolvePendingReconciliation({
|
|
469
|
+
chatId,
|
|
470
|
+
reconciliationId,
|
|
471
|
+
status: normalizedStatus,
|
|
472
|
+
resolutionNote: note,
|
|
473
|
+
resolvedBy: principal.id,
|
|
474
|
+
});
|
|
475
|
+
if (!updated) {
|
|
476
|
+
return { status: 404, data: { detail: 'reconciliation not found' } };
|
|
477
|
+
}
|
|
478
|
+
const ledgerSummary = normalizedStatus === 'confirmed_executed'
|
|
479
|
+
? `[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.`
|
|
480
|
+
: `[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.`;
|
|
481
|
+
await this.store.addMessage(chatId, 'system', ledgerSummary);
|
|
482
|
+
this.broadcast?.('reconciliation:updated', { chatId, reconciliation: updated });
|
|
483
|
+
return { status: 200, data: { reconciliation: updated, ledgerNote: ledgerSummary } };
|
|
484
|
+
}
|
|
485
|
+
const surfacesListMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/surfaces$/);
|
|
486
|
+
if (surfacesListMatch) {
|
|
487
|
+
const chatId = decodeURIComponent(surfacesListMatch[1]);
|
|
488
|
+
if (!await this.store.getChat(chatId)) {
|
|
489
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
490
|
+
}
|
|
491
|
+
if (method === 'GET') {
|
|
492
|
+
const rows = await ensurePhase9Store(this.store).listChatUiSurfaces(chatId);
|
|
493
|
+
const surfaces = rows.map((r) => ({
|
|
494
|
+
...(r.state.rawPayload && typeof r.state.rawPayload === 'object'
|
|
495
|
+
? r.state.rawPayload
|
|
496
|
+
: {}),
|
|
497
|
+
surfaceId: r.surfaceId,
|
|
498
|
+
revision: r.revision,
|
|
499
|
+
resolvedData: r.state.resolvedData ?? {},
|
|
500
|
+
sourceHashes: r.state.sourceHashes ?? {},
|
|
501
|
+
}));
|
|
502
|
+
return { status: 200, data: { surfaces } };
|
|
503
|
+
}
|
|
504
|
+
if (method === 'POST') {
|
|
505
|
+
const surface = await renderAndPersistUiSurface({
|
|
506
|
+
store: this.store,
|
|
507
|
+
chatId,
|
|
508
|
+
principal: request.principal,
|
|
509
|
+
raw: this.toRecord(request.body),
|
|
510
|
+
});
|
|
511
|
+
this.broadcast?.('ui_surface:updated', { chatId, surface });
|
|
512
|
+
return { status: 200, data: { surface } };
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
const surfaceRefreshMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/surfaces\/([^/]+)\/refresh$/);
|
|
516
|
+
if (surfaceRefreshMatch && method === 'GET') {
|
|
517
|
+
const chatId = decodeURIComponent(surfaceRefreshMatch[1]);
|
|
518
|
+
const surfaceId = decodeURIComponent(surfaceRefreshMatch[2]);
|
|
519
|
+
if (!await this.store.getChat(chatId)) {
|
|
520
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
521
|
+
}
|
|
522
|
+
const surface = await refreshPersistedUiSurface({
|
|
523
|
+
store: this.store,
|
|
524
|
+
chatId,
|
|
525
|
+
surfaceId,
|
|
526
|
+
principal: request.principal,
|
|
527
|
+
});
|
|
528
|
+
if (!surface)
|
|
529
|
+
return { status: 404, data: { detail: 'surface not found' } };
|
|
530
|
+
return { status: 200, data: { surface } };
|
|
531
|
+
}
|
|
532
|
+
const surfaceActionMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/surfaces\/([^/]+)\/actions$/);
|
|
533
|
+
if (surfaceActionMatch && method === 'POST') {
|
|
534
|
+
const chatId = decodeURIComponent(surfaceActionMatch[1]);
|
|
535
|
+
const surfaceId = decodeURIComponent(surfaceActionMatch[2]);
|
|
536
|
+
if (!await this.store.getChat(chatId)) {
|
|
537
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
538
|
+
}
|
|
539
|
+
return await dispatchUiSurfaceAction({
|
|
540
|
+
store: this.store,
|
|
541
|
+
toolRouter: this.toolRouter,
|
|
542
|
+
chatId,
|
|
543
|
+
surfaceId,
|
|
544
|
+
principal: request.principal,
|
|
545
|
+
originChannel: request.originChannel,
|
|
546
|
+
body: this.toRecord(request.body),
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
const factChainMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/fact-chain$/);
|
|
550
|
+
if (factChainMatch && method === 'GET') {
|
|
551
|
+
const chatId = decodeURIComponent(factChainMatch[1]);
|
|
552
|
+
if (!await this.store.getChat(chatId)) {
|
|
553
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
554
|
+
}
|
|
555
|
+
const rawKind = url.searchParams.get('targetKind') ?? 'message';
|
|
556
|
+
const targetKind = rawKind === 'tool' || rawKind === 'deliverable' ? rawKind : 'message';
|
|
557
|
+
const targetId = url.searchParams.get('targetId') ?? '';
|
|
558
|
+
const graph = await assembleFactChainGraph({
|
|
559
|
+
store: this.store,
|
|
560
|
+
chatId,
|
|
561
|
+
targetKind,
|
|
562
|
+
targetId,
|
|
563
|
+
});
|
|
564
|
+
return { status: 200, data: { graph } };
|
|
565
|
+
}
|
|
566
|
+
const deliverablesListMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/deliverables$/);
|
|
567
|
+
if (deliverablesListMatch && method === 'GET') {
|
|
568
|
+
const chatId = decodeURIComponent(deliverablesListMatch[1]);
|
|
569
|
+
if (!await this.store.getChat(chatId)) {
|
|
570
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
571
|
+
}
|
|
572
|
+
const deliverables = await ensurePhase9Store(this.store).listChatDeliverables(chatId);
|
|
573
|
+
return { status: 200, data: { deliverables } };
|
|
574
|
+
}
|
|
575
|
+
const deliverableSnapshotMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/deliverables\/([^/]+)\/snapshot$/);
|
|
576
|
+
if (deliverableSnapshotMatch && method === 'GET') {
|
|
577
|
+
const chatId = decodeURIComponent(deliverableSnapshotMatch[1]);
|
|
578
|
+
const deliverableId = decodeURIComponent(deliverableSnapshotMatch[2]);
|
|
579
|
+
const deliverables = await ensurePhase9Store(this.store).listChatDeliverables(chatId);
|
|
580
|
+
const deliv = deliverables.find((d) => d.id === deliverableId);
|
|
581
|
+
if (!deliv || !deliv.reportPath) {
|
|
582
|
+
return { status: 404, data: { detail: 'deliverable snapshot not found' } };
|
|
583
|
+
}
|
|
584
|
+
return {
|
|
585
|
+
kind: 'file',
|
|
586
|
+
status: 200,
|
|
587
|
+
filePath: deliv.reportPath,
|
|
588
|
+
contentType: deliv.mimeType || 'application/octet-stream',
|
|
589
|
+
fileName: deliv.fileName,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
409
592
|
const goalMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/goal$/);
|
|
410
593
|
if (goalMatch) {
|
|
411
594
|
const chatId = goalMatch[1];
|
|
@@ -478,6 +661,12 @@ export class LocalBackendRouter {
|
|
|
478
661
|
data: success ? { success: true } : { detail: 'loop not found' },
|
|
479
662
|
};
|
|
480
663
|
}
|
|
664
|
+
if (method === 'GET' && pathname === '/api/v2/auth/bootstrap') {
|
|
665
|
+
const data = await resolvePublicBootstrap(request.headers ?? {}, {
|
|
666
|
+
...(url.searchParams.get('safe') === '1' ? { safeMode: true } : {}),
|
|
667
|
+
});
|
|
668
|
+
return { status: 200, data };
|
|
669
|
+
}
|
|
481
670
|
if (method === 'GET' && pathname === '/api/v2/auth/me') {
|
|
482
671
|
const authProvider = getAuthProvider();
|
|
483
672
|
if (authProvider) {
|
|
@@ -491,6 +680,70 @@ export class LocalBackendRouter {
|
|
|
491
680
|
}
|
|
492
681
|
return { status: 200, data: buildLocalApiUser() };
|
|
493
682
|
}
|
|
683
|
+
const effectivePrincipal = Object.freeze({
|
|
684
|
+
...(request.principal ?? LOCAL_DEFAULT_PRINCIPAL),
|
|
685
|
+
});
|
|
686
|
+
const effectiveOriginChannel = parseOriginChannel(request.originChannel ?? request.headers?.['x-steerable-origin-channel'], 'web');
|
|
687
|
+
if (pathname === '/api/v2/applications/active') {
|
|
688
|
+
if (method === 'GET') {
|
|
689
|
+
const application = await resolveActiveApplication(this.store, {
|
|
690
|
+
safeMode: url.searchParams.get('safe') === '1',
|
|
691
|
+
});
|
|
692
|
+
return {
|
|
693
|
+
status: 200,
|
|
694
|
+
data: {
|
|
695
|
+
application,
|
|
696
|
+
available: listRegisteredApplications(),
|
|
697
|
+
profiles: listRegisteredAgentProfiles(),
|
|
698
|
+
},
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
if (method === 'POST') {
|
|
702
|
+
const payload = this.toRecord(request.body);
|
|
703
|
+
const appId = String(payload.applicationId ?? 'default').trim() || 'default';
|
|
704
|
+
try {
|
|
705
|
+
const application = await setActiveApplication(this.store, appId);
|
|
706
|
+
return { status: 200, data: { application } };
|
|
707
|
+
}
|
|
708
|
+
catch (err) {
|
|
709
|
+
return {
|
|
710
|
+
status: 400,
|
|
711
|
+
data: { detail: err instanceof Error ? err.message : String(err) },
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return this.notFound('Not found');
|
|
716
|
+
}
|
|
717
|
+
if (method === 'POST' && pathname === '/api/v2/applications/reset') {
|
|
718
|
+
const application = await resetActiveApplication(this.store);
|
|
719
|
+
return { status: 200, data: { application } };
|
|
720
|
+
}
|
|
721
|
+
if (pathname === '/api/v2/credentials' && method === 'GET') {
|
|
722
|
+
const items = await defaultCredentialBroker.listMetadata(this.store, effectivePrincipal);
|
|
723
|
+
return { status: 200, data: { items } };
|
|
724
|
+
}
|
|
725
|
+
const credMatch = pathname.match(/^\/api\/v2\/credentials\/([^/]+)$/);
|
|
726
|
+
if (credMatch) {
|
|
727
|
+
const sourceId = decodeURIComponent(credMatch[1]);
|
|
728
|
+
try {
|
|
729
|
+
if (method === 'PUT' || method === 'POST') {
|
|
730
|
+
const payload = this.toRecord(request.body);
|
|
731
|
+
const item = await defaultCredentialBroker.setCredential(this.store, effectivePrincipal, sourceId, payload);
|
|
732
|
+
return { status: 200, data: { item } };
|
|
733
|
+
}
|
|
734
|
+
if (method === 'DELETE') {
|
|
735
|
+
const deleted = await defaultCredentialBroker.deleteCredential(this.store, effectivePrincipal, sourceId);
|
|
736
|
+
return { status: 200, data: { deleted } };
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
catch (err) {
|
|
740
|
+
if (err instanceof CredentialAccessError) {
|
|
741
|
+
return { status: err.status, data: { detail: err.message } };
|
|
742
|
+
}
|
|
743
|
+
throw err;
|
|
744
|
+
}
|
|
745
|
+
return this.notFound('Not found');
|
|
746
|
+
}
|
|
494
747
|
if (pathname === '/api/v2/portable/config' ||
|
|
495
748
|
pathname === '/api/v2/portable/preview' ||
|
|
496
749
|
pathname === '/api/v2/portable/chats' ||
|
|
@@ -1286,18 +1539,160 @@ export class LocalBackendRouter {
|
|
|
1286
1539
|
}
|
|
1287
1540
|
const compactMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/compact$/);
|
|
1288
1541
|
if (compactMatch && method === 'POST') {
|
|
1289
|
-
const chatId = compactMatch[1];
|
|
1542
|
+
const chatId = decodeURIComponent(compactMatch[1]);
|
|
1290
1543
|
const chat = await this.store.getChat(chatId);
|
|
1291
1544
|
if (!chat)
|
|
1292
1545
|
return { status: 404, data: { detail: 'chat not found' } };
|
|
1546
|
+
const body = this.toRecord(request.body);
|
|
1547
|
+
const focus = typeof body.focus === 'string' && body.focus.trim() ? body.focus.trim() : undefined;
|
|
1548
|
+
const keepHeadTurns = typeof body.keepHeadTurns === 'number' && Number.isInteger(body.keepHeadTurns)
|
|
1549
|
+
? body.keepHeadTurns
|
|
1550
|
+
: undefined;
|
|
1551
|
+
const keepTailMessages = typeof body.keepTailMessages === 'number' && Number.isInteger(body.keepTailMessages)
|
|
1552
|
+
? body.keepTailMessages
|
|
1553
|
+
: undefined;
|
|
1554
|
+
const supervisor = getSidecarSupervisor();
|
|
1555
|
+
const activeStreamId = getActiveCoreLoopStreamId(chatId);
|
|
1556
|
+
if (activeStreamId && supervisor) {
|
|
1557
|
+
const queued = await supervisor.compactChat(activeStreamId, {
|
|
1558
|
+
focus,
|
|
1559
|
+
keepHeadTurns,
|
|
1560
|
+
keepTailMessages,
|
|
1561
|
+
});
|
|
1562
|
+
return {
|
|
1563
|
+
status: 200,
|
|
1564
|
+
data: {
|
|
1565
|
+
compacted: 0,
|
|
1566
|
+
queuedOnActiveTurn: queued,
|
|
1567
|
+
compactionEpoch: getSessionCompactionEpoch(chatId),
|
|
1568
|
+
},
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
if (supervisor) {
|
|
1572
|
+
const activeRecordId = (await this.store.getChatRecordId(chatId)) ?? chatId;
|
|
1573
|
+
const llm = resolveRuntimeLlmSettings(await this.store.getLlmSettings());
|
|
1574
|
+
const rpcRes = await supervisor.sessionCompact({
|
|
1575
|
+
recordId: activeRecordId,
|
|
1576
|
+
focus,
|
|
1577
|
+
keepHeadTurns,
|
|
1578
|
+
keepTailMessages,
|
|
1579
|
+
...(llm?.provider ? { provider: llm.provider } : {}),
|
|
1580
|
+
...(llm?.model ? { model: llm.model } : {}),
|
|
1581
|
+
...(llm?.apiKey ? { apiKey: llm.apiKey } : {}),
|
|
1582
|
+
...(llm?.baseUrl ? { baseUrl: llm.baseUrl } : {}),
|
|
1583
|
+
});
|
|
1584
|
+
if (rpcRes && rpcRes.recordExists) {
|
|
1585
|
+
if (rpcRes.compacted > 0) {
|
|
1586
|
+
await this.store.replaceChatMessages(chatId, rpcRes.messages
|
|
1587
|
+
.filter((m) => m.role === 'user' || m.role === 'assistant')
|
|
1588
|
+
.map((m) => ({
|
|
1589
|
+
role: m.role,
|
|
1590
|
+
content: m.content,
|
|
1591
|
+
})));
|
|
1592
|
+
const epoch = bumpSessionCompactionEpoch(chatId);
|
|
1593
|
+
return {
|
|
1594
|
+
status: 200,
|
|
1595
|
+
data: {
|
|
1596
|
+
compacted: rpcRes.compacted,
|
|
1597
|
+
preTokens: rpcRes.preTokens,
|
|
1598
|
+
postTokens: rpcRes.postTokens,
|
|
1599
|
+
preBytes: rpcRes.preBytes,
|
|
1600
|
+
postBytes: rpcRes.postBytes,
|
|
1601
|
+
summaryText: rpcRes.summaryText ?? '',
|
|
1602
|
+
compactionEpoch: epoch,
|
|
1603
|
+
},
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
return {
|
|
1607
|
+
status: 200,
|
|
1608
|
+
data: {
|
|
1609
|
+
compacted: 0,
|
|
1610
|
+
preTokens: rpcRes.preTokens,
|
|
1611
|
+
postTokens: rpcRes.postTokens,
|
|
1612
|
+
preBytes: rpcRes.preBytes,
|
|
1613
|
+
postBytes: rpcRes.postBytes,
|
|
1614
|
+
compactionEpoch: getSessionCompactionEpoch(chatId),
|
|
1615
|
+
},
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1293
1619
|
const plan = compactHistory(await this.historyTurns(chatId));
|
|
1294
|
-
if (!plan)
|
|
1295
|
-
return {
|
|
1620
|
+
if (!plan) {
|
|
1621
|
+
return {
|
|
1622
|
+
status: 200,
|
|
1623
|
+
data: { compacted: 0, compactionEpoch: getSessionCompactionEpoch(chatId) },
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1296
1626
|
await this.store.deleteMessagesFrom(chatId, plan.deleteFromId);
|
|
1297
1627
|
for (const write of plan.writes) {
|
|
1298
1628
|
await this.store.addMessage(chatId, write.role, write.content, write.messageMetadata);
|
|
1299
1629
|
}
|
|
1300
|
-
|
|
1630
|
+
const epoch = bumpSessionCompactionEpoch(chatId);
|
|
1631
|
+
return {
|
|
1632
|
+
status: 200,
|
|
1633
|
+
data: { compacted: plan.compacted, compactionEpoch: epoch },
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
const contextStatusMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/context-status$/);
|
|
1637
|
+
if (contextStatusMatch && method === 'GET') {
|
|
1638
|
+
const chatId = decodeURIComponent(contextStatusMatch[1]);
|
|
1639
|
+
const chat = await this.store.getChat(chatId);
|
|
1640
|
+
if (!chat)
|
|
1641
|
+
return { status: 404, data: { detail: 'chat not found' } };
|
|
1642
|
+
const llm = resolveRuntimeLlmSettings(await this.store.getLlmSettings());
|
|
1643
|
+
const supervisor = getSidecarSupervisor();
|
|
1644
|
+
const activeRecordId = (await this.store.getChatRecordId(chatId)) ?? chatId;
|
|
1645
|
+
const rpcStatus = supervisor
|
|
1646
|
+
? await supervisor.sessionContextStatus({
|
|
1647
|
+
recordId: activeRecordId,
|
|
1648
|
+
...(llm?.model ? { model: llm.model } : {}),
|
|
1649
|
+
...(llm?.provider ? { provider: llm.provider } : {}),
|
|
1650
|
+
...(llm?.baseUrl ? { baseUrl: llm.baseUrl } : {}),
|
|
1651
|
+
})
|
|
1652
|
+
: null;
|
|
1653
|
+
const uiMessages = await this.store.listMessages(chatId);
|
|
1654
|
+
let lastPromptTokens = 0;
|
|
1655
|
+
let lastCachedTokens = 0;
|
|
1656
|
+
let lastCacheCreationTokens = 0;
|
|
1657
|
+
for (const msg of uiMessages) {
|
|
1658
|
+
if (msg.role !== 'assistant' || !msg.messageMetadata)
|
|
1659
|
+
continue;
|
|
1660
|
+
try {
|
|
1661
|
+
const meta = JSON.parse(msg.messageMetadata);
|
|
1662
|
+
if (meta?.turnUsage) {
|
|
1663
|
+
lastPromptTokens = Number(meta.turnUsage.promptTokens ?? 0);
|
|
1664
|
+
lastCachedTokens = Number(meta.turnUsage.cachedPromptTokens ?? 0);
|
|
1665
|
+
lastCacheCreationTokens = Number(meta.turnUsage.cacheCreationTokens ?? 0);
|
|
1666
|
+
break;
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
catch {
|
|
1670
|
+
// ignore malformed metadata
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
const fallbackBytes = uiMessages.reduce((sum, m) => sum + Buffer.byteLength(m.content || '', 'utf8') + 64, 0);
|
|
1674
|
+
const fallbackTokens = Math.ceil(fallbackBytes / 3.5);
|
|
1675
|
+
const maxRequestBytes = Number(process.env.STEERABLE_MAX_REQUEST_BYTES || 0) > 0
|
|
1676
|
+
? Number(process.env.STEERABLE_MAX_REQUEST_BYTES)
|
|
1677
|
+
: 4_194_304;
|
|
1678
|
+
return {
|
|
1679
|
+
status: 200,
|
|
1680
|
+
data: {
|
|
1681
|
+
chatId,
|
|
1682
|
+
recordId: activeRecordId,
|
|
1683
|
+
estimatedTokens: rpcStatus?.recordExists
|
|
1684
|
+
? rpcStatus.estimatedTokens
|
|
1685
|
+
: Math.max(lastPromptTokens, fallbackTokens),
|
|
1686
|
+
maxContextTokens: rpcStatus?.maxContextTokens ?? 131_072,
|
|
1687
|
+
estimatedBytes: rpcStatus?.recordExists ? rpcStatus.estimatedBytes : fallbackBytes,
|
|
1688
|
+
maxRequestBytes: rpcStatus?.maxRequestBytes ?? maxRequestBytes,
|
|
1689
|
+
promptTokens: lastPromptTokens,
|
|
1690
|
+
cachedPromptTokens: lastCachedTokens,
|
|
1691
|
+
cacheCreationTokens: lastCacheCreationTokens,
|
|
1692
|
+
compactionCount: rpcStatus?.compactionCount ?? 0,
|
|
1693
|
+
compactionEpoch: getSessionCompactionEpoch(chatId),
|
|
1694
|
+
},
|
|
1695
|
+
};
|
|
1301
1696
|
}
|
|
1302
1697
|
const forkMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/fork$/);
|
|
1303
1698
|
if (forkMatch && method === 'POST') {
|
|
@@ -2043,6 +2438,95 @@ export class LocalBackendRouter {
|
|
|
2043
2438
|
}
|
|
2044
2439
|
return { status: 200, data: { posture: supervisor.getSandboxPosture(), egress } };
|
|
2045
2440
|
}
|
|
2441
|
+
if (method === 'GET' && pathname === '/api/v2/license/status') {
|
|
2442
|
+
const supervisor = await whenSidecarSupervisor();
|
|
2443
|
+
if (!supervisor) {
|
|
2444
|
+
return {
|
|
2445
|
+
status: 200,
|
|
2446
|
+
data: {
|
|
2447
|
+
enforced: false,
|
|
2448
|
+
state: 'disabled',
|
|
2449
|
+
errorCode: null,
|
|
2450
|
+
message: null,
|
|
2451
|
+
licenseId: null,
|
|
2452
|
+
customer: null,
|
|
2453
|
+
product: null,
|
|
2454
|
+
features: [],
|
|
2455
|
+
notBefore: null,
|
|
2456
|
+
notAfter: null,
|
|
2457
|
+
graceDays: null,
|
|
2458
|
+
daysRemaining: null,
|
|
2459
|
+
graceDaysRemaining: null,
|
|
2460
|
+
maxUsers: null,
|
|
2461
|
+
maxConcurrentRuns: null,
|
|
2462
|
+
activeConcurrentRuns: 0,
|
|
2463
|
+
deploymentId: null,
|
|
2464
|
+
},
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
return { status: 200, data: await supervisor.getLicenseStatus() };
|
|
2468
|
+
}
|
|
2469
|
+
if (method === 'POST' && pathname === '/api/v2/license/reload') {
|
|
2470
|
+
const supervisor = await whenSidecarSupervisor();
|
|
2471
|
+
if (!supervisor) {
|
|
2472
|
+
return {
|
|
2473
|
+
status: 200,
|
|
2474
|
+
data: {
|
|
2475
|
+
enforced: false,
|
|
2476
|
+
state: 'disabled',
|
|
2477
|
+
errorCode: null,
|
|
2478
|
+
message: null,
|
|
2479
|
+
licenseId: null,
|
|
2480
|
+
customer: null,
|
|
2481
|
+
product: null,
|
|
2482
|
+
features: [],
|
|
2483
|
+
notBefore: null,
|
|
2484
|
+
notAfter: null,
|
|
2485
|
+
graceDays: null,
|
|
2486
|
+
daysRemaining: null,
|
|
2487
|
+
graceDaysRemaining: null,
|
|
2488
|
+
maxUsers: null,
|
|
2489
|
+
maxConcurrentRuns: null,
|
|
2490
|
+
activeConcurrentRuns: 0,
|
|
2491
|
+
deploymentId: null,
|
|
2492
|
+
},
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
return { status: 200, data: await supervisor.reloadLicense() };
|
|
2496
|
+
}
|
|
2497
|
+
if (method === 'POST' && pathname === '/api/v2/license/verify') {
|
|
2498
|
+
const payload = this.toRecord(request.body);
|
|
2499
|
+
const content = typeof payload.content === 'string' ? payload.content : '';
|
|
2500
|
+
if (!content.trim()) {
|
|
2501
|
+
return { status: 400, data: { error: 'content required' } };
|
|
2502
|
+
}
|
|
2503
|
+
const supervisor = await whenSidecarSupervisor();
|
|
2504
|
+
if (!supervisor) {
|
|
2505
|
+
return {
|
|
2506
|
+
status: 200,
|
|
2507
|
+
data: {
|
|
2508
|
+
enforced: false,
|
|
2509
|
+
state: 'disabled',
|
|
2510
|
+
errorCode: null,
|
|
2511
|
+
message: null,
|
|
2512
|
+
licenseId: null,
|
|
2513
|
+
customer: null,
|
|
2514
|
+
product: null,
|
|
2515
|
+
features: [],
|
|
2516
|
+
notBefore: null,
|
|
2517
|
+
notAfter: null,
|
|
2518
|
+
graceDays: null,
|
|
2519
|
+
daysRemaining: null,
|
|
2520
|
+
graceDaysRemaining: null,
|
|
2521
|
+
maxUsers: null,
|
|
2522
|
+
maxConcurrentRuns: null,
|
|
2523
|
+
activeConcurrentRuns: 0,
|
|
2524
|
+
deploymentId: null,
|
|
2525
|
+
},
|
|
2526
|
+
};
|
|
2527
|
+
}
|
|
2528
|
+
return { status: 200, data: await supervisor.verifyLicense(content) };
|
|
2529
|
+
}
|
|
2046
2530
|
if (method === 'GET' && pathname === '/api/v2/llm/account') {
|
|
2047
2531
|
const settings = resolveRuntimeLlmSettings(await this.store.getLlmSettings());
|
|
2048
2532
|
const account = await readLlmAccount(settings, {
|
|
@@ -2401,10 +2885,16 @@ export class LocalBackendRouter {
|
|
|
2401
2885
|
params: packMatch.params,
|
|
2402
2886
|
query: url.searchParams,
|
|
2403
2887
|
body: request.body,
|
|
2888
|
+
principal: effectivePrincipal,
|
|
2889
|
+
originChannel: effectiveOriginChannel,
|
|
2404
2890
|
...(request.headers ? { headers: request.headers } : {}),
|
|
2405
2891
|
});
|
|
2406
2892
|
}
|
|
2407
|
-
const packHttp = await invokePackHttpRoute(method, pathname, request.body
|
|
2893
|
+
const packHttp = await invokePackHttpRoute(method, pathname, request.body, {
|
|
2894
|
+
principal: effectivePrincipal,
|
|
2895
|
+
originChannel: effectiveOriginChannel,
|
|
2896
|
+
query: Object.fromEntries(url.searchParams.entries()),
|
|
2897
|
+
});
|
|
2408
2898
|
if (packHttp)
|
|
2409
2899
|
return packHttp;
|
|
2410
2900
|
return this.fallbackResponse(method, pathname);
|
|
@@ -2624,6 +3114,15 @@ export class LocalBackendRouter {
|
|
|
2624
3114
|
});
|
|
2625
3115
|
const turnEntry = { abort: turnAbort, done: turnDone };
|
|
2626
3116
|
this.activeTurnRuns.set(chatId, turnEntry);
|
|
3117
|
+
const streamOriginChannel = parseOriginChannel(request.originChannel ??
|
|
3118
|
+
request.headers?.['x-steerable-origin-channel'] ??
|
|
3119
|
+
payload.originChannel, 'web');
|
|
3120
|
+
const turnSec = beginTurnSecurityContext({
|
|
3121
|
+
chatId,
|
|
3122
|
+
principal: request.principal ?? LOCAL_DEFAULT_PRINCIPAL,
|
|
3123
|
+
originChannel: streamOriginChannel,
|
|
3124
|
+
store: this.store,
|
|
3125
|
+
});
|
|
2627
3126
|
try {
|
|
2628
3127
|
return await this.withChatWriteLock(chatId, emit, async (emit) => {
|
|
2629
3128
|
// W7-1: resume=true(仅 send 路由)续跑 durable record 里被中断的 turn,
|
|
@@ -2932,6 +3431,7 @@ export class LocalBackendRouter {
|
|
|
2932
3431
|
});
|
|
2933
3432
|
}
|
|
2934
3433
|
finally {
|
|
3434
|
+
endTurnSecurityContext(chatId, turnSec);
|
|
2935
3435
|
if (this.activeTurnRuns.get(chatId) === turnEntry) {
|
|
2936
3436
|
this.activeTurnRuns.delete(chatId);
|
|
2937
3437
|
}
|
|
@@ -4142,7 +4642,22 @@ export class LocalBackendRouter {
|
|
|
4142
4642
|
},
|
|
4143
4643
|
execSandbox,
|
|
4144
4644
|
approval: approval
|
|
4145
|
-
? {
|
|
4645
|
+
? {
|
|
4646
|
+
...approval,
|
|
4647
|
+
writableRoots: turnFileRoots,
|
|
4648
|
+
pathBase: workspaceRoot,
|
|
4649
|
+
pendingReconciliations: await (async () => {
|
|
4650
|
+
const allRecs = await ensurePhase9Store(this.store).listPendingReconciliations(chatId, { includeResolved: true });
|
|
4651
|
+
const blocking = {};
|
|
4652
|
+
for (const rec of allRecs) {
|
|
4653
|
+
if ((rec.status === 'pending' || rec.status === 'confirmed_executed') &&
|
|
4654
|
+
!(rec.toolName in blocking)) {
|
|
4655
|
+
blocking[rec.toolName] = rec.id;
|
|
4656
|
+
}
|
|
4657
|
+
}
|
|
4658
|
+
return blocking;
|
|
4659
|
+
})(),
|
|
4660
|
+
}
|
|
4146
4661
|
: undefined,
|
|
4147
4662
|
// delegate-on-pool 统一:模型的多代理面收敛为单工具
|
|
4148
4663
|
// delegate_subagent(默认开)。内置画像集(explore/research/coder)
|
|
@@ -4368,10 +4883,22 @@ export class LocalBackendRouter {
|
|
|
4368
4883
|
sidecarLost = finalOutcome.sidecarLost === true;
|
|
4369
4884
|
turnUsage = finalOutcome.usage;
|
|
4370
4885
|
// 干净失败的趟(sidecar 正常收流但 status=failed,如 LLM 401/超时)
|
|
4371
|
-
// 不走下面的 catch——这里补发 error
|
|
4372
|
-
//
|
|
4373
|
-
if (completionStatus === 'failed'
|
|
4374
|
-
|
|
4886
|
+
// 不走下面的 catch——这里补发 error 事件,并确保补全 failureInfo,
|
|
4887
|
+
// 否则前端或续跑(Continue)分支落库时缺少 failure 元数据而退化为 Not classified。
|
|
4888
|
+
if (completionStatus === 'failed') {
|
|
4889
|
+
if (!failureInfo && completionReason) {
|
|
4890
|
+
const fallbackKind = classifyErrorMessage(completionReason);
|
|
4891
|
+
if (fallbackKind !== 'unknown') {
|
|
4892
|
+
failureInfo = { errorKind: fallbackKind };
|
|
4893
|
+
}
|
|
4894
|
+
}
|
|
4895
|
+
if (completionReason) {
|
|
4896
|
+
emit(this.sse('error', {
|
|
4897
|
+
message: completionReason,
|
|
4898
|
+
...(failureInfo ? { failure: failureInfo } : {}),
|
|
4899
|
+
...(outcomeTraceId ? { traceId: outcomeTraceId } : {}),
|
|
4900
|
+
}));
|
|
4901
|
+
}
|
|
4375
4902
|
}
|
|
4376
4903
|
}
|
|
4377
4904
|
catch (err) {
|
|
@@ -4387,7 +4914,12 @@ export class LocalBackendRouter {
|
|
|
4387
4914
|
completionStatus = 'failed';
|
|
4388
4915
|
completionReason = err instanceof Error ? err.message : String(err);
|
|
4389
4916
|
failureInfo = readTurnFailureInfo(err);
|
|
4390
|
-
|
|
4917
|
+
if (!failureInfo && completionReason) {
|
|
4918
|
+
const fallbackKind = classifyErrorMessage(completionReason);
|
|
4919
|
+
if (fallbackKind !== 'unknown') {
|
|
4920
|
+
failureInfo = { errorKind: fallbackKind };
|
|
4921
|
+
}
|
|
4922
|
+
}
|
|
4391
4923
|
}
|
|
4392
4924
|
// streamCoreLoopTurn attaches the sidecar trace id to failures — the
|
|
4393
4925
|
// partial trace of a failed turn is the primary dogfood signal.
|
|
@@ -4396,6 +4928,13 @@ export class LocalBackendRouter {
|
|
|
4396
4928
|
outcomeTraceId = failureTraceId;
|
|
4397
4929
|
passTraceIds.push(failureTraceId);
|
|
4398
4930
|
}
|
|
4931
|
+
if (completionStatus === 'failed') {
|
|
4932
|
+
emit(this.sse('error', {
|
|
4933
|
+
message: completionReason,
|
|
4934
|
+
...(failureInfo ? { failure: failureInfo } : {}),
|
|
4935
|
+
...(outcomeTraceId ? { traceId: outcomeTraceId } : {}),
|
|
4936
|
+
}));
|
|
4937
|
+
}
|
|
4399
4938
|
}
|
|
4400
4939
|
// 可靠性统计(R4):一回合一条终态记录,与 token 用量分开记——用量
|
|
4401
4940
|
// 是每趟各一条(自动续跑的花费是真实发生的),终态只有一个。
|
|
@@ -4489,28 +5028,36 @@ export class LocalBackendRouter {
|
|
|
4489
5028
|
// settled — the crash would then look like a normal stopped turn and
|
|
4490
5029
|
// "continue last reply" would never be offered. The record stays on the
|
|
4491
5030
|
// user turn, which is what the resume path replays.
|
|
5031
|
+
const activeSec = getTurnSecurityContext(chatId);
|
|
5032
|
+
const safeAssistantText = activeSec?.redactor.hasSecrets
|
|
5033
|
+
? activeSec.redactor.redactString(assistantText)
|
|
5034
|
+
: assistantText;
|
|
5035
|
+
const rawAssistantMeta = {
|
|
5036
|
+
completionStatus,
|
|
5037
|
+
completionReason,
|
|
5038
|
+
executedActions,
|
|
5039
|
+
timeline,
|
|
5040
|
+
mode: chatMode,
|
|
5041
|
+
coreloop: true,
|
|
5042
|
+
traceId: outcomeTraceId,
|
|
5043
|
+
...(parentAgentId ? { agentId: parentAgentId } : {}),
|
|
5044
|
+
...(children.length > 0 ? { orchestrationChildEvents: children } : {}),
|
|
5045
|
+
...(durationMs != null ? { durationMs } : {}),
|
|
5046
|
+
...(autoContinuations > 0 ? { autoContinuations } : {}),
|
|
5047
|
+
...(turnFiles.length > 0 ? { turnFiles } : {}),
|
|
5048
|
+
// R6: the turn's bill, kept on the row so a replayed message shows
|
|
5049
|
+
// the same figures the live turn did — the child rows only carry
|
|
5050
|
+
// their own slice, and the per-turn total is not derivable from
|
|
5051
|
+
// them (the parent's own spend is not in any child).
|
|
5052
|
+
...(turnUsage ? { usage: turnUsage } : {}),
|
|
5053
|
+
...(failureInfo ? { failure: failureInfo } : {}),
|
|
5054
|
+
};
|
|
5055
|
+
const safeAssistantMeta = activeSec?.redactor.hasSecrets
|
|
5056
|
+
? activeSec.redactor.redactUnknown(rawAssistantMeta)
|
|
5057
|
+
: rawAssistantMeta;
|
|
4492
5058
|
const assistant = sidecarLost
|
|
4493
5059
|
? 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
|
-
}));
|
|
5060
|
+
: await this.store.addMessage(chatId, 'assistant', safeAssistantText, JSON.stringify(safeAssistantMeta));
|
|
4514
5061
|
if (!sidecarLost) {
|
|
4515
5062
|
try {
|
|
4516
5063
|
await recordInsightTurn(this.store, {
|
|
@@ -4564,6 +5111,21 @@ export class LocalBackendRouter {
|
|
|
4564
5111
|
const durationMs = typeof sidecarTrace.durationMs === 'number'
|
|
4565
5112
|
? sidecarTrace.durationMs
|
|
4566
5113
|
: null;
|
|
5114
|
+
const rawTracePayload = {
|
|
5115
|
+
coreloop: true,
|
|
5116
|
+
trace: sidecarTrace,
|
|
5117
|
+
spans: fetched.spans ?? [],
|
|
5118
|
+
events: fetched.events ?? [],
|
|
5119
|
+
...(fetched.eventsTruncated
|
|
5120
|
+
? {
|
|
5121
|
+
eventsTruncated: true,
|
|
5122
|
+
eventsTotal: fetched.eventsTotal,
|
|
5123
|
+
}
|
|
5124
|
+
: {}),
|
|
5125
|
+
};
|
|
5126
|
+
const safeTracePayload = activeSec?.redactor.hasSecrets
|
|
5127
|
+
? activeSec.redactor.redactUnknown(rawTracePayload)
|
|
5128
|
+
: rawTracePayload;
|
|
4567
5129
|
await this.store.saveTrace({
|
|
4568
5130
|
id: traceId,
|
|
4569
5131
|
chatId,
|
|
@@ -4573,18 +5135,7 @@ export class LocalBackendRouter {
|
|
|
4573
5135
|
startedAtMs: durationMs != null ? Date.now() - durationMs : Date.now(),
|
|
4574
5136
|
durationMs,
|
|
4575
5137
|
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
|
-
},
|
|
5138
|
+
payload: safeTracePayload,
|
|
4588
5139
|
});
|
|
4589
5140
|
}
|
|
4590
5141
|
catch (err) {
|
|
@@ -4630,7 +5181,13 @@ export class LocalBackendRouter {
|
|
|
4630
5181
|
emit(this.sseData({ type: 'turn_usage', usage: turnUsage }));
|
|
4631
5182
|
}
|
|
4632
5183
|
if (assistant) {
|
|
4633
|
-
emit(this.sseData({
|
|
5184
|
+
emit(this.sseData({
|
|
5185
|
+
type: 'message_id',
|
|
5186
|
+
messageId: assistant.id,
|
|
5187
|
+
...(typeof assistant.messageMetadata === 'string' && assistant.messageMetadata
|
|
5188
|
+
? { messageMetadata: assistant.messageMetadata }
|
|
5189
|
+
: {}),
|
|
5190
|
+
}));
|
|
4634
5191
|
}
|
|
4635
5192
|
emit('data: [DONE]\n\n');
|
|
4636
5193
|
this.runTitleGenInBackground(chatId, shouldGenerateTitle, firstUserMessageForTitle);
|