@tangle-network/agent-app 0.54.1 → 0.55.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/{DesignCanvas-BVBMDXBZ.js → DesignCanvas-OWE67ZX3.js} +4 -4
- package/dist/DesignCanvasEditor-VJ3R7RM2.js +15 -0
- package/dist/{TimelineEditor-52YEPDX5.js → TimelineEditor-7KBPJQLT.js} +3 -3
- package/dist/assets/index.js +1 -26
- package/dist/assets/index.js.map +1 -1
- package/dist/assets/schema.d.ts +0 -26
- package/dist/assistant/index.js +3 -3
- package/dist/chat-routes/index.js +2 -2
- package/dist/chat-store/index.js +1 -11
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/parts.d.ts +0 -10
- package/dist/{chunk-JB2GFEOC.js → chunk-2N7PDPLC.js} +3 -3
- package/dist/{chunk-CUXCWQMW.js → chunk-47UDWWUN.js} +1 -5
- package/dist/chunk-47UDWWUN.js.map +1 -0
- package/dist/{chunk-XDB7IBYE.js → chunk-5FAKBTCK.js} +1 -22
- package/dist/chunk-5FAKBTCK.js.map +1 -0
- package/dist/{chunk-HQ7R6CGM.js → chunk-6NYVAURR.js} +2 -2
- package/dist/{chunk-TY2DALJG.js → chunk-7TYQ43TP.js} +1 -10
- package/dist/chunk-7TYQ43TP.js.map +1 -0
- package/dist/{chunk-RRWC77YY.js → chunk-CFGA7PXM.js} +2 -2
- package/dist/{chunk-YJYPXMDL.js → chunk-DKHM4B4A.js} +3 -3
- package/dist/{chunk-ZGY6QB4F.js → chunk-MEKOWH5E.js} +2 -2
- package/dist/{chunk-H6XQZFTT.js → chunk-OHWQUKBP.js} +1 -5
- package/dist/{chunk-H6XQZFTT.js.map → chunk-OHWQUKBP.js.map} +1 -1
- package/dist/{chunk-IJDPERPL.js → chunk-PFOJRQ3Q.js} +3 -3
- package/dist/{chunk-4XBRPVL3.js → chunk-RSTPXLC3.js} +2 -2
- package/dist/{chunk-BVKQKGRK.js → chunk-SISVELAA.js} +1 -9
- package/dist/chunk-SISVELAA.js.map +1 -0
- package/dist/{chunk-DVOJNI6T.js → chunk-V4JZ5OYC.js} +1 -21
- package/dist/chunk-V4JZ5OYC.js.map +1 -0
- package/dist/{chunk-LEECH4MY.js → chunk-YHR2P7FY.js} +5 -16
- package/dist/chunk-YHR2P7FY.js.map +1 -0
- package/dist/design-canvas/export-presets.d.ts +0 -2
- package/dist/design-canvas/index.js +1 -11
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas/mcp-tools.d.ts +0 -6
- package/dist/design-canvas-react/engine.js +3 -3
- package/dist/design-canvas-react/export.d.ts +0 -7
- package/dist/design-canvas-react/index.js +6 -8
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/preflight/cli.js +1 -2
- package/dist/preflight/cli.js.map +1 -1
- package/dist/preflight/index.d.ts +1 -34
- package/dist/preflight/index.js +3 -6
- package/dist/public-consultation/index.js +2 -2
- package/dist/sequences/drizzle.js +1 -1
- package/dist/sequences/index.js +1 -7
- package/dist/sequences/index.js.map +1 -1
- package/dist/sequences/mcp-tools.d.ts +0 -2
- package/dist/sequences/model.d.ts +0 -6
- package/dist/sequences-react/index.js +3 -3
- package/dist/studio/generation.d.ts +0 -5
- package/dist/studio/index.js +1 -3
- package/dist/studio-react/index.js +1 -1
- package/dist/web-react/index.js +3 -5
- package/dist/web-react/work-product.d.ts +0 -2
- package/dist/work-product-react/index.js +1 -1
- package/package.json +1 -1
- package/dist/DesignCanvasEditor-IBFHC25D.js +0 -15
- package/dist/chunk-BVKQKGRK.js.map +0 -1
- package/dist/chunk-CUXCWQMW.js.map +0 -1
- package/dist/chunk-DVOJNI6T.js.map +0 -1
- package/dist/chunk-LEECH4MY.js.map +0 -1
- package/dist/chunk-TY2DALJG.js.map +0 -1
- package/dist/chunk-XDB7IBYE.js.map +0 -1
- /package/dist/{DesignCanvas-BVBMDXBZ.js.map → DesignCanvas-OWE67ZX3.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-IBFHC25D.js.map → DesignCanvasEditor-VJ3R7RM2.js.map} +0 -0
- /package/dist/{TimelineEditor-52YEPDX5.js.map → TimelineEditor-7KBPJQLT.js.map} +0 -0
- /package/dist/{chunk-JB2GFEOC.js.map → chunk-2N7PDPLC.js.map} +0 -0
- /package/dist/{chunk-HQ7R6CGM.js.map → chunk-6NYVAURR.js.map} +0 -0
- /package/dist/{chunk-RRWC77YY.js.map → chunk-CFGA7PXM.js.map} +0 -0
- /package/dist/{chunk-YJYPXMDL.js.map → chunk-DKHM4B4A.js.map} +0 -0
- /package/dist/{chunk-ZGY6QB4F.js.map → chunk-MEKOWH5E.js.map} +0 -0
- /package/dist/{chunk-IJDPERPL.js.map → chunk-PFOJRQ3Q.js.map} +0 -0
- /package/dist/{chunk-4XBRPVL3.js.map → chunk-RSTPXLC3.js.map} +0 -0
|
@@ -43,5 +43,3 @@ export declare const SEQUENCE_MEDIA_KINDS: readonly ["video", "image", "audio"];
|
|
|
43
43
|
export declare const MAX_CAPTION_BATCH = 500;
|
|
44
44
|
/** Resolve an array of immutable sequence MCP tool definitions for timeline and frame operations */
|
|
45
45
|
export declare const SEQUENCE_MCP_TOOLS: readonly SequenceMcpToolDefinition[];
|
|
46
|
-
/** Resolve the SequenceMcpToolDefinition matching the given name or return undefined */
|
|
47
|
-
export declare function findSequenceMcpTool(name: string): SequenceMcpToolDefinition | undefined;
|
|
@@ -149,12 +149,6 @@ export declare function clampClipStart(input: {
|
|
|
149
149
|
durationFrames: number;
|
|
150
150
|
sequenceDurationFrames: number;
|
|
151
151
|
}): number;
|
|
152
|
-
/** Clamp clip duration to fit within sequence bounds and minimum length constraints */
|
|
153
|
-
export declare function clampClipDuration(input: {
|
|
154
|
-
startFrame: number;
|
|
155
|
-
durationFrames: number;
|
|
156
|
-
sequenceDurationFrames: number;
|
|
157
|
-
}): number;
|
|
158
152
|
/** Validate that a clip's start and duration fit within the sequence duration without overflow */
|
|
159
153
|
export declare function assertClipFitsSequence(input: {
|
|
160
154
|
startFrame: number;
|
|
@@ -52,8 +52,8 @@ import {
|
|
|
52
52
|
trimClipCommand,
|
|
53
53
|
trimEndDrag,
|
|
54
54
|
trimStartDrag
|
|
55
|
-
} from "../chunk-
|
|
56
|
-
import "../chunk-
|
|
55
|
+
} from "../chunk-MEKOWH5E.js";
|
|
56
|
+
import "../chunk-SISVELAA.js";
|
|
57
57
|
|
|
58
58
|
// src/sequences-react/media/transcription.ts
|
|
59
59
|
var DEFAULT_WHISPER_MODEL = "onnx-community/whisper-large-v3-turbo";
|
|
@@ -187,7 +187,7 @@ function createWhisperTranscriptionProvider(opts) {
|
|
|
187
187
|
|
|
188
188
|
// src/sequences-react/lazy.tsx
|
|
189
189
|
import React from "react";
|
|
190
|
-
var SequenceTimelineEditorLazy = React.lazy(() => import("../TimelineEditor-
|
|
190
|
+
var SequenceTimelineEditorLazy = React.lazy(() => import("../TimelineEditor-7KBPJQLT.js"));
|
|
191
191
|
export {
|
|
192
192
|
BrandMark,
|
|
193
193
|
COMMAND_HISTORY_LIMIT,
|
|
@@ -61,11 +61,6 @@ export declare function selectedModelsWithDefaults(current: Partial<Record<Gener
|
|
|
61
61
|
export declare function preferredModelId(type: GenerationType, catalog: MediaModelCatalogResponse | null): string | undefined;
|
|
62
62
|
/** True when a model list offers nothing sendable: no models, or every model unavailable. */
|
|
63
63
|
export declare function laneUnavailable(models: readonly MediaModelOption[]): boolean;
|
|
64
|
-
/** DEPRECATED (the composer renders availability in the pill/menu/lane states since #463) — resolve the status message for a media model.
|
|
65
|
-
* @deprecated The composer no longer renders an availability status line (#463) — availability is
|
|
66
|
-
* carried by the model pill, the menu rows, and the lane-down notice. Kept only for external
|
|
67
|
-
* consumers; removal is a breaking change. */
|
|
68
|
-
export declare function modelMessage(model: MediaModelOption | undefined, loading: boolean, count: number): string | null;
|
|
69
64
|
/** Define fields required to configure and request various types of media generation */
|
|
70
65
|
export interface GenerationRequestFields {
|
|
71
66
|
workspaceId: string;
|
package/dist/studio/index.js
CHANGED
|
@@ -32,7 +32,6 @@ import {
|
|
|
32
32
|
mergeGenerationPages,
|
|
33
33
|
mergeLiveGeneration,
|
|
34
34
|
mergeLoaderAndLive,
|
|
35
|
-
modelMessage,
|
|
36
35
|
normalizeImageCount,
|
|
37
36
|
normalizeVaultPath,
|
|
38
37
|
optimisticGeneration,
|
|
@@ -49,7 +48,7 @@ import {
|
|
|
49
48
|
textToVideoSibling,
|
|
50
49
|
userSafeGenerationMessage,
|
|
51
50
|
validateCustomImageSize
|
|
52
|
-
} from "../chunk-
|
|
51
|
+
} from "../chunk-7TYQ43TP.js";
|
|
53
52
|
export {
|
|
54
53
|
FALLBACK_VIDEO_MODEL_OPTIONS,
|
|
55
54
|
GENERATION_TYPES,
|
|
@@ -84,7 +83,6 @@ export {
|
|
|
84
83
|
mergeGenerationPages,
|
|
85
84
|
mergeLiveGeneration,
|
|
86
85
|
mergeLoaderAndLive,
|
|
87
|
-
modelMessage,
|
|
88
86
|
normalizeImageCount,
|
|
89
87
|
normalizeVaultPath,
|
|
90
88
|
optimisticGeneration,
|
package/dist/web-react/index.js
CHANGED
|
@@ -134,7 +134,7 @@ import {
|
|
|
134
134
|
withoutRecordGridCreated,
|
|
135
135
|
withoutRecordGridRemoved,
|
|
136
136
|
withoutRecordGridUpdate
|
|
137
|
-
} from "../chunk-
|
|
137
|
+
} from "../chunk-PFOJRQ3Q.js";
|
|
138
138
|
import {
|
|
139
139
|
SessionHistoryPanel,
|
|
140
140
|
formatSessionTimestamp,
|
|
@@ -158,10 +158,9 @@ import {
|
|
|
158
158
|
ReviewQueuePanel,
|
|
159
159
|
WorkProductCard,
|
|
160
160
|
mergeReviewQueuePages,
|
|
161
|
-
reviewQueueStateLabel,
|
|
162
161
|
workProductPartsFromMessageParts,
|
|
163
162
|
workProductStatusLabel
|
|
164
|
-
} from "../chunk-
|
|
163
|
+
} from "../chunk-47UDWWUN.js";
|
|
165
164
|
import {
|
|
166
165
|
parseReviewQueueItem
|
|
167
166
|
} from "../chunk-GEYACSFW.js";
|
|
@@ -224,7 +223,7 @@ import {
|
|
|
224
223
|
isChatAttachmentPart,
|
|
225
224
|
mentionInputToPart,
|
|
226
225
|
mentionPartsFromMessageParts
|
|
227
|
-
} from "../chunk-
|
|
226
|
+
} from "../chunk-V4JZ5OYC.js";
|
|
228
227
|
import "../chunk-ZVEEWGDK.js";
|
|
229
228
|
import {
|
|
230
229
|
DISPATCH_MAX_MEDIA_PARTS,
|
|
@@ -454,7 +453,6 @@ export {
|
|
|
454
453
|
resolveProvenanceStanding,
|
|
455
454
|
responseErrorMessage,
|
|
456
455
|
restoreChatInteractions,
|
|
457
|
-
reviewQueueStateLabel,
|
|
458
456
|
rollUpProvenanceStanding,
|
|
459
457
|
sameRecordGridValue,
|
|
460
458
|
segmentMentionContent,
|
|
@@ -22,8 +22,6 @@ import { parseReviewQueueItem, type ReviewQueueItem, type ReviewQueueState } fro
|
|
|
22
22
|
import type { EvidenceEntry, ExceptionEntry, ProfileBacktestSummary, QualityCheck, WorkProductPersistedPart, WorkProductProvenance, WorkProductStatus } from '../work-product/types';
|
|
23
23
|
export { parseReviewQueueItem };
|
|
24
24
|
export type { ReviewQueueItem, ReviewQueueState };
|
|
25
|
-
/** Human label for a queue state. */
|
|
26
|
-
export declare function reviewQueueStateLabel(state: ReviewQueueState): string;
|
|
27
25
|
/** Human label for a work-product status. */
|
|
28
26
|
export declare function workProductStatusLabel(status: WorkProductStatus): string;
|
|
29
27
|
/** Every persisted work-product anchor on one message, re-validated. */
|
package/package.json
CHANGED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
DesignCanvasEditor
|
|
3
|
-
} from "./chunk-LEECH4MY.js";
|
|
4
|
-
import "./chunk-YJYPXMDL.js";
|
|
5
|
-
import "./chunk-TMKSWEVQ.js";
|
|
6
|
-
import "./chunk-RRWC77YY.js";
|
|
7
|
-
import "./chunk-HQ7R6CGM.js";
|
|
8
|
-
import "./chunk-H6XQZFTT.js";
|
|
9
|
-
import "./chunk-YNSPVKMS.js";
|
|
10
|
-
import "./chunk-3NCPXNBZ.js";
|
|
11
|
-
import "./chunk-TXD5HXLE.js";
|
|
12
|
-
export {
|
|
13
|
-
DesignCanvasEditor
|
|
14
|
-
};
|
|
15
|
-
//# sourceMappingURL=DesignCanvasEditor-IBFHC25D.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sequences/model.ts"],"sourcesContent":["/**\n * Frame-accurate sequence timeline model — the product-agnostic spine of the\n * sequences surface. A sequence is a fixed-fps, fixed-duration timeline of\n * tracks; clips sit on tracks at integer frame positions with non-destructive\n * source in/out points. Products bind this model to their own storage through\n * `SequenceStore` (./store) and surface it to agents through the MCP toolset\n * (./mcp).\n *\n * All positions and durations are integer FRAMES at the sequence's fps.\n * Seconds appear only at the API edge (agent tools speak seconds; the\n * dispatcher converts exactly once). Nothing here touches a database, the DOM,\n * or React.\n */\n\nexport const MIN_SEQUENCE_CLIP_FRAMES = 1\n\n/** Track kinds. `reference` holds non-rendered guide media; `agent` holds the\n * agent-decision lane rendered as markers, never as media. */\nexport type SequenceTrackKind = 'video' | 'audio' | 'caption' | 'reference' | 'agent'\n\n/** Define sequence status as one of the specific lifecycle stages draft, active, exporting, or archived */\nexport type SequenceStatus = 'draft' | 'active' | 'exporting' | 'archived'\n\n/** Define export formats available for sequence data including video, subtitle, and metadata types */\nexport type SequenceExportFormat = 'mp4' | 'otio' | 'xml' | 'edl' | 'vtt' | 'srt' | 'contact_sheet'\n\n/** Represent export status of a sequence as queued, processing, completed, failed, or cancelled */\nexport type SequenceExportStatus = 'queued' | 'processing' | 'completed' | 'failed' | 'cancelled'\n\n/** Define media types allowed in a sequence including video, image, and audio */\nexport type SequenceMediaKind = 'video' | 'image' | 'audio'\n\n/** Describe metadata and properties of a media sequence including dimensions, duration, and status */\nexport interface SequenceMeta {\n id: string\n title: string\n fps: number\n width: number\n height: number\n aspectRatio: string\n durationFrames: number\n status: SequenceStatus\n metadata: Record<string, unknown>\n}\n\n/** Define properties and state for a sequence track including id, kind, name, order, and flags */\nexport interface SequenceTrack {\n id: string\n kind: SequenceTrackKind\n name: string\n sortOrder: number\n locked: boolean\n muted: boolean\n metadata: Record<string, unknown>\n}\n\n/** Resolved playable media behind a clip. The store resolves product-specific\n * references (generation rows, asset rows) into this shape; the core model\n * never sees the product's tables. */\nexport interface SequenceClipMedia {\n url: string\n kind: SequenceMediaKind\n /** Natural duration of the source media when known. */\n durationSeconds?: number\n /** Provider job state for media still rendering upstream. */\n providerStatus?: 'queued' | 'processing' | 'completed' | 'failed'\n}\n\n/** Define properties for a media sequence clip including timing, source, track, and caption details */\nexport interface SequenceClip {\n id: string\n trackId: string\n label: string\n startFrame: number\n durationFrames: number\n /** Source-relative in point (frames into the source media). */\n sourceInFrame: number\n /** Source-relative out point; null = natural end of the source. */\n sourceOutFrame: number | null\n disabled: boolean\n /** Caption/text body for clips on caption tracks. */\n text?: string\n /** BCP-47 language tag for caption clips (e.g. 'en', 'es', 'ja'). */\n language?: string\n /** Opaque product reference to a generation row, when the clip came from one. */\n generationId?: string\n /** Opaque product reference to an asset row, when the clip came from one. */\n assetId?: string\n media?: SequenceClipMedia\n metadata: Record<string, unknown>\n}\n\n/** One entry in the sequence's decision log — human edits, agent proposals,\n * agent edits, exports, and notes all land here so the edit history is a\n * single auditable lane. */\nexport interface SequenceDecision {\n id: string\n clipId: string | null\n kind: 'human_edit' | 'agent_proposal' | 'agent_edit' | 'export' | 'note'\n instruction: string\n reasoningSummary: string | null\n accepted: boolean | null\n metadata: Record<string, unknown>\n createdAt: Date\n}\n\n/** Describe a record representing the export details and status of a sequence */\nexport interface SequenceExportRecord {\n id: string\n format: SequenceExportFormat\n status: SequenceExportStatus\n resultUrl: string | null\n metadata: Record<string, unknown>\n createdAt: Date\n}\n\n/** The full timeline aggregate — what `get_timeline_state` returns and what\n * every operation validates against. */\nexport interface SequenceTimeline {\n sequence: SequenceMeta\n tracks: SequenceTrack[]\n clips: SequenceClip[]\n}\n\n/** What is on screen/audible at a single frame — the answer shape for\n * \"what is happening at 0:34\". */\nexport interface SequenceFrameSnapshot {\n frame: number\n seconds: number\n /** Active (enabled, in-range) clips at this frame, with their track. */\n active: Array<{ track: SequenceTrack; clip: SequenceClip }>\n /** Caption text visible at this frame, in track sort order. */\n captions: Array<{ text: string; language?: string; clipId: string }>\n}\n\n// ---------------------------------------------------------------------------\n// Frame math\n// ---------------------------------------------------------------------------\n\n/** Convert seconds to the nearest whole number of frames based on frames per second */\nexport function secondsToFrames(seconds: number, fps: number): number {\n if (!Number.isFinite(seconds) || seconds < 0) throw new Error('seconds must be a non-negative finite number')\n assertFps(fps)\n return Math.round(seconds * fps)\n}\n\n/** Convert a frame count to seconds based on the given frames per second rate */\nexport function framesToSeconds(frames: number, fps: number): number {\n if (!Number.isInteger(frames) || frames < 0) throw new Error('frames must be a non-negative integer')\n assertFps(fps)\n return frames / fps\n}\n\n/** Format a number of seconds into a string with integer or two-decimal precision suffix s */\nexport function formatSeconds(seconds: number): string {\n return Number.isInteger(seconds) ? `${seconds}s` : `${seconds.toFixed(2)}s`\n}\n\n/** `m:ss.ff` timecode for UI and agent-readable frame references. */\nexport function formatTimecode(frames: number, fps: number): string {\n assertFps(fps)\n if (!Number.isInteger(frames) || frames < 0) throw new Error('frames must be a non-negative integer')\n const totalSeconds = Math.floor(frames / fps)\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n const residualFrames = frames % fps\n return `${minutes}:${String(seconds).padStart(2, '0')}.${String(residualFrames).padStart(2, '0')}`\n}\n\n/** Define the start frame and duration in frames for a timeline clip's bounds */\nexport interface TimelineClipBounds {\n startFrame: number\n durationFrames: number\n}\n\n/** Define a time range with inclusive start and end frame numbers */\nexport interface TimelineInterval {\n startFrame: number\n endFrame: number\n}\n\n/** Clamp the clip start frame within the valid range of the sequence duration and clip length */\nexport function clampClipStart(input: {\n startFrame: number\n durationFrames: number\n sequenceDurationFrames: number\n}): number {\n assertSequenceDuration(input.sequenceDurationFrames)\n assertClipDuration(input.durationFrames)\n return Math.max(0, Math.min(input.sequenceDurationFrames - input.durationFrames, input.startFrame))\n}\n\n/** Clamp clip duration to fit within sequence bounds and minimum length constraints */\nexport function clampClipDuration(input: {\n startFrame: number\n durationFrames: number\n sequenceDurationFrames: number\n}): number {\n assertSequenceDuration(input.sequenceDurationFrames)\n if (input.startFrame < 0 || input.startFrame >= input.sequenceDurationFrames) {\n throw new Error('startFrame must be inside the sequence')\n }\n return Math.max(MIN_SEQUENCE_CLIP_FRAMES, Math.min(input.durationFrames, input.sequenceDurationFrames - input.startFrame))\n}\n\n/** Validate that a clip's start and duration fit within the sequence duration without overflow */\nexport function assertClipFitsSequence(input: {\n startFrame: number\n durationFrames: number\n sequenceDurationFrames: number\n label: string\n}): void {\n assertSequenceDuration(input.sequenceDurationFrames)\n assertClipDuration(input.durationFrames)\n if (!Number.isInteger(input.startFrame) || input.startFrame < 0) {\n throw new Error(`${input.label} startFrame must be a non-negative integer`)\n }\n if (input.startFrame + input.durationFrames > input.sequenceDurationFrames) {\n throw new Error(`${input.label} extends beyond the sequence duration`)\n }\n}\n\n/** Place a caption near the playhead inside FREE space only — the caption\n * track never double-books. Prefers fps*3 frames, floors at fps. The gap\n * holding (or first after) the playhead wins; with everything ahead occupied\n * the latest earlier gap is used instead. Throws when no gap can hold the\n * minimum — the caller must supply explicit bounds or clear space. */\nexport function chooseCaptionPlacement(input: {\n playheadFrame: number\n fps: number\n sequenceDurationFrames: number\n occupiedIntervals: TimelineInterval[]\n}): TimelineClipBounds {\n const preferredDurationFrames = Math.min(input.fps * 3, input.sequenceDurationFrames)\n const minimumDurationFrames = Math.min(input.fps, preferredDurationFrames)\n const occupied = input.occupiedIntervals\n .map((interval) => ({\n startFrame: Math.max(0, interval.startFrame),\n endFrame: Math.min(input.sequenceDurationFrames, interval.endFrame),\n }))\n .filter((interval) => interval.endFrame > interval.startFrame)\n .sort((a, b) => a.startFrame - b.startFrame)\n\n // Merge overlaps so the gap walk sees each free run exactly once.\n const merged: TimelineInterval[] = []\n for (const interval of occupied) {\n const last = merged[merged.length - 1]\n if (last && interval.startFrame <= last.endFrame) last.endFrame = Math.max(last.endFrame, interval.endFrame)\n else merged.push({ ...interval })\n }\n\n const gaps: TimelineInterval[] = []\n let cursor = 0\n for (const interval of merged) {\n if (interval.startFrame > cursor) gaps.push({ startFrame: cursor, endFrame: interval.startFrame })\n cursor = interval.endFrame\n }\n if (cursor < input.sequenceDurationFrames) gaps.push({ startFrame: cursor, endFrame: input.sequenceDurationFrames })\n\n const usable = gaps.filter((gap) => gap.endFrame - gap.startFrame >= minimumDurationFrames)\n const latestUsable = usable[usable.length - 1]\n if (latestUsable === undefined) {\n throw new Error(\n `no free gap of at least ${minimumDurationFrames} frames on the caption track — pass explicit startFrame/durationFrames or clear space first`,\n )\n }\n const gap = usable.find((candidate) => candidate.endFrame > input.playheadFrame) ?? latestUsable\n const durationFrames = Math.min(preferredDurationFrames, gap.endFrame - gap.startFrame)\n const startFrame = Math.max(gap.startFrame, Math.min(input.playheadFrame, gap.endFrame - durationFrames))\n return { startFrame, durationFrames }\n}\n\n/** Resolve everything active at one frame — the core of `get_frame_at_time`. */\nexport function snapshotFrame(timeline: SequenceTimeline, frame: number): SequenceFrameSnapshot {\n if (!Number.isInteger(frame) || frame < 0) throw new Error('frame must be a non-negative integer')\n if (frame >= timeline.sequence.durationFrames) {\n throw new Error(`frame ${frame} is beyond the sequence (${timeline.sequence.durationFrames} frames)`)\n }\n const trackById = new Map(timeline.tracks.map((track) => [track.id, track]))\n const sortedTracks = [...timeline.tracks].sort((a, b) => a.sortOrder - b.sortOrder)\n const trackOrder = new Map(sortedTracks.map((track, index) => [track.id, index]))\n\n const active = timeline.clips\n .filter((clip) => !clip.disabled && clip.startFrame <= frame && frame < clip.startFrame + clip.durationFrames)\n .map((clip) => {\n const track = trackById.get(clip.trackId)\n if (!track) throw new Error(`clip ${clip.id} references unknown track ${clip.trackId}`)\n return { track, clip }\n })\n .sort((a, b) => (trackOrder.get(a.track.id) ?? 0) - (trackOrder.get(b.track.id) ?? 0))\n\n const captions = active\n .filter(({ track, clip }) => track.kind === 'caption' && typeof clip.text === 'string' && clip.text.length > 0)\n .map(({ clip }) => ({ text: clip.text as string, language: clip.language, clipId: clip.id }))\n\n return {\n frame,\n seconds: framesToSeconds(frame, timeline.sequence.fps),\n active,\n captions,\n }\n}\n\n/** Occupied intervals on one track, for placement collision checks. */\nexport function trackIntervals(timeline: SequenceTimeline, trackId: string): TimelineInterval[] {\n return timeline.clips\n .filter((clip) => clip.trackId === trackId && !clip.disabled)\n .map((clip) => ({ startFrame: clip.startFrame, endFrame: clip.startFrame + clip.durationFrames }))\n .sort((a, b) => a.startFrame - b.startFrame)\n}\n\nfunction assertFps(fps: number): void {\n if (!Number.isInteger(fps) || fps <= 0) throw new Error('fps must be a positive integer')\n}\n\nfunction assertSequenceDuration(sequenceDurationFrames: number): void {\n if (!Number.isInteger(sequenceDurationFrames) || sequenceDurationFrames < MIN_SEQUENCE_CLIP_FRAMES) {\n throw new Error('sequenceDurationFrames must be a positive integer')\n }\n}\n\nfunction assertClipDuration(durationFrames: number): void {\n if (!Number.isInteger(durationFrames) || durationFrames < MIN_SEQUENCE_CLIP_FRAMES) {\n throw new Error('durationFrames must be a positive integer')\n }\n}\n"],"mappings":";AAcO,IAAM,2BAA2B;AA8HjC,SAAS,gBAAgB,SAAiB,KAAqB;AACpE,MAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,EAAG,OAAM,IAAI,MAAM,8CAA8C;AAC5G,YAAU,GAAG;AACb,SAAO,KAAK,MAAM,UAAU,GAAG;AACjC;AAGO,SAAS,gBAAgB,QAAgB,KAAqB;AACnE,MAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,EAAG,OAAM,IAAI,MAAM,uCAAuC;AACpG,YAAU,GAAG;AACb,SAAO,SAAS;AAClB;AAGO,SAAS,c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AAK,MAAM,MAAM,SAAS,aAAa,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,CAAC,EAC7G,IAAI,CAAC,EAAE,KAAK,OAAO,EAAE,MAAM,KAAK,MAAgB,UAAU,KAAK,UAAU,QAAQ,KAAK,GAAG,EAAE;AAE9F,SAAO;AAAA,IACL;AAAA,IACA,SAAS,gBAAgB,OAAO,SAAS,SAAS,GAAG;AAAA,IACrD;AAAA,IACA;AAAA,EACF;AACF;AAGO,SAAS,eAAe,UAA4B,SAAqC;AAC9F,SAAO,SAAS,MACb,OAAO,CAAC,SAAS,KAAK,YAAY,WAAW,CAAC,KAAK,QAAQ,EAC3D,IAAI,CAAC,UAAU,EAAE,YAAY,KAAK,YAAY,UAAU,KAAK,aAAa,KAAK,eAAe,EAAE,EAChG,KAAK,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU;AAC/C;AAEA,SAAS,UAAU,KAAmB;AACpC,MAAI,CAAC,OAAO,UAAU,GAAG,KAAK,OAAO,EAAG,OAAM,IAAI,MAAM,gCAAgC;AAC1F;AAEA,SAAS,uBAAuB,wBAAsC;AACpE,MAAI,CAAC,OAAO,UAAU,sBAAsB,KAAK,yBAAyB,0BAA0B;AAClG,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AACF;AAEA,SAAS,mBAAmB,gBAA8B;AACxD,MAAI,CAAC,OAAO,UAAU,cAAc,KAAK,iBAAiB,0BAA0B;AAClF,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AACF;","names":["gap"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/web-react/work-product.tsx"],"sourcesContent":["/**\n * Work-product review surfaces — the sandbox-ui-FREE half of the vertical:\n *\n * - {@link ReviewQueuePanel}: the practice/matters/campaign review queue over\n * a `fetchQueue(cursor)` data port (the `AgentActivityPanel` shape).\n * - {@link WorkProductCard}: the persisted `type:'work_product'` transcript\n * anchor rendered inside `ChatMessages` — chat stays the driver surface.\n * - {@link EvidenceLineageTable}: target → claim → source rows with\n * click-through via an injected `resolveSourceUrl` (the\n * `MessageAttachments.resolveFileUrl` pattern).\n * - {@link ExceptionList} / {@link QualityCheckList}: severity-badged\n * exception rows and pass/fail check rows.\n * - {@link ProvenanceStamp}: profileHash prefix + runId + serving-model\n * chips + the optional backtest slot (\"182 cases · composite 0.81 ·\n * trust PASS\" — or \"quality: unverified\" when the trust gate failed).\n *\n * Anything hosting sandbox-ui (DiffView, CodeView, PillTabs) lives in\n * `./work-product-react` instead — this module must stay importable without\n * the optional sandbox-ui peer.\n */\n\nimport { useCallback, useEffect, useState } from 'react'\nimport { StatusPill, type StatusTone } from '@tangle-network/ui/primitives'\n\nimport {\n parseReviewQueueItem,\n type ReviewQueueItem,\n type ReviewQueueState,\n} from '../work-product/queue'\nimport type {\n EvidenceEntry,\n ExceptionEntry,\n ProfileBacktestSummary,\n QualityCheck,\n WorkProductPersistedPart,\n WorkProductProvenance,\n WorkProductStatus,\n} from '../work-product/types'\nimport { persistedPartToWorkProduct } from '../work-product/types'\n\nexport { parseReviewQueueItem }\nexport type { ReviewQueueItem, ReviewQueueState }\n\n// ── shared presentation vocabulary ────────────────────────────────────────\n\nconst STATE_LABELS: Record<ReviewQueueState, string> = {\n intake: 'Intake',\n missing_info: 'Missing info',\n working: 'Working',\n ready_for_review: 'Ready for review',\n changes_requested: 'Changes requested',\n approved: 'Approved',\n blocked: 'Blocked',\n}\n\n// Tones are ui's StatusPill vocabulary, so a queue state carries the same glyph\n// and colour as every other status in the product. Warning is \"needs a person\";\n// working is still moving (an open ring).\nconst STATE_TONES: Record<ReviewQueueState, StatusTone> = {\n intake: 'neutral',\n missing_info: 'warning',\n working: 'running',\n ready_for_review: 'success',\n changes_requested: 'warning',\n approved: 'success',\n blocked: 'danger',\n}\n\nconst STATUS_LABELS: Record<WorkProductStatus, string> = {\n draft: 'Draft',\n blocked: 'Blocked',\n ready: 'Ready for review',\n changes_requested: 'Changes requested',\n approved: 'Approved',\n superseded: 'Superseded',\n}\n\n// A draft is not yet a state anyone acts on, so it is neutral rather than the\n// brand accent it used to borrow.\nconst STATUS_TONES: Record<WorkProductStatus, StatusTone> = {\n draft: 'neutral',\n blocked: 'danger',\n ready: 'success',\n changes_requested: 'warning',\n approved: 'success',\n superseded: 'neutral',\n}\n\n/** Human label for a queue state. */\nexport function reviewQueueStateLabel(state: ReviewQueueState): string {\n return STATE_LABELS[state]\n}\n\n/** Human label for a work-product status. */\nexport function workProductStatusLabel(status: WorkProductStatus): string {\n return STATUS_LABELS[status]\n}\n\nfunction StatePill({ state }: { state: ReviewQueueState }) {\n return <StatusPill tone={STATE_TONES[state]}>{STATE_LABELS[state]}</StatusPill>\n}\n\nfunction WorkProductStatusPill({ status }: { status: WorkProductStatus }) {\n return <StatusPill tone={STATUS_TONES[status]}>{STATUS_LABELS[status]}</StatusPill>\n}\n\n// ── transcript anchor helpers + card ──────────────────────────────────────\n\n/** Every persisted work-product anchor on one message, re-validated. */\nexport function workProductPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | null | undefined,\n): WorkProductPersistedPart[] {\n if (!parts) return []\n const out: WorkProductPersistedPart[] = []\n for (const part of parts) {\n const typed = persistedPartToWorkProduct(part)\n if (typed) out.push(typed)\n }\n return out\n}\n\n/** Properties for the transcript anchor card rendered in chat */\nexport interface WorkProductCardProps {\n part: WorkProductPersistedPart\n /** Open the work product (queue detail / pane) — the card's only action. */\n onOpen?: (part: WorkProductPersistedPart) => void\n className?: string\n}\n\n/** The chat transcript anchor card for one work-product version — a compact,\n * system-authored pointer, not a parallel review surface. */\nexport function WorkProductCard({ part, onOpen, className }: WorkProductCardProps) {\n return (\n <div\n className={`flex items-center gap-3 rounded-xl border border-border bg-card px-4 py-3 ${className ?? ''}`}\n data-work-product-id={part.ref.id}\n >\n <span className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary\">\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <path d=\"m9 15 2 2 4-4\" />\n </svg>\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold text-foreground\">{part.title}</p>\n <p className=\"text-xs text-muted-foreground\">\n {part.kind && <span className=\"font-mono\">{part.kind}</span>}\n {part.kind && ' · '}v{part.ref.version}\n </p>\n </div>\n <WorkProductStatusPill status={part.status} />\n {onOpen && (\n <button\n type=\"button\"\n onClick={() => onOpen(part)}\n className=\"rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground transition hover:bg-accent\"\n >\n Review\n </button>\n )}\n </div>\n )\n}\n\n// ── review queue panel ────────────────────────────────────────────────────\n\n/** One fetched page of queue items with an optional continuation cursor */\nexport interface ReviewQueuePage {\n items: ReviewQueueItem[]\n /** Opaque continuation token; absent ⇒ no further pages. */\n nextCursor?: string\n}\n\n/** Properties for the review queue panel over a fetch data port */\nexport interface ReviewQueuePanelProps {\n /** Data port — fetch one page of queue items (the projection's output,\n * re-validated here at the JSON boundary). */\n fetchQueue: (cursor?: string) => Promise<ReviewQueuePage>\n /** Open one queue item (navigate to its thread / detail pane). */\n onSelect?: (item: ReviewQueueItem) => void\n title?: string\n emptyLabel?: string\n className?: string\n}\n\n/** Merge a fetched page into held rows: dedupe by scopeKey, incoming wins,\n * newest updatedAt first. Exported for tests. */\nexport function mergeReviewQueuePages(existing: ReviewQueueItem[], incoming: ReviewQueueItem[]): ReviewQueueItem[] {\n const byScope = new Map<string, ReviewQueueItem>()\n for (const item of existing) byScope.set(item.scopeKey, item)\n for (const item of incoming) byScope.set(item.scopeKey, item)\n return [...byScope.values()].sort((a, b) => b.updatedAt - a.updatedAt)\n}\n\n/** The workspace review queue — cursor-paged, refreshable, selection via\n * callback. States, counts, and provenance render from the projection; the\n * panel holds no domain logic. */\nexport function ReviewQueuePanel({\n fetchQueue,\n onSelect,\n title = 'Review queue',\n emptyLabel = 'Nothing awaiting review.',\n className,\n}: ReviewQueuePanelProps) {\n const [items, setItems] = useState<ReviewQueueItem[]>([])\n const [cursor, setCursor] = useState<string | undefined>(undefined)\n const [loading, setLoading] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n const load = useCallback(\n async (from?: string) => {\n setLoading(true)\n setError(null)\n try {\n const page = await fetchQueue(from)\n const validated = page.items\n .map((item) => parseReviewQueueItem(item))\n .filter((item): item is ReviewQueueItem => item !== null)\n setItems((prev) => mergeReviewQueuePages(from === undefined ? [] : prev, validated))\n setCursor(page.nextCursor)\n } catch (e) {\n setError(e instanceof Error ? e.message : String(e))\n } finally {\n setLoading(false)\n }\n },\n [fetchQueue],\n )\n\n useEffect(() => {\n void load()\n }, [load])\n\n return (\n <div className={`space-y-2 ${className ?? ''}`}>\n <div className=\"flex items-center gap-2\">\n <h2 className=\"flex-1 text-sm font-semibold\">{title}</h2>\n <button\n type=\"button\"\n onClick={() => void load()}\n disabled={loading}\n aria-label=\"Refresh\"\n className=\"rounded-md p-1.5 text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:opacity-50\"\n >\n <svg viewBox=\"0 0 24 24\" className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 12a9 9 0 1 1-2.64-6.36\" />\n <polyline points=\"21 3 21 9 15 9\" />\n </svg>\n </button>\n </div>\n {error && <p className=\"rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive\">{error}</p>}\n {!error && items.length === 0 && !loading && (\n <p className=\"rounded-md border border-dashed border-border px-3 py-4 text-center text-xs text-muted-foreground\">{emptyLabel}</p>\n )}\n {/* The queue renders neither rows nor the empty copy while `loading`, so\n the announcement is the only thing a screen reader has during the wait.\n Kept mounted with changing text: an inserted live region that already\n carries its message is not reliably announced. */}\n <span role=\"status\" aria-live=\"polite\" aria-busy={loading} className=\"sr-only\">\n {loading ? 'Loading review queue…' : ''}\n </span>\n <ul className=\"space-y-1.5\" aria-busy={loading}>\n {items.map((item) => (\n <li key={item.scopeKey}>\n <button\n type=\"button\"\n onClick={() => onSelect?.(item)}\n className=\"flex w-full items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 text-left transition hover:border-primary/40 hover:bg-accent\"\n >\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-medium text-foreground\">\n {item.workProduct?.title ?? item.scopeKey}\n {item.workProduct && <span className=\"ml-1.5 text-xs text-muted-foreground\">v{item.workProduct.version}</span>}\n </p>\n <p className=\"mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground\">\n {item.workProduct?.kind && <span className=\"font-mono\">{item.workProduct.kind}</span>}\n {item.pendingAsk && <span>asks: {item.pendingAsk.title}</span>}\n {item.blockingExceptions > 0 && (\n <span className=\"text-destructive\">{item.blockingExceptions} blocking</span>\n )}\n {item.failedChecks > 0 && <span className=\"text-warning\">{item.failedChecks} failed checks</span>}\n {item.provenance && item.provenance.profileHash && (\n <span className=\"font-mono\">{item.provenance.profileHash.slice(0, 8)}</span>\n )}\n </p>\n </div>\n <StatePill state={item.state} />\n </button>\n </li>\n ))}\n </ul>\n {cursor && (\n <button\n type=\"button\"\n onClick={() => void load(cursor)}\n disabled={loading}\n className=\"w-full rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition hover:bg-accent disabled:opacity-50\"\n >\n Load more\n </button>\n )}\n </div>\n )\n}\n\n// ── evidence lineage table ────────────────────────────────────────────────\n\n/** Properties for the evidence lineage table with source click-through */\nexport interface EvidenceLineageTableProps {\n evidence: readonly EvidenceEntry[]\n /** Resolve one entry's source document to an openable URL (signed\n * object-store/vault download) — the `resolveFileUrl` pattern. Absent →\n * sources render as plain refs without links. */\n resolveSourceUrl?: (entry: EvidenceEntry) => string\n className?: string\n}\n\nfunction locatorLabel(entry: EvidenceEntry): string | null {\n const parts: string[] = []\n if (entry.locator.page !== undefined) parts.push(`p.${entry.locator.page}`)\n if (entry.locator.range) parts.push(entry.locator.range)\n return parts.length ? parts.join(' · ') : null\n}\n\n/** Target → claim → source lineage rows: the \"every material value traceable\n * to source evidence\" surface. Each row names the artifact target, the\n * claim, and the source document location supporting it. */\nexport function EvidenceLineageTable({ evidence, resolveSourceUrl, className }: EvidenceLineageTableProps) {\n if (evidence.length === 0) {\n return <p className={`text-xs text-muted-foreground ${className ?? ''}`}>No evidence recorded.</p>\n }\n return (\n <div className={`overflow-x-auto ${className ?? ''}`}>\n <table className=\"w-full border-collapse text-left text-sm\">\n <thead>\n <tr className=\"border-b border-border text-xs uppercase tracking-[0.05em] text-muted-foreground\">\n <th className=\"py-1.5 pr-3 font-medium\">Target</th>\n <th className=\"py-1.5 pr-3 font-medium\">Claim</th>\n <th className=\"py-1.5 font-medium\">Source</th>\n </tr>\n </thead>\n <tbody>\n {evidence.map((entry) => {\n const url = resolveSourceUrl?.(entry)\n const locator = locatorLabel(entry)\n return (\n <tr key={entry.id} className=\"border-b border-border align-top\">\n <td className=\"py-2 pr-3 font-mono text-xs text-foreground\">{entry.target}</td>\n <td className=\"py-2 pr-3 text-sm leading-snug text-foreground\">\n {entry.claim}\n {entry.locator.quote && (\n // The basis is what a reviewer weighs, so it has to be\n // visible per row, not only in the aggregate check detail.\n // A platform-sliced quote came out of the document's own\n // bytes; a model-typed one was proved to occur but was\n // transcribed. Same text, different strength of evidence.\n <span\n className={`mt-0.5 block border-l-2 pl-2 text-xs italic ${\n entry.locator.quoteBasis === 'span'\n ? 'border-primary/60 text-foreground'\n : 'border-border text-muted-foreground'\n }`}\n title={\n entry.locator.quoteBasis === 'span'\n ? 'Sliced from the source document by the platform'\n : entry.locator.quoteBasis === 'model'\n ? 'Quoted by the agent, verified to occur in the source'\n : 'Unverified quote'\n }\n >\n “{entry.locator.quote}”\n {entry.locator.quoteBasis && (\n <span className=\"ml-1.5 align-middle text-xs not-italic uppercase tracking-[0.05em] text-muted-foreground\">\n {entry.locator.quoteBasis === 'span' ? 'from source' : 'verified'}\n </span>\n )}\n </span>\n )}\n </td>\n <td className=\"py-2 text-xs\">\n {url ? (\n <a\n href={url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"font-mono text-primary underline-offset-2 hover:underline\"\n >\n {entry.sourceRef}\n </a>\n ) : (\n <span className=\"font-mono text-muted-foreground\">{entry.sourceRef}</span>\n )}\n {locator && <span className=\"ml-1.5 text-muted-foreground\">{locator}</span>}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n}\n\n// ── exceptions + checks ───────────────────────────────────────────────────\n\nconst SEVERITY_TONES: Record<ExceptionEntry['severity'], string> = {\n blocking: 'bg-destructive/10 text-destructive',\n material: 'bg-warning/10 text-warning',\n advisory: 'bg-secondary text-muted-foreground',\n}\n\n/** Properties for the severity-badged exception list */\nexport interface ExceptionListProps {\n exceptions: readonly ExceptionEntry[]\n className?: string\n}\n\n/** Severity-badged exception rows with resolution state. */\nexport function ExceptionList({ exceptions, className }: ExceptionListProps) {\n if (exceptions.length === 0) {\n return <p className={`text-xs text-muted-foreground ${className ?? ''}`}>No exceptions flagged.</p>\n }\n return (\n <ul className={`space-y-1.5 ${className ?? ''}`}>\n {exceptions.map((entry) => (\n <li key={entry.id} className=\"flex items-start gap-2.5 rounded-lg border border-border bg-card px-3 py-2\">\n <span className={`mt-0.5 inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-[0.05em] ${SEVERITY_TONES[entry.severity]}`}>\n {entry.severity}\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className={`text-sm leading-snug ${entry.resolved ? 'text-muted-foreground line-through' : 'text-foreground'}`}>\n {entry.message}\n </p>\n <p className=\"mt-0.5 flex flex-wrap gap-x-2 text-xs text-muted-foreground\">\n <span className=\"font-mono\">{entry.kind}</span>\n {entry.targets && entry.targets.length > 0 && <span className=\"font-mono\">{entry.targets.join(', ')}</span>}\n {entry.resolved && <span>resolved{entry.resolvedBy ? ` by ${entry.resolvedBy}` : ''}</span>}\n {entry.resolutionNote && <span>{entry.resolutionNote}</span>}\n </p>\n </div>\n </li>\n ))}\n </ul>\n )\n}\n\n/** Properties for the pass/fail quality check list */\nexport interface QualityCheckListProps {\n checks: readonly QualityCheck[]\n className?: string\n}\n\n/** Pass/fail quality-check rows tagged with their source (agent self-report,\n * platform gate, judge ensemble). */\nexport function QualityCheckList({ checks, className }: QualityCheckListProps) {\n if (checks.length === 0) {\n return <p className={`text-xs text-muted-foreground ${className ?? ''}`}>No checks recorded.</p>\n }\n return (\n <ul className={`space-y-1 ${className ?? ''}`}>\n {checks.map((check) => (\n <li key={check.id} className=\"flex items-start gap-2 rounded-md px-1 py-1\">\n {check.passed ? (\n <svg viewBox=\"0 0 24 24\" className=\"mt-0.5 h-3.5 w-3.5 shrink-0 text-success\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n ) : (\n <svg viewBox=\"0 0 24 24\" className=\"mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </svg>\n )}\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm text-foreground\">\n {check.name}\n <span className=\"ml-1.5 text-xs uppercase tracking-[0.05em] text-muted-foreground\">{check.source}</span>\n </p>\n {check.detail && <p className=\"text-xs leading-snug text-muted-foreground\">{check.detail}</p>}\n </div>\n </li>\n ))}\n </ul>\n )\n}\n\n// ── provenance stamp ──────────────────────────────────────────────────────\n\n/** Properties for the provenance stamp with the optional backtest slot */\nexport interface ProvenanceStampProps {\n provenance: Pick<WorkProductProvenance, 'profileHash' | 'runId' | 'servingModels'> &\n Partial<Pick<WorkProductProvenance, 'costUsd' | 'producedAt'>>\n /** The product-resolved backtest summary for this profile hash. When its\n * trust gate failed, the composite renders as \"quality: unverified\" —\n * never a naked number. */\n backtest?: ProfileBacktestSummary\n className?: string\n}\n\n/** Truncated id with an ellipsis marker, so a sliced hash never passes as complete. */\nfunction truncateId(id: string, length: number): string {\n return id.length > length ? `${id.slice(0, length)}…` : id\n}\n\n/** The audit line a reviewer approves against: which configuration produced\n * this document, what served it, and how that configuration measured on its\n * backtest. */\nexport function ProvenanceStamp({ provenance, backtest, className }: ProvenanceStampProps) {\n return (\n <div className={`flex flex-wrap items-center gap-x-2.5 gap-y-1 text-xs text-muted-foreground ${className ?? ''}`}>\n <span className=\"font-mono\" title={provenance.profileHash}>\n profile {provenance.profileHash ? truncateId(provenance.profileHash, 10) : '—'}\n </span>\n <span className=\"font-mono\" title={provenance.runId}>\n run {provenance.runId ? truncateId(provenance.runId, 10) : '—'}\n </span>\n {provenance.servingModels.length > 0 ? (\n provenance.servingModels.map((model) => (\n <span key={model} className=\"rounded-full bg-secondary px-2 py-0.5 font-mono\">\n {model}\n </span>\n ))\n ) : (\n <span className=\"italic\">serving model pending</span>\n )}\n {typeof provenance.costUsd === 'number' && <span>${provenance.costUsd.toFixed(provenance.costUsd < 0.01 ? 4 : 2)}</span>}\n {backtest &&\n (backtest.trust === 'pass' ? (\n <span className=\"text-success\">\n {backtest.cases} backtest cases · composite {backtest.composite.toFixed(2)} · trust PASS\n </span>\n ) : (\n <span className=\"text-warning\" title={backtest.trustReasons.join('; ')}>\n quality: unverified\n </span>\n ))}\n </div>\n )\n}\n"],"mappings":";;;;;;;;AAqBA,SAAS,aAAa,WAAW,gBAAgB;AACjD,SAAS,kBAAmC;AA6EnC,cAuCD,YAvC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-store/parts.ts"],"sourcesContent":["/**\n * The stored shape of `message.parts` — one typed vocabulary for every part a\n * product persists into a chat transcript. NOT an ad-hoc union reverse-\n * engineered from product schemas; each member is matched field-for-field to\n * its canonical source:\n *\n * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s\n * `normalizePersistedPart` produces from the harness lane's\n * `message.part.updated` events (ADC sidecar\n * `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in\n * an `{id, sessionID, messageID}` envelope; the projection strips the\n * session/message ids and keeps the per-segment part id).\n * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical\n * `MessagePartSchema` members (ADC\n * `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries\n * the harness's per-step usage receipt — tokens\n * `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is\n * also the shape the message-level token/cost columns mirror.\n * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned\n * sub-agent task).\n * - `interaction` / `notice`: the persisted-part codecs in\n * `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,\n * `noticePart`) — type-only imports, one source of truth for their statuses\n * and field shapes.\n * - `plan`: the durable-plan projection in `/plans`, derived from the sandbox\n * SDK's authoritative plan lifecycle.\n * - `work_product`: the persisted work-product anchor card in\n * `/work-product`'s contract (`workProductToPersistedPart` /\n * `persistedPartToWorkProduct`) — SYSTEM-authored on the ready transition\n * and updated on a reviewer verdict; no prompt teaches an agent to author\n * one.\n * - `mention`: an `@`-picked reference to a file that already lives in the\n * workspace sandbox (`FileMention` in `/chat-routes`'s wire contract, plus\n * the image/file discriminant). Neither transport lane produces it — the\n * turn route persists it from the request's `mentions` field — but it is a\n * part a product persists into a transcript, so it belongs in this\n * vocabulary rather than in a parallel one.\n *\n * `@tangle-network/agent-interface` exports the canonical wire `Part` union,\n * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that\n * is deliberately NOT persisted, so the stored union is defined here as the\n * envelope-free projection (a type-level coverage check against the peer's\n * `Part['type']` lives in the tests). Contribute-down candidate: if\n * agent-interface grows envelope-free persisted-part types, re-export them\n * here and delete these definitions.\n *\n * Two transport lanes serialize into this SAME stored shape:\n * - harness lane: canonical `message.part.updated` parts, merged/normalized by\n * `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);\n * - router/openai-compat lane: `text_delta`/`tool_call` stream events are\n * mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +\n * `/stream`'s `normalizeToolEvent`) and then persisted identically — the\n * store never sees a router-specific shape.\n */\n\nimport type { Part as HarnessWirePart } from '@tangle-network/agent-interface'\nimport type {\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionAnswers,\n InteractionPersistedPart,\n NoticeKind,\n NoticePersistedPart,\n} from '../web-react/chat-interactions'\nimport { persistedPartToInteraction } from '../interactions/contract'\nimport {\n persistedPartToWorkProduct,\n type WorkProductPersistedPart,\n} from '../work-product/types'\nimport {\n persistedPartToPlan,\n planToPersistedPart,\n type ChatPlanPersistedPart,\n} from '../plans/index'\n// `./wire` is import-free by construction, so this edge costs the store\n// nothing and keeps ONE image-extension table for the whole mention layer.\nimport {\n mentionKindForPath,\n type ChatAttachmentInput,\n type ChatAttachmentKind,\n type ChatMentionKind,\n type FileMention,\n} from '../chat-routes/wire'\n\nexport type { ChatMentionKind, ChatAttachmentKind }\n\n/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */\nexport interface ChatPartTime {\n start?: number\n end?: number\n}\n\n/** `id` is the harness's per-segment identity; absent on legacy/router parts,\n * which collapse to a single logical text stream. Never invented client-side. */\nexport interface ChatTextPart {\n type: 'text'\n text: string\n id?: string\n}\n\n/** Define a reasoning part of a chat with text content and optional metadata fields */\nexport interface ChatReasoningPart {\n type: 'reasoning'\n text: string\n id?: string\n time?: ChatPartTime\n}\n\n/** Superset of the sidecar's status enum (`pending|running|completed|failed`)\n * and agent-interface's `ToolState` statuses; `error` is the persisted\n * terminal form `/stream`'s `normalizePersistedPart` settles on. */\nexport type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed'\n\n/** Describe the current state and data of a chat tool including status, input, output, and metadata */\nexport interface ChatToolState {\n status: ChatToolStatus\n input?: unknown\n output?: unknown\n error?: string\n title?: string\n metadata?: Record<string, unknown>\n time?: ChatPartTime\n}\n\n/** Define a chat component representing a tool with its state and optional call identifier */\nexport interface ChatToolPart {\n type: 'tool'\n id: string\n tool: string\n callID?: string\n state: ChatToolState\n}\n\n/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file\n * shapes; response-side every field besides `type` is optional. `name` is the\n * attachment-flavored display label an uploaded/promoted file carries (see\n * {@link ChatAttachmentPart}) — absent on a harness-emitted file part, which\n * uses `filename`. */\nexport interface ChatFilePart {\n type: 'file'\n id?: string\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\n/** Define properties for an image part within a chat message including optional metadata fields */\nexport interface ChatImagePart {\n type: 'image'\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Define a subtask part of a chat with prompt, description, agent, and optional identifier */\nexport interface ChatSubtaskPart {\n type: 'subtask'\n prompt: string\n description: string\n agent: string\n id?: string\n}\n\n/** OpenCode step-boundary marker — no renderable text; preserved so mappers\n * never coerce it into a \"[object Object]\" text part. */\nexport interface ChatStepStartPart {\n type: 'step-start'\n}\n\n/** Per-step usage receipt as the harness reports it (sidecar\n * `StepFinishPartSchema`). The message-level token/cost columns are this\n * shape flattened. */\nexport interface ChatUsageTokens {\n total?: number\n input?: number\n output?: number\n reasoning?: number\n cache?: {\n write?: number\n read?: number\n }\n}\n\n/** Define a chat step finish part indicating completion with optional reason, tokens, and cost */\nexport interface ChatStepFinishPart {\n type: 'step-finish'\n reason?: string\n tokens?: ChatUsageTokens\n cost?: number\n}\n\n/** Persisted human-in-the-loop ask — byte-matches\n * `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */\nexport interface ChatInteractionPart {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n answers?: InteractionAnswers\n cancelReason?: string\n}\n\n/** Resolve a chat plan part by aliasing it to the persisted chat plan part type */\nexport type ChatPlanPart = ChatPlanPersistedPart\n\n/** Persisted work-product anchor card — byte-matches\n * `workProductToPersistedPart` in `/work-product`'s contract. Written by the\n * PLATFORM on the ready transition (and updated on a verdict); never\n * authored by a prompt. */\nexport type ChatWorkProductPart = WorkProductPersistedPart\n\n/** Persisted one-line transcript notice — byte-matches `noticePart` in\n * `/web-react`'s chat-interactions contract. */\nexport interface ChatNoticePart {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n}\n\n/**\n * A file the user `@`-mentioned on this turn: a workspace-relative path into\n * the sandbox, never bytes. `type: 'mention'` is its own discriminant\n * precisely so it does NOT collide with the `file`/`image` attachment parts —\n * an attachment carries content the product uploaded, a mention points at\n * something the box already has, and a transcript renders them differently\n * (an inline pill, not an attachment card).\n *\n * `path` is the identity: mentioning one file twice in a turn folds to one\n * part. `turnId` is optional and set by products that rebuild a turn's\n * mentions on retry.\n */\nexport interface ChatMentionPart {\n type: 'mention'\n mentionKind: ChatMentionKind\n path: string\n name: string\n size?: number\n turnId?: string\n}\n\n// The \"byte-matches\" claims above, enforced at compile time: the interaction\n// contract's codec output types and the stored part types must stay mutually\n// assignable, so a codec field added on one side without the other fails here.\ntype MutuallyAssignable<A extends B, B> = A\ntype _CodecEmitsStorableInteractionPart = MutuallyAssignable<InteractionPersistedPart, ChatInteractionPart>\ntype _StoredInteractionPartFeedsCodec = MutuallyAssignable<ChatInteractionPart, InteractionPersistedPart>\ntype _CodecEmitsStorableNoticePart = MutuallyAssignable<NoticePersistedPart, ChatNoticePart>\ntype _StoredNoticePartFeedsCodec = MutuallyAssignable<ChatNoticePart, NoticePersistedPart>\ntype _CodecEmitsStorablePlanPart = MutuallyAssignable<ChatPlanPersistedPart, ChatPlanPart>\ntype _StoredPlanPartFeedsCodec = MutuallyAssignable<ChatPlanPart, ChatPlanPersistedPart>\ntype _CodecEmitsStorableWorkProductPart = MutuallyAssignable<WorkProductPersistedPart, ChatWorkProductPart>\ntype _StoredWorkProductPartFeedsCodec = MutuallyAssignable<ChatWorkProductPart, WorkProductPersistedPart>\n\n/** Represent parts of a chat message including text, reasoning, tools, files, images, subtasks, steps, interactions, notices, plans, and mentions */\nexport type ChatMessagePart =\n | ChatTextPart\n | ChatReasoningPart\n | ChatToolPart\n | ChatFilePart\n | ChatImagePart\n | ChatSubtaskPart\n | ChatStepStartPart\n | ChatStepFinishPart\n | ChatInteractionPart\n | ChatNoticePart\n | ChatPlanPart\n | ChatWorkProductPart\n | ChatMentionPart\n\n/** Every canonical harness wire-part kind must be storable — compile-time\n * guarantee that a new agent-interface part kind cannot silently fall out of\n * the persisted vocabulary. */\nexport type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart['type']\n\n/**\n * The typed projection at the `/stream` → `/chat-store` boundary. The stream\n * normalizers (`normalizePersistedPart`/`mergePersistedPart`/\n * `finalizeAssistantParts`) deliberately produce untyped `JsonRecord`s — they\n * normalize wire shapes and do not own the stored vocabulary. THIS module\n * owns it, so this is where rows gain the `ChatMessagePart` type: each entry\n * is validated against its kind's required fields and narrowed, junk is\n * dropped, and — enforced by the exhaustiveness check below — no storable\n * kind can silently fall out (the step-finish/interaction trap).\n */\nexport function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[] {\n const out: ChatMessagePart[] = []\n for (const part of parts) {\n const typed = toChatMessagePart(part)\n if (typed) out.push(typed)\n }\n return out\n}\n\nconst str = (value: unknown): value is string => typeof value === 'string'\n\nfunction toChatMessagePart(part: Record<string, unknown>): ChatMessagePart | null {\n if (!part || typeof part !== 'object') return null\n const type = part.type as ChatMessagePart['type'] | undefined\n switch (type) {\n case 'text':\n case 'reasoning':\n return str(part.text) ? (part as unknown as ChatTextPart | ChatReasoningPart) : null\n case 'tool':\n return str(part.id) && str(part.tool) && part.state && typeof part.state === 'object'\n ? (part as unknown as ChatToolPart)\n : null\n case 'file':\n case 'image':\n return part as unknown as ChatFilePart | ChatImagePart\n case 'subtask':\n return str(part.prompt) && str(part.description) && str(part.agent)\n ? (part as unknown as ChatSubtaskPart)\n : null\n case 'step-start':\n return { type: 'step-start' }\n case 'step-finish':\n return part as unknown as ChatStepFinishPart\n case 'interaction':\n return persistedPartToInteraction(part) ? (part as unknown as ChatInteractionPart) : null\n case 'notice':\n return str(part.id) && str(part.noticeKind) && str(part.text)\n ? (part as unknown as ChatNoticePart)\n : null\n case 'plan': {\n const plan = persistedPartToPlan(part)\n return plan ? ({ ...part, ...planToPersistedPart(plan) } as ChatPlanPart) : null\n }\n case 'work_product':\n // Validate via the codec but keep the original row (extra fields the\n // product persisted round-trip, matching the interaction case).\n return persistedPartToWorkProduct(part) ? (part as unknown as ChatWorkProductPart) : null\n case 'mention':\n return isChatMentionPart(part) ? part : null\n case undefined:\n return null\n default: {\n // Compile-time exhaustiveness: a new ChatMessagePart kind that is not\n // handled above makes `type` non-never here and this line fails.\n const _exhaustive: never = type\n void _exhaustive\n return null\n }\n }\n}\n\n/** Resolve whether a ChatMessagePart is specifically a ChatToolPart based on its type property */\nexport function isChatToolPart(part: ChatMessagePart): part is ChatToolPart {\n return part.type === 'tool'\n}\n\n/** Resolve whether a chat message part is a text part based on its type property */\nexport function isChatTextPart(part: ChatMessagePart): part is ChatTextPart {\n return part.type === 'text'\n}\n\n/** Resolve whether a ChatMessagePart is a ChatInteractionPart based on its type property */\nexport function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart {\n return part.type === 'interaction'\n}\n\n/** Resolve whether a chat message part is a persisted chat plan part */\nexport function isChatPlanPart(part: ChatMessagePart): part is ChatPlanPart {\n return part.type === 'plan'\n}\n\n/** Resolve whether a chat message part is a persisted work-product anchor */\nexport function isChatWorkProductPart(part: ChatMessagePart): part is ChatWorkProductPart {\n return part.type === 'work_product'\n}\n\n/** Determine if a chat message part represents the completion of a chat step */\nexport function isChatStepFinishPart(part: ChatMessagePart): part is ChatStepFinishPart {\n return part.type === 'step-finish'\n}\n\n/** Widened to `unknown` — unlike its siblings this guard also runs over raw\n * untyped stored rows (a transcript renderer reads `message.parts` before the\n * typed projection), which is exactly what {@link mentionPartsFromMessageParts}\n * needs. `path` and `name` carry the pill; a row missing either is unrenderable.\n *\n * Mirrors the write contract exactly (`parseFileMention` in `/chat-routes`,\n * then {@link mentionInputToPart}): a blank `name` is rejected there and so is\n * rejected here, and `size` — optional, but typed `number` once present — is\n * type-checked so `'12'` or `null` cannot ride through the guard wearing a\n * type it does not have. Negative sizes are NOT re-rejected: the wire screens\n * them, `mentionInputToPart` trusts its input, and a read guard stricter than\n * what the writer can emit would drop rows it produced itself. */\nexport function isChatMentionPart(part: unknown): part is ChatMentionPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n if (record.size !== undefined && (typeof record.size !== 'number' || !Number.isFinite(record.size))) {\n return false\n }\n return (\n record.type === 'mention' &&\n typeof record.path === 'string' &&\n record.path.length > 0 &&\n typeof record.name === 'string' &&\n record.name.trim().length > 0 &&\n (record.mentionKind === 'image' || record.mentionKind === 'file')\n )\n}\n\n/** Every mention part on one message, in stored order. The projection a\n * transcript renderer runs before deciding which mentions the message text\n * already shows inline (see `segmentMentionContent` in `/web-react`). */\nexport function mentionPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | ReadonlyArray<ChatMessagePart> | null | undefined,\n): ChatMentionPart[] {\n if (!parts) return []\n return (parts as ReadonlyArray<unknown>).filter(isChatMentionPart)\n}\n\n/** A validated wire mention (`parseFileMentions` in `/chat-routes`) as the\n * part the turn route persists. An absent/non-finite `size` is DROPPED rather\n * than stored as `undefined`, so a stored row never carries a key that means\n * nothing. */\nexport function mentionInputToPart(input: FileMention): ChatMentionPart {\n const part: ChatMentionPart = {\n type: 'mention',\n mentionKind: mentionKindForPath(input.path),\n path: input.path,\n name: input.name,\n }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n return part\n}\n\n// ── attachments ──────────────────────────────────────────────────────────\n//\n// An attachment is a file the product uploaded into its own store (vault /\n// object-store) ahead of the turn — content the box did not already have,\n// unlike a `@`-mention. It persists NOT as a new `ChatMessagePart` union\n// member but as an attachment-flavored `file`/`image` part: `type` is the\n// existing `image`/`file` discriminant, with `path` + `name` load-bearing.\n// That reuse is deliberate — a transcript already renders `file`/`image`\n// parts, and `toChatMessagePart` passes them through by cast (fields survive),\n// so an attachment slots into the same stored `parts` array without a parallel\n// vocabulary. These helpers own the input→part projection, the path-keyed\n// stream key, and the agent-facing prompt block, all byte-identical to the gtm\n// source they were lifted from (gtm-agent#618 adoption reproduces its rows and\n// dispatched prompt bytes through them).\n\n/** `image` for any `image/*` mime, `file` for everything else (including an\n * absent/empty mime) — the same split the composer and the persisted-part\n * discriminant both key on. */\nexport function attachmentKindForMime(mime?: string): ChatAttachmentKind {\n return mime?.startsWith('image/') ? 'image' : 'file'\n}\n\n/** Stream/transcript part key for an attachment — ONE declaration, owned by\n * `/stream`'s normalizer (whose `getPartKey` routes path-bearing file/image\n * parts through it). Re-exported here (not redefined) so the root barrel's\n * star-exports of both modules resolve to the same symbol instead of\n * colliding (TS2308 in the dts build). */\nexport { attachmentPartKey } from '../stream/stream-normalizer'\n\n/**\n * Persisted attachment part: structurally an attachment-flavored `ChatFilePart`\n * / `ChatImagePart` (`path` + `name` promoted to required) rather than a\n * separate union member — see the section note above. The index signature keeps\n * it a `Record<string, unknown>` so it drops into the same untyped `parts`\n * arrays every other stored part rides in, and lets the `type`-driven\n * constructors below build it without union-discriminant gymnastics.\n */\nexport interface ChatAttachmentPart {\n type: ChatAttachmentKind\n path: string\n name: string\n size?: number\n mediaType?: string\n turnId?: string\n [key: string]: unknown\n}\n\n/** True for any `image`/`file` part carrying a non-empty string `path`.\n * DELIBERATELY also matches a sidecar path-bearing file part (a mention-style\n * `file` part with only `path`) — the guard is a structural attachment shape,\n * not proof of provenance; a caller that needs to exclude those filters\n * upstream. The `path.length > 0` check diverges from gtm's original guard\n * (which only checked `typeof`), mirroring sibling {@link isChatMentionPart}:\n * read-side robustness against a stored `{type:'file', path:''}` row — which\n * would otherwise render a malformed `(vault: )` pointer line — justifies the\n * small divergence from byte-for-byte gtm parity here; no legitimate write\n * path ever produces an empty `path`. */\nexport function isChatAttachmentPart(part: unknown): part is ChatAttachmentPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n return (\n (record.type === 'image' || record.type === 'file') &&\n typeof record.path === 'string' &&\n record.path.length > 0\n )\n}\n\n/** Drop absent/empty optional fields rather than persisting `undefined`/`''`\n * — keeps stored parts minimal. */\nexport function attachmentInputToPart(input: ChatAttachmentInput): ChatAttachmentPart {\n const part: ChatAttachmentPart = { type: input.kind, path: input.path, name: input.name }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n if (input.mediaType) part.mediaType = input.mediaType\n return part\n}\n\n/** Every attachment part on one message's stored `parts`, in stored order. */\nexport function attachmentPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | null | undefined,\n): ChatAttachmentPart[] {\n if (!parts) return []\n return parts.filter(isChatAttachmentPart)\n}\n\n/** gtm's exact default header for {@link buildAttachmentPromptBlock} — kept\n * byte-identical because it feeds dispatched prompts (gtm-agent#618\n * reproduces the prompt bytes through this module). Override only with intent. */\nexport const DEFAULT_ATTACHMENT_PROMPT_HEADER =\n 'Attached files (already saved to the workspace vault — read them from these paths):'\n\n/** Same C0-control/DEL sweep as `/chat-routes`'s `resolve-attachments.ts`\n * (kept as a separate literal rather than a shared import — this module is\n * the read side and must stay usable over PERSISTED rows the wire validator\n * never saw). Replaced with a single space, not stripped or collapsed: this\n * is defense-in-depth for legacy/corrupt stored rows that bypassed wire\n * validation, not the primary control — a name/path a `resolveChatAttachments`\n * call validated today never contains one, so this is a no-op on legitimate\n * input and gtm byte-compat holds. */\nconst PROMPT_BLOCK_CONTROL_CHARS = /[\\x00-\\x1F\\x7F]/g\n\n/**\n * The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in `message.content`. Empty array → `''` so callers can append\n * unconditionally. The sole producer of this text: both the current turn's\n * dispatch and history projection ({@link historyContentWithAttachments}) build\n * it from here, so the two can never drift. `header` overrides the first line\n * ({@link DEFAULT_ATTACHMENT_PROMPT_HEADER}); the per-file line format is fixed.\n *\n * Every interpolated `name`/`path` is swept for control characters first\n * (newline/carriage-return/tab included) and each one replaced with a single\n * space — a single-line-per-file guarantee. Without it, a control character\n * riding through on a PERSISTED row (`historyContentWithAttachments` reads\n * whatever is already stored; a legacy or hand-edited row was never re-checked\n * against `resolveChatAttachments`) could inject extra lines — fabricated\n * pointer entries or instructions — into a prompt the agent trusts verbatim.\n * The wire-side validator is the primary control; this is the backstop for\n * rows it never saw.\n */\nexport function buildAttachmentPromptBlock(\n atts: ReadonlyArray<Pick<ChatAttachmentPart, 'name' | 'path'>>,\n header: string = DEFAULT_ATTACHMENT_PROMPT_HEADER,\n): string {\n if (atts.length === 0) return ''\n const clean = (value: string) => value.replace(PROMPT_BLOCK_CONTROL_CHARS, ' ')\n const lines = atts.map((a) => `- ${clean(a.name)} (vault: ${clean(a.path)})`)\n return `\\n\\n${header}\\n${lines.join('\\n')}`\n}\n\n/**\n * History projection for a persisted message: `content` unchanged when it\n * carries no attachment parts, else the block is appended once. The\n * no-double-annotation guarantee holds under the invariant that the block is\n * never persisted INTO `message.content` — it is appended only at read time,\n * by this function and the current turn's dispatch, both sourcing from\n * `attachmentPartsFromMessageParts` — never by content inspection. This\n * function does not (and cannot) detect an already-embedded block by scanning\n * `content` for its text: a message whose stored `content` happens to already\n * contain the block's bytes, alongside attachment parts, still gets the block\n * appended a second time. See the pinned test for that boundary.\n */\nexport function historyContentWithAttachments(\n message: {\n content: string\n parts?: ReadonlyArray<Record<string, unknown>> | null\n },\n header?: string,\n): string {\n const attachmentParts = attachmentPartsFromMessageParts(message.parts)\n if (attachmentParts.length === 0) return message.content\n return `${message.content}${buildAttachmentPromptBlock(att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