@steerable/agent-shell 0.13.1 → 0.14.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.
@@ -0,0 +1,39 @@
1
+ /** Maximum long-edge dimension sent to vision models by default. */
2
+ export declare const MODEL_IMAGE_MAX_DIMENSION = 1568;
3
+ /** Re-encode lossless PNG projections to JPEG once they exceed 512 KiB. */
4
+ export declare const MODEL_IMAGE_REENCODE_THRESHOLD_BYTES: number;
5
+ /** Default JPEG quality when transcoding model-bound projections. */
6
+ export declare const MODEL_IMAGE_JPEG_QUALITY = 82;
7
+ export interface NormalizeModelImageOptions {
8
+ maxEdge?: number;
9
+ reencodeThresholdBytes?: number;
10
+ jpegQuality?: number;
11
+ /** Explicit output format requested by a caller (`view_image.format`). */
12
+ forceFormat?: 'png' | 'jpeg';
13
+ }
14
+ export interface NormalizedModelImageBuffer {
15
+ buffer: Buffer;
16
+ mediaType: string;
17
+ width: number;
18
+ height: number;
19
+ resized: boolean;
20
+ reencoded: boolean;
21
+ }
22
+ /**
23
+ * Normalize an in-memory image buffer for model-visible projection.
24
+ * Non-raster or synthetic test buffers pass through unchanged.
25
+ */
26
+ export declare function normalizeModelImageBuffer(bytes: Buffer, mediaType: string, options?: NormalizeModelImageOptions): NormalizedModelImageBuffer;
27
+ export interface ToolImagePayload {
28
+ b64: string;
29
+ media_type: string;
30
+ }
31
+ /**
32
+ * Normalize a `{ b64, media_type }` tool `_image` payload in-memory.
33
+ * Synthetic non-raster base64 strings (unit test fixtures) pass through untouched.
34
+ */
35
+ export declare function normalizeToolImagePayload(payload: ToolImagePayload, options?: NormalizeModelImageOptions): ToolImagePayload & {
36
+ width?: number;
37
+ height?: number;
38
+ normalized?: boolean;
39
+ };
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Multimodal ingress dual-track normalization (Phase 10 R2 / P1-03).
3
+ *
4
+ * Dual-track invariant:
5
+ * 1. Original files on disk (attachments, exports, workspace files) are
6
+ * NEVER modified or overwritten — scripts, OCR, and user downloads
7
+ * always read byte-identical originals.
8
+ * 2. Only the model-bound inline projection (`LlmImage` / `_image`) is
9
+ * downscaled so its long edge is <= `MODEL_IMAGE_MAX_DIMENSION` (1568px)
10
+ * and re-encoded to JPEG (`MODEL_IMAGE_JPEG_QUALITY` = 82) whenever the
11
+ * rendered payload exceeds `MODEL_IMAGE_REENCODE_THRESHOLD_BYTES`
12
+ * (512 KiB), preventing Retina/4K screenshots from blowing the 4 MiB
13
+ * gateway request body ceiling.
14
+ */
15
+ import { decodeRasterBuffer } from '../raster-image.js';
16
+ /** Maximum long-edge dimension sent to vision models by default. */
17
+ export const MODEL_IMAGE_MAX_DIMENSION = 1568;
18
+ /** Re-encode lossless PNG projections to JPEG once they exceed 512 KiB. */
19
+ export const MODEL_IMAGE_REENCODE_THRESHOLD_BYTES = 512 * 1024;
20
+ /** Default JPEG quality when transcoding model-bound projections. */
21
+ export const MODEL_IMAGE_JPEG_QUALITY = 82;
22
+ function targetDimensions(width, height, maxEdge) {
23
+ if (width <= 0 || height <= 0)
24
+ return { width: 0, height: 0, resized: false };
25
+ if (width <= maxEdge && height <= maxEdge) {
26
+ return { width, height, resized: false };
27
+ }
28
+ const scale = Math.min(maxEdge / width, maxEdge / height);
29
+ return {
30
+ width: Math.max(1, Math.round(width * scale)),
31
+ height: Math.max(1, Math.round(height * scale)),
32
+ resized: true,
33
+ };
34
+ }
35
+ /**
36
+ * Normalize an in-memory image buffer for model-visible projection.
37
+ * Non-raster or synthetic test buffers pass through unchanged.
38
+ */
39
+ export function normalizeModelImageBuffer(bytes, mediaType, options = {}) {
40
+ const maxEdge = options.maxEdge ?? MODEL_IMAGE_MAX_DIMENSION;
41
+ const threshold = options.reencodeThresholdBytes ?? MODEL_IMAGE_REENCODE_THRESHOLD_BYTES;
42
+ const jpegQuality = options.jpegQuality ?? MODEL_IMAGE_JPEG_QUALITY;
43
+ const decoded = decodeRasterBuffer(bytes, mediaType);
44
+ if (decoded.isEmpty()) {
45
+ return {
46
+ buffer: bytes,
47
+ mediaType,
48
+ width: 0,
49
+ height: 0,
50
+ resized: false,
51
+ reencoded: false,
52
+ };
53
+ }
54
+ const { width: srcW, height: srcH } = decoded.getSize();
55
+ const target = targetDimensions(srcW, srcH, maxEdge);
56
+ const needsTranscodeCheck = options.forceFormat != null || bytes.length > threshold || target.resized;
57
+ if (!needsTranscodeCheck) {
58
+ return {
59
+ buffer: bytes,
60
+ mediaType,
61
+ width: srcW,
62
+ height: srcH,
63
+ resized: false,
64
+ reencoded: false,
65
+ };
66
+ }
67
+ const rendered = target.resized
68
+ ? decoded.resize({ width: target.width, height: target.height, quality: 'good' })
69
+ : decoded;
70
+ const naturalFormat = mediaType === 'image/jpeg' ? 'jpeg' : 'png';
71
+ const requestedFormat = options.forceFormat ?? naturalFormat;
72
+ let outMediaType = requestedFormat === 'jpeg' ? 'image/jpeg' : 'image/png';
73
+ let outBuffer = requestedFormat === 'jpeg' ? rendered.toJPEG(jpegQuality) : rendered.toPNG();
74
+ let reencoded = requestedFormat !== naturalFormat;
75
+ if (outBuffer.length > threshold &&
76
+ options.forceFormat == null &&
77
+ outMediaType !== 'image/jpeg') {
78
+ outMediaType = 'image/jpeg';
79
+ outBuffer = rendered.toJPEG(jpegQuality);
80
+ reencoded = true;
81
+ }
82
+ else if (outBuffer.length > threshold &&
83
+ options.forceFormat == null &&
84
+ outMediaType === 'image/jpeg' &&
85
+ !target.resized) {
86
+ const tighter = rendered.toJPEG(Math.min(jpegQuality, 75));
87
+ if (tighter.length < outBuffer.length) {
88
+ outBuffer = tighter;
89
+ reencoded = true;
90
+ }
91
+ }
92
+ const finalSize = rendered.getSize();
93
+ return {
94
+ buffer: outBuffer,
95
+ mediaType: outMediaType,
96
+ width: finalSize.width,
97
+ height: finalSize.height,
98
+ resized: target.resized,
99
+ reencoded,
100
+ };
101
+ }
102
+ /**
103
+ * Normalize a `{ b64, media_type }` tool `_image` payload in-memory.
104
+ * Synthetic non-raster base64 strings (unit test fixtures) pass through untouched.
105
+ */
106
+ export function normalizeToolImagePayload(payload, options) {
107
+ if (!payload || typeof payload.b64 !== 'string' || !payload.b64) {
108
+ return payload;
109
+ }
110
+ let rawBytes;
111
+ try {
112
+ rawBytes = Buffer.from(payload.b64, 'base64');
113
+ }
114
+ catch {
115
+ return payload;
116
+ }
117
+ if (rawBytes.length < 8) {
118
+ return payload;
119
+ }
120
+ const res = normalizeModelImageBuffer(rawBytes, payload.media_type || 'image/png', options);
121
+ if (!res.resized && !res.reencoded && res.buffer === rawBytes) {
122
+ return payload;
123
+ }
124
+ return {
125
+ b64: res.buffer.toString('base64'),
126
+ media_type: res.mediaType,
127
+ width: res.width,
128
+ height: res.height,
129
+ normalized: true,
130
+ };
131
+ }
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { readFileSync, statSync } from 'fs';
22
22
  import { basename, extname } from 'path';
23
+ import { MODEL_IMAGE_JPEG_QUALITY, MODEL_IMAGE_REENCODE_THRESHOLD_BYTES, } from './attachments/image-normalizer.js';
23
24
  import { builtinRasterSupports, createRasterImageDecoder } from './raster-image.js';
24
25
  /** Refuse to read source files larger than this (10 MB). */
25
26
  export const IMAGE_MAX_SOURCE_BYTES = 10 * 1024 * 1024;
@@ -153,9 +154,11 @@ export function processViewImage(input, decoder) {
153
154
  const outputFormat = input.format ?? (['.jpg', '.jpeg'].includes(sourceExt) ? 'jpeg' : 'png');
154
155
  let mediaType = outputFormat === 'jpeg' ? 'image/jpeg' : 'image/png';
155
156
  let buffer = outputFormat === 'jpeg' ? rendered.toJPEG(85) : rendered.toPNG();
156
- if (buffer.length > IMAGE_MAX_ENCODED_BYTES && input.format == null && outputFormat === 'png') {
157
+ if (buffer.length > MODEL_IMAGE_REENCODE_THRESHOLD_BYTES &&
158
+ input.format == null &&
159
+ outputFormat === 'png') {
157
160
  mediaType = 'image/jpeg';
158
- buffer = rendered.toJPEG(80);
161
+ buffer = rendered.toJPEG(MODEL_IMAGE_JPEG_QUALITY);
159
162
  }
160
163
  if (buffer.length > IMAGE_MAX_ENCODED_BYTES) {
161
164
  return {
@@ -343,13 +346,15 @@ export function processImageAttachments(files, decoder) {
343
346
  const rendered = target.resized
344
347
  ? image.resize({ width: target.width, height: target.height, quality: 'good' })
345
348
  : image;
346
- // PNG for graphics/screenshots (lossless), JPEG for photos (smaller).
349
+ // PNG for compact graphics/screenshots, JPEG for photos or PNGs over 512 KiB
350
+ // so Retina/4K screenshots never blow the 4 MiB gateway request ceiling while
351
+ // keeping the original file on disk completely untouched (R2 dual-track).
347
352
  const preferJpeg = ['.jpg', '.jpeg'].includes(extname(file.path).toLowerCase());
348
353
  let mediaType = preferJpeg ? 'image/jpeg' : 'image/png';
349
354
  let buffer = preferJpeg ? rendered.toJPEG(85) : rendered.toPNG();
350
- if (buffer.length > IMAGE_MAX_ENCODED_BYTES && mediaType !== 'image/jpeg') {
355
+ if (buffer.length > MODEL_IMAGE_REENCODE_THRESHOLD_BYTES && mediaType !== 'image/jpeg') {
351
356
  mediaType = 'image/jpeg';
352
- buffer = rendered.toJPEG(80);
357
+ buffer = rendered.toJPEG(MODEL_IMAGE_JPEG_QUALITY);
353
358
  }
354
359
  if (buffer.length > IMAGE_MAX_ENCODED_BYTES) {
355
360
  notes.push(`- ${label}:压缩后仍超过 ${formatMb(IMAGE_MAX_ENCODED_BYTES)}MB,未附加`);
@@ -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';
@@ -69,6 +70,7 @@ import { beginTurnSecurityContext, endTurnSecurityContext, getTurnSecurityContex
69
70
  import { ensurePhase9Store } from '../storage/fde-fallback.js';
70
71
  import { dispatchUiSurfaceAction, refreshPersistedUiSurface, renderAndPersistUiSurface, } from './ui-surface.js';
71
72
  import { assembleFactChainGraph } from './fact-chain.js';
73
+ import { bumpSessionCompactionEpoch, getSessionCompactionEpoch, } from '../memory/injector.js';
72
74
  import { handleMemoryHttpRoute } from '../memory/routes.js';
73
75
  function stringRecord(value) {
74
76
  if (!value || typeof value !== 'object' || Array.isArray(value))
@@ -1537,18 +1539,160 @@ export class LocalBackendRouter {
1537
1539
  }
1538
1540
  const compactMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/compact$/);
1539
1541
  if (compactMatch && method === 'POST') {
1540
- const chatId = compactMatch[1];
1542
+ const chatId = decodeURIComponent(compactMatch[1]);
1541
1543
  const chat = await this.store.getChat(chatId);
1542
1544
  if (!chat)
1543
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
+ }
1544
1619
  const plan = compactHistory(await this.historyTurns(chatId));
1545
- if (!plan)
1546
- return { status: 200, data: { compacted: 0 } };
1620
+ if (!plan) {
1621
+ return {
1622
+ status: 200,
1623
+ data: { compacted: 0, compactionEpoch: getSessionCompactionEpoch(chatId) },
1624
+ };
1625
+ }
1547
1626
  await this.store.deleteMessagesFrom(chatId, plan.deleteFromId);
1548
1627
  for (const write of plan.writes) {
1549
1628
  await this.store.addMessage(chatId, write.role, write.content, write.messageMetadata);
1550
1629
  }
1551
- return { status: 200, data: { compacted: plan.compacted } };
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
+ };
1552
1696
  }
1553
1697
  const forkMatch = pathname.match(/^\/api\/v2\/chats\/([^/]+)\/fork$/);
1554
1698
  if (forkMatch && method === 'POST') {
@@ -2294,6 +2438,95 @@ export class LocalBackendRouter {
2294
2438
  }
2295
2439
  return { status: 200, data: { posture: supervisor.getSandboxPosture(), egress } };
2296
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
+ }
2297
2530
  if (method === 'GET' && pathname === '/api/v2/llm/account') {
2298
2531
  const settings = resolveRuntimeLlmSettings(await this.store.getLlmSettings());
2299
2532
  const account = await readLlmAccount(settings, {
@@ -4650,10 +4883,22 @@ export class LocalBackendRouter {
4650
4883
  sidecarLost = finalOutcome.sidecarLost === true;
4651
4884
  turnUsage = finalOutcome.usage;
4652
4885
  // 干净失败的趟(sidecar 正常收流但 status=failed,如 LLM 401/超时)
4653
- // 不走下面的 catch——这里补发 error 事件,否则前端只渲染一条空消息,
4654
- // 用户完全看不到失败原因。
4655
- if (completionStatus === 'failed' && completionReason) {
4656
- emit(this.sse('error', { message: completionReason }));
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
+ }
4657
4902
  }
4658
4903
  }
4659
4904
  catch (err) {
@@ -4669,7 +4914,12 @@ export class LocalBackendRouter {
4669
4914
  completionStatus = 'failed';
4670
4915
  completionReason = err instanceof Error ? err.message : String(err);
4671
4916
  failureInfo = readTurnFailureInfo(err);
4672
- emit(this.sse('error', { message: completionReason }));
4917
+ if (!failureInfo && completionReason) {
4918
+ const fallbackKind = classifyErrorMessage(completionReason);
4919
+ if (fallbackKind !== 'unknown') {
4920
+ failureInfo = { errorKind: fallbackKind };
4921
+ }
4922
+ }
4673
4923
  }
4674
4924
  // streamCoreLoopTurn attaches the sidecar trace id to failures — the
4675
4925
  // partial trace of a failed turn is the primary dogfood signal.
@@ -4678,6 +4928,13 @@ export class LocalBackendRouter {
4678
4928
  outcomeTraceId = failureTraceId;
4679
4929
  passTraceIds.push(failureTraceId);
4680
4930
  }
4931
+ if (completionStatus === 'failed') {
4932
+ emit(this.sse('error', {
4933
+ message: completionReason,
4934
+ ...(failureInfo ? { failure: failureInfo } : {}),
4935
+ ...(outcomeTraceId ? { traceId: outcomeTraceId } : {}),
4936
+ }));
4937
+ }
4681
4938
  }
4682
4939
  // 可靠性统计(R4):一回合一条终态记录,与 token 用量分开记——用量
4683
4940
  // 是每趟各一条(自动续跑的花费是真实发生的),终态只有一个。
@@ -4924,7 +5181,13 @@ export class LocalBackendRouter {
4924
5181
  emit(this.sseData({ type: 'turn_usage', usage: turnUsage }));
4925
5182
  }
4926
5183
  if (assistant) {
4927
- emit(this.sseData({ type: 'message_id', messageId: assistant.id }));
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
+ }));
4928
5191
  }
4929
5192
  emit('data: [DONE]\n\n');
4930
5193
  this.runTitleGenInBackground(chatId, shouldGenerateTitle, firstUserMessageForTitle);
@@ -13,6 +13,10 @@
13
13
  */
14
14
  import { type Principal } from '../auth/index.js';
15
15
  import { MemoryStore } from './store.js';
16
+ /** Read the current compaction epoch for a chat session (default 0). */
17
+ export declare function getSessionCompactionEpoch(chatId: string): number;
18
+ /** Increment and return the compaction epoch after a CompactionBoundary rewrite. */
19
+ export declare function bumpSessionCompactionEpoch(chatId: string): number;
16
20
  export interface MemoryTurnInjection {
17
21
  /** Immutable snapshot block for the session's initial user prefix (empty if no memory). */
18
22
  readonly anchoredPrefixNote: string;
@@ -14,9 +14,20 @@
14
14
  import { LOCAL_DEFAULT_PRINCIPAL } from '../auth/index.js';
15
15
  import { TENANT_INJECT_BUDGET_BYTES, USER_INJECT_BUDGET_BYTES, WORKSPACE_INJECT_BUDGET_BYTES, } from './store.js';
16
16
  const sessionMemoryMap = new Map();
17
+ const sessionCompactionEpochMap = new Map();
18
+ /** Read the current compaction epoch for a chat session (default 0). */
19
+ export function getSessionCompactionEpoch(chatId) {
20
+ return sessionCompactionEpochMap.get(chatId) ?? 0;
21
+ }
22
+ /** Increment and return the compaction epoch after a CompactionBoundary rewrite. */
23
+ export function bumpSessionCompactionEpoch(chatId) {
24
+ const next = (sessionCompactionEpochMap.get(chatId) ?? 0) + 1;
25
+ sessionCompactionEpochMap.set(chatId, next);
26
+ return next;
27
+ }
17
28
  export async function buildMemoryTurnInjection(options) {
18
29
  const mode = await options.memoryStore.getPermissionMode();
19
- const epoch = options.compactionEpoch ?? 0;
30
+ const epoch = options.compactionEpoch ?? getSessionCompactionEpoch(options.chatId);
20
31
  const existing = sessionMemoryMap.get(options.chatId);
21
32
  if (mode === 'off') {
22
33
  return {
@@ -1,6 +1,12 @@
1
- import type { ImageDecoder } from './image-attachment.js';
1
+ import type { DecodedImage, ImageDecoder } from './image-attachment.js';
2
2
  /** True when the built-in decoder can read this path's extension. */
3
3
  export declare function builtinRasterSupports(filePath: string): boolean;
4
+ /**
5
+ * Decode an in-memory PNG or JPEG buffer into a crop/resize/encode surface.
6
+ * Non-raster or malformed buffers return `EMPTY_IMAGE` so callers can pass
7
+ * synthetic test stubs or unsupported formats through untouched.
8
+ */
9
+ export declare function decodeRasterBuffer(bytes: Buffer, mediaType?: string): DecodedImage;
4
10
  /**
5
11
  * Decode a local PNG or JPEG into a crop/resize/encode surface.
6
12
  * Unreadable or unsupported files yield an empty image.
@@ -16,6 +16,40 @@ const RASTER_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg']);
16
16
  export function builtinRasterSupports(filePath) {
17
17
  return RASTER_EXTENSIONS.has(extname(filePath).toLowerCase());
18
18
  }
19
+ /**
20
+ * Decode an in-memory PNG or JPEG buffer into a crop/resize/encode surface.
21
+ * Non-raster or malformed buffers return `EMPTY_IMAGE` so callers can pass
22
+ * synthetic test stubs or unsupported formats through untouched.
23
+ */
24
+ export function decodeRasterBuffer(bytes, mediaType) {
25
+ if (!bytes || bytes.length < 4)
26
+ return EMPTY_IMAGE;
27
+ const isPng = mediaType === 'image/png' ||
28
+ (bytes.length >= 8 &&
29
+ bytes[0] === 0x89 &&
30
+ bytes[1] === 0x50 &&
31
+ bytes[2] === 0x4e &&
32
+ bytes[3] === 0x47);
33
+ const isJpeg = mediaType === 'image/jpeg' || (bytes[0] === 0xff && bytes[1] === 0xd8);
34
+ try {
35
+ if (isPng && bytes[0] === 0x89 && bytes[1] === 0x50) {
36
+ const png = PNG.sync.read(bytes);
37
+ if (png.width < 1 || png.height < 1)
38
+ return EMPTY_IMAGE;
39
+ return new RasterImage(png.width, png.height, Buffer.from(png.data));
40
+ }
41
+ if (isJpeg && bytes[0] === 0xff && bytes[1] === 0xd8) {
42
+ const decoded = jpeg.decode(bytes, { useTArray: true, formatAsRGBA: true });
43
+ if (decoded.width < 1 || decoded.height < 1)
44
+ return EMPTY_IMAGE;
45
+ return new RasterImage(decoded.width, decoded.height, Buffer.from(decoded.data));
46
+ }
47
+ }
48
+ catch {
49
+ return EMPTY_IMAGE;
50
+ }
51
+ return EMPTY_IMAGE;
52
+ }
19
53
  /**
20
54
  * Decode a local PNG or JPEG into a crop/resize/encode surface.
21
55
  * Unreadable or unsupported files yield an empty image.
@@ -11,4 +11,4 @@
11
11
  */
12
12
  export { SidecarSupervisor } from './supervisor.js';
13
13
  export { SidecarBootError, SidecarMethodError, SidecarShutdownError, SidecarSandboxUnavailableError, } from './errors.js';
14
- export type { SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarChildEvent, SidecarChildUsage, SidecarHealthSnapshot, SidecarMethodOptions, SidecarRawChunk, SidecarSandboxPosture, SidecarSessionForkResult, SidecarStartOptions, SidecarStreamChunk, SidecarStreamDone, SidecarStreamError, SidecarToolResult, } from './types.js';
14
+ export type { SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarChildEvent, SidecarChildUsage, SidecarHealthSnapshot, SidecarLicenseState, SidecarLicenseStatus, SidecarMethodOptions, SidecarRawChunk, SidecarSandboxPosture, SidecarSessionForkResult, SidecarStartOptions, SidecarStreamChunk, SidecarStreamDone, SidecarStreamError, SidecarToolResult, } from './types.js';
@@ -7,6 +7,7 @@
7
7
  * on the CoreLoop path the framework's blocking semantics apply.
8
8
  */
9
9
  import { createHash } from 'node:crypto';
10
+ import { normalizeToolImagePayload, } from '../attachments/image-normalizer.js';
10
11
  import { classifyShellCommand } from './safety-patterns.js';
11
12
  import { isRejectedBeforeEffectError } from './rejected-before-effect.js';
12
13
  import { compactToolResultJson } from '../local-backend/context-compactor.js';
@@ -30,13 +31,28 @@ function capResultForModelContext(out) {
30
31
  : null;
31
32
  const image = data?._image;
32
33
  if (image && typeof image === 'object') {
34
+ const imgRecord = image;
35
+ const normalizedImage = typeof imgRecord.b64 === 'string' && typeof imgRecord.media_type === 'string'
36
+ ? normalizeToolImagePayload(imgRecord)
37
+ : image;
33
38
  const textOnly = { ...record, data: { ...data } };
34
39
  delete textOnly.data._image;
35
40
  const capped = capResultForModelContext(textOnly);
36
41
  const cappedData = capped.data && typeof capped.data === 'object'
37
42
  ? capped.data
38
43
  : {};
39
- return { ...capped, data: { ...cappedData, _image: image } };
44
+ return {
45
+ ...capped,
46
+ data: {
47
+ ...cappedData,
48
+ _image: typeof normalizedImage.b64 === 'string'
49
+ ? {
50
+ b64: normalizedImage.b64,
51
+ media_type: normalizedImage.media_type,
52
+ }
53
+ : image,
54
+ },
55
+ };
40
56
  }
41
57
  }
42
58
  const json = JSON.stringify(out);
@@ -10,7 +10,7 @@
10
10
  * - kill the process when the Electron app quits.
11
11
  */
12
12
  import { EventEmitter } from 'node:events';
13
- import type { SidecarApplyEditsResult, SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarHealthSnapshot, SidecarMethodOptions, SidecarModelCatalog, SidecarReverseHandler, SidecarSandboxPosture, SidecarSessionBranches, SidecarSessionForkOutcome, SidecarSessionMessages, SidecarSessionTree, SidecarChildrenList, SidecarSkillModule, SidecarStartOptions, SidecarToolResult } from './types.js';
13
+ import type { SidecarApplyEditsResult, SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarHealthSnapshot, SidecarLicenseStatus, SidecarMethodOptions, SidecarModelCatalog, SidecarReverseHandler, SidecarSandboxPosture, SidecarSessionBranches, SidecarSessionCompactParams, SidecarSessionCompactResult, SidecarSessionContextStatus, SidecarSessionForkOutcome, SidecarSessionMessages, SidecarSessionTree, SidecarChildrenList, SidecarSkillModule, SidecarStartOptions, SidecarToolResult } from './types.js';
14
14
  /**
15
15
  * Tool names carried by a `tool.list` reply.
16
16
  *
@@ -147,6 +147,30 @@ export declare class SidecarSupervisor extends EventEmitter {
147
147
  * the read path for rendering a branch after a switch. Soft-fail null.
148
148
  */
149
149
  sessionMessages(recordId: string): Promise<SidecarSessionMessages | null>;
150
+ /**
151
+ * Phase 10 R3: authoritatively compact a durable session in `sessions.db`
152
+ * (with optional Partial Compaction `focus`, `keepHeadTurns`, `keepTailMessages`).
153
+ */
154
+ sessionCompact(params: SidecarSessionCompactParams): Promise<SidecarSessionCompactResult | null>;
155
+ /**
156
+ * Phase 10 R3: fetch live token & wire-byte budget status for `sessions.db`.
157
+ */
158
+ sessionContextStatus(params: {
159
+ recordId: string;
160
+ model?: string;
161
+ provider?: string;
162
+ baseUrl?: string;
163
+ maxContextTokens?: number;
164
+ maxRequestBytes?: number;
165
+ }): Promise<SidecarSessionContextStatus | null>;
166
+ /**
167
+ * Phase 10 R3: queue manual/partial compaction on an active CoreLoop turn.
168
+ */
169
+ compactChat(streamId: string, options?: {
170
+ focus?: string;
171
+ keepHeadTurns?: number;
172
+ keepTailMessages?: number;
173
+ }): Promise<boolean>;
150
174
  /**
151
175
  * Every child agent recorded for one parent session.
152
176
  *
@@ -191,6 +215,12 @@ export declare class SidecarSupervisor extends EventEmitter {
191
215
  onReverseRequest(method: string, handler: SidecarReverseHandler): void;
192
216
  /** Returns the most recent ready snapshot collected at boot. */
193
217
  getBootSnapshot(): SidecarHealthSnapshot | null;
218
+ /** Query commercial license status from the native engine (`disabled` on public builds). */
219
+ getLicenseStatus(): Promise<SidecarLicenseStatus>;
220
+ /** Hot-reload the `.lic` file inside the native engine without restarting the sidecar. */
221
+ reloadLicense(): Promise<SidecarLicenseStatus>;
222
+ /** Pre-verify candidate `.lic` text before atomic disk replacement. */
223
+ verifyLicense(content: string): Promise<SidecarLicenseStatus>;
194
224
  /**
195
225
  * W4-3: the layer-1 (sidecar process sandbox) posture recorded at
196
226
  * spawn-plan time. This is the value the renderer reads (via
@@ -307,6 +307,41 @@ export class SidecarSupervisor extends EventEmitter {
307
307
  return null;
308
308
  }
309
309
  }
310
+ /**
311
+ * Phase 10 R3: authoritatively compact a durable session in `sessions.db`
312
+ * (with optional Partial Compaction `focus`, `keepHeadTurns`, `keepTailMessages`).
313
+ */
314
+ async sessionCompact(params) {
315
+ try {
316
+ return await this.call('agent.session.compact', { ...params }, { timeoutMs: 60_000 });
317
+ }
318
+ catch {
319
+ return null;
320
+ }
321
+ }
322
+ /**
323
+ * Phase 10 R3: fetch live token & wire-byte budget status for `sessions.db`.
324
+ */
325
+ async sessionContextStatus(params) {
326
+ try {
327
+ return await this.call('agent.session.context_status', { ...params }, { timeoutMs: 10_000 });
328
+ }
329
+ catch {
330
+ return null;
331
+ }
332
+ }
333
+ /**
334
+ * Phase 10 R3: queue manual/partial compaction on an active CoreLoop turn.
335
+ */
336
+ async compactChat(streamId, options) {
337
+ try {
338
+ const res = await this.call('agent.chat.compact', { streamId, ...options }, { timeoutMs: 5_000 });
339
+ return res.ok === true;
340
+ }
341
+ catch {
342
+ return false;
343
+ }
344
+ }
310
345
  /**
311
346
  * Every child agent recorded for one parent session.
312
347
  *
@@ -375,6 +410,18 @@ export class SidecarSupervisor extends EventEmitter {
375
410
  getBootSnapshot() {
376
411
  return this.readyHealth;
377
412
  }
413
+ /** Query commercial license status from the native engine (`disabled` on public builds). */
414
+ async getLicenseStatus() {
415
+ return this.call('license.status', {});
416
+ }
417
+ /** Hot-reload the `.lic` file inside the native engine without restarting the sidecar. */
418
+ async reloadLicense() {
419
+ return this.call('license.reload', {});
420
+ }
421
+ /** Pre-verify candidate `.lic` text before atomic disk replacement. */
422
+ async verifyLicense(content) {
423
+ return this.call('license.verify', { content });
424
+ }
378
425
  /**
379
426
  * W4-3: the layer-1 (sidecar process sandbox) posture recorded at
380
427
  * spawn-plan time. This is the value the renderer reads (via
@@ -184,6 +184,46 @@ export interface SidecarSessionMessages {
184
184
  content: string;
185
185
  }>;
186
186
  }
187
+ /** Phase 10 R3: `agent.session.compact` parameters (supports Partial Compaction). */
188
+ export interface SidecarSessionCompactParams {
189
+ recordId: string;
190
+ focus?: string;
191
+ keepHeadTurns?: number;
192
+ keepTailMessages?: number;
193
+ provider?: string;
194
+ model?: string;
195
+ apiKey?: string;
196
+ baseUrl?: string;
197
+ maxContextTokens?: number;
198
+ maxRequestBytes?: number;
199
+ }
200
+ /** Phase 10 R3: `agent.session.compact` result. */
201
+ export interface SidecarSessionCompactResult {
202
+ recordId: string;
203
+ recordExists: boolean;
204
+ compacted: number;
205
+ preTokens: number;
206
+ postTokens: number;
207
+ preBytes: number;
208
+ postBytes: number;
209
+ summaryText?: string;
210
+ messages: Array<{
211
+ seq: number;
212
+ role: string;
213
+ content: string;
214
+ }>;
215
+ }
216
+ /** Phase 10 R3: `agent.session.context_status` result. */
217
+ export interface SidecarSessionContextStatus {
218
+ recordId: string;
219
+ recordExists: boolean;
220
+ estimatedTokens: number;
221
+ maxContextTokens: number;
222
+ estimatedBytes: number;
223
+ maxRequestBytes: number;
224
+ messageCount: number;
225
+ compactionCount: number;
226
+ }
187
227
  /**
188
228
  * `agent.children.list` result: the durable child-agent index for one parent
189
229
  * session. `status` is composed, never stored raw — a terminal row reports
@@ -768,3 +808,29 @@ export interface SidecarModelCatalog {
768
808
  reasoningEffort: string | null;
769
809
  };
770
810
  }
811
+ export type SidecarLicenseState = 'disabled' | 'valid' | 'expiring' | 'grace' | 'expired' | 'invalid';
812
+ export interface SidecarLicenseStatus {
813
+ enforced: boolean;
814
+ state: SidecarLicenseState;
815
+ errorCode: string | null;
816
+ message: string | null;
817
+ licenseId: string | null;
818
+ customer: string | null;
819
+ product: string | null;
820
+ features: string[];
821
+ issuedAt?: string | null;
822
+ notBefore: string | null;
823
+ notAfter: string | null;
824
+ graceDays: number | null;
825
+ expiringNoticeDays?: number | null;
826
+ daysRemaining: number | null;
827
+ graceDaysRemaining: number | null;
828
+ maxUsers: number | null;
829
+ maxConcurrentRuns: number | null;
830
+ activeConcurrentRuns: number;
831
+ deploymentId: string | null;
832
+ boundDeploymentId?: string | null;
833
+ keyEnvironment?: string | null;
834
+ observedNow?: number;
835
+ maxRecordedTime?: number | null;
836
+ }
@@ -18,7 +18,7 @@
18
18
  * 也没观测过终态,按完成计是唯一诚实的读法。
19
19
  */
20
20
  /** Provider failure classification, as `LLMError.kind` names them. */
21
- export type FailureKind = 'transport' | 'rate_limit' | 'server' | 'auth' | 'invalid_request' | 'context_overflow' | 'unknown';
21
+ export type FailureKind = 'transport' | 'rate_limit' | 'server' | 'auth' | 'invalid_request' | 'context_overflow' | 'license' | 'unknown';
22
22
  /** One failure category with its count. */
23
23
  export interface FailureKindCount {
24
24
  kind: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steerable/agent-shell",
3
- "version": "0.13.1",
3
+ "version": "0.14.1",
4
4
  "description": "Steerable framework — product-neutral Node HostRuntime and headless HTTP server shared by Tauri desktop and browser deployments; scenario packs extend it through @steerable/pack-sdk.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://steerableframework.com/",
@@ -53,10 +53,10 @@
53
53
  "jpeg-js": "^0.4.4",
54
54
  "node-pty": "^1.1.0",
55
55
  "pngjs": "^7.0.0",
56
- "@steerable/agent-harness": "0.13.1",
57
- "@steerable/agent-protocol": "0.13.1",
58
- "@steerable/agent-runtime": "0.13.1",
59
- "@steerable/pack-sdk": "0.13.1"
56
+ "@steerable/agent-harness": "0.14.1",
57
+ "@steerable/agent-protocol": "0.14.1",
58
+ "@steerable/agent-runtime": "0.14.1",
59
+ "@steerable/pack-sdk": "0.14.1"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/better-sqlite3": "^7.6.13",