feat(context): persist typed inline context references #10233
Closedchrisdeeming(GitHub profile, opens in a new tab)wants to merge 20 commits into
main fromrefs/pull/10233/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- packages/shared/src/composerContextLegacy.ts line 155OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +135,21 @@135+ section = sectionStart[1]!;136+ sections[section] = [];137+ }138+ }139+ return {140+ version: 1,141+ contextId: legacyId("element", index),142+ kind: "element",143+ label: `<${inner}>`,144+ pageUrl: fields.url ?? "",145+ pageTitle: null,146+ tagName: inner.toLowerCase(),147+ selector: fields.selector ?? null,148+ htmlPreview: (sections.html ?? []).join("\n").trimEnd(),149+ componentName: /[A-Z]/.test(inner) ? inner : null,150+ source: fields.source ? parseSource(fields.source) : null,151+ styles: (sections.styles ?? []).join("\n").trimEnd(),152+ };153+}154+155+function previewRecord(body: string, index: number): PreviewAnnotationContextRecord {packages/shared/src/composerContextLegacy.ts lines 299 to 301OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +281,21 @@281+ const terminal = stripTrailing(rest, TRAILING_TERMINAL);282+ if (terminal) {283+ rest = terminal.text;284+ terminalEntries.unshift(...parseEntries(terminal.match[1] ?? ""));285+ continue;286+ }287+ break;288+ }289+290+ const terminals = terminalEntries291+ .map((entry, index) => terminalRecord(entry, index + 1))292+ .filter((record) => record !== null);293+ const elements = elementEntries294+ .map((entry, index) => elementRecord(entry, index + 1))295+ .filter((record) => record !== null);296+ const previews = previewBodies.map((body, index) => previewRecord(body, index + 1));297+ const appendedReviews = trailingReviewTokens.map((index) => reviews[index]!);298+299+ let body = rest.replace(/\uE000(\d+)\uE000/g, (_whole, index: string) =>300+ formatComposerContextReference(reviews[Number(index)]!),301+ );packages/contracts/src/orchestration.ts line 1239Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -984,3 +987,4 @@984987 role: Schema.Literal("user"),985988 text: Schema.String,986989 attachments: Schema.Array(Schema.Union([UploadChatAttachment, ChatAttachment])),990+ context: Schema.optional(OrchestrationMessageContext),packages/contracts/src/composerContext.ts line 234OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +214,21 @@214+ TerminalContextRecord,215+ ElementContextRecord,216+ PreviewAnnotationContextRecord,217+ ReviewCommentContextRecord,218+ MentionContextRecord,219+ SkillContextRecord,220+]);221+export type KnownComposerContextRecord = typeof KnownComposerContextRecord.Type;222+223+export const ComposerContextRecord = Schema.Union([224+ ...KnownComposerContextRecord.members,225+ UnknownContextRecord,226+]);227+export type ComposerContextRecord = typeof ComposerContextRecord.Type;228+229+export const COMPOSER_CONTEXT_MAX_RECORDS = 200;230+231+/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */232+export const OrchestrationMessageContext = Schema.Struct({233+ version: Schema.Literal(1),234+ records: ForwardCompatibleArray(ComposerContextRecord).check(packages/shared/src/composerContextReferences.ts lines 265 to 266OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +246,21 @@246+ : "payload" in record247+ ? JSON.stringify(record.payload)248+ : formatComposerContextProviderPayload(record);249+ if (body === null) return null;250+ return `${open}>\n${escapeComposerContextPayloadText(body)}\n</${CONTEXT_ENTRY_TAG}>`;251+}252+253+/**254+ * What the provider reads: every reference becomes an in-place marker, and each unique255+ * referenced payload appears once in a trailing envelope, in first-reference order.256+ * Unreferenced records are not emitted. Binary attachments travel on their own channel.257+ */258+export function projectComposerContextForProvider(input: {259+ text: string;260+ records: ReadonlyArray<ComposerContextRecord>;261+}): string {262+ const occurrences = collectComposerContextReferences(input.text);263+ if (occurrences.length === 0) return input.text;264+ const recordsById = new Map(input.records.map((record) => [record.contextId, record]));265+ const body = replaceComposerContextReferences(input.text, (occurrence) =>266+ formatComposerContextProviderMarker(occurrence.kind, occurrence.label, occurrence.contextId),packages/contracts/src/composerContext.ts line 234OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +214,21 @@214+ TerminalContextRecord,215+ ElementContextRecord,216+ PreviewAnnotationContextRecord,217+ ReviewCommentContextRecord,218+ MentionContextRecord,219+ SkillContextRecord,220+]);221+export type KnownComposerContextRecord = typeof KnownComposerContextRecord.Type;222+223+export const ComposerContextRecord = Schema.Union([224+ ...KnownComposerContextRecord.members,225+ UnknownContextRecord,226+]);227+export type ComposerContextRecord = typeof ComposerContextRecord.Type;228+229+export const COMPOSER_CONTEXT_MAX_RECORDS = 200;230+231+/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */232+export const OrchestrationMessageContext = Schema.Struct({233+ version: Schema.Literal(1),234+ records: ForwardCompatibleArray(ComposerContextRecord).check(packages/shared/src/composerContextLegacy.ts lines 315 to 316OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +296,21 @@296+ const previews = previewBodies.map((body, index) => previewRecord(body, index + 1));297+ const appendedReviews = trailingReviewTokens.map((index) => reviews[index]!);298+299+ let body = rest.replace(/\uE000(\d+)\uE000/g, (_whole, index: string) =>300+ formatComposerContextReference(reviews[Number(index)]!),301+ );302+303+ // Placeholders bind to terminal entries in order, like the old materialize step did.304+ let placeholderIndex = 0;305+ body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {306+ const record = terminals[placeholderIndex];307+ placeholderIndex += 1;308+ return record ? formatComposerContextReference(record) : "";309+ });310+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the311+ // placeholder; each such label becomes the chip in place.312+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));313+ for (const record of terminals) {314+ if (placedTerminals.has(record)) continue;315+ const label = inlineTerminalLabel(record);316+ const at = body.indexOf(label);
- packages/shared/src/composerContextReferences.ts line 229Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +209,21 @@209+ );210+ }211+ if (record.screenshotContextId) lines.push(`screenshot: ref=${record.screenshotContextId}`);212+ for (const [index, element] of (record.elements ?? []).entries()) {213+ lines.push(`element ${index + 1}:`, indent(formatElementDetails(element).join("\n")));214+ }215+ return lines.join("\n");216+ }217+ case "review-comment": {218+ const lines = [219+ `file: ${record.filePath}`,220+ `range: ${record.rangeLabel} (${record.startIndex}-${record.endIndex})`,221+ `section: ${record.sectionTitle}`,222+ ];223+ if (record.text.trim()) lines.push("comment:", indent(record.text.trim()));224+ if (record.diff.trim()) {225+ lines.push(`${record.fenceLanguage ?? "diff"}:`, indent(record.diff.trimEnd()));226+ }227+ return lines.join("\n");228+ }229+ case "mention":packages/shared/src/composerContextReferences.ts line 263OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +243,21 @@243+ record.kind === "mention" || record.kind === "skill"244+ ? null245+ : "payload" in record246+ ? JSON.stringify(record.payload)247+ : formatComposerContextProviderPayload(record);248+ if (body === null) return null;249+ return `${open}>\n${escapeComposerContextPayloadText(body)}\n</${CONTEXT_ENTRY_TAG}>`;250+}251+252+/**253+ * What the provider reads: every reference becomes an in-place marker, and each unique254+ * referenced payload appears once in a trailing envelope, in first-reference order.255+ * Unreferenced records are not emitted. Binary attachments travel on their own channel.256+ */257+export function projectComposerContextForProvider(input: {258+ text: string;259+ records: ReadonlyArray<ComposerContextRecord>;260+}): string {261+ const occurrences = collectComposerContextReferences(input.text);262+ if (occurrences.length === 0) return input.text;263+ const recordsById = new Map(input.records.map((record) => [record.contextId, record]));packages/shared/src/composerContextLegacy.ts lines 397 to 403Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +313,21 @@313+314+ let body = rest.replace(reviewTokenPattern, (_whole, index: string) =>315+ formatComposerContextReference(reviews[Number(index)]!),316+ );317+318+ // Placeholders bind to terminal entries in order, like the old materialize step did.319+ let placeholderIndex = 0;320+ body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {321+ const record = terminals[placeholderIndex];322+ placeholderIndex += 1;323+ return record ? formatComposerContextReference(record) : "";324+ });325+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the326+ // placeholder; each such label becomes the chip in place.327+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));328+ for (const record of terminals) {329+ if (placedTerminals.has(record)) continue;330+ const label = inlineTerminalLabel(record);331+ let at = body.indexOf(label);332+ while (at !== -1 && /[\d-]/.test(body[at + label.length] ?? "")) {333+ at = body.indexOf(label, at + 1);
- packages/contracts/src/composerContext.ts line 268Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +216,21 @@216+ PreviewAnnotationContextRecord,217+ ReviewCommentContextRecord,218+ MentionContextRecord,219+ SkillContextRecord,220+]);221+export type KnownComposerContextRecord = typeof KnownComposerContextRecord.Type;222+223+export const ComposerContextRecord = Schema.Union([224+ ...KnownComposerContextRecord.members,225+ UnknownContextRecord,226+]);227+export type ComposerContextRecord = typeof ComposerContextRecord.Type;228+229+const COMPOSER_CONTEXT_MAX_RECORDS = 200;230+231+/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */232+export const OrchestrationMessageContext = Schema.Struct({233+ version: Schema.Literal(1),234+ records: Schema.Array(Schema.Unknown)235+ .check(Schema.isMaxLength(COMPOSER_CONTEXT_MAX_RECORDS))236+ .pipe(Schema.decodeTo(ForwardCompatibleArray(ComposerContextRecord)))
- packages/shared/src/composerContextLegacy.ts line 354Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +276,21 @@276+ const tokens = trailingReviewTokenPattern.exec(rest);277+ if (tokens && tokens[0].length > 0) {278+ trailingReviewTokens.push(279+ ...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),280+ );281+ rest = rest.slice(0, tokens.index).replace(/\n+$/, "");282+ }283+ for (;;) {284+ const preview = stripTrailing(rest, TRAILING_PREVIEW);285+ if (preview) {286+ rest = preview.text;287+ previewBodies.unshift(preview.match[1] ?? "");288+ continue;289+ }290+ const element = stripTrailing(rest, TRAILING_ELEMENT);291+ if (element) {292+ rest = element.text;293+ elementEntries.unshift(...parseEntries(element.match[1] ?? ""));294+ continue;295+ }296+ const terminal = stripTrailing(rest, TRAILING_TERMINAL);packages/shared/src/composerContextLegacy.ts lines 248 to 249Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +214,21 @@214+ const endIndex = attributes.endIndex;215+ if (!filePath || !sectionId || !/^\d+$/.test(startIndex ?? "") || !/^\d+$/.test(endIndex ?? "")) {216+ return null;217+ }218+ const fences = Array.from(rawBody.matchAll(REVIEW_FENCE));219+ const fence = fences.at(-1);220+ const rangeLabel = attributes.rangeLabel?.trim() || "line";221+ const basename = filePath.split(/[\\/]/).at(-1) ?? filePath;222+ return {223+ version: 1,224+ contextId: legacyId("review-comment", index),225+ kind: "review-comment",226+ label: `${basename} ${rangeLabel}`,227+ sectionId,228+ sectionTitle: attributes.sectionTitle?.trim() || "Review",229+ filePath,230+ startIndex: Math.min(Number(startIndex), Number(endIndex)),231+ endIndex: Math.max(Number(startIndex), Number(endIndex)),232+ rangeLabel,233+ text: rawBody.slice(0, fence?.index ?? rawBody.length).trim(),234+ diff: fence?.[3] ?? "",
- packages/shared/src/composerContextLegacy.ts lines 30 to 30OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+11+import { formatComposerContextReference } from "./composerContextReferences.ts";12+13+/**14+ * Upgrades a message written before inline context references: trailing15+ * `<terminal_context>`, `<element_context>` and `<preview_annotation>` blocks, inline or16+ * trailing `<review_comment>` blocks, and U+FFFC terminal placeholders. Produces canonical17+ * reference links plus records so old messages render and copy through the new path.18+ * Event history is never rewritten; this runs in memory on read.19+ */20+21+export interface UpgradedLegacyContext {22+ text: string;23+ records: ComposerContextRecord[];24+}25+26+const PLACEHOLDER = "";27+const TRAILING_TERMINAL = /\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;28+const TRAILING_ELEMENT = /\n*<element_context>\n([\s\S]*?)\n<\/element_context>\s*$/;29+const TRAILING_PREVIEW =30+ /\n*<preview_annotation>\n((?:(?!<preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;
- packages/shared/src/composerContextLegacy.ts lines 96 to 106Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ const header = /^(.*?) (?:line (\d+)|lines (\d+)-(\d+))$/.exec(entry.header);83+ if (!header) return null;84+ const terminalLabel = header[1]!.trim();85+ if (!terminalLabel) return null;86+ const lineStart = Number(header[2] ?? header[3]);87+ const lineEnd = Number(header[2] ?? header[4]);88+ const text = entry.body89+ .split("\n")90+ .map((line) => line.replace(/^\d+ \| ?/, ""))91+ .join("\n");92+ return {93+ version: 1,94+ contextId: legacyId("terminal", index),95+ kind: "terminal",96+ label: entry.header,97+ terminalId: terminalLabel.toLowerCase().replace(/\s+/g, "-"),98+ terminalLabel,99+ lineStart,100+ lineEnd,101+ text,102+ };
- packages/contracts/src/composerContext.ts line 175Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +155,21 @@155+ kind: Schema.Literal("preview-annotation"),156+ annotationId: ShortString,157+ pageUrl: ShortString,158+ pageTitle: NullableShortString,159+ comment: BoundedString(COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS),160+ targetSummary: ShortString,161+ styleChanges: Schema.Array(ShortString).check(Schema.isMaxLength(200)),162+ /** Picked elements inside the annotation, with the detail the agent needs to find them. */163+ elements: Schema.optional(Schema.Array(ElementContextDetails).check(Schema.isMaxLength(50))),164+ /** Original target ids and edits allow pasted annotations to retain exact style changes. */165+ elementIds: Schema.optional(Schema.Array(ShortString).check(Schema.isMaxLength(50))),166+ styleChangeDetails: Schema.optional(167+ Schema.Array(168+ Schema.Struct({169+ targetId: ShortString,170+ selector: NullableShortString,171+ property: ShortString,172+ previousValue: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),173+ value: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),174+ }),175+ ).check(Schema.isMaxLength(200)),packages/shared/src/composerContextLegacy.ts line 344OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +324,21 @@324+ let body = rest.replace(reviewTokenPattern, (_whole, index: string) =>325+ formatComposerContextReference(reviews[Number(index)]!),326+ );327+328+ // Placeholders bind to terminal entries in order, like the old materialize step did.329+ let placeholderIndex = 0;330+ body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {331+ const record = terminals[placeholderIndex];332+ placeholderIndex += 1;333+ return record ? formatComposerContextReference(record) : "";334+ });335+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the336+ // placeholder; each such label becomes the chip in place.337+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));338+ for (const record of terminals) {339+ if (placedTerminals.has(record)) continue;340+ const label = inlineTerminalLabel(record);341+ let at = body.indexOf(label);342+ while (343+ at !== -1 &&344+ (/[\w@.-]/.test(body[at - 1] ?? "") || /[\d-]/.test(body[at + label.length] ?? ""))
- packages/shared/src/composerContextLegacy.ts line 299OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +279,21 @@279+ // Only reviews that trailed the original text were appended by the old send path; a280+ // review that sat before other blocks keeps its place.281+ const trailingReviewTokens: number[] = [];282+ const tokens = trailingReviewTokenPattern.exec(rest);283+ if (tokens && tokens[0].length > 0) {284+ trailingReviewTokens.push(285+ ...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),286+ );287+ rest = rest.slice(0, tokens.index).replace(/\n+$/, "");288+ }289+ for (;;) {290+ const preview = stripTrailing(rest, TRAILING_PREVIEW);291+ if (preview) {292+ rest = preview.text;293+ previewBodies.unshift(preview.match[1] ?? "");294+ continue;295+ }296+ const element = stripTrailing(rest, TRAILING_ELEMENT);297+ if (element) {298+ const entries = parseEntries(element.match[1] ?? "");299+ if (entries.length === 0 || entries.some((entry) => elementRecord(entry, 1) === null)) break;
- packages/shared/src/composerContextLegacy.ts line 345OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +325,21 @@325+ formatComposerContextReference(reviews[Number(index)]!),326+ );327+328+ // Placeholders bind to terminal entries in order, like the old materialize step did.329+ let placeholderIndex = 0;330+ body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {331+ const record = terminals[placeholderIndex];332+ placeholderIndex += 1;333+ return record ? formatComposerContextReference(record) : "";334+ });335+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the336+ // placeholder; each such label becomes the chip in place.337+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));338+ for (const record of terminals) {339+ if (placedTerminals.has(record)) continue;340+ const label = inlineTerminalLabel(record);341+ let at = body.indexOf(label);342+ while (343+ at !== -1 &&344+ (/[\p{L}\p{N}\p{M}_@.-]$/u.test(body.slice(0, at)) ||345+ /^[\p{L}\p{N}\p{M}_-]/u.test(body.slice(at + label.length)))
- packages/shared/src/composerContextLegacy.ts line 31OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+import { formatComposerContextReference } from "./composerContextReferences.ts";12+13+/**14+ * Upgrades a message written before inline context references: trailing15+ * `<terminal_context>`, `<element_context>` and `<preview_annotation>` blocks, inline or16+ * trailing `<review_comment>` blocks, and U+FFFC terminal placeholders. Produces canonical17+ * reference links plus records so old messages render and copy through the new path.18+ * Event history is never rewritten; this runs in memory on read.19+ */20+21+export interface UpgradedLegacyContext {22+ text: string;23+ records: ComposerContextRecord[];24+}25+26+const PLACEHOLDER = "";27+const TRAILING_TERMINAL = /\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;28+const TRAILING_ELEMENT = /\n*<element_context>\n([\s\S]*?)\n<\/element_context>\s*$/;29+const TRAILING_PREVIEW =30+ /\n*<preview_annotation>\n((?:(?!\n<\/preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;31+const INLINE_REVIEW = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
- packages/shared/src/composerContextLegacy.ts line 63OutdatedResolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+ header: string;44+ body: string;45+}46+47+function parseEntries(block: string): ParsedEntry[] {48+ const entries: ParsedEntry[] = [];49+ let current: { header: string; bodyLines: string[] } | null = null;50+ const commit = () => {51+ if (!current) return;52+ entries.push({ header: current.header, body: current.bodyLines.join("\n").trimEnd() });53+ current = null;54+ };55+ for (const line of block.split("\n")) {56+ const headerMatch = /^- (.+):$/.exec(line);57+ if (headerMatch) {58+ commit();59+ current = { header: headerMatch[1]!, bodyLines: [] };60+ continue;61+ }62+ if (current && line.startsWith(" ")) current.bodyLines.push(line.slice(2));63+ else if (line.trim().length > 0) return [];
- packages/shared/src/composerContextLegacy.ts line 318Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +295,21 @@295+ parts.push(text.slice(consumed));296+ return parts.join("");297+}298+299+export function upgradeLegacyContextMessage(text: string): UpgradedLegacyContext {300+ if (!LEGACY_MARKERS.test(text)) return { text, records: [] };301+302+ const terminalEntries: ParsedEntry[] = [];303+ const elementEntries: ParsedEntry[] = [];304+ const previewBodies: string[] = [];305+ const reviews: ReviewCommentContextRecord[] = [];306+307+ // A literal private-use token in the message must never be mistaken for our placeholder.308+ let reviewToken = REVIEW_TOKEN;309+ while (text.includes(reviewToken)) reviewToken += reviewToken;310+ const reviewTokenPattern = new RegExp(`${reviewToken}(\\d+)${reviewToken}`, "g");311+ const trailingReviewTokenPattern = new RegExp(`(?:\\s*${reviewToken}\\d+${reviewToken})+\\s*$`);312+313+ // Review blocks become tokens in place first so they neither hide the trailing blocks314+ // behind them nor lose their position. Unparseable blocks stay as text.315+ let rest = replaceReviewBlocks(text, (whole, attributes, rawBody) => {
- packages/shared/src/composerContextLegacy.ts line 162Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +142,21 @@142+ }143+ }144+ return {145+ version: 1,146+ contextId: legacyId("element", index),147+ kind: "element",148+ label: `<${inner}>`,149+ pageUrl: fields.url ?? "",150+ pageTitle: null,151+ tagName: inner.toLowerCase(),152+ selector: fields.selector ?? null,153+ htmlPreview: (sections.html ?? []).join("\n").trimEnd(),154+ componentName: /[A-Z]/.test(inner) ? inner : null,155+ source: fields.source ? parseSource(fields.source) : null,156+ styles: (sections.styles ?? []).join("\n").trimEnd(),157+ };158+}159+160+function previewRecord(body: string, index: number): PreviewAnnotationContextRecord | null {161+ const lines = body.split("\n");162+ const read = (prefix: string) =>
- docs/internals/composer-context-references.md line 60Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+rejects direct `crypto.randomUUID()` there.40+41+## Canonical reference syntax42+43+[`composerContextReferences.ts`][shared] owns the grammar:44+45+```text46+[label](t3-context://v1/<kind>/<contextId>)47+48+```49+50+The parser accepts exactly the `t3-context:` scheme, the `v1` host, one kind segment matching51+`[a-z][a-z0-9-]{0,39}`, and one id segment matching `[a-z0-9_-]{1,128}`. Query strings, fragments,52+credentials, and extra segments are rejected. Labels are sanitized to survive a Markdown link (no53+brackets or line breaks, at most 200 characters, never empty). Links that fail to parse are54+ordinary text. `collectComposerInlineTokens` already rejects URI schemes for file links, so a55+context link is never mistaken for a mention.56+57+## Provider projection58+59+`projectComposerContextForProvider({ text, records })` builds what the provider reads:
- packages/shared/src/composerContextLegacy.ts lines 409 to 409OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +389,21 @@389+ return record ? formatComposerContextReference(record) : "";390+ });391+ // Sent messages carry the materialized `@terminal-1:509-514` label instead of the392+ // placeholder; each such label becomes the chip in place.393+ const placedTerminals = new Set(terminals.slice(0, placeholderIndex));394+ for (const record of terminals) {395+ if (placedTerminals.has(record)) continue;396+ const label = inlineTerminalLabel(record);397+ let at = body.indexOf(label);398+ while (399+ at !== -1 &&400+ (/[\p{L}\p{N}\p{M}_@.-]$/u.test(body.slice(0, at)) ||401+ /^(?:[\p{L}\p{N}\p{M}_-]|[.@]+[\p{L}\p{N}\p{M}_-])/u.test(body.slice(at + label.length)))402+ ) {403+ at = body.indexOf(label, at + 1);404+ }405+ if (at === -1) continue;406+ body = `${body.slice(0, at)}${formatComposerContextReference(record)}${body.slice(at + label.length)}`;407+ placedTerminals.add(record);408+ }409+ body = body.replace(/[ \t]+$/gm, "").trimEnd();docs/internals/composer-context-references.md lines 31 to 31OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+## Two linked concepts12+13+A **context record** is the payload. It lives in `message.context.records`, keyed by a14+ `contextId`. Records never contain bytes: image and file records bind to an existing15+ `ChatAttachment` by id.16+A **context reference** is one occurrence in the document. It is a Markdown link in17+ `message.text` that carries only the kind and the `contextId`. Two references can point at one18+ record. A reference's label is display text and never identity.19+20+[`composerContext.ts`][contract] defines version 1 of the record union. Every record has21+`version`, `contextId`, `kind`, and `label`, plus kind-specific fields with bounded lengths. The22+union is open: a kind this build does not know decodes to `UnknownContextRecord` with its23+`payload` preserved, and known kinds are excluded from that member so a malformed image record24+fails its own schema rather than sliding through unchecked. `OrchestrationMessageContext` wraps25+the records with `ForwardCompatibleArray`, so one undecodable record is dropped instead of failing26+the whole message. The field is optional on `OrchestrationMessage`, both turn-start commands, and27+`ThreadMessageSentPayload`. The decider and projector carry it through untouched.28+29+## Identity namespaces30+31+`ComposerContextId` (`ctx_…`): durable payload identity. Branded.
- @@ -0,0 +2,21 @@2+ COMPOSER_CONTEXT_LABEL_MAX_CHARS,3+ type ComposerContextId,4+ type ComposerContextKind,5+ type ComposerContextRecord,6+ type ElementContextDetails,7+ type KnownComposerContextRecord,8+} from "@t3tools/contracts";9+10+/**11+ * Canonical inline reference: `[label](t3-context://v1/<kind>/<contextId>)`, or the image12+ * form ``. The link carries position and identity only; the payload lives in the13+ * message's context records. Labels are display text and never identity.14+ */15+16+const CONTEXT_PROTOCOL = "t3-context:";17+const COMPOSER_CONTEXT_HREF_PREFIX = `${CONTEXT_PROTOCOL}//v1/`;18+const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;19+const CONTEXT_ID_PATTERN = /^[a-z0-9_-]{1,128}$/i;20+const MAX_LINK_LABEL_LENGTH = 512;21+const CONTEXT_LINK = new RegExp(22+ String.raw`(!?)\[([^\]\n]{0,${MAX_LINK_LABEL_LENGTH}})\]\((${COMPOSER_CONTEXT_HREF_PREFIX}[^\s)]{1,200})\)`,
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed