@nextclaw/kernel 0.18.4 → 0.18.5

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/index.js CHANGED
@@ -2,11 +2,11 @@ import { AUTOMATIC_UPDATE_CHECK_INTERVAL_MS, getAutomaticUpdateCheckDelay, resol
2
2
  import { n as getUnsignedUpdateManifest, r as serializeUnsignedUpdateManifest, t as UpdateManifestReader } from "./update-manifest.types-C0qPrjGQ.js";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, createHmac, randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
5
- import { CHAT_CONTINUATION_TARGET_MESSAGE_METADATA_KEY, CHAT_CONVERSATION_EXCERPT_TOKEN_KIND, CHAT_INLINE_TOKENS_METADATA_KEY, CHAT_INLINE_TOKENS_SCHEMA_VERSION, CHAT_PROJECT_TOKEN_KIND, CHAT_SESSION_MATERIALIZATION_METADATA_KEY, CHAT_SYSTEM_OBJECT_TOKEN_KIND, CHAT_UI_RESOURCE_TOKEN_KIND, CHAT_WORKSPACE_DIRECTORY_TOKEN_KIND, CHAT_WORKSPACE_EXCERPT_TOKEN_KIND, CHAT_WORKSPACE_FILE_TOKEN_KIND, Contribution as Contribution$1, EventBus, EventBus as EventBus$1, Ingress, Ingress as Ingress$1, PANEL_APP_INLINE_HOST_CONTRACT, PANEL_APP_SCROLL_RESTORATION_CONTRACT, SYSTEM_OBJECT_REFERENCE_DEFAULT_LIMIT, SYSTEM_OBJECT_REFERENCE_MAX_LIMIT, SYSTEM_OBJECT_TYPE_CRON_JOB, SYSTEM_OBJECT_TYPE_INBOX_DELIVERY, UI_CONTENT_PARAMS_HOST_CONTRACT, classifyDiagnosticError, createPanelAppResourceUri, createSystemObjectReferenceUri, createTypedKey, eventKeys, eventKeys as eventKeys$1, ingressKeys, ingressKeys as ingressKeys$1, isRuntimeDefaultModelValue, isSilentReplyNcpMessage, normalizeRuntimeModelSelectionMode, parseSystemObjectReferenceUri, readChatUiResourceReference, readInlineContentHeight, readSystemObjectResolvedReference, readUiContentParams } from "@nextclaw/shared";
5
+ import { CHAT_CONTINUATION_TARGET_MESSAGE_METADATA_KEY, CHAT_CONVERSATION_EXCERPT_TOKEN_KIND, CHAT_INLINE_TOKENS_METADATA_KEY, CHAT_INLINE_TOKENS_SCHEMA_VERSION, CHAT_PROJECT_TOKEN_KIND, CHAT_SESSION_MATERIALIZATION_METADATA_KEY, CHAT_SYSTEM_OBJECT_TOKEN_KIND, CHAT_UI_RESOURCE_TOKEN_KIND, CHAT_WORKSPACE_DIRECTORY_TOKEN_KIND, CHAT_WORKSPACE_EXCERPT_TOKEN_KIND, CHAT_WORKSPACE_FILE_TOKEN_KIND, Contribution as Contribution$1, EventBus, EventBus as EventBus$1, Ingress, Ingress as Ingress$1, PANEL_APP_INLINE_HOST_CONTRACT, PANEL_APP_SCROLL_RESTORATION_CONTRACT, SYSTEM_OBJECT_REFERENCE_DEFAULT_LIMIT, SYSTEM_OBJECT_REFERENCE_MAX_LIMIT, SYSTEM_OBJECT_TYPE_CRON_JOB, SYSTEM_OBJECT_TYPE_INBOX_DELIVERY, UI_CONTENT_PARAMS_HOST_CONTRACT, classifyDiagnosticError, createPanelAppResourceUri, createSessionResourceUri, createSystemObjectReferenceUri, createTypedKey, eventKeys, eventKeys as eventKeys$1, ingressKeys, ingressKeys as ingressKeys$1, isRuntimeDefaultModelValue, isSilentReplyNcpMessage, normalizeRuntimeModelSelectionMode, parseSystemObjectReferenceUri, readChatUiResourceReference, readInlineContentHeight, readSystemObjectResolvedReference, readUiContentParams } from "@nextclaw/shared";
6
6
  import { LocalAssetStore, MODEL_ROUND_PART_OFFSETS, buildAssetContentPath, buildOpenAiFunctionTool, isTextLikeAsset, ncpMessageToOpenAiMessageGroups, ncpMessageToOpenAiMessages, validateToolArgs } from "@nextclaw/ncp-agent-runtime";
7
7
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
8
8
  import { accessSync, appendFileSync, chmodSync, constants, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
9
- import { APP_NAME, AgentRouteResolver, BUILTIN_MAIN_AGENT_ID, CLEAR_THINKING_TOKENS, CONTEXT_COMPACTION_METADATA_KEY, ConfigSchema, ContextCompactionService, ContextWindowBudgetService, CronService, CronTool, DEFAULT_PANELS_DIR, DEFAULT_PROJECT_SKILLS_DIR_NAME, DEFAULT_SERVICE_APPS_DIR, DEFAULT_SESSION_SEARCH_LIMIT, DEFAULT_WORKSPACE_REPOSITORY_IDENTITY_RESOLVER, DIAGNOSTIC_CORRELATION_METADATA_KEY, DiagnosticRuntime, EditFileTool, ExecTool, ExtensionChannelAdapter, GatewayTool, InputBudgetPruner, LLMProvider, ListDirTool, LiteLLMProvider, LocalExecutionClaimService, MAX_SESSION_SEARCH_LIMIT, MemoryGetTool, MemorySearchTool, MemoryStore, MessageBus, MessageTool, ProviderModelDiscoveryService, ProviderRegistry, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV as RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV$1, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV as RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV$1, RUNTIME_INSTANCE_DISTRIBUTION_ENV, RUNTIME_INSTANCE_DISTRIBUTION_ENV as RUNTIME_INSTANCE_DISTRIBUTION_ENV$1, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV as RUNTIME_INSTANCE_INSTALLATION_KIND_ENV$1, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV as RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV$1, ReadFileTool, SILENT_REPLY_TOKEN, SessionProjectContextResolver, SessionSearchService, SkillsLoader, THINKING_LEVELS, ViewImageTool, WebFetchTool, WebSearchTool, WriteFileTool, buildCompressingCompactionCheckpoint, buildConfigSchema, buildContextWindowSnapshot, buildReloadPlan, buildSessionRequestToolResult, buildToolCatalogEntries, createAgentProfile, createAssistantStreamDeltaControlMessage, createAssistantStreamResetControlMessage, createCompletedSessionRequest, createFailedSessionRequest, createRunningSessionRequest, createRuntimeChildEnv, createTypingStopControlMessage, diffConfigPaths, ensureDir, estimateInputTokens, evaluateSilentReply, expandHome, findEffectiveAgentProfile, getConfigPath, getDataDir, getDataPath, getLogsPath, getSessionsPath, getWorkspacePath, getWorkspacePathFromConfig, isNextclawControlMessage, loadConfig, mergeExtensionConfigView, modelSupportsVision, normalizeAgentProfileId, normalizeInlineSecretRefs, normalizeModelThinkingCapability, normalizeProviderModelConfig, normalizeToolParams, parseAgentScopedSessionKey, parseThinkingLevel, readCompressedContextCompactionCheckpoint, readOptionalString, readParentSessionId, readSessionProjectRoot, redactConfigObject, removeAgentProfile, resolveConfigSecrets, resolveDefaultAgentProfileId, resolveEffectiveAgentProfiles, resolveNextclawSelfManageGuidePaths, resolveProviderRuntime, resolveRuntimeCommandLaunch, resolveSecretRef, resolveSessionProjectContext, resolveSessionWorkspacePath, resolveThinkingLevel, safeFilename, sanitizeOutboundAssistantContent, saveConfig, summarizeSessionRequestTask, toExtensionConfigView, updateAgentProfile } from "@nextclaw/core";
9
+ import { APP_NAME, AgentRouteResolver, BUILTIN_MAIN_AGENT_ID, CLEAR_THINKING_TOKENS, CONTEXT_COMPACTION_METADATA_KEY, ConfigSchema, ContextCompactionService, ContextWindowBudgetService, CronService, CronTool, DEFAULT_PANELS_DIR, DEFAULT_PROJECT_SKILLS_DIR_NAME, DEFAULT_SERVICE_APPS_DIR, DEFAULT_SESSION_SEARCH_LIMIT, DEFAULT_WORKSPACE_REPOSITORY_IDENTITY_RESOLVER, DIAGNOSTIC_CORRELATION_METADATA_KEY, DiagnosticRuntime, EditFileTool, ExecTool, ExtensionChannelAdapter, GatewayTool, InputBudgetPruner, LLMProvider, ListDirTool, LiteLLMProvider, LocalExecutionClaimService, MAX_SESSION_SEARCH_LIMIT, MemoryGetTool, MemorySearchTool, MemoryStore, MessageBus, MessageTool, ProviderModelDiscoveryService, ProviderRegistry, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV as RUNTIME_INSTANCE_DESKTOP_DATA_DIRECTORY_ENV$1, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV, RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV as RUNTIME_INSTANCE_DESKTOP_LOGS_DIRECTORY_ENV$1, RUNTIME_INSTANCE_DISTRIBUTION_ENV, RUNTIME_INSTANCE_DISTRIBUTION_ENV as RUNTIME_INSTANCE_DISTRIBUTION_ENV$1, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV, RUNTIME_INSTANCE_INSTALLATION_KIND_ENV as RUNTIME_INSTANCE_INSTALLATION_KIND_ENV$1, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV, RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV as RUNTIME_INSTANCE_PORTABLE_DATA_ROOT_ENV$1, ReadFileTool, SILENT_REPLY_TOKEN, SessionProjectContextResolver, SessionSearchService, SkillsLoader, THINKING_LEVELS, ViewImageTool, WebFetchTool, WebSearchTool, WriteFileTool, buildCompressingCompactionCheckpoint, buildConfigSchema, buildContextWindowSnapshot, buildLocalizedTextMap, buildReloadPlan, buildSessionRequestToolResult, buildToolCatalogEntries, createAgentProfile, createAssistantStreamDeltaControlMessage, createAssistantStreamResetControlMessage, createCompletedSessionRequest, createFailedSessionRequest, createRunningSessionRequest, createRuntimeChildEnv, createTypingStopControlMessage, diffConfigPaths, ensureDir, estimateInputTokens, evaluateSilentReply, expandHome, findEffectiveAgentProfile, getConfigPath, getDataDir, getDataPath, getLogsPath, getSessionsPath, getWorkspacePath, getWorkspacePathFromConfig, isNextclawControlMessage, loadConfig, mergeExtensionConfigView, modelSupportsVision, normalizeAgentProfileId, normalizeInlineSecretRefs, normalizeModelThinkingCapability, normalizeProviderModelConfig, normalizeToolParams, parseAgentScopedSessionKey, parseSkillFrontmatter, parseSkillFrontmatter as parseSkillFrontmatter$1, parseThinkingLevel, readCompressedContextCompactionCheckpoint, readOptionalString, readParentSessionId, readSessionProjectRoot, redactConfigObject, removeAgentProfile, resolveConfigSecrets, resolveDefaultAgentProfileId, resolveEffectiveAgentProfiles, resolveNextclawSelfManageGuidePaths, resolveProviderRuntime, resolveRuntimeCommandLaunch, resolveSecretRef, resolveSessionProjectContext, resolveSessionWorkspacePath, resolveThinkingLevel, safeFilename, sanitizeOutboundAssistantContent, saveConfig, stripSkillFrontmatter, stripSkillFrontmatter as stripSkillFrontmatter$1, summarizeSessionRequestTask, toExtensionConfigView, updateAgentProfile } from "@nextclaw/core";
10
10
  import { NCP_AI_EXECUTION_METADATA_KEY, NCP_INTERNAL_VISIBILITY_METADATA_KEY, NCP_RUN_TRIGGER_METADATA_KEY, NcpEventType, OBSERVATION_EVENT_EXTENSION_TYPE, createUnavailableNcpAiExecutionMetadata, isHiddenNcpMessage, normalizeAssistantText, parseNcpRunTriggerInput, readNcpAiExecutionMetadata, sanitizeAssistantReplyTags } from "@nextclaw/ncp";
11
11
  import { DefaultNcpAgentConversationStateManager, insertMessageByTimeline, mergeToolExecutionTiming } from "@nextclaw/ncp-toolkit";
12
12
  import { access, appendFile, chmod, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
@@ -16,7 +16,6 @@ import { fileURLToPath } from "node:url";
16
16
  import { BUILTIN_PROVIDER_PLUGINS } from "@nextclaw/runtime";
17
17
  import { McpRegistryService, McpServerLifecycleManager, normalizeMcpServerName } from "@nextclaw/mcp";
18
18
  import { McpNcpToolRegistryAdapter } from "@nextclaw/ncp-mcp";
19
- import { parse } from "yaml";
20
19
  import { createInterface } from "node:readline";
21
20
  import { HttpRuntimeConfigResolver, HttpRuntimeNcpAgentRuntime } from "@nextclaw/nextclaw-ncp-runtime-http-client";
22
21
  import { StdioRuntimeConfigResolver, StdioRuntimeNcpAgentRuntime, probeStdioRuntime } from "@nextclaw/nextclaw-ncp-runtime-stdio-client";
@@ -2013,7 +2012,7 @@ const BUILTIN_RUNTIME_PRESENTATION = {
2013
2012
  }
2014
2013
  }
2015
2014
  };
2016
- function readString$11(value) {
2015
+ function readString$10(value) {
2017
2016
  if (typeof value !== "string") return;
2018
2017
  return value.trim() || void 0;
2019
2018
  }
@@ -2022,7 +2021,7 @@ function readRecord$3(value) {
2022
2021
  return value;
2023
2022
  }
2024
2023
  function resolveBuiltinRuntimePresentation(value) {
2025
- const normalized = readString$11(value)?.toLowerCase();
2024
+ const normalized = readString$10(value)?.toLowerCase();
2026
2025
  if (!normalized) return null;
2027
2026
  if (!(normalized in BUILTIN_RUNTIME_PRESENTATION)) return null;
2028
2027
  return BUILTIN_RUNTIME_PRESENTATION[normalized] ?? null;
@@ -2043,13 +2042,13 @@ function resolveAgentRuntimeEntries(params) {
2043
2042
  entries.set(DEFAULT_AGENT_RUNTIME_ENTRY_ID, buildNativeRuntimeEntry(params.config));
2044
2043
  for (const [rawId, rawEntry] of Object.entries(params.config.agents.runtimes.entries ?? {})) {
2045
2044
  const id = rawId.trim().toLowerCase();
2046
- const type = readString$11(rawEntry.type)?.toLowerCase();
2045
+ const type = readString$10(rawEntry.type)?.toLowerCase();
2047
2046
  if (!id || !type) continue;
2048
2047
  const explicitIcon = normalizeAgentRuntimeSessionTypeIcon(rawEntry.icon);
2049
2048
  const builtinPresentation = resolveBuiltinRuntimePresentation(id) ?? resolveBuiltinRuntimePresentation(type);
2050
2049
  entries.set(id, {
2051
2050
  id,
2052
- label: readString$11(rawEntry.label) ?? builtinPresentation?.label ?? id,
2051
+ label: readString$10(rawEntry.label) ?? builtinPresentation?.label ?? id,
2053
2052
  ...explicitIcon ?? builtinPresentation?.icon ? { icon: explicitIcon ?? builtinPresentation?.icon } : {},
2054
2053
  type,
2055
2054
  enabled: rawEntry.enabled !== false,
@@ -3127,7 +3126,7 @@ function parseServiceAppManifest(raw, options = {}) {
3127
3126
  } catch (error) {
3128
3127
  throw new Error(`service-app.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
3129
3128
  }
3130
- if (!isRecord$21(parsed)) throw new Error("service-app.json must contain an object.");
3129
+ if (!isRecord$20(parsed)) throw new Error("service-app.json must contain an object.");
3131
3130
  const id = readRequiredString$9(parsed, "id");
3132
3131
  if (!SERVICE_APP_ID_PATTERN$1.test(id)) throw new Error("service app id must be kebab-case.");
3133
3132
  const protocol = readOptionalString$14(parsed, "protocol") ?? "mcp";
@@ -3156,12 +3155,12 @@ function parseServiceAppManifest(raw, options = {}) {
3156
3155
  }
3157
3156
  function readServiceAppProvides(value) {
3158
3157
  if (value === void 0) return void 0;
3159
- if (!isRecord$21(value)) throw new Error("service app provides must be an object.");
3158
+ if (!isRecord$20(value)) throw new Error("service app provides must be an object.");
3160
3159
  if (value.capabilities === void 0) return void 0;
3161
3160
  if (!Array.isArray(value.capabilities)) throw new Error("service app provides.capabilities must be an array.");
3162
3161
  const seen = /* @__PURE__ */ new Set();
3163
3162
  const capabilities = value.capabilities.map((entry, index) => {
3164
- if (!isRecord$21(entry)) throw new Error(`service app provides.capabilities[${index}] must be an object.`);
3163
+ if (!isRecord$20(entry)) throw new Error(`service app provides.capabilities[${index}] must be an object.`);
3165
3164
  const id = readRequirementIdentifier(entry, "id", `provides.capabilities[${index}].id`);
3166
3165
  const version = readOptionalString$14(entry, "version");
3167
3166
  if (!version) throw new Error(`service app provides.capabilities[${index}].version is required.`);
@@ -3189,7 +3188,7 @@ function readCapabilityResourceTypes(value, index) {
3189
3188
  }
3190
3189
  function readServiceAppRequirements(value, protocol) {
3191
3190
  if (value === void 0) return void 0;
3192
- if (!isRecord$21(value)) throw new Error("service app requires must be an object.");
3191
+ if (!isRecord$20(value)) throw new Error("service app requires must be an object.");
3193
3192
  const capabilities = readCapabilityRequirements(value.capabilities, protocol);
3194
3193
  const resources = readResourceRequirements(value.resources);
3195
3194
  const modelSlots = readModelCapabilitySlots(value.modelSlots);
@@ -3213,7 +3212,7 @@ function readCapabilitySlots(value, name, hasModelLimits) {
3213
3212
  const seen = /* @__PURE__ */ new Set();
3214
3213
  return value.map((entry, index) => {
3215
3214
  const field = `requires.${name}[${index}]`;
3216
- if (!isRecord$21(entry)) throw new Error(`service app ${field} must be an object.`);
3215
+ if (!isRecord$20(entry)) throw new Error(`service app ${field} must be an object.`);
3217
3216
  const allowed = hasModelLimits ? [
3218
3217
  "id",
3219
3218
  "title",
@@ -3255,7 +3254,7 @@ function readCapabilityRequirements(value, protocol) {
3255
3254
  if (!Array.isArray(value)) throw new Error("service app requires.capabilities must be an array.");
3256
3255
  const seen = /* @__PURE__ */ new Set();
3257
3256
  return value.map((entry, index) => {
3258
- if (!isRecord$21(entry)) throw new Error(`service app requires.capabilities[${index}] must be an object.`);
3257
+ if (!isRecord$20(entry)) throw new Error(`service app requires.capabilities[${index}] must be an object.`);
3259
3258
  const id = readRequirementIdentifier(entry, "id", `requires.capabilities[${index}].id`);
3260
3259
  const version = readOptionalString$14(entry, "version");
3261
3260
  const key = `${id}@${version ?? "*"}`;
@@ -3278,7 +3277,7 @@ function readCapabilityRequirements(value, protocol) {
3278
3277
  }
3279
3278
  function readWitContract(value, fieldName, role) {
3280
3279
  if (value === void 0) return void 0;
3281
- if (!isRecord$21(value)) throw new Error(`service app ${fieldName} must be an object.`);
3280
+ if (!isRecord$20(value)) throw new Error(`service app ${fieldName} must be an object.`);
3282
3281
  const packageName = readOptionalString$14(value, "package");
3283
3282
  if (!packageName || !WIT_PACKAGE_PATTERN.test(packageName)) throw new Error(`service app ${fieldName}.package must be a WIT package identifier.`);
3284
3283
  const interfaceName = readRequirementIdentifier(value, "interface", `${fieldName}.interface`);
@@ -3305,7 +3304,7 @@ function readResourceRequirements(value) {
3305
3304
  if (!Array.isArray(value)) throw new Error("service app requires.resources must be an array.");
3306
3305
  const seen = /* @__PURE__ */ new Set();
3307
3306
  return value.map((entry, index) => {
3308
- if (!isRecord$21(entry)) throw new Error(`service app requires.resources[${index}] must be an object.`);
3307
+ if (!isRecord$20(entry)) throw new Error(`service app requires.resources[${index}] must be an object.`);
3309
3308
  const binding = readRequirementIdentifier(entry, "binding", `requires.resources[${index}].binding`);
3310
3309
  if (seen.has(binding)) throw new Error(`service app requires.resources contains duplicate binding ${binding}.`);
3311
3310
  seen.add(binding);
@@ -3326,7 +3325,7 @@ function readRequirementIdentifier(record, key, fieldName) {
3326
3325
  }
3327
3326
  function readExternalRemediation(value, fieldPrefix) {
3328
3327
  if (value === void 0) return void 0;
3329
- if (!isRecord$21(value) || value.kind !== "agent-setup") throw new Error(`service app ${fieldPrefix}.remediation.kind must be agent-setup.`);
3328
+ if (!isRecord$20(value) || value.kind !== "agent-setup") throw new Error(`service app ${fieldPrefix}.remediation.kind must be agent-setup.`);
3330
3329
  const summary = readOptionalString$14(value, "summary");
3331
3330
  if (!summary) throw new Error(`service app ${fieldPrefix}.remediation.summary is required.`);
3332
3331
  return {
@@ -3337,7 +3336,7 @@ function readExternalRemediation(value, fieldPrefix) {
3337
3336
  }
3338
3337
  function readServiceAppLifecycle(value) {
3339
3338
  if (value === void 0) return { mode: "action" };
3340
- if (!isRecord$21(value)) throw new Error("service app lifecycle must be an object.");
3339
+ if (!isRecord$20(value)) throw new Error("service app lifecycle must be an object.");
3341
3340
  const mode = readOptionalString$14(value, "mode") ?? "action";
3342
3341
  if (mode === "action") return { mode };
3343
3342
  if (mode === "provider") return { mode };
@@ -3365,7 +3364,7 @@ function readServiceAppId(record, key, fieldName) {
3365
3364
  }
3366
3365
  function readPortableComponentEntry(record) {
3367
3366
  const component = record.component;
3368
- if (!isRecord$21(component)) throw new Error("service app component is required for wasi-component.");
3367
+ if (!isRecord$20(component)) throw new Error("service app component is required for wasi-component.");
3369
3368
  const entry = readRequiredString$9(component, "entry").replace(/\\/g, "/");
3370
3369
  if (path.isAbsolute(entry) || entry.includes("\0") || entry.split("/").includes("..")) throw new Error("service app component.entry must be a package-relative path.");
3371
3370
  if (!entry.endsWith(".wasm")) throw new Error("service app component.entry must reference a .wasm file.");
@@ -3373,16 +3372,16 @@ function readPortableComponentEntry(record) {
3373
3372
  }
3374
3373
  function readManifestActions(value) {
3375
3374
  if (value === void 0) throw new Error("service app actions are required.");
3376
- if (!isRecord$21(value)) throw new Error("service app actions must be an object.");
3375
+ if (!isRecord$20(value)) throw new Error("service app actions must be an object.");
3377
3376
  if (Object.keys(value).length === 0) throw new Error("service app actions cannot be empty.");
3378
3377
  const actions = {};
3379
3378
  for (const [name, action] of Object.entries(value)) {
3380
3379
  if (!name.trim()) throw new Error("service app action name cannot be empty.");
3381
- if (!isRecord$21(action)) throw new Error(`service app action ${name} must be an object.`);
3380
+ if (!isRecord$20(action)) throw new Error(`service app action ${name} must be an object.`);
3382
3381
  const risk = readOptionalString$14(action, "risk");
3383
3382
  if (risk !== void 0 && !SERVICE_ACTION_RISKS.has(risk)) throw new Error(`service app action ${name} has invalid risk.`);
3384
3383
  const inputSchema = action.inputSchema;
3385
- if (inputSchema !== void 0 && !isRecord$21(inputSchema)) throw new Error(`service app action ${name} inputSchema must be an object.`);
3384
+ if (inputSchema !== void 0 && !isRecord$20(inputSchema)) throw new Error(`service app action ${name} inputSchema must be an object.`);
3386
3385
  const timeoutMs = readOptionalNumber$1(action, "timeoutMs");
3387
3386
  if (timeoutMs !== void 0 && (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 3e5)) throw new Error(`service app action ${name} timeoutMs must be an integer between 100 and 300000.`);
3388
3387
  actions[name] = {
@@ -3417,7 +3416,7 @@ function readOptionalNumber$1(record, key) {
3417
3416
  if (typeof record[key] !== "number") throw new Error(`service app ${key} must be number.`);
3418
3417
  return record[key];
3419
3418
  }
3420
- function isRecord$21(value) {
3419
+ function isRecord$20(value) {
3421
3420
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3422
3421
  }
3423
3422
  //#endregion
@@ -5365,14 +5364,14 @@ var ExtensionLifecycleService = class {
5365
5364
  };
5366
5365
  //#endregion
5367
5366
  //#region src/features/extension-runtime/utils/extension-runtime-payload.utils.ts
5368
- function readString$10(value) {
5367
+ function readString$9(value) {
5369
5368
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
5370
5369
  }
5371
5370
  function readRecord$2(value) {
5372
5371
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
5373
5372
  }
5374
5373
  function readRequiredString$8(value, name) {
5375
- const trimmed = readString$10(value);
5374
+ const trimmed = readString$9(value);
5376
5375
  if (!trimmed) throw new Error(`${name} is required`);
5377
5376
  return trimmed;
5378
5377
  }
@@ -5387,16 +5386,16 @@ function readTextContent(value) {
5387
5386
  function readInboundAttachments(value) {
5388
5387
  if (!Array.isArray(value)) return [];
5389
5388
  return value.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).map((entry) => ({
5390
- ...readString$10(entry.id) ? { id: readString$10(entry.id) } : {},
5391
- ...readString$10(entry.name) ? { name: readString$10(entry.name) } : {},
5392
- ...readString$10(entry.path) ? { path: readString$10(entry.path) } : {},
5393
- ...readString$10(entry.url) ? { url: readString$10(entry.url) } : {},
5394
- ...readString$10(entry.assetUri) ? { assetUri: readString$10(entry.assetUri) } : {},
5395
- ...readString$10(entry.mimeType) ? { mimeType: readString$10(entry.mimeType) } : {},
5389
+ ...readString$9(entry.id) ? { id: readString$9(entry.id) } : {},
5390
+ ...readString$9(entry.name) ? { name: readString$9(entry.name) } : {},
5391
+ ...readString$9(entry.path) ? { path: readString$9(entry.path) } : {},
5392
+ ...readString$9(entry.url) ? { url: readString$9(entry.url) } : {},
5393
+ ...readString$9(entry.assetUri) ? { assetUri: readString$9(entry.assetUri) } : {},
5394
+ ...readString$9(entry.mimeType) ? { mimeType: readString$9(entry.mimeType) } : {},
5396
5395
  ...readOptionalNumber(entry.size) !== void 0 ? { size: readOptionalNumber(entry.size) } : {},
5397
- ...readString$10(entry.source) ? { source: readString$10(entry.source) } : {},
5396
+ ...readString$9(entry.source) ? { source: readString$9(entry.source) } : {},
5398
5397
  ...entry.status === "ready" || entry.status === "remote-only" ? { status: entry.status } : {},
5399
- ...readString$10(entry.errorCode) ? { errorCode: readString$10(entry.errorCode) } : {}
5398
+ ...readString$9(entry.errorCode) ? { errorCode: readString$9(entry.errorCode) } : {}
5400
5399
  }));
5401
5400
  }
5402
5401
  function toInboundMessage(value) {
@@ -5428,7 +5427,7 @@ function normalizeAuthPollResult(value) {
5428
5427
  return {
5429
5428
  channel: readRequiredString$8(record.channel, "channel"),
5430
5429
  status: record.status,
5431
- message: readString$10(record.message),
5430
+ message: readString$9(record.message),
5432
5431
  nextPollMs: readOptionalNumber(record.nextPollMs),
5433
5432
  accountId: typeof record.accountId === "string" ? record.accountId : null,
5434
5433
  notes: Array.isArray(record.notes) ? record.notes.filter((note) => typeof note === "string") : [],
@@ -5462,10 +5461,10 @@ var ExtensionIngressDiagnosticsService = class {
5462
5461
  event: readRequiredString$8(payload.event, "event"),
5463
5462
  component: readRequiredString$8(payload.component, "component"),
5464
5463
  outcome: readRequiredString$8(payload.outcome, "outcome"),
5465
- correlationId: readString$10(payload.correlationId),
5466
- parentCorrelationId: readString$10(payload.parentCorrelationId),
5467
- reasonCode: readString$10(payload.reasonCode),
5468
- providerCode: readString$10(payload.providerCode),
5464
+ correlationId: readString$9(payload.correlationId),
5465
+ parentCorrelationId: readString$9(payload.parentCorrelationId),
5466
+ reasonCode: readString$9(payload.reasonCode),
5467
+ providerCode: readString$9(payload.providerCode),
5469
5468
  durationMs: readOptionalNumber(payload.durationMs),
5470
5469
  attempt: readOptionalNumber(payload.attempt),
5471
5470
  facts: {
@@ -5609,12 +5608,12 @@ var ExtensionAuthLeaseService = class {
5609
5608
  if (kind === "channel.auth.poll") {
5610
5609
  const sessionId = readRequiredString$8(payload.sessionId, "sessionId");
5611
5610
  const result = value ? readRecord$2(value) : null;
5612
- const status = result ? readString$10(result.status) : null;
5611
+ const status = result ? readString$9(result.status) : null;
5613
5612
  if (status === "authorized") await this.retainHandoff(extensionId, channelId, generation);
5614
5613
  if (!result || status === "authorized" || status === "expired" || status === "error") this.releaseSession(extensionId, sessionId);
5615
5614
  return;
5616
5615
  }
5617
- if (kind === "channel.auth.connect" && readString$10(readRecord$2(value).status) === "authorized") {
5616
+ if (kind === "channel.auth.connect" && readString$9(readRecord$2(value).status) === "authorized") {
5618
5617
  await this.retainHandoff(extensionId, channelId, generation);
5619
5618
  return;
5620
5619
  }
@@ -5733,7 +5732,7 @@ const BUILTIN_EXTENSION_PACKAGES = [
5733
5732
  "@nextclaw/channel-extension-weixin"
5734
5733
  ];
5735
5734
  const runtimeRequire = createRequire(import.meta.url);
5736
- function readString$9(value) {
5735
+ function readString$8(value) {
5737
5736
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
5738
5737
  }
5739
5738
  function readStringArray$1(value) {
@@ -5782,16 +5781,16 @@ function toManifest(value, rootDir) {
5782
5781
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("extension manifest must be an object");
5783
5782
  const record = value;
5784
5783
  const server = readRecord$1(record.server);
5785
- const id = readString$9(record.id);
5786
- const command = readString$9(server.command);
5784
+ const id = readString$8(record.id);
5785
+ const command = readString$8(server.command);
5787
5786
  if (!id) throw new Error("extension manifest id is required");
5788
5787
  if (server.type !== "stdio") throw new Error("extension server.type must be stdio");
5789
5788
  if (!command) throw new Error("extension server.command is required");
5790
5789
  return {
5791
5790
  id,
5792
5791
  rootDir,
5793
- ...readString$9(record.name) ? { name: readString$9(record.name) } : {},
5794
- ...readString$9(record.version) ? { version: readString$9(record.version) } : {},
5792
+ ...readString$8(record.name) ? { name: readString$8(record.name) } : {},
5793
+ ...readString$8(record.version) ? { version: readString$8(record.version) } : {},
5795
5794
  server: {
5796
5795
  type: "stdio",
5797
5796
  command,
@@ -5987,13 +5986,13 @@ var ExtensionObservationRuntimeService = class {
5987
5986
  eventId,
5988
5987
  eventType,
5989
5988
  occurredAt,
5990
- observedAt: readString$10(event.observedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
5991
- ...readString$10(event.cursor) ? { cursor: readString$10(event.cursor) } : {},
5992
- ...readString$10(event.dedupeKey) ? { dedupeKey: readString$10(event.dedupeKey) } : {},
5989
+ observedAt: readString$9(event.observedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
5990
+ ...readString$9(event.cursor) ? { cursor: readString$9(event.cursor) } : {},
5991
+ ...readString$9(event.dedupeKey) ? { dedupeKey: readString$9(event.dedupeKey) } : {},
5993
5992
  payload: event.payload,
5994
5993
  ...Array.isArray(event.sourceRefs) && event.sourceRefs.every((value) => typeof value === "string") ? { sourceRefs: event.sourceRefs } : {},
5995
- ...readString$10(event.causationId) ? { causationId: readString$10(event.causationId) } : {},
5996
- ...readString$10(event.correlationId) ? { correlationId: readString$10(event.correlationId) } : {}
5994
+ ...readString$9(event.causationId) ? { causationId: readString$9(event.causationId) } : {},
5995
+ ...readString$9(event.correlationId) ? { correlationId: readString$9(event.correlationId) } : {}
5997
5996
  }
5998
5997
  }) ?? { accepted: false };
5999
5998
  };
@@ -6078,13 +6077,13 @@ function stableStringify(value) {
6078
6077
  }
6079
6078
  function sortValue(value) {
6080
6079
  if (Array.isArray(value)) return value.map(sortValue);
6081
- if (!isRecord$20(value)) return value;
6080
+ if (!isRecord$19(value)) return value;
6082
6081
  return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortValue(value[key])]));
6083
6082
  }
6084
6083
  function normalizeJsonValue(value) {
6085
6084
  if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return value;
6086
6085
  if (Array.isArray(value)) return value.map(normalizeJsonValue);
6087
- if (isRecord$20(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeJsonValue(item)]));
6086
+ if (isRecord$19(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeJsonValue(item)]));
6088
6087
  throw new Error("Capability grant target must be JSON-compatible.");
6089
6088
  }
6090
6089
  function requireString$1(value, field) {
@@ -6092,7 +6091,7 @@ function requireString$1(value, field) {
6092
6091
  if (!normalized) throw new Error(`Capability grant ${field} is required.`);
6093
6092
  return normalized;
6094
6093
  }
6095
- function isRecord$20(value) {
6094
+ function isRecord$19(value) {
6096
6095
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6097
6096
  }
6098
6097
  //#endregion
@@ -6576,10 +6575,10 @@ function toGrantRecord(grants) {
6576
6575
  }));
6577
6576
  }
6578
6577
  function normalizeStoreData(value) {
6579
- if (!isRecord$19(value) || value.version !== 1 || !isRecord$19(value.grants)) throw new Error("Capability grant store is invalid.");
6578
+ if (!isRecord$18(value) || value.version !== 1 || !isRecord$18(value.grants)) throw new Error("Capability grant store is invalid.");
6580
6579
  const grants = [];
6581
6580
  for (const grant of Object.values(value.grants)) {
6582
- if (!isRecord$19(grant) || !isRecord$19(grant.subject) || !isRecord$19(grant.resource) || !Array.isArray(grant.access) || !grant.access.every((item) => typeof item === "string") || typeof grant.declarationFingerprint !== "string" || typeof grant.grantedAt !== "string") throw new Error("Capability grant store contains an invalid grant.");
6581
+ if (!isRecord$18(grant) || !isRecord$18(grant.subject) || !isRecord$18(grant.resource) || !Array.isArray(grant.access) || !grant.access.every((item) => typeof item === "string") || typeof grant.declarationFingerprint !== "string" || typeof grant.grantedAt !== "string") throw new Error("Capability grant store contains an invalid grant.");
6583
6582
  const request = normalizeCapabilityGrantRequest({
6584
6583
  subject: {
6585
6584
  type: String(grant.subject.type ?? ""),
@@ -6603,11 +6602,11 @@ function normalizeStoreData(value) {
6603
6602
  grants: toGrantRecord(grants)
6604
6603
  };
6605
6604
  }
6606
- function isRecord$19(value) {
6605
+ function isRecord$18(value) {
6607
6606
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6608
6607
  }
6609
6608
  function isMissingFileError$2(error) {
6610
- return isRecord$19(error) && error.code === "ENOENT";
6609
+ return isRecord$18(error) && error.code === "ENOENT";
6611
6610
  }
6612
6611
  //#endregion
6613
6612
  //#region src/features/capability-grants/managers/capability-grant.manager.ts
@@ -7111,10 +7110,10 @@ var DesktopNodeReplService = class {
7111
7110
  }
7112
7111
  async handleWorkerMessage(key, worker, value) {
7113
7112
  const message = asRecord$1(value);
7114
- const executionId = readString$8(message.executionId);
7113
+ const executionId = readString$7(message.executionId);
7115
7114
  if (!executionId || !worker.pending.has(executionId)) return;
7116
7115
  if (message.type === "desktop.request") {
7117
- const requestId = readString$8(message.requestId);
7116
+ const requestId = readString$7(message.requestId);
7118
7117
  if (!requestId) return;
7119
7118
  try {
7120
7119
  const result = await this.invokeDesktop(worker.pending.get(executionId).caller, message.operation, message.args);
@@ -7145,7 +7144,7 @@ var DesktopNodeReplService = class {
7145
7144
  }
7146
7145
  if (message.type === "error") {
7147
7146
  const error = asRecord$1(message.error);
7148
- this.reject(worker, executionId, replError(readString$8(error.code) ?? "repl_execution_failed", readString$8(error.message) ?? "node_repl execution failed."));
7147
+ this.reject(worker, executionId, replError(readString$7(error.code) ?? "repl_execution_failed", readString$7(error.message) ?? "node_repl execution failed."));
7149
7148
  return;
7150
7149
  }
7151
7150
  this.stopWorker(key, worker);
@@ -7291,7 +7290,7 @@ function readKeyboardModifiers(value) {
7291
7290
  if (new Set(value).size !== value.length) throw replError("invalid_tool_arguments", "modifiers cannot contain duplicates.");
7292
7291
  return value;
7293
7292
  }
7294
- function readString$8(value) {
7293
+ function readString$7(value) {
7295
7294
  return typeof value === "string" && value.trim() ? value : void 0;
7296
7295
  }
7297
7296
  function trimOutput(value) {
@@ -7762,9 +7761,9 @@ var ExtensionDesktopRuntimeService = class {
7762
7761
  method: readRequiredString$8(payload.method, "method"),
7763
7762
  payload: readRecord$2(payload.payload),
7764
7763
  caller: {
7765
- ...readString$10(caller.sessionId) ? { sessionId: readString$10(caller.sessionId) } : {},
7766
- ...readString$10(caller.agentRunId) ? { agentRunId: readString$10(caller.agentRunId) } : {},
7767
- ...readString$10(caller.subscriptionId) ? { subscriptionId: readString$10(caller.subscriptionId) } : {}
7764
+ ...readString$9(caller.sessionId) ? { sessionId: readString$9(caller.sessionId) } : {},
7765
+ ...readString$9(caller.agentRunId) ? { agentRunId: readString$9(caller.agentRunId) } : {},
7766
+ ...readString$9(caller.subscriptionId) ? { subscriptionId: readString$9(caller.subscriptionId) } : {}
7768
7767
  }
7769
7768
  });
7770
7769
  };
@@ -7905,7 +7904,7 @@ var ExtensionRuntimeService = class {
7905
7904
  const desired = /* @__PURE__ */ new Map();
7906
7905
  const channelConfig = readRecord$2(config.channels);
7907
7906
  for (const manifest of this.manifests) for (const channel of manifest.contributes?.channels ?? []) {
7908
- const channelId = readString$10(channel.id);
7907
+ const channelId = readString$9(channel.id);
7909
7908
  if (!channelId || readRecord$2(channelConfig[channelId]).enabled !== true) continue;
7910
7909
  desired.set(this.persistentLeaseKey(manifest.id, channelId), {
7911
7910
  manifest,
@@ -7982,15 +7981,15 @@ var ExtensionRuntimeService = class {
7982
7981
  channel,
7983
7982
  chatId,
7984
7983
  senderId,
7985
- content: readString$10(payload.rawText) ?? readString$10(payload.commandName) ?? "",
7984
+ content: readString$9(payload.rawText) ?? readString$9(payload.commandName) ?? "",
7986
7985
  timestamp: /* @__PURE__ */ new Date(),
7987
7986
  attachments: [],
7988
7987
  metadata
7989
7988
  },
7990
- forcedAgentId: readString$10(metadata.target_agent_id),
7991
- sessionKeyOverride: readString$10(metadata.session_key_override)
7989
+ forcedAgentId: readString$9(metadata.target_agent_id),
7990
+ sessionKeyOverride: readString$9(metadata.session_key_override)
7992
7991
  });
7993
- const rawText = readString$10(payload.rawText);
7992
+ const rawText = readString$9(payload.rawText);
7994
7993
  if (rawText) return await registry.executeText(rawText, {
7995
7994
  channel,
7996
7995
  chatId,
@@ -8023,7 +8022,7 @@ var ExtensionRuntimeService = class {
8023
8022
  this.pendingRequests.delete(requestId);
8024
8023
  pending.cleanup();
8025
8024
  if (payload.ok === false) {
8026
- const message = readString$10(readRecord$2(payload.error).message) ?? "Extension request failed";
8025
+ const message = readString$9(readRecord$2(payload.error).message) ?? "Extension request failed";
8027
8026
  pending.reject(new Error(message));
8028
8027
  return { accepted: true };
8029
8028
  }
@@ -8134,9 +8133,9 @@ var ExtensionRuntimeService = class {
8134
8133
  };
8135
8134
  assertAuthorized = (envelope, context) => {
8136
8135
  const credential = this.lifecycle.authenticateCredential({
8137
- extensionId: readString$10(envelope.extensionId) ?? null,
8138
- generation: readString$10(envelope.generation) ?? null,
8139
- token: readString$10(context.token) ?? null
8136
+ extensionId: readString$9(envelope.extensionId) ?? null,
8137
+ generation: readString$9(envelope.generation) ?? null,
8138
+ token: readString$9(context.token) ?? null
8140
8139
  });
8141
8140
  if (!credential) throw new Error("Unauthorized ingress token");
8142
8141
  return credential;
@@ -8278,11 +8277,11 @@ var ExtensionManager = class {
8278
8277
  //#endregion
8279
8278
  //#region src/utils/model-message-vision.utils.ts
8280
8279
  const IMAGE_OMITTED_TEXT = "[Image omitted: the selected model is not configured for vision input.]";
8281
- function isRecord$18(value) {
8280
+ function isRecord$17(value) {
8282
8281
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8283
8282
  }
8284
8283
  function isImageContentPart(value) {
8285
- if (!isRecord$18(value)) return false;
8284
+ if (!isRecord$17(value)) return false;
8286
8285
  const type = value.type;
8287
8286
  return type === "image_url" || type === "input_image";
8288
8287
  }
@@ -8298,7 +8297,7 @@ function normalizeContentWithoutVision(content) {
8298
8297
  };
8299
8298
  });
8300
8299
  if (!sawImage) return content;
8301
- const textParts = parts.filter((part) => isRecord$18(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text.trim()).filter(Boolean);
8300
+ const textParts = parts.filter((part) => isRecord$17(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text.trim()).filter(Boolean);
8302
8301
  if (textParts.length === parts.length) return textParts.join("\n\n");
8303
8302
  return parts;
8304
8303
  }
@@ -9618,7 +9617,7 @@ function parsePanelAppFolderManifest(raw) {
9618
9617
  } catch (error) {
9619
9618
  throw new Error(`panel-app.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
9620
9619
  }
9621
- if (!isRecord$17(parsed)) throw new Error("panel-app.json must contain an object.");
9620
+ if (!isRecord$16(parsed)) throw new Error("panel-app.json must contain an object.");
9622
9621
  const id = readOptionalString$13(parsed, "id");
9623
9622
  if (id && !PANEL_APP_ID_PATTERN.test(id)) throw new Error("panel app id must be kebab-case.");
9624
9623
  return {
@@ -9705,7 +9704,7 @@ function readStringArray(value, key) {
9705
9704
  if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new Error(`panel app ${key} must be a string array.`);
9706
9705
  return [...new Set(value.map((entry) => entry.trim()).filter(Boolean))];
9707
9706
  }
9708
- function isRecord$17(value) {
9707
+ function isRecord$16(value) {
9709
9708
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9710
9709
  }
9711
9710
  function normalizeTextValue(value) {
@@ -10254,7 +10253,7 @@ const PANEL_APP_AGENT_MAX_CONTEXT_CHARS = 8e4;
10254
10253
  function normalizePanelAppGenerateObjectInput(input) {
10255
10254
  const peerId = input.peerId.trim();
10256
10255
  const prompt = input.prompt.trim();
10257
- if (!peerId || !prompt || !isRecord$16(input.schema)) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "invalid generateObject request");
10256
+ if (!peerId || !prompt || !isRecord$15(input.schema)) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "invalid generateObject request");
10258
10257
  if (prompt.length > PANEL_APP_AGENT_MAX_PROMPT_CHARS) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "generateObject prompt is too large");
10259
10258
  if (stringifyJsonValue(input.context ?? null).length > PANEL_APP_AGENT_MAX_CONTEXT_CHARS) throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "generateObject context is too large");
10260
10259
  return {
@@ -10395,7 +10394,7 @@ function readStructuredResultEvent(event, resultToolCallId) {
10395
10394
  };
10396
10395
  }
10397
10396
  function assertToolResultContent(content) {
10398
- if (!isRecord$16(content) || content.ok !== false || !isRecord$16(content.error)) return;
10397
+ if (!isRecord$15(content) || content.ok !== false || !isRecord$15(content.error)) return;
10399
10398
  if (content.error.code === "invalid_tool_arguments") throw new PanelAppError("AGENT_OBJECT_RESULT_SCHEMA_INVALID", "agent object result did not match the schema");
10400
10399
  throw new PanelAppError("AGENT_OBJECT_REQUEST_FAILED", typeof content.error.message === "string" ? content.error.message : "agent object request failed");
10401
10400
  }
@@ -10411,7 +10410,7 @@ function stringifyJsonValue(value) {
10411
10410
  throw new PanelAppError("PANEL_APP_AGENT_REQUEST_INVALID", "value is not JSON serializable");
10412
10411
  }
10413
10412
  }
10414
- function isRecord$16(value) {
10413
+ function isRecord$15(value) {
10415
10414
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
10416
10415
  }
10417
10416
  //#endregion
@@ -11547,7 +11546,7 @@ function recordProductActivityBestEffort(sink, signal) {
11547
11546
  }
11548
11547
  //#endregion
11549
11548
  //#region src/utils/agent-run-trigger.utils.ts
11550
- function isRecord$15(value) {
11549
+ function isRecord$14(value) {
11551
11550
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11552
11551
  }
11553
11552
  function readOptionalString$12(value) {
@@ -11555,7 +11554,7 @@ function readOptionalString$12(value) {
11555
11554
  }
11556
11555
  function readSourceRunSpec(message) {
11557
11556
  const value = message.metadata?.[AGENT_RUN_MESSAGE_RUN_SPEC_METADATA_KEY];
11558
- return isRecord$15(value) ? value : {};
11557
+ return isRecord$14(value) ? value : {};
11559
11558
  }
11560
11559
  const SOURCE_CONTEXT_KEYS = [
11561
11560
  "channel",
@@ -11950,80 +11949,6 @@ var SessionRunManager = class {
11950
11949
  };
11951
11950
  };
11952
11951
  //#endregion
11953
- //#region src/utils/skill-frontmatter.utils.ts
11954
- function parseSkillFrontmatter(raw) {
11955
- const frontmatter = parseFrontmatterBlock(raw);
11956
- if (!frontmatter) return {};
11957
- const parsed = parseYamlFrontmatter(frontmatter);
11958
- const summaryI18n = readLocalizedTextMap(parsed, "summaryi18n", "summary_i18n");
11959
- const descriptionI18n = readLocalizedTextMap(parsed, "descriptioni18n", "description_i18n");
11960
- return {
11961
- name: readString$7(parsed, "name"),
11962
- summary: readString$7(parsed, "summary"),
11963
- summaryI18n: mergeLocalizedTextMap(summaryI18n, { zh: readString$7(parsed, "summaryzh", "summary_zh") }),
11964
- description: readString$7(parsed, "description"),
11965
- descriptionI18n: mergeLocalizedTextMap(descriptionI18n, { zh: readString$7(parsed, "descriptionzh", "description_zh") }),
11966
- author: readString$7(parsed, "author"),
11967
- tags: readTags(parsed)
11968
- };
11969
- }
11970
- function stripSkillFrontmatter(raw) {
11971
- const normalized = raw.replace(/\r\n/g, "\n");
11972
- const match = normalized.match(/^---\n[\s\S]*?\n---\n?/);
11973
- return match ? normalized.slice(match[0].length).trim() : normalized.trim();
11974
- }
11975
- function buildLocalizedTextMap(englishText, ...maps) {
11976
- return {
11977
- ...mergeLocalizedTextMap(...maps) ?? {},
11978
- en: englishText
11979
- };
11980
- }
11981
- function parseFrontmatterBlock(raw) {
11982
- return raw.replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/)?.[1] ?? null;
11983
- }
11984
- function parseYamlFrontmatter(raw) {
11985
- try {
11986
- const parsed = parse(raw);
11987
- return isRecord$14(parsed) ? parsed : {};
11988
- } catch (error) {
11989
- const message = error instanceof Error ? error.message : String(error);
11990
- throw new Error(`Invalid SKILL.md frontmatter: ${message}`);
11991
- }
11992
- }
11993
- function readString$7(record, ...names) {
11994
- const value = readValue(record, names);
11995
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
11996
- }
11997
- function readLocalizedTextMap(record, ...names) {
11998
- const value = readValue(record, names);
11999
- if (!isRecord$14(value)) return;
12000
- const localized = Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0).map(([locale, text]) => [normalizeLocaleTag(locale), text.trim()]));
12001
- return Object.keys(localized).length > 0 ? localized : void 0;
12002
- }
12003
- function readTags(record) {
12004
- const value = readValue(record, ["tags"]);
12005
- const normalized = (Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : []).filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean);
12006
- return normalized.length > 0 ? normalized : void 0;
12007
- }
12008
- function mergeLocalizedTextMap(...maps) {
12009
- const localized = Object.fromEntries(maps.flatMap((map) => Object.entries(map ?? {}).filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0).map(([locale, text]) => [normalizeLocaleTag(locale), text.trim()])));
12010
- return Object.keys(localized).length > 0 ? localized : void 0;
12011
- }
12012
- function readValue(record, names) {
12013
- const normalizedNames = names.map(normalizeFrontmatterKey);
12014
- const matchingKey = Object.keys(record).find((candidate) => normalizedNames.includes(normalizeFrontmatterKey(candidate)));
12015
- return matchingKey ? record[matchingKey] : void 0;
12016
- }
12017
- function normalizeFrontmatterKey(raw) {
12018
- return raw.replace(/[-_]/g, "").toLowerCase();
12019
- }
12020
- function normalizeLocaleTag(raw) {
12021
- return raw.trim().toLowerCase();
12022
- }
12023
- function isRecord$14(value) {
12024
- return typeof value === "object" && value !== null && !Array.isArray(value);
12025
- }
12026
- //#endregion
12027
11952
  //#region src/managers/skill.manager.ts
12028
11953
  var SkillManager = class {
12029
11954
  loader;
@@ -12063,7 +11988,7 @@ var SkillManager = class {
12063
11988
  ...summary,
12064
11989
  metadata: this.getSkillMetadata(skill),
12065
11990
  raw,
12066
- bodyRaw: stripSkillFrontmatter(raw)
11991
+ bodyRaw: stripSkillFrontmatter$1(raw)
12067
11992
  };
12068
11993
  };
12069
11994
  findBuiltinSkill = (name) => {
@@ -12076,7 +12001,7 @@ var SkillManager = class {
12076
12001
  buildInstalledSkillSummary = (skill) => {
12077
12002
  const raw = readFileSync(skill.path, "utf8");
12078
12003
  const metadata = this.getSkillMetadata(skill);
12079
- const frontmatter = parseSkillFrontmatter(raw);
12004
+ const frontmatter = parseSkillFrontmatter$1(raw);
12080
12005
  return {
12081
12006
  ref: skill.ref,
12082
12007
  name: skill.name,
@@ -12269,27 +12194,28 @@ function truncateLabel(value) {
12269
12194
  }
12270
12195
  //#endregion
12271
12196
  //#region src/utils/ncp-agent-session-replay-event.utils.ts
12272
- function readSupersededSyntheticRecoveryIndexes(events) {
12273
- const superseded = /* @__PURE__ */ new Set();
12274
- const futureMessageIds = /* @__PURE__ */ new Set();
12275
- const futureRunIds = /* @__PURE__ */ new Set();
12276
- const futureToolCallMessageIds = /* @__PURE__ */ new Map();
12277
- for (let index = events.length - 1; index >= 0; index -= 1) {
12278
- const event = events[index];
12279
- if (event.type === NcpEventType.RunError && event.payload.interrupted === true && (event.payload.messageId && futureMessageIds.has(event.payload.messageId) || event.payload.runId && futureRunIds.has(event.payload.runId))) superseded.add(index);
12197
+ var SessionReplaySupersessionTracker = class {
12198
+ interrupted = [];
12199
+ lastContinuationByMessageId = /* @__PURE__ */ new Map();
12200
+ lastContinuationByRunId = /* @__PURE__ */ new Map();
12201
+ toolOwners = /* @__PURE__ */ new Map();
12202
+ observe = (event, index) => {
12203
+ const messageId = readEventMessageId(event);
12204
+ const runId = readEventRunId(event);
12280
12205
  const toolCallId = readEventToolCallId(event);
12281
- const mappedToolMessageId = toolCallId ? futureToolCallMessageIds.get(toolCallId) : void 0;
12282
- if (mappedToolMessageId) futureMessageIds.add(mappedToolMessageId);
12283
- if (isReplayContinuationEvent(event)) {
12284
- const messageId = readEventMessageId(event);
12285
- const runId = readEventRunId(event);
12286
- if (messageId) futureMessageIds.add(messageId);
12287
- if (runId) futureRunIds.add(runId);
12288
- if (toolCallId && messageId) futureToolCallMessageIds.set(toolCallId, messageId);
12289
- }
12290
- }
12291
- return superseded;
12292
- }
12206
+ if (toolCallId && messageId) this.toolOwners.set(toolCallId, messageId);
12207
+ if (event.type === NcpEventType.RunError && event.payload.interrupted === true) this.interrupted.push({
12208
+ index,
12209
+ messageId,
12210
+ runId
12211
+ });
12212
+ if (!isReplayContinuationEvent(event)) return;
12213
+ const ownerMessageId = messageId ?? (toolCallId ? this.toolOwners.get(toolCallId) ?? null : null);
12214
+ if (ownerMessageId) this.lastContinuationByMessageId.set(ownerMessageId, index);
12215
+ if (runId) this.lastContinuationByRunId.set(runId, index);
12216
+ };
12217
+ finish = () => new Set(this.interrupted.filter(({ index, messageId, runId }) => (messageId ? (this.lastContinuationByMessageId.get(messageId) ?? -1) > index : false) || (runId ? (this.lastContinuationByRunId.get(runId) ?? -1) > index : false)).map(({ index }) => index));
12218
+ };
12293
12219
  function isReplayContinuationEvent(event) {
12294
12220
  if (isJournalOnlyEvent(event)) return false;
12295
12221
  if (event.type === "session.snapshot.message") return true;
@@ -12439,15 +12365,6 @@ function readReplayToolOwners(event) {
12439
12365
  if (event.type === NcpEventType.MessageToolCallStart && event.payload.messageId) owners.set(event.payload.toolCallId, event.payload.messageId);
12440
12366
  return owners;
12441
12367
  }
12442
- function needsReplayToolHistory(events, seeds) {
12443
- const owners = seedReplayToolOwners(seeds);
12444
- for (const event of events) {
12445
- const toolCallId = readEventToolCallId(event);
12446
- if (toolCallId && !readEventMessageId(event) && !owners.has(toolCallId)) return true;
12447
- for (const [callId, messageId] of readReplayToolOwners(event)) owners.set(callId, messageId);
12448
- }
12449
- return false;
12450
- }
12451
12368
  //#endregion
12452
12369
  //#region src/utils/ncp-agent-session-replay.utils.ts
12453
12370
  var ReplayContext = class {
@@ -12474,12 +12391,24 @@ var ReplayContext = class {
12474
12391
  }
12475
12392
  };
12476
12393
  };
12477
- async function replayNcpAgentSessionEvents(events, seedMessages = [], activeMessageId, allowUnknownStreamingBootstrap = true) {
12478
- const context = await createReplayContext(seedMessages, activeMessageId);
12479
- await replayJournalEvents(context, events, allowUnknownStreamingBootstrap);
12480
- const snapshot = context.stateManager.getSnapshot();
12481
- return (snapshot.streamingMessage ? insertMessageByTimeline(snapshot.messages, snapshot.streamingMessage) : snapshot.messages).map(context.compactionRecovery.terminalize);
12482
- }
12394
+ var SessionEventReplayer = class SessionEventReplayer {
12395
+ constructor(context, allowUnknownStreamingBootstrap) {
12396
+ this.context = context;
12397
+ this.allowUnknownStreamingBootstrap = allowUnknownStreamingBootstrap;
12398
+ }
12399
+ static create = async (seedMessages = [], activeMessageId, allowUnknownStreamingBootstrap = true) => new SessionEventReplayer(await createReplayContext(seedMessages, activeMessageId), allowUnknownStreamingBootstrap);
12400
+ append = async (event, eventIndex, supersededSyntheticRecoveryIndexes) => {
12401
+ if (isJournalOnlyEvent(event)) return;
12402
+ const replayEvent = createReplayEvent(event, this.context.toolResultsByCallId);
12403
+ updateActiveTailRunIds(this.context.activeTailRunIds, replayEvent, eventIndex);
12404
+ if (supersededSyntheticRecoveryIndexes.has(eventIndex)) return;
12405
+ await replayJournalEvent(this.context, replayEvent, this.allowUnknownStreamingBootstrap);
12406
+ };
12407
+ finish = () => {
12408
+ const snapshot = this.context.stateManager.getSnapshot();
12409
+ return (snapshot.streamingMessage ? insertMessageByTimeline(snapshot.messages, snapshot.streamingMessage) : snapshot.messages).map(this.context.compactionRecovery.terminalize);
12410
+ };
12411
+ };
12483
12412
  async function createReplayContext(seedMessages, activeMessageId) {
12484
12413
  const stateManager = new DefaultNcpAgentConversationStateManager();
12485
12414
  if (seedMessages.length > 0) stateManager.hydrate({
@@ -12497,16 +12426,6 @@ async function createReplayContext(seedMessages, activeMessageId) {
12497
12426
  });
12498
12427
  return new ReplayContext(stateManager, seedMessages);
12499
12428
  }
12500
- async function replayJournalEvents(context, events, allowUnknownStreamingBootstrap) {
12501
- const supersededSyntheticRecoveryIndexes = readSupersededSyntheticRecoveryIndexes(events);
12502
- for (const [eventIndex, event] of events.entries()) {
12503
- if (isJournalOnlyEvent(event)) continue;
12504
- const replayEvent = createReplayEvent(event, context.toolResultsByCallId);
12505
- updateActiveTailRunIds(context.activeTailRunIds, replayEvent, eventIndex);
12506
- if (supersededSyntheticRecoveryIndexes.has(eventIndex)) continue;
12507
- await replayJournalEvent(context, replayEvent, allowUnknownStreamingBootstrap);
12508
- }
12509
- }
12510
12429
  function updateActiveTailRunIds(activeTailRunIds, event, eventIndex) {
12511
12430
  if (event.type === NcpEventType.RunStarted) {
12512
12431
  activeTailRunIds.add(event.payload.runId ?? event.payload.messageId ?? `run-event-${eventIndex}`);
@@ -12611,6 +12530,7 @@ function createNcpAgentSessionJournalMetadataEntry(record) {
12611
12530
  _type: "metadata",
12612
12531
  version: 1,
12613
12532
  created_at: record.createdAt ?? record.updatedAt,
12533
+ updated_at: record.updatedAt,
12614
12534
  ...normalizeNcpAgentId(record.agentId) ? { agent_id: normalizeNcpAgentId(record.agentId) } : {},
12615
12535
  metadata: structuredClone(record.metadata ?? {})
12616
12536
  };
@@ -21921,15 +21841,19 @@ var NcpAgentSessionJournalParser = class {
21921
21841
  nextSeq = 1;
21922
21842
  projectedJournalOffset = 0;
21923
21843
  events = [];
21844
+ constructor(collectEvents = true) {
21845
+ this.collectEvents = collectEvents;
21846
+ }
21924
21847
  append = (line, index, lineEndOffset) => {
21925
- if (!line.trim()) return;
21848
+ if (!line.trim()) return null;
21926
21849
  const parsed = this.parseLine(line, index);
21927
- if (!parsed) return;
21850
+ if (!parsed) return null;
21928
21851
  if (parsed._type === "metadata") {
21929
21852
  this.applyMetadata(parsed);
21930
- return;
21853
+ return null;
21931
21854
  }
21932
- if (parsed._type === "event" && isRecord$12(parsed.event)) this.applyEvent(parsed, lineEndOffset);
21855
+ if (parsed._type === "event" && isRecord$12(parsed.event)) return this.applyEvent(parsed, lineEndOffset);
21856
+ return null;
21933
21857
  };
21934
21858
  finish = () => ({
21935
21859
  metadata: this.metadata,
@@ -21961,20 +21885,43 @@ var NcpAgentSessionJournalParser = class {
21961
21885
  const eventTimestamp = toIsoString(entry.timestamp, this.updatedAt);
21962
21886
  this.updatedAt = eventTimestamp;
21963
21887
  const replayEvent = attachNcpAgentSessionJournalTimestamp(structuredClone(entry.event), eventTimestamp);
21964
- this.events.push(replayEvent);
21888
+ if (this.collectEvents) this.events.push(replayEvent);
21965
21889
  if (isNcpAgentSessionMessageProjectionBoundaryEvent(replayEvent)) this.projectedJournalOffset = lineEndOffset;
21890
+ return replayEvent;
21966
21891
  };
21967
21892
  };
21968
- function parseNcpAgentSessionJournal(raw) {
21969
- const parser = new NcpAgentSessionJournalParser();
21970
- let byteOffset = 0;
21971
- const lines = raw.split("\n");
21972
- for (const [index, line] of lines.entries()) {
21973
- const lineEndOffset = byteOffset + Buffer.byteLength(line, "utf-8") + (index < lines.length - 1 ? 1 : 0);
21974
- parser.append(line, index, lineEndOffset);
21975
- byteOffset = lineEndOffset;
21893
+ async function scanSessionJournal(params) {
21894
+ const { endOffset, onEvent, path } = params;
21895
+ const startOffset = Math.max(0, params.startOffset ?? 0);
21896
+ const parser = new NcpAgentSessionJournalParser(false);
21897
+ if (endOffset <= startOffset) return parser.finish();
21898
+ const file = await open(path, "r");
21899
+ const stream = file.createReadStream({
21900
+ start: startOffset,
21901
+ end: endOffset - 1,
21902
+ encoding: "utf-8",
21903
+ autoClose: false
21904
+ });
21905
+ const lines = createInterface({
21906
+ input: stream,
21907
+ crlfDelay: Infinity
21908
+ });
21909
+ let lineIndex = 0;
21910
+ let byteOffset = startOffset;
21911
+ try {
21912
+ for await (const line of lines) {
21913
+ const lineEndOffset = Math.min(endOffset, byteOffset + Buffer.byteLength(line, "utf-8") + 1);
21914
+ const event = parser.append(line, lineIndex, lineEndOffset);
21915
+ if (event) await onEvent?.(event, lineIndex);
21916
+ byteOffset = lineEndOffset;
21917
+ lineIndex += 1;
21918
+ }
21919
+ return parser.finish();
21920
+ } finally {
21921
+ lines.close();
21922
+ stream.destroy();
21923
+ await file.close();
21976
21924
  }
21977
- return parser.finish();
21978
21925
  }
21979
21926
  //#endregion
21980
21927
  //#region src/stores/ncp-agent-session-metadata.store.ts
@@ -21999,12 +21946,14 @@ var NcpAgentSessionMetadataStore = class {
21999
21946
  const parsed = JSON.parse(await readFile(this.metadataPath(sessionId), "utf-8"));
22000
21947
  if (!isRecord$12(parsed) || parsed._type !== "metadata" || !isRecord$12(parsed.metadata)) throw new Error(`invalid ncp agent session metadata sidecar: ${sessionId}`);
22001
21948
  const createdAt = toIsoString(parsed.created_at, activitySnapshot.createdAt);
21949
+ const sidecarUpdatedAt = toIsoString(parsed.updated_at, activitySnapshot.updatedAt);
21950
+ const updatedAt = Date.parse(sidecarUpdatedAt) > Date.parse(activitySnapshot.updatedAt) ? sidecarUpdatedAt : activitySnapshot.updatedAt;
22002
21951
  const agentId = normalizeNcpAgentId(typeof parsed.agent_id === "string" ? parsed.agent_id : void 0);
22003
21952
  return {
22004
21953
  metadata: structuredClone(parsed.metadata),
22005
21954
  ...agentId ? { agentId } : {},
22006
21955
  createdAt,
22007
- updatedAt: activitySnapshot.updatedAt
21956
+ updatedAt
22008
21957
  };
22009
21958
  } catch (error) {
22010
21959
  if ((error && typeof error === "object" && "code" in error ? error.code : void 0) === "ENOENT") return activitySnapshot;
@@ -22100,32 +22049,110 @@ function readCompactionStatus(message) {
22100
22049
  }
22101
22050
  //#endregion
22102
22051
  //#region src/stores/ncp-agent-session-message-projection-tail.store.ts
22052
+ const TOOL_CALL_START_EVENT_NEEDLE = `"type":"${NcpEventType.MessageToolCallStart}"`;
22103
22053
  async function readNcpAgentSessionProjectionTail(journalPath, meta, readMessage) {
22104
22054
  const file = await open(journalPath, "r");
22105
22055
  try {
22106
22056
  const { size } = await file.stat();
22107
22057
  const offset = meta.projectedJournalOffset;
22108
22058
  if (offset < 0 || offset >= size) return [];
22109
- const buffer = Buffer.alloc(size - offset);
22110
- const result = await file.read(buffer, 0, buffer.length, offset);
22111
- const journal = parseNcpAgentSessionJournal(buffer.subarray(0, result.bytesRead).toString("utf-8"));
22112
22059
  const seedIds = new Set(meta.pendingCompactionMessageIds);
22113
22060
  if (meta.activeMessageId) seedIds.add(meta.activeMessageId);
22114
- for (const event of journal.events) if (event.type === NcpEventType.RunFinished || event.type === NcpEventType.RunError || event.type === NcpEventType.RunMetadata || event.type === NcpEventType.MessageAbort) {
22115
- const messageId = readEventMessageId(event);
22116
- if (messageId) seedIds.add(messageId);
22117
- }
22118
- const seeds = (await Promise.all([...seedIds].map(readMessage))).filter((message) => Boolean(message));
22119
- if (needsReplayToolHistory(journal.events, seeds)) {
22120
- const prefix = Buffer.alloc(size);
22121
- const full = await file.read(prefix, 0, size, 0);
22122
- return await replayNcpAgentSessionEvents(parseNcpAgentSessionJournal(prefix.subarray(0, full.bytesRead).toString("utf-8")).events);
22061
+ const toolOwners = seedReplayToolOwners((await Promise.all([...seedIds].map(readMessage))).filter((message) => Boolean(message)));
22062
+ const missingToolCallIds = /* @__PURE__ */ new Set();
22063
+ const supersessionTracker = new SessionReplaySupersessionTracker();
22064
+ await scanSessionJournal({
22065
+ path: journalPath,
22066
+ startOffset: offset,
22067
+ endOffset: size,
22068
+ onEvent: (event, eventIndex) => {
22069
+ supersessionTracker.observe(event, eventIndex);
22070
+ const toolCallId = readEventToolCallId(event);
22071
+ if (toolCallId && !readEventMessageId(event) && !toolOwners.has(toolCallId)) missingToolCallIds.add(toolCallId);
22072
+ for (const [callId, messageId] of readReplayToolOwners(event)) toolOwners.set(callId, messageId);
22073
+ if (event.type === NcpEventType.RunFinished || event.type === NcpEventType.RunError || event.type === NcpEventType.RunMetadata || event.type === NcpEventType.MessageAbort) {
22074
+ const messageId = readEventMessageId(event);
22075
+ if (messageId) seedIds.add(messageId);
22076
+ }
22077
+ }
22078
+ });
22079
+ let seeds = (await Promise.all([...seedIds].map(readMessage))).filter((message) => Boolean(message));
22080
+ if (missingToolCallIds.size > 0) {
22081
+ const historicalOwners = await readHistoricalToolOwners(file, offset, missingToolCallIds);
22082
+ const ownerMessageIds = new Set(historicalOwners.values());
22083
+ const ownerSeeds = (await Promise.all([...ownerMessageIds].map(readMessage))).filter((message) => Boolean(message));
22084
+ seeds = deduplicateMessages([...seeds, ...ownerSeeds]);
22085
+ const unresolvedToolCallIds = [...missingToolCallIds].filter((toolCallId) => {
22086
+ const ownerMessageId = historicalOwners.get(toolCallId);
22087
+ return !ownerMessageId || !seeds.some((message) => message.id === ownerMessageId);
22088
+ });
22089
+ if (unresolvedToolCallIds.length > 0) console.warn("[ncp-agent-session-journal] unresolved historical tool owners", {
22090
+ sessionId: meta.sessionId,
22091
+ toolCallIds: unresolvedToolCallIds,
22092
+ fallback: "ignore-unowned-tail-events"
22093
+ });
22123
22094
  }
22124
- return await replayNcpAgentSessionEvents(journal.events, seeds, meta.activeMessageId, false);
22095
+ const replayer = await SessionEventReplayer.create(seeds, meta.activeMessageId, false);
22096
+ const supersededSyntheticRecoveryIndexes = supersessionTracker.finish();
22097
+ await scanSessionJournal({
22098
+ path: journalPath,
22099
+ startOffset: offset,
22100
+ endOffset: size,
22101
+ onEvent: async (event, eventIndex) => {
22102
+ await replayer.append(event, eventIndex, supersededSyntheticRecoveryIndexes);
22103
+ }
22104
+ });
22105
+ return replayer.finish();
22125
22106
  } finally {
22126
22107
  await file.close();
22127
22108
  }
22128
22109
  }
22110
+ async function readHistoricalToolOwners(file, endOffset, targetToolCallIds) {
22111
+ const owners = /* @__PURE__ */ new Map();
22112
+ if (endOffset <= 0 || targetToolCallIds.size === 0) return owners;
22113
+ const stream = file.createReadStream({
22114
+ start: 0,
22115
+ end: endOffset - 1,
22116
+ encoding: "utf-8",
22117
+ autoClose: false
22118
+ });
22119
+ const lines = createInterface({
22120
+ input: stream,
22121
+ crlfDelay: Infinity
22122
+ });
22123
+ try {
22124
+ for await (const line of lines) {
22125
+ if (!line.includes(TOOL_CALL_START_EVENT_NEEDLE)) continue;
22126
+ const owner = readToolCallOwner(line);
22127
+ if (!owner || !targetToolCallIds.has(owner.toolCallId)) continue;
22128
+ owners.set(owner.toolCallId, owner.messageId);
22129
+ if (owners.size === targetToolCallIds.size) break;
22130
+ }
22131
+ return owners;
22132
+ } finally {
22133
+ lines.close();
22134
+ stream.destroy();
22135
+ }
22136
+ }
22137
+ function readToolCallOwner(line) {
22138
+ let parsed;
22139
+ try {
22140
+ parsed = JSON.parse(line);
22141
+ } catch {
22142
+ return null;
22143
+ }
22144
+ if (!isRecord$12(parsed) || !isRecord$12(parsed.event) || parsed.event.type !== NcpEventType.MessageToolCallStart) return null;
22145
+ const payload = isRecord$12(parsed.event.payload) ? parsed.event.payload : null;
22146
+ const toolCallId = typeof payload?.toolCallId === "string" ? payload.toolCallId.trim() : "";
22147
+ const messageId = typeof payload?.messageId === "string" ? payload.messageId.trim() : "";
22148
+ return toolCallId && messageId ? {
22149
+ toolCallId,
22150
+ messageId
22151
+ } : null;
22152
+ }
22153
+ function deduplicateMessages(messages) {
22154
+ return [...new Map(messages.map((message) => [message.id, message])).values()];
22155
+ }
22129
22156
  //#endregion
22130
22157
  //#region src/stores/ncp-agent-session-message-projection-persistence.store.ts
22131
22158
  const PROJECTION_ROOT_DIRECTORY = ".message-projections";
@@ -22279,6 +22306,20 @@ var NcpAgentSessionMessageProjectionPersistenceStore = class {
22279
22306
  tailMessages: await this.readJournalTailMessages(sessionId, meta)
22280
22307
  });
22281
22308
  };
22309
+ readAll = async (sessionId) => {
22310
+ let meta = await this.readMeta(sessionId);
22311
+ const journalStat = await stat(this.journalPath(sessionId));
22312
+ if (meta && meta.projectedJournalOffset > journalStat.size) meta = null;
22313
+ if (!meta) return null;
22314
+ const tailMessages = await this.readJournalTailMessages(sessionId, meta);
22315
+ const stableMessages = meta.total > 0 ? await this.readMessages(sessionId, 1, meta.total) : [];
22316
+ const byId = new Map(stableMessages.map((message) => [message.id, message]));
22317
+ for (const message of tailMessages) byId.set(message.id, message);
22318
+ return {
22319
+ messages: [...byId.values()],
22320
+ meta
22321
+ };
22322
+ };
22282
22323
  readPage = async (params) => {
22283
22324
  const { cursor, limit: requestedLimit, sessionId, tailMessages } = params;
22284
22325
  const meta = await this.readMeta(sessionId);
@@ -22320,8 +22361,11 @@ var NcpAgentSessionMessageProjectionPersistenceStore = class {
22320
22361
  readMessageOrdinals = async (sessionId, meta) => {
22321
22362
  const cached = this.messageOrdinals.get(sessionId);
22322
22363
  if (cached) return cached;
22323
- const messages = meta.total > 0 ? await this.readMessages(sessionId, 1, meta.total) : [];
22324
- const ordinals = new Map(messages.map((message, index) => [message.id, index + 1]));
22364
+ const ordinals = /* @__PURE__ */ new Map();
22365
+ for (let ordinal = 1; ordinal <= meta.total; ordinal += 1) {
22366
+ const message = (await this.readMessages(sessionId, ordinal, ordinal))[0];
22367
+ if (message) ordinals.set(message.id, ordinal);
22368
+ }
22325
22369
  this.messageOrdinals.set(sessionId, ordinals);
22326
22370
  return ordinals;
22327
22371
  };
@@ -22399,6 +22443,16 @@ var NcpAgentSessionMessageProjectionStore = class {
22399
22443
  this.persistence = new NcpAgentSessionMessageProjectionPersistenceStore(journalDir);
22400
22444
  }
22401
22445
  readMeta = async (sessionId) => await this.enqueue(sessionId, async () => this.degradedSessionIds.has(sessionId) ? null : await this.persistence.readMeta(sessionId));
22446
+ readAllSnapshot = async (sessionId) => {
22447
+ if (this.degradedSessionIds.has(sessionId)) return null;
22448
+ try {
22449
+ return await this.persistence.readAll(sessionId);
22450
+ } catch (error) {
22451
+ if (!(error instanceof Error)) throw error;
22452
+ this.degrade(sessionId, "readAllSnapshot", error);
22453
+ return null;
22454
+ }
22455
+ };
22402
22456
  rebuild = async (params) => {
22403
22457
  await this.mutate(params.sessionId, "rebuild", async () => {
22404
22458
  await this.persistence.rebuild(params);
@@ -22530,6 +22584,125 @@ var NcpAgentSessionMessageProjectionStore = class {
22530
22584
  };
22531
22585
  };
22532
22586
  //#endregion
22587
+ //#region src/stores/session-journal-loader.store.ts
22588
+ var SessionJournalLoaderStore = class {
22589
+ constructor(metadataStore, messageProjectionStore) {
22590
+ this.metadataStore = metadataStore;
22591
+ this.messageProjectionStore = messageProjectionStore;
22592
+ }
22593
+ load = async (sessionId, path) => {
22594
+ let journalStat;
22595
+ try {
22596
+ journalStat = await stat(path);
22597
+ } catch {
22598
+ return null;
22599
+ }
22600
+ const projected = await this.messageProjectionStore.readAllSnapshot(sessionId);
22601
+ if (projected) {
22602
+ const journalTail = await this.readLastJournalState(path, journalStat.size);
22603
+ const { agentId, createdAt, updatedAt, metadata } = await this.metadataStore.read(sessionId, {
22604
+ metadata: {},
22605
+ createdAt: journalStat.birthtime.toISOString(),
22606
+ updatedAt: journalTail.updatedAt ?? journalStat.mtime.toISOString()
22607
+ });
22608
+ return {
22609
+ record: {
22610
+ sessionId,
22611
+ ...agentId ? { agentId } : {},
22612
+ messages: projected.messages,
22613
+ createdAt,
22614
+ updatedAt,
22615
+ metadata
22616
+ },
22617
+ nextSeq: journalTail.nextSeq,
22618
+ journalOffset: journalStat.size,
22619
+ projectedJournalOffset: projected.meta.projectedJournalOffset
22620
+ };
22621
+ }
22622
+ return await this.loadFromJournalStream(sessionId, path, journalStat.size);
22623
+ };
22624
+ loadFromJournalStream = async (sessionId, path, journalOffset) => {
22625
+ const supersessionTracker = new SessionReplaySupersessionTracker();
22626
+ const parsedJournal = await scanSessionJournal({
22627
+ path,
22628
+ endOffset: journalOffset,
22629
+ onEvent: (event, eventIndex) => supersessionTracker.observe(event, eventIndex)
22630
+ });
22631
+ const { agentId, createdAt, updatedAt, metadata } = await this.metadataStore.read(sessionId, parsedJournal);
22632
+ const replayer = await SessionEventReplayer.create();
22633
+ const supersededSyntheticRecoveryIndexes = supersessionTracker.finish();
22634
+ await scanSessionJournal({
22635
+ path,
22636
+ endOffset: journalOffset,
22637
+ onEvent: async (event, eventIndex) => {
22638
+ await replayer.append(event, eventIndex, supersededSyntheticRecoveryIndexes);
22639
+ }
22640
+ });
22641
+ return {
22642
+ record: {
22643
+ sessionId,
22644
+ ...agentId ? { agentId } : {},
22645
+ messages: replayer.finish(),
22646
+ createdAt,
22647
+ updatedAt,
22648
+ metadata
22649
+ },
22650
+ nextSeq: parsedJournal.nextSeq,
22651
+ journalOffset,
22652
+ projectedJournalOffset: parsedJournal.projectedJournalOffset
22653
+ };
22654
+ };
22655
+ readLastJournalState = async (path, size) => {
22656
+ if (size <= 0) return {
22657
+ nextSeq: 1,
22658
+ updatedAt: null
22659
+ };
22660
+ const file = await open(path, "r");
22661
+ const chunkBytes = 64 * 1024;
22662
+ let position = size;
22663
+ let suffix = Buffer.alloc(0);
22664
+ try {
22665
+ while (position > 0) {
22666
+ const start = Math.max(0, position - chunkBytes);
22667
+ const chunk = Buffer.alloc(position - start);
22668
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, start);
22669
+ const data = Buffer.concat([chunk.subarray(0, bytesRead), suffix]);
22670
+ let lineEnd = data.length;
22671
+ for (;;) {
22672
+ const newline = data.lastIndexOf(10, lineEnd - 1);
22673
+ if (newline < 0) break;
22674
+ const state = this.readStateFromJournalLine(data.subarray(newline + 1, lineEnd));
22675
+ if (state) return state;
22676
+ lineEnd = newline;
22677
+ }
22678
+ suffix = data.subarray(0, lineEnd);
22679
+ position = start;
22680
+ }
22681
+ return this.readStateFromJournalLine(suffix) ?? {
22682
+ nextSeq: 1,
22683
+ updatedAt: null
22684
+ };
22685
+ } finally {
22686
+ await file.close();
22687
+ }
22688
+ };
22689
+ readStateFromJournalLine = (line) => {
22690
+ if (line.length === 0) return null;
22691
+ try {
22692
+ const entry = JSON.parse(line.toString("utf-8"));
22693
+ const seq = Number(entry._type === "event" ? entry.seq : NaN);
22694
+ if (!Number.isFinite(seq)) return null;
22695
+ const updatedAt = typeof entry.timestamp === "string" && Number.isFinite(Date.parse(entry.timestamp)) ? new Date(entry.timestamp).toISOString() : null;
22696
+ return {
22697
+ nextSeq: Math.trunc(seq) + 1,
22698
+ updatedAt
22699
+ };
22700
+ } catch {
22701
+ return null;
22702
+ }
22703
+ };
22704
+ };
22705
+ //#endregion
22533
22706
  //#region src/stores/ncp-agent-session-catalog-migration.store.ts
22534
22707
  async function scanNcpAgentSessionCatalogJournals(params) {
22535
22708
  const diagnostics = [];
@@ -23021,6 +23194,7 @@ var NcpAgentSessionJournalStore = class {
23021
23194
  writeChains = /* @__PURE__ */ new Map();
23022
23195
  metadataStore;
23023
23196
  messageProjectionStore;
23197
+ journalLoaderStore;
23024
23198
  unfinishedRunStore;
23025
23199
  summaryIndexStore;
23026
23200
  summaryReadStore;
@@ -23032,6 +23206,7 @@ var NcpAgentSessionJournalStore = class {
23032
23206
  if (loaded) this.sessions.set(sessionId, loaded);
23033
23207
  return loaded;
23034
23208
  } });
23209
+ this.journalLoaderStore = new SessionJournalLoaderStore(this.metadataStore, this.messageProjectionStore);
23035
23210
  this.summaryIndexStore = new NcpAgentSessionSummaryIndexStore(journalDir, async (sessionId) => this.loadSession(sessionId), async (sessionId) => {
23036
23211
  try {
23037
23212
  const journalStat = await stat(this.sessionPath(sessionId));
@@ -23133,32 +23308,64 @@ var NcpAgentSessionJournalStore = class {
23133
23308
  };
23134
23309
  setSessionMetadataNow = async (params) => {
23135
23310
  const { metadata, sessionId } = params;
23136
- const loaded = this.sessions.get(sessionId) ?? await this.loadSession(sessionId);
23137
- if (!loaded) return false;
23311
+ let journalStat;
23312
+ try {
23313
+ journalStat = await stat(this.sessionPath(sessionId));
23314
+ } catch {
23315
+ return false;
23316
+ }
23317
+ const cached = this.sessions.get(sessionId);
23318
+ const summary = await this.summaryReadStore.get(sessionId);
23319
+ const activity = await this.metadataStore.read(sessionId, {
23320
+ metadata: {},
23321
+ createdAt: cached?.record.createdAt ?? summary?.createdAt ?? journalStat.birthtime.toISOString(),
23322
+ updatedAt: cached?.record.updatedAt ?? summary?.updatedAt ?? journalStat.mtime.toISOString()
23323
+ });
23138
23324
  const nextRecord = {
23139
- ...loaded.record,
23325
+ sessionId,
23326
+ ...activity.agentId ? { agentId: activity.agentId } : {},
23327
+ messages: [],
23328
+ createdAt: activity.createdAt,
23329
+ updatedAt: activity.updatedAt,
23140
23330
  metadata: structuredClone(metadata)
23141
23331
  };
23142
23332
  await this.metadataStore.write(nextRecord);
23143
- this.sessions.set(sessionId, {
23144
- record: nextRecord,
23145
- nextSeq: loaded.nextSeq,
23146
- journalOffset: loaded.journalOffset,
23147
- projectedJournalOffset: loaded.projectedJournalOffset
23148
- });
23149
- this.nextSeqBySession.set(sessionId, loaded.nextSeq);
23150
- await this.summaryIndexStore.upsert(createNcpAgentSessionSummary(nextRecord));
23333
+ if (cached) {
23334
+ const record = {
23335
+ ...cached.record,
23336
+ metadata: structuredClone(metadata)
23337
+ };
23338
+ this.sessions.set(sessionId, {
23339
+ ...cached,
23340
+ record
23341
+ });
23342
+ }
23343
+ await this.summaryIndexStore.upsert(summary ? {
23344
+ ...summary,
23345
+ metadata: structuredClone(metadata)
23346
+ } : createNcpAgentSessionSummary(nextRecord));
23151
23347
  return true;
23152
23348
  };
23153
23349
  updateSessionMetadataNow = async (params) => {
23154
23350
  const { sessionId, metadata, expectedMetadata } = params;
23155
- const loaded = this.sessions.get(sessionId) ?? await this.loadSession(sessionId);
23156
- if (!loaded) return false;
23157
- if (expectedMetadata && Object.entries(expectedMetadata).some(([key, value]) => loaded.record.metadata?.[key] !== value)) return false;
23351
+ let journalStat;
23352
+ try {
23353
+ journalStat = await stat(this.sessionPath(sessionId));
23354
+ } catch {
23355
+ return false;
23356
+ }
23357
+ const cached = this.sessions.get(sessionId);
23358
+ const summary = await this.summaryReadStore.get(sessionId);
23359
+ const activity = await this.metadataStore.read(sessionId, {
23360
+ metadata: {},
23361
+ createdAt: cached?.record.createdAt ?? summary?.createdAt ?? journalStat.birthtime.toISOString(),
23362
+ updatedAt: cached?.record.updatedAt ?? summary?.updatedAt ?? journalStat.mtime.toISOString()
23363
+ });
23364
+ if (expectedMetadata && Object.entries(expectedMetadata).some(([key, value]) => activity.metadata?.[key] !== value)) return false;
23158
23365
  return await this.setSessionMetadataNow({
23159
23366
  sessionId,
23160
23367
  metadata: {
23161
- ...loaded.record.metadata ? structuredClone(loaded.record.metadata) : {},
23368
+ ...structuredClone(activity.metadata),
23162
23369
  ...structuredClone(metadata)
23163
23370
  }
23164
23371
  });
@@ -23258,31 +23465,9 @@ var NcpAgentSessionJournalStore = class {
23258
23465
  });
23259
23466
  };
23260
23467
  loadSession = async (sessionId) => {
23261
- let raw;
23262
- try {
23263
- raw = await readFile(this.sessionPath(sessionId), "utf-8");
23264
- } catch {
23265
- return null;
23266
- }
23267
- const parsedJournal = parseNcpAgentSessionJournal(raw);
23268
- const { agentId, createdAt, updatedAt, metadata } = await this.metadataStore.read(sessionId, parsedJournal);
23269
- const { events, nextSeq, projectedJournalOffset } = parsedJournal;
23270
- const messages = await replayNcpAgentSessionEvents(events);
23271
- const record = {
23272
- sessionId,
23273
- ...agentId ? { agentId } : {},
23274
- messages,
23275
- createdAt,
23276
- updatedAt,
23277
- metadata
23278
- };
23279
- this.nextSeqBySession.set(sessionId, nextSeq);
23280
- return {
23281
- record,
23282
- nextSeq,
23283
- journalOffset: Buffer.byteLength(raw, "utf-8"),
23284
- projectedJournalOffset
23285
- };
23468
+ const loaded = await this.journalLoaderStore.load(sessionId, this.sessionPath(sessionId));
23469
+ if (loaded) this.nextSeqBySession.set(sessionId, loaded.nextSeq);
23470
+ return loaded;
23286
23471
  };
23287
23472
  appendJournalEntry = async (path, entry) => {
23288
23473
  await appendFile(path, `${serializeNcpAgentSessionJournalEntry(entry)}\n`, "utf-8");
@@ -24809,7 +24994,7 @@ var ReplyFormatContextProvider = class {
24809
24994
  "Visualization gate: for an explicit visualization/chart/diagram/timeline/dashboard/status-result view, the FIRST tool call MUST be `read_file` for the built-in `visualize-output` SKILL.md; also read it before a strong implicit visual candidate. Data fidelity: use only supported facts and mathematics, calculate derived values with a tool, verify the artifact, apply no unsupplied threshold or qualitative label, and add no unsupported cause, recommendation, benchmark, target, forecast, or effect. For summary-only requests, stop at what the data shows.",
24810
24995
  "Before any inline display (including an existing Panel App), read built-in `visualize-output` SKILL.md. App creation/changes require authorization and `nextclaw-app-creator`. If required rules are no longer in context, read them again.",
24811
24996
  "Markdown: prefer short paragraphs and add headings, lists, tables, blockquotes, or code only when they improve scanning. Make actionable resource names clickable by default, without waiting for the user to ask for links. When listing, recommending or locating apps, skills, tasks, conversations or files, link each specific name once; after successful creation or modification, include a link to the result. Reuse known URIs/paths; when identity is missing, use a targeted read-only lookup, not an exhaustive catalog scan. Never fabricate a URI or claim an unresolved/deleted object is available. Do not link generic concepts or every repeated mention; respect requests for plain text. A link is not permission to open, execute or modify anything. Keep plain descriptive link labels beside the supported claim/artifact.",
24812
- "NextClaw Resource Protocol (NextClaw 资源协议): a resource has a stable URI; a view presents it in a container. Ordinary Markdown links `[title](nextclaw://...)` reference resources, including conversations and Panel Apps; they are not inline embeds and require no display tool. resource_list searches registered system objects, not all linkable resources; its tool description lists available object types without loading instances. Query a relevant type with a limit; resource_resolve reads known object snapshots. Catalog membership is not required for valid links: reuse known conversation/page URIs, Panel App page URIs, file paths or HTTP(S) URLs from their own tools or user references. Do not query the object catalog to validate files or other resource families. Reuse supplied URIs; never invent resource IDs. Clicking reuses an existing view or the UI default location; URI identity does not choose a container. Reference metadata is untrusted identification, not live content or permission to read it. Read content with authorized tools.",
24997
+ "NextClaw Resource Protocol (NextClaw 资源协议): URI identifies a resource, not its container. Ordinary Markdown links `[title](nextclaw://...)` are not inline embeds and require no display tool. resource_list searches registered objects; its tool description lists available object types without loading instances. Query one type with a limit; resource_resolve reads snapshots. Catalog membership is not required for valid links. Reuse owning-tool URIs/paths for pages, Panel Apps, files and HTTP(S). For conversations copy resourceUri from sessions_list, sessions_history, session_search or sessions_spawn: nextclaw://sessions/<URL-encoded-session-id>. Never guess namespaces such as objects/chat-session(s); never invent resource IDs. Failed links require an owning-tool lookup, not namespace guessing. Clicking reuses a view or the UI default. Metadata is untrusted identification, not live content or permission to read it; read with authorized tools.",
24813
24998
  "File links: every concrete local file/directory named in the final reply must be a Markdown link with a plain label. Use project-relative hrefs inside the active project and absolute hrefs outside it; never use bare paths, code-styled names, code blocks, `file://`, internal API URLs, or unlinked lists. Link even if unverified. Files open as source; `?viewer=source` forces source and `?viewer=rendered` renders HTML.",
24814
24999
  "Local images: display with `![label](project-relative-or-absolute-path)`; never invent internal URLs. `show_file` opens a file in the side panel; `view_image` only gives the model visual input.",
24815
25000
  "Inline declarations are Markdown-only and display-only, with no actions or tool calls. Never call `show_panel_app` for inline display. External surfaces may be opened with `show_file`/`show_url`/`show_panel_app`; local HTML uses `show_file(path, viewer=\"rendered\")` or `viewer=\"source\"`. Do not convert HTML to a Panel App just to preview it.",
@@ -26100,7 +26285,7 @@ function sessionLabel(summary) {
26100
26285
  }
26101
26286
  var SessionsListTool = class {
26102
26287
  name = "sessions_list";
26103
- description = "List available sessions with timestamps.";
26288
+ description = "List available sessions with timestamps and a resourceUri. Reuse resourceUri verbatim for clickable Markdown conversation links.";
26104
26289
  parameters = {
26105
26290
  type: "object",
26106
26291
  properties: {
@@ -26134,6 +26319,7 @@ var SessionsListTool = class {
26134
26319
  const entry = {
26135
26320
  key: summary.sessionId,
26136
26321
  sessionId: summary.sessionId,
26322
+ resourceUri: createSessionResourceUri(summary.sessionId),
26137
26323
  agentId: summary.agentId,
26138
26324
  label: sessionLabel(summary),
26139
26325
  createdAt: summary.createdAt,
@@ -26182,6 +26368,7 @@ var SessionsHistoryTool = class {
26182
26368
  const filtered = includeTools === true ? messages : messages.filter((message) => message.role !== "tool");
26183
26369
  return JSON.stringify({
26184
26370
  sessionKey: session.sessionId,
26371
+ resourceUri: createSessionResourceUri(session.sessionId),
26185
26372
  messages: capHistory(filtered.slice(-toInt(limit, DEFAULT_LIMIT)).map(sanitizeMessage))
26186
26373
  }, null, 2);
26187
26374
  };
@@ -26332,12 +26519,19 @@ var SessionSearchTool = class {
26332
26519
  if (!isRecord$3(args)) throw new Error("session_search requires an object argument.");
26333
26520
  const issues = this.validateArgs(args);
26334
26521
  if (issues.length > 0) throw new Error(issues.join(" "));
26335
- return this.queryService.search({
26522
+ const result = await this.queryService.search({
26336
26523
  query: normalizeString$1(args.query) ?? "",
26337
26524
  limit: readOptionalInteger(args.limit),
26338
26525
  includeCurrentSession: readOptionalBoolean(args.includeCurrentSession),
26339
26526
  currentSessionId: this.context.currentSessionId
26340
26527
  });
26528
+ return {
26529
+ ...result,
26530
+ hits: result.hits.map((hit) => ({
26531
+ ...hit,
26532
+ resourceUri: createSessionResourceUri(hit.sessionId)
26533
+ }))
26534
+ };
26341
26535
  };
26342
26536
  };
26343
26537
  //#endregion
@@ -26462,22 +26656,28 @@ var SessionSpawnTool = class {
26462
26656
  const parentSessionId = scope === "child" ? this.readParentSessionIdOrThrow() : void 0;
26463
26657
  const contextInheritance = inheritContext ? { anchorToolCallId: toolCallId } : void 0;
26464
26658
  const trigger = attachSourceToolCall(this.readTriggerOrThrow(), toolCallId);
26465
- if (start) return this.sessionRequestManager.spawnSessionAndRequest({
26466
- sourceSessionId: this.sourceSessionId,
26467
- sourceToolCallId: toolCallId,
26468
- sourceSessionMetadata: this.sourceSessionMetadata,
26469
- task,
26470
- title: readOptionalString$5(rawTitle),
26471
- agentId: readOptionalString$5(rawAgentId),
26472
- model: readOptionalString$5(rawModel),
26473
- runtime: readOptionalString$5(rawRuntime),
26474
- contextInheritance,
26475
- handoffDepth: this.handoffDepth,
26476
- parentSessionId,
26477
- notify,
26478
- wait,
26479
- trigger
26480
- });
26659
+ if (start) {
26660
+ const result = await this.sessionRequestManager.spawnSessionAndRequest({
26661
+ sourceSessionId: this.sourceSessionId,
26662
+ sourceToolCallId: toolCallId,
26663
+ sourceSessionMetadata: this.sourceSessionMetadata,
26664
+ task,
26665
+ title: readOptionalString$5(rawTitle),
26666
+ agentId: readOptionalString$5(rawAgentId),
26667
+ model: readOptionalString$5(rawModel),
26668
+ runtime: readOptionalString$5(rawRuntime),
26669
+ contextInheritance,
26670
+ handoffDepth: this.handoffDepth,
26671
+ parentSessionId,
26672
+ notify,
26673
+ wait,
26674
+ trigger
26675
+ });
26676
+ return {
26677
+ ...result,
26678
+ resourceUri: createSessionResourceUri(result.sessionId)
26679
+ };
26680
+ }
26481
26681
  const session = await this.sessionManager.createSession({
26482
26682
  sourceSessionId: this.sourceSessionId,
26483
26683
  task,
@@ -26493,6 +26693,7 @@ var SessionSpawnTool = class {
26493
26693
  return {
26494
26694
  kind: "nextclaw.session",
26495
26695
  sessionId: session.sessionId,
26696
+ resourceUri: createSessionResourceUri(session.sessionId),
26496
26697
  agentId: session.agentId,
26497
26698
  parentSessionId: session.parentSessionId,
26498
26699
  isChildSession: Boolean(session.parentSessionId),