import { z } from "zod"; import { roleModelSchema, roleSlugSchema, threadRoleSnapshotSchema } from "./agent-role.js"; import { harnessIdSchema, harnessThinkingOptionIdSchema, hostThreadIdSchema } from "./ids.js"; export const GROUP_CONTEXT_MAX_BYTES = 16_384; export const GROUP_MEMORY_MAX_BYTES = 4_096; export const GROUP_BOARD_MAX_TASKS = 200; export const GROUP_TASK_TITLE_MAX_LENGTH = 200; export const GROUP_TASK_NOTE_MAX_LENGTH = 500; export const GROUP_TASK_DETAIL_MAX_LENGTH = 8_000; export const GROUP_TASK_MAX_ARTIFACTS = 12; export const GROUP_TASK_ARTIFACT_PATH_MAX_LENGTH = 4_096; export const GROUP_TASK_ARTIFACT_LABEL_MAX_LENGTH = 120; export const GROUP_BOARD_RECENT_DONE_LIMIT = 5; export const GROUP_NO_REPLY_MARKER = "[[NO_REPLY]]"; export const DEFAULT_GROUP_MAX_AGENT_HOPS = 10; export const LEGACY_MAX_GROUP_AGENT_HOPS = 20; export const MAX_GROUP_AGENT_HOPS = 200; export const GROUP_NOTICE_MAX_LENGTH = 2_000; let cachedUtf8Encoder: TextEncoder | null | undefined; export function groupUtf8ByteLength(text: string): number { if (cachedUtf8Encoder === undefined) { cachedUtf8Encoder = typeof TextEncoder === "function" ? new TextEncoder() : null; } if (cachedUtf8Encoder !== null) { return cachedUtf8Encoder.encode(text).length; } let bytes = 0; for (let i = 0; i < text.length; i += 1) { const code = text.charCodeAt(i); if (code <= 0x7f) { bytes += 1; } else if (code <= 0x7ff) { bytes += 2; } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) { const next = text.charCodeAt(i + 1); if (next >= 0xdc00 && next <= 0xdfff) { bytes += 4; i += 1; } else { bytes += 3; } } else { bytes += 3; } } return bytes; } /** True when an Agent explicitly emits the protocol silence marker and nothing else. */ export function isGroupNoReply(text: string): boolean { const trimmed = text.trim(); if (trimmed === GROUP_NO_REPLY_MARKER) return true; if ( trimmed.length === GROUP_NO_REPLY_MARKER.length + 2 && trimmed.startsWith("`") && trimmed.endsWith("`") ) { return trimmed.slice(1, -1) === GROUP_NO_REPLY_MARKER; } return false; } export const remoteGroupRoomIdSchema = z.string().regex(/^remote:[A-Za-z0-9_-]{8,512}$/u); export const groupRoomIdSchema = z.union([z.uuidv4(), remoteGroupRoomIdSchema]); export const groupMemberIdSchema = z.uuidv4(); export const groupTaskIdSchema = z.uuidv4(); export const groupMemberHandleSchema = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u); export const groupUnmentionedPolicySchema = z.enum(["none", "last_speaker", "all"]); export const groupMemberStatusSchema = z.enum(["active", "muted", "removed"]); export const groupTaskStatusSchema = z.enum([ "todo", "in_progress", "blocked", "done", "cancelled", ]); export const groupTaskActorTypeSchema = z.enum(["user", "agent"]); const nonnegativeInteger = z.int().nonnegative(); const positiveInteger = z.int().positive(); const maxAgentHopsSchema = nonnegativeInteger.max(MAX_GROUP_AGENT_HOPS); const nonblankString = z.string().refine((value) => value.trim().length > 0); const timestamp = z.iso.datetime(); const optionalMemberEdits = { handle: groupMemberHandleSchema.optional(), displayName: nonblankString.optional(), note: z.string().optional(), }; export const groupMemberSchema = z.object({ memberId: groupMemberIdSchema, threadId: hostThreadIdSchema, handle: groupMemberHandleSchema, displayName: nonblankString, note: z.string().optional(), roleSlug: roleSlugSchema.optional(), roleSnapshot: threadRoleSnapshotSchema.optional(), harnessId: harnessIdSchema, status: groupMemberStatusSchema, projectless: z.boolean().optional(), showInSidebar: z.boolean().optional(), joinedAtSeq: nonnegativeInteger, lastDeliveredSeq: nonnegativeInteger, lastRosterVersion: nonnegativeInteger, lastMemoryVersion: nonnegativeInteger.default(0), lastBoardVersion: nonnegativeInteger.default(0), createdAt: timestamp, }); export const groupProjectlessWorkspaceSchema = z.object({ workspaceRoot: nonblankString, outputDirectory: nonblankString, }); export const groupRoomRemoteHostSchema = z.object({ hostId: nonblankString, displayName: nonblankString, state: nonblankString.optional(), color: z.string().optional(), filePreview: z.boolean().optional(), memberSidebarVisibility: z.boolean().optional(), sharedMemory: z.boolean().optional(), }); const groupRoomObjectSchema = z .object({ roomId: groupRoomIdSchema, title: nonblankString, defaultCwd: nonblankString, projectlessWorkspace: groupProjectlessWorkspaceSchema.optional(), unmentionedPolicy: groupUnmentionedPolicySchema.default("none"), unmentionedMemberId: groupMemberIdSchema.optional(), allowAgentMentions: z.boolean().default(true), maxAgentHops: maxAgentHopsSchema.default(DEFAULT_GROUP_MAX_AGENT_HOPS), relayHopLimit: maxAgentHopsSchema.optional(), lastSeq: nonnegativeInteger, lastSpeakerMemberId: groupMemberIdSchema.optional(), rosterVersion: nonnegativeInteger, memoryVersion: nonnegativeInteger.default(0), memorySha256: z .string() .regex(/^[0-9a-f]{64}$/u) .optional(), boardVersion: nonnegativeInteger.default(0), humanEpoch: nonnegativeInteger, relayPaused: z.boolean(), pinned: z.boolean(), createdAt: timestamp, updatedAt: timestamp, members: z.array(groupMemberSchema), remote: groupRoomRemoteHostSchema.optional(), }) .superRefine(({ members, unmentionedPolicy, unmentionedMemberId }, context) => { if (unmentionedMemberId !== undefined && unmentionedPolicy !== "none") { context.addIssue({ code: "custom", path: ["unmentionedMemberId"], message: 'A default member can only be set when unmentionedPolicy is "none"', }); } const handles = new Set(); for (const [index, { handle, status }] of members.entries()) { if (status === "removed") continue; if (handles.has(handle)) { context.addIssue({ code: "custom", path: ["members", index, "handle"], message: "Handle must be unique among non-removed members", }); } handles.add(handle); } }); export const groupRoomSchema = z.preprocess((value) => { if (typeof value === "object" && value !== null && !Array.isArray(value)) { const record = value as Record; if (record.unmentionedPolicy === "member" && record.unmentionedMemberId !== undefined) { return { ...record, unmentionedPolicy: "none" }; } } return value; }, groupRoomObjectSchema); export const groupRoomSummarySchema = groupRoomSchema; export const groupAttachmentSchema = z.object({ kind: z.enum(["image", "file"]), attachmentId: nonblankString.max(256), name: nonblankString.max(256), path: nonblankString.max(4096), bytes: nonnegativeInteger, mediaType: nonblankString.max(128).optional(), width: positiveInteger.optional(), height: positiveInteger.optional(), }); export const groupMessageSchema = z.object({ roomId: groupRoomIdSchema, seq: positiveInteger, messageId: nonblankString, senderType: z.enum(["user", "agent", "system"]), senderMemberId: groupMemberIdSchema.optional(), senderHandle: groupMemberHandleSchema.optional(), senderName: z.string().optional(), senderThreadId: hostThreadIdSchema.optional(), sourceTurnId: nonblankString.optional(), replyToSeq: positiveInteger.optional(), content: z.string(), attachments: z.array(groupAttachmentSchema).max(12).optional(), mentionedMemberIds: z.array(groupMemberIdSchema), mentionAll: z.boolean().optional(), hopCount: nonnegativeInteger, durationMs: nonnegativeInteger.optional(), createdAt: timestamp, }); const newThreadOptions = { ...optionalMemberEdits, model: roleModelSchema.optional(), thinkingOptionId: harnessThinkingOptionIdSchema.optional(), worktree: z.boolean().optional(), }; export const groupCreateMemberInputSchema = z.discriminatedUnion("kind", [ z.strictObject({ kind: z.literal("role"), roleSlug: roleSlugSchema, ...newThreadOptions }), z.strictObject({ kind: z.literal("harness"), harnessId: harnessIdSchema, ...newThreadOptions }), z.strictObject({ kind: z.literal("existing"), threadId: hostThreadIdSchema, ...optionalMemberEdits, includeRecentHistory: z.boolean().default(true).optional(), }), ]); export const GROUPS_LIST_METHOD = "codexhost/groups/list"; export const GROUPS_GET_METHOD = "codexhost/groups/get"; export const GROUPS_CREATE_METHOD = "codexhost/groups/create"; export const GROUPS_UPDATE_METHOD = "codexhost/groups/update"; export const GROUPS_DELETE_METHOD = "codexhost/groups/delete"; export const GROUPS_ADD_MEMBER_METHOD = "codexhost/groups/member/add"; export const GROUPS_UPDATE_MEMBER_METHOD = "codexhost/groups/member/update"; export const GROUPS_REMOVE_MEMBER_METHOD = "codexhost/groups/member/remove"; export const GROUPS_REBIND_MEMBER_METHOD = "codexhost/groups/member/rebind"; export const GROUPS_POST_MESSAGE_METHOD = "codexhost/groups/message/post"; export const GROUPS_READ_MESSAGES_METHOD = "codexhost/groups/messages/read"; export const GROUPS_READ_MEMORY_METHOD = "codexhost/groups/memory/read"; export const GROUPS_UPDATE_MEMORY_METHOD = "codexhost/groups/memory/update"; export const GROUPS_LIST_TASKS_METHOD = "codexhost/groups/tasks/list"; export const GROUPS_CREATE_TASK_METHOD = "codexhost/groups/tasks/create"; export const GROUPS_UPDATE_TASK_METHOD = "codexhost/groups/tasks/update"; export const GROUPS_DELETE_TASK_METHOD = "codexhost/groups/tasks/delete"; export const GROUPS_INSPECT_CWD_METHOD = "codexhost/groups/cwd/inspect"; export const GROUPS_CHANGED_EVENT = "codexhost/groups/changed"; const roomIdentity = { roomId: groupRoomIdSchema }; const memberIdentity = { ...roomIdentity, memberId: groupMemberIdSchema }; const roomEdits = { title: nonblankString.optional(), unmentionedPolicy: groupUnmentionedPolicySchema.optional(), allowAgentMentions: z.boolean().optional(), maxAgentHops: maxAgentHopsSchema.optional(), }; export const groupsListParamsSchema = z.strictObject({}); export const groupsListResultSchema = z.object({ rooms: z.array(groupRoomSchema) }); export const groupsGetParamsSchema = z.strictObject({ ...roomIdentity, limit: positiveInteger.optional(), beforeSeq: positiveInteger.optional(), }); export const groupsGetResultSchema = z.object({ room: groupRoomSchema.nullable(), messages: z.array(groupMessageSchema), hasMore: z.boolean(), }); export const groupsCreateParamsSchema = z.strictObject({ ...roomEdits, defaultCwd: nonblankString.optional(), members: z.array(groupCreateMemberInputSchema), }); export const groupsCreateResultSchema = z.object({ room: groupRoomSchema }); export const groupsUpdateParamsSchema = z .strictObject({ ...roomIdentity, ...roomEdits, unmentionedMemberId: groupMemberIdSchema.nullable().optional(), pinned: z.boolean().optional(), relayPaused: z.boolean().optional(), }) .superRefine(({ unmentionedPolicy, unmentionedMemberId }, context) => { if ( unmentionedMemberId !== undefined && unmentionedMemberId !== null && unmentionedPolicy !== undefined && unmentionedPolicy !== "none" ) { context.addIssue({ code: "custom", path: ["unmentionedMemberId"], message: 'A default member can only be set when unmentionedPolicy is "none"', }); } }); export const groupsUpdateResultSchema = groupsCreateResultSchema; export const groupsDeleteParamsSchema = z.strictObject(roomIdentity); export const groupsDeleteResultSchema = z.object({ deleted: z.boolean() }); export const groupsAddMemberParamsSchema = z.strictObject({ ...roomIdentity, member: groupCreateMemberInputSchema, }); export const groupsAddMemberResultSchema = z.object({ room: groupRoomSchema, member: groupMemberSchema, }); export const groupsUpdateMemberParamsSchema = z.strictObject({ ...memberIdentity, ...optionalMemberEdits, status: groupMemberStatusSchema.optional(), showInSidebar: z.boolean().optional(), }); export const groupsUpdateMemberResultSchema = groupsAddMemberResultSchema; export const groupsRemoveMemberParamsSchema = z.strictObject(memberIdentity); export const groupsRemoveMemberResultSchema = groupsCreateResultSchema; export const groupsRebindMemberParamsSchema = z.strictObject({ ...memberIdentity, threadId: hostThreadIdSchema, redeliverFrom: positiveInteger.optional(), note: z.string().optional(), }); export const groupCliRebindMemberParamsSchema = z .strictObject({ ...roomIdentity, memberId: groupMemberIdSchema.optional(), memberHandle: groupMemberHandleSchema.optional(), threadId: hostThreadIdSchema, redeliverFrom: positiveInteger.optional(), note: z.string().optional(), }) .refine( (value) => (value.memberId !== undefined) !== (value.memberHandle !== undefined), "Provide exactly one of memberId or memberHandle", ); export const groupsRebindMemberResultSchema = z.object({ room: groupRoomSchema, member: groupMemberSchema, previousThreadId: hostThreadIdSchema, awakened: z.boolean(), }); export const groupCliListMemberSchema = z.object({ memberId: groupMemberIdSchema, threadId: hostThreadIdSchema, handle: groupMemberHandleSchema, displayName: nonblankString, status: groupMemberStatusSchema, harnessId: harnessIdSchema, roleSlug: roleSlugSchema.optional(), roleName: nonblankString.optional(), }); export const groupCliListEntrySchema = z.object({ roomId: groupRoomIdSchema, title: nonblankString, memberCount: nonnegativeInteger, updatedAt: timestamp, member: groupCliListMemberSchema.optional(), }); export const groupCliListParamsSchema = z.strictObject({ threadId: hostThreadIdSchema.optional(), }); export const groupCliListResultSchema = z.object({ rooms: z.array(groupCliListEntrySchema), }); export const groupsPostMessageParamsSchema = z .strictObject({ ...roomIdentity, content: z.string().max(64_000), attachments: z.array(groupAttachmentSchema).max(12).optional(), replyToSeq: positiveInteger.optional(), targetMemberIds: z.array(groupMemberIdSchema).optional(), mentionAll: z.boolean().optional(), notice: z.boolean().optional(), }) .superRefine((value, context) => { if (value.notice === true) { if (value.content.trim().length === 0) { context.addIssue({ code: "custom", path: ["content"], message: "Notice content is required", }); } if (value.content.length > GROUP_NOTICE_MAX_LENGTH) { context.addIssue({ code: "custom", path: ["content"], message: `Notice content must be at most ${GROUP_NOTICE_MAX_LENGTH} characters`, }); } if ( (value.targetMemberIds?.length ?? 0) > 0 || value.mentionAll === true || (value.attachments?.length ?? 0) > 0 ) { context.addIssue({ code: "custom", path: ["notice"], message: "System notices cannot target members or include attachments", }); } return; } if (value.content.trim().length === 0 && (value.attachments?.length ?? 0) === 0) { context.addIssue({ code: "custom", path: ["content"], message: "Message content or at least one attachment is required", }); } }); export const groupsPostMessageResultSchema = z.object({ room: groupRoomSchema, message: groupMessageSchema, awakenedMemberIds: z.array(groupMemberIdSchema), }); export const groupsReadMessagesParamsSchema = z.strictObject({ ...roomIdentity, fromSeq: positiveInteger.optional(), toSeq: positiveInteger.optional(), limit: positiveInteger.optional(), }); export const groupsReadMessagesResultSchema = z.object({ ...roomIdentity, messages: z.array(groupMessageSchema), totalSeq: nonnegativeInteger, }); export const groupsReadMemoryParamsSchema = z.strictObject(roomIdentity); export const groupsReadMemoryResultSchema = z.object({ ...roomIdentity, memoryVersion: nonnegativeInteger, content: z.string(), updatedAt: timestamp, }); export const groupsUpdateMemoryParamsSchema = z.strictObject({ ...roomIdentity, content: z .string() .refine( (value) => groupUtf8ByteLength(value) <= GROUP_MEMORY_MAX_BYTES, `Shared room memory must be at most ${GROUP_MEMORY_MAX_BYTES} UTF-8 bytes`, ), expectedVersion: nonnegativeInteger.optional(), }); export const groupsUpdateMemoryResultSchema = z.object({ room: groupRoomSchema, memoryVersion: nonnegativeInteger, content: z.string(), updatedAt: timestamp, }); const groupTaskTitleSchema = nonblankString.refine( (value) => value.trim().length <= GROUP_TASK_TITLE_MAX_LENGTH, `Task title must be at most ${GROUP_TASK_TITLE_MAX_LENGTH} characters`, ); const groupTaskNoteSchema = z .string() .refine( (value) => value.trim().length <= GROUP_TASK_NOTE_MAX_LENGTH, `Task progress note must be at most ${GROUP_TASK_NOTE_MAX_LENGTH} characters`, ); const groupTaskDetailSchema = z .string() .refine( (value) => value.trim().length <= GROUP_TASK_DETAIL_MAX_LENGTH, `Task detail summary must be at most ${GROUP_TASK_DETAIL_MAX_LENGTH} characters`, ); export const groupTaskArtifactKindSchema = z.enum(["image", "video", "audio", "file"]); export const groupTaskArtifactSchema = z.object({ path: nonblankString.refine( (value) => value.trim().length <= GROUP_TASK_ARTIFACT_PATH_MAX_LENGTH, `Artifact path must be at most ${GROUP_TASK_ARTIFACT_PATH_MAX_LENGTH} characters`, ), label: nonblankString .refine( (value) => value.trim().length <= GROUP_TASK_ARTIFACT_LABEL_MAX_LENGTH, `Artifact label must be at most ${GROUP_TASK_ARTIFACT_LABEL_MAX_LENGTH} characters`, ) .optional(), kind: groupTaskArtifactKindSchema.optional(), }); export const groupTaskArtifactsSchema = z .array(groupTaskArtifactSchema) .max(GROUP_TASK_MAX_ARTIFACTS); export const groupTaskSchema = z.object({ taskId: groupTaskIdSchema, shortId: positiveInteger, roomId: groupRoomIdSchema, title: groupTaskTitleSchema, status: groupTaskStatusSchema, needsHuman: z.boolean().default(false), createdByType: groupTaskActorTypeSchema, createdByMemberId: groupMemberIdSchema.optional(), assignedByType: groupTaskActorTypeSchema.optional(), assignedByMemberId: groupMemberIdSchema.optional(), assigneeMemberId: groupMemberIdSchema.optional(), progressNote: groupTaskNoteSchema.optional(), detail: groupTaskDetailSchema.optional(), artifacts: groupTaskArtifactsSchema.optional(), sourceMessageSeq: positiveInteger.optional(), createdAt: timestamp, updatedAt: timestamp, completedAt: timestamp.optional(), }); export const groupTaskBoardStateSchema = z.object({ nextShortId: positiveInteger.default(1), tasks: z.array(groupTaskSchema).max(GROUP_BOARD_MAX_TASKS).default([]), }); export const groupsListTasksParamsSchema = z.strictObject(roomIdentity); export const groupsListTasksResultSchema = z.object({ ...roomIdentity, boardVersion: nonnegativeInteger, tasks: z.array(groupTaskSchema), updatedAt: timestamp, }); export const groupsCreateTaskParamsSchema = z.strictObject({ ...roomIdentity, title: groupTaskTitleSchema, status: groupTaskStatusSchema.optional(), assigneeMemberId: groupMemberIdSchema.optional(), needsHuman: z.boolean().optional(), progressNote: groupTaskNoteSchema.optional(), detail: groupTaskDetailSchema.optional(), artifacts: groupTaskArtifactsSchema.optional(), sourceMessageSeq: positiveInteger.optional(), }); export const groupsCreateTaskResultSchema = z.object({ room: groupRoomSchema, boardVersion: nonnegativeInteger, task: groupTaskSchema, }); export const groupsUpdateTaskParamsSchema = z.strictObject({ ...roomIdentity, taskId: groupTaskIdSchema, title: groupTaskTitleSchema.optional(), status: groupTaskStatusSchema.optional(), assigneeMemberId: groupMemberIdSchema.nullable().optional(), needsHuman: z.boolean().optional(), progressNote: groupTaskNoteSchema.nullable().optional(), detail: groupTaskDetailSchema.nullable().optional(), artifacts: groupTaskArtifactsSchema.nullable().optional(), sourceMessageSeq: positiveInteger.nullable().optional(), }); export const groupsUpdateTaskResultSchema = z.object({ room: groupRoomSchema, boardVersion: nonnegativeInteger, task: groupTaskSchema, }); export const groupsDeleteTaskParamsSchema = z.strictObject({ ...roomIdentity, taskId: groupTaskIdSchema, }); export const groupsDeleteTaskResultSchema = z.object({ room: groupRoomSchema, boardVersion: nonnegativeInteger, deleted: z.boolean(), }); export const groupsInspectCwdParamsSchema = z.strictObject({ cwd: nonblankString, roomId: groupRoomIdSchema.optional(), }); export const groupsInspectCwdResultSchema = z.object({ isGitRepo: z.boolean(), }); export type GroupRoomId = z.infer; export type GroupMemberId = z.infer; export type GroupMemberHandle = z.infer; export type GroupUnmentionedPolicy = z.infer; export type GroupMemberStatus = z.infer; export type GroupMember = z.infer; export type GroupProjectlessWorkspace = z.infer; export type GroupRoomRemoteHost = z.infer; export type GroupRoom = z.infer; export type GroupRoomSummary = z.infer; /** Resolve a room's effective relay hop limit (`0` = unlimited, `1..200` = finite cap). */ export function resolveGroupMaxAgentHops( room: Pick, ): number { return room.relayHopLimit ?? room.maxAgentHops; } /** * Encode a relay hop limit into forward-compatible room fields: `maxAgentHops` stays in `1..20` * for readers constrained to that range, while `relayHopLimit` carries `0` or `21..200`. */ export function encodeGroupMaxAgentHops( hops: number, ): Pick { const validated = maxAgentHopsSchema.parse(hops); if (validated >= 1 && validated <= LEGACY_MAX_GROUP_AGENT_HOPS) { return { maxAgentHops: validated }; } return { maxAgentHops: LEGACY_MAX_GROUP_AGENT_HOPS, relayHopLimit: validated, }; } /** Normalize a room's hop fields so `maxAgentHops` always remains within `1..20`. */ export function normalizeGroupRoomMaxAgentHops(room: GroupRoom): GroupRoom { const { relayHopLimit: _ignored, ...rest } = room; return { ...rest, ...encodeGroupMaxAgentHops(resolveGroupMaxAgentHops(room)), }; } export type GroupAttachment = z.infer; export type GroupMessage = z.infer; export type GroupCreateMemberInput = z.infer; export type GroupsListParams = z.infer; export type GroupsListResult = z.infer; export type GroupsGetParams = z.infer; export type GroupsGetResult = z.infer; export type GroupsCreateParams = z.infer; export type GroupsCreateResult = z.infer; export type GroupsUpdateParams = z.infer; export type GroupsUpdateResult = z.infer; export type GroupsDeleteParams = z.infer; export type GroupsDeleteResult = z.infer; export type GroupsAddMemberParams = z.infer; export type GroupsAddMemberResult = z.infer; export type GroupsUpdateMemberParams = z.infer; export type GroupsUpdateMemberResult = z.infer; export type GroupsRemoveMemberParams = z.infer; export type GroupsRemoveMemberResult = z.infer; export type GroupsRebindMemberParams = z.infer; export type GroupCliRebindMemberParams = z.infer; export type GroupsRebindMemberResult = z.infer; export type GroupCliListMember = z.infer; export type GroupCliListEntry = z.infer; export type GroupCliListParams = z.infer; export type GroupCliListResult = z.infer; export type GroupsPostMessageParams = z.infer; export type GroupsPostMessageResult = z.infer; export type GroupsReadMessagesParams = z.infer; export type GroupsReadMessagesResult = z.infer; export type GroupsReadMemoryParams = z.infer; export type GroupsReadMemoryResult = z.infer; export type GroupsUpdateMemoryParams = z.infer; export type GroupsUpdateMemoryResult = z.infer; export type GroupTaskId = z.infer; export type GroupTaskStatus = z.infer; export type GroupTaskActorType = z.infer; export type GroupTaskArtifactKind = z.infer; export type GroupTaskArtifact = z.infer; export type GroupTask = z.infer; export type GroupTaskBoardState = z.infer; export type GroupsListTasksParams = z.infer; export type GroupsListTasksResult = z.infer; export type GroupsCreateTaskParams = z.infer; export type GroupsCreateTaskResult = z.infer; export type GroupsUpdateTaskParams = z.infer; export type GroupsUpdateTaskResult = z.infer; export type GroupsDeleteTaskParams = z.infer; export type GroupsDeleteTaskResult = z.infer; export type GroupsInspectCwdParams = z.infer; export type GroupsInspectCwdResult = z.infer; export const GROUP_MEMBER_MENTION_SCHEME = "group-member://"; export const GROUP_MEMBER_MENTION_ALL_TARGET = "all"; const GROUP_MEMBER_MENTION_LINK_PATTERN = /\[@([^\]\n]+)\]\(group-member:\/\/([A-Za-z0-9._:%-]+)\)/gu; function sanitizeGroupMentionLabel(label: string): string { const cleaned = label .trim() .replace(/^@+/u, "") .replace(/[[\]()\n\r]+/gu, " ") .replace(/\s+/gu, " ") .trim(); return cleaned.length > 0 ? cleaned : "member"; } function encodeGroupMentionTarget(target: string): string { const trimmed = target.trim(); if (!trimmed) throw new Error("Group mention target must not be empty"); return encodeURIComponent(trimmed).replace(/%3A/giu, ":"); } function decodeGroupMentionTarget(raw: string): string | null { try { const decoded = decodeURIComponent(raw).trim(); return decoded.length > 0 ? decoded : null; } catch { return null; } } /** * Format an internal group mention carrier `[@displayName](group-member://)` * shared by the composer, Host mention parser, Agent roster, and message renderers. */ export function formatGroupMemberMentionLink(label: string, target: string): string { return `[@${sanitizeGroupMentionLabel(label)}](${GROUP_MEMBER_MENTION_SCHEME}${encodeGroupMentionTarget(target)})`; } export type GroupMentionSegment = | { readonly kind: "text"; readonly text: string } | { readonly kind: "mention"; readonly label: string; readonly target: string; readonly raw: string; }; /** Split plain text into prose runs and structured `group-member://` mentions. */ export function splitGroupMentionSegments(text: string): GroupMentionSegment[] { const segments: GroupMentionSegment[] = []; let cursor = 0; for (const match of text.matchAll(GROUP_MEMBER_MENTION_LINK_PATTERN)) { const start = match.index ?? 0; const raw = match[0]; const label = match[1]?.trim() ?? ""; const decoded = match[2] ? decodeGroupMentionTarget(match[2]) : null; if (!label || decoded === null) continue; if (start > cursor) segments.push({ kind: "text", text: text.slice(cursor, start) }); segments.push({ kind: "mention", label, target: decoded, raw }); cursor = start + raw.length; } if (cursor < text.length) segments.push({ kind: "text", text: text.slice(cursor) }); return segments; } function isIndentedCodeLine(line: string): boolean { return /^(?: {4}| {0,3}\t)/u.test(line); } /** Mask CommonMark fenced, indented, and inline code while preserving exact character offsets. */ export function maskGroupMentionCode(content: string): string { const lines = content.split("\n"); let fence: { run: string; quotes: number } | undefined; let inParagraph = false; let prevQuotes = 0; const proseLines: string[] = []; for (const line of lines) { let body = line; let quotes = 0; while (/^ {0,3}>[ \t]?/u.test(body)) { body = body.replace(/^ {0,3}>[ \t]?/u, ""); quotes++; } const blank = body.trim().length === 0; if (fence && quotes < fence.quotes && !blank) fence = undefined; if (quotes !== prevQuotes && isIndentedCodeLine(body)) inParagraph = false; prevQuotes = quotes; const marker = /^ *(?:(?:[-+*]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})([^\r]*)\r?$/u.exec(body); const run = marker?.[1]; const rest = marker?.[2] ?? ""; if (fence) { if (run && run[0] === fence.run[0] && run.length >= fence.run.length && !rest.trim()) { fence = undefined; inParagraph = false; } proseLines.push(" ".repeat(line.length)); continue; } if (blank) { inParagraph = false; proseLines.push(" ".repeat(line.length)); continue; } if (!inParagraph && isIndentedCodeLine(body)) { proseLines.push(" ".repeat(line.length)); continue; } if (run && (run[0] === "~" || !rest.includes("`"))) { fence = { run, quotes }; inParagraph = false; proseLines.push(" ".repeat(line.length)); continue; } inParagraph = true; proseLines.push(body.padStart(line.length, " ")); } return proseLines .join("\n") .split(/(\n\s*\n)/u) .map((paragraph) => { const runs = [...paragraph.matchAll(/`+/gu)]; const nextByLength = new Map(); const closing: (number | undefined)[] = []; for (let i = runs.length - 1; i >= 0; i--) { const length = runs[i]![0].length; closing[i] = nextByLength.get(length); nextByLength.set(length, i); } let output = ""; let cursor = 0; for (let i = 0; i < runs.length; i++) { const start = runs[i]!.index; const end = closing[i]; if (end === undefined) continue; let escapes = 0; while (paragraph[start - escapes - 1] === "\\") escapes++; if (escapes % 2) continue; const endOffset = runs[end]!.index + runs[end]![0].length; // A non-whitespace gap prevents multi-word mentions from matching across inline code. output += paragraph.slice(cursor, start) + "\0".repeat(endOffset - start); cursor = endOffset; i = end; } return output + paragraph.slice(cursor); }) .join(""); } /** Replace internal `group-member://` carriers with readable `@label` text for excerpts/previews. */ export function stripGroupMentionLinks(text: string): string { return text.replace( GROUP_MEMBER_MENTION_LINK_PATTERN, (full, label: string, rawTarget: string) => label.trim() && decodeGroupMentionTarget(rawTarget) !== null ? `@${label.trim()}` : full, ); } export interface ParsedGroupContextEntry { readonly seq?: number; readonly from: string; readonly senderType?: "user" | "agent" | "system"; readonly content: string; } export interface ParsedGroupContextMessage { readonly roomTitle: string; readonly roomId?: string; readonly you?: string; readonly messages: readonly ParsedGroupContextEntry[]; readonly hasOmittedEarlier: boolean; } function unescapeGroupXml(text: string): string { return text.replace(/&(amp|lt|gt|quot|#(\d+));/gu, (full, entity: string, digits?: string) => { if (digits !== undefined) return String.fromCharCode(Number(digits)); switch (entity) { case "amp": return "&"; case "lt": return "<"; case "gt": return ">"; case "quot": return '"'; default: return full; } }); } function readXmlAttribute(attrs: string, name: string): string | undefined { const match = new RegExp(`(?:^|\\s)${name}="([^"]*)"`, "u").exec(attrs); return match?.[1] === undefined ? undefined : unescapeGroupXml(match[1]); } /** * Parse a `...` wake envelope sent to a member Thread * into display-ready structured data, supporting both slim and legacy envelopes. */ export function parseGroupContextMessage(text: string): ParsedGroupContextMessage | null { const trimmed = text.trim(); if (!trimmed.startsWith("")) { return null; } const openMatch = /^]*)>/u.exec(trimmed); if (!openMatch?.[1]) return null; const openAttrs = openMatch[1]; const roomTitle = readXmlAttribute(openAttrs, "room"); if (roomTitle === undefined) return null; const roomId = readXmlAttribute(openAttrs, "room_id"); const you = readXmlAttribute(openAttrs, "you"); const messagesOpen = trimmed.indexOf(""); const messagesClose = trimmed.lastIndexOf(""); if (messagesOpen < 0 || messagesClose < messagesOpen) return null; const inner = trimmed.slice(messagesOpen + "".length, messagesClose); const messages: ParsedGroupContextEntry[] = []; const msgPattern = /]*)>([\s\S]*?)<\/msg>/gu; for (const match of inner.matchAll(msgPattern)) { const attrs = match[1] ?? ""; const rawContent = match[2] ?? ""; const from = readXmlAttribute(attrs, "from") ?? "user"; const seqRaw = readXmlAttribute(attrs, "seq"); const seq = seqRaw !== undefined && /^\d+$/u.test(seqRaw) ? Number(seqRaw) : undefined; const senderTypeRaw = readXmlAttribute(attrs, "sender_type"); const senderType = senderTypeRaw === "user" || senderTypeRaw === "agent" || senderTypeRaw === "system" ? senderTypeRaw : from === "user" ? "user" : "agent"; messages.push({ ...(seq === undefined ? {} : { seq }), from, senderType, content: unescapeGroupXml(rawContent), }); } return { roomTitle, ...(roomId === undefined ? {} : { roomId }), ...(you === undefined ? {} : { you }), messages, hasOmittedEarlier: trimmed.slice(0, messagesOpen).includes("Earlier messages ("), }; }