nexum-code 0.13.5 → 0.14.7

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.
@@ -6,7 +6,7 @@ const __dirname = __cjsShimDirname(__filename);
6
6
  import { i as __require, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk-D90kvbyJ.mjs";
7
7
  import { C as join$1, D as resolve$1, E as relative$1, S as isAbsolute$1, T as parse$7, a as isSupportedFile, b as basename$1, i as ingestFile, r as ingestDirectory, t as multiSearch, w as normalize, x as dirname$2, y as KnowledgeStore } from "./src-BH9W5k24.mjs";
8
8
  import { t as require_base64_js } from "./base64-js-DzVmk6Nb.mjs";
9
- import { a as setLocale, i as getLocale, n as assertNexumHostIdentity, o as t, r as createNexumDefaultHeaders, t as TextInputDialogComponent } from "./text-input-dialog-Bncn0-6m.mjs";
9
+ import { a as setLocale, i as getLocale, n as assertNexumHostIdentity, o as t, r as createNexumDefaultHeaders, t as TextInputDialogComponent } from "./text-input-dialog-DL5a0FC3.mjs";
10
10
  import { createRequire } from "node:module";
11
11
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
12
12
  import * as fs$1 from "node:fs/promises";
@@ -9277,7 +9277,8 @@ var AnthropicChatProvider = class {
9277
9277
  return new Anthropic({
9278
9278
  apiKey,
9279
9279
  baseURL: this._baseUrl,
9280
- defaultHeaders: this._defaultHeaders
9280
+ defaultHeaders: this._defaultHeaders,
9281
+ maxRetries: 0
9281
9282
  });
9282
9283
  }
9283
9284
  withThinking(effort) {
@@ -10412,7 +10413,7 @@ var require_gaxios = /* @__PURE__ */ __commonJSMin(((exports) => {
10412
10413
  * @returns A proxy agent
10413
10414
  */
10414
10415
  static async #getProxyAgent() {
10415
- this.#proxyAgent ||= (await import("./dist-AcjRoBBn.mjs").then((m) => /* @__PURE__ */ __toESM(m.default))).HttpsProxyAgent;
10416
+ this.#proxyAgent ||= (await import("./dist-CFFnObvk.mjs").then((m) => /* @__PURE__ */ __toESM(m.default))).HttpsProxyAgent;
10416
10417
  return this.#proxyAgent;
10417
10418
  }
10418
10419
  static async #getFetch() {
@@ -44633,7 +44634,8 @@ var NexumFiles = class {
44633
44634
  this._client = options.apiKey === void 0 || options.apiKey.length === 0 ? void 0 : new OpenAI({
44634
44635
  apiKey: options.apiKey,
44635
44636
  baseURL: options.baseUrl,
44636
- defaultHeaders: options.defaultHeaders
44637
+ defaultHeaders: options.defaultHeaders,
44638
+ maxRetries: 0
44637
44639
  });
44638
44640
  }
44639
44641
  /**
@@ -44692,7 +44694,8 @@ var NexumFiles = class {
44692
44694
  return new OpenAI({
44693
44695
  apiKey: requireProviderApiKey("NexumFiles.uploadVideo", a, this._apiKey),
44694
44696
  baseURL: this._baseUrl,
44695
- defaultHeaders
44697
+ defaultHeaders,
44698
+ maxRetries: 0
44696
44699
  });
44697
44700
  });
44698
44701
  }
@@ -44961,7 +44964,8 @@ var NexumChatProvider = class {
44961
44964
  this._client = this._apiKey === void 0 ? void 0 : new OpenAI({
44962
44965
  apiKey: this._apiKey,
44963
44966
  baseURL: this._baseUrl,
44964
- defaultHeaders: this._defaultHeaders
44967
+ defaultHeaders: this._defaultHeaders,
44968
+ maxRetries: 0
44965
44969
  });
44966
44970
  }
44967
44971
  get modelName() {
@@ -45077,7 +45081,8 @@ var NexumChatProvider = class {
45077
45081
  return new OpenAI({
45078
45082
  apiKey: requireProviderApiKey("NexumChatProvider", a, this._apiKey),
45079
45083
  baseURL: this._baseUrl,
45080
- defaultHeaders
45084
+ defaultHeaders,
45085
+ maxRetries: 0
45081
45086
  });
45082
45087
  });
45083
45088
  }
@@ -45346,7 +45351,8 @@ var OpenAILegacyChatProvider = class {
45346
45351
  _buildClient(apiKey, auth) {
45347
45352
  const clientOpts = {
45348
45353
  apiKey,
45349
- baseURL: this._baseUrl
45354
+ baseURL: this._baseUrl,
45355
+ maxRetries: 0
45350
45356
  };
45351
45357
  const defaultHeaders = mergeRequestHeaders(this._defaultHeaders, auth?.headers);
45352
45358
  if (defaultHeaders !== void 0) clientOpts["defaultHeaders"] = defaultHeaders;
@@ -45993,7 +45999,8 @@ var OpenAIResponsesChatProvider = class {
45993
45999
  _buildClient(apiKey, auth) {
45994
46000
  const clientOpts = {
45995
46001
  apiKey,
45996
- baseURL: this._baseUrl
46002
+ baseURL: this._baseUrl,
46003
+ maxRetries: 0
45997
46004
  };
45998
46005
  const defaultHeaders = mergeRequestHeaders(this._defaultHeaders, auth?.headers);
45999
46006
  if (defaultHeaders !== void 0) clientOpts["defaultHeaders"] = defaultHeaders;
@@ -47334,6 +47341,236 @@ function resolveGlobalLogPath(homeDir) {
47334
47341
  return join$1(homeDir, "logs", "nexum-code.log");
47335
47342
  }
47336
47343
  //#endregion
47344
+ //#region ../../node_modules/.pnpm/@antfu+utils@9.3.0/node_modules/@antfu/utils/dist/index.mjs
47345
+ function uniq(array) {
47346
+ return Array.from(new Set(array));
47347
+ }
47348
+ function notNullish(v) {
47349
+ return v != null;
47350
+ }
47351
+ function objectMap(obj, fn) {
47352
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish));
47353
+ }
47354
+ function sleep$1(ms, callback) {
47355
+ return new Promise((resolve) => setTimeout(async () => {
47356
+ await callback?.();
47357
+ resolve();
47358
+ }, ms));
47359
+ }
47360
+ function createControlledPromise() {
47361
+ let resolve, reject;
47362
+ const promise = new Promise((_resolve, _reject) => {
47363
+ resolve = _resolve;
47364
+ reject = _reject;
47365
+ });
47366
+ promise.resolve = resolve;
47367
+ promise.reject = reject;
47368
+ return promise;
47369
+ }
47370
+ //#endregion
47371
+ //#region ../../packages/agent-core/src/utils/abort.ts
47372
+ function abortError() {
47373
+ const error = /* @__PURE__ */ new Error("Aborted");
47374
+ error.name = "AbortError";
47375
+ return error;
47376
+ }
47377
+ /**
47378
+ * Marks an abort the user triggered deliberately (e.g. pressing ESC to
47379
+ * interrupt the agent), as distinct from a timeout, an internal error, or any
47380
+ * other programmatic abort. It travels as the AbortSignal's `reason`, so code
47381
+ * that settles an interrupted operation can tell a user interruption apart from
47382
+ * a failure and report it to the model accordingly instead of emitting a
47383
+ * neutral "was aborted" that the model mistakes for a system problem.
47384
+ *
47385
+ * `name` stays 'AbortError' so existing `isAbortError()` checks (and
47386
+ * `AbortSignal.throwIfAborted()`) keep treating it as an abort.
47387
+ */
47388
+ var UserCancellationError = class extends Error {
47389
+ userCancelled = true;
47390
+ constructor() {
47391
+ super("Aborted by the user");
47392
+ this.name = "AbortError";
47393
+ }
47394
+ };
47395
+ function userCancellationReason() {
47396
+ return new UserCancellationError();
47397
+ }
47398
+ function isUserCancellation(value) {
47399
+ return value instanceof UserCancellationError;
47400
+ }
47401
+ function abortable(promise, signal) {
47402
+ signal.throwIfAborted();
47403
+ return new Promise((resolve, reject) => {
47404
+ const onAbort = () => {
47405
+ reject(abortError());
47406
+ };
47407
+ signal.addEventListener("abort", onAbort, { once: true });
47408
+ promise.then(resolve, reject).finally(() => {
47409
+ signal.removeEventListener("abort", onAbort);
47410
+ });
47411
+ });
47412
+ }
47413
+ function linkAbortSignal(source, target) {
47414
+ const onAbort = () => {
47415
+ target.abort(source.reason);
47416
+ };
47417
+ if (source.aborted) {
47418
+ onAbort();
47419
+ return () => {};
47420
+ }
47421
+ source.addEventListener("abort", onAbort, { once: true });
47422
+ return () => {
47423
+ source.removeEventListener("abort", onAbort);
47424
+ };
47425
+ }
47426
+ function createDeadlineAbortSignal(source, timeoutMs) {
47427
+ const controller = new AbortController();
47428
+ const unlinkAbortSignal = linkAbortSignal(source, controller);
47429
+ let didTimeout = false;
47430
+ let timeout = setTimeout(() => {
47431
+ didTimeout = true;
47432
+ controller.abort(abortError());
47433
+ }, timeoutMs);
47434
+ return {
47435
+ signal: controller.signal,
47436
+ timedOut: () => didTimeout,
47437
+ clear: () => {
47438
+ if (timeout !== void 0) clearTimeout(timeout);
47439
+ timeout = void 0;
47440
+ unlinkAbortSignal();
47441
+ }
47442
+ };
47443
+ }
47444
+ //#endregion
47445
+ //#region ../../packages/agent-core/src/loop/errors.ts
47446
+ /**
47447
+ * Loop-local error helpers.
47448
+ */
47449
+ function createMaxStepsExceededError(maxSteps, message) {
47450
+ return new NexumError(ErrorCodes.LOOP_MAX_STEPS_EXCEEDED, message ?? `Turn exceeded maxSteps=${maxSteps}`, { details: { maxSteps } });
47451
+ }
47452
+ function isMaxStepsExceededError(error) {
47453
+ return isNexumError(error) && error.code === ErrorCodes.LOOP_MAX_STEPS_EXCEEDED;
47454
+ }
47455
+ function isAbortError$1(err) {
47456
+ if (err instanceof Error) return err.name === "AbortError";
47457
+ return false;
47458
+ }
47459
+ function errorMessage$4(err) {
47460
+ if (err instanceof Error) return err.message;
47461
+ return String(err);
47462
+ }
47463
+ const BASE_DELAY_MS = 500;
47464
+ const MAX_DELAY_MS = 32e3;
47465
+ const RETRY_FACTOR = 2;
47466
+ const JITTER_FACTOR = .25;
47467
+ async function chatWithRetry(input) {
47468
+ const maxAttempts = input.maxAttempts ?? 10;
47469
+ if (input.llm.isRetryableError === void 0 || maxAttempts <= 1) {
47470
+ const effectiveMaxAttempts = Math.max(maxAttempts, 1);
47471
+ try {
47472
+ return await input.llm.chat(paramsForAttempt(input, 1, effectiveMaxAttempts));
47473
+ } catch (error) {
47474
+ logRequestFailure(input, error, 1, effectiveMaxAttempts);
47475
+ throw error;
47476
+ }
47477
+ }
47478
+ const delays = retryBackoffDelays(maxAttempts);
47479
+ for (let attempt = 1;; attempt += 1) try {
47480
+ return await input.llm.chat(paramsForAttempt(input, attempt, maxAttempts));
47481
+ } catch (error) {
47482
+ if (error instanceof APIContextOverflowError) {
47483
+ logRequestFailure(input, error, attempt, maxAttempts);
47484
+ throw error;
47485
+ }
47486
+ if (error instanceof APIProviderRateLimitError && error.reason === "QUOTA_EXHAUSTED") {
47487
+ logRequestFailure(input, error, attempt, maxAttempts);
47488
+ throw error;
47489
+ }
47490
+ if (attempt >= maxAttempts || !input.llm.isRetryableError(error)) {
47491
+ logRequestFailure(input, error, attempt, maxAttempts);
47492
+ throw error;
47493
+ }
47494
+ const delayMs = computeDelayMs(error, delays, attempt);
47495
+ input.params.signal.throwIfAborted();
47496
+ input.dispatchEvent({
47497
+ type: "step.retrying",
47498
+ turnId: input.turnId,
47499
+ step: input.currentStep,
47500
+ stepUuid: input.stepUuid,
47501
+ failedAttempt: attempt,
47502
+ nextAttempt: attempt + 1,
47503
+ maxAttempts,
47504
+ delayMs,
47505
+ ...retryErrorFields(error)
47506
+ });
47507
+ await sleepForRetry(delayMs, input.params.signal);
47508
+ }
47509
+ }
47510
+ function computeDelayMs(error, delays, attempt) {
47511
+ const retryAfter = readRetryAfterMs(error);
47512
+ if (retryAfter !== null) return retryAfter;
47513
+ if (error instanceof APIProviderRateLimitError) return calculateRateLimitBackoffMs(error.reason);
47514
+ return delays[attempt - 1] ?? 0;
47515
+ }
47516
+ /**
47517
+ * Server-requested backoff carried on an `APIStatusError` (parsed from
47518
+ * the `Retry-After` response header). When present and positive it
47519
+ * overrides the computed backoff - a server `Retry-After` directive
47520
+ * takes precedence over the local exponential delay.
47521
+ */
47522
+ function readRetryAfterMs(error) {
47523
+ if (typeof error !== "object" || error === null) return null;
47524
+ const value = error.retryAfterMs;
47525
+ return typeof value === "number" && value > 0 ? value : null;
47526
+ }
47527
+ function logRequestFailure(input, error, attempt, maxAttempts) {
47528
+ if (isAbortError$1(error) || input.params.signal.aborted) return;
47529
+ input.log?.warn("llm request failed", {
47530
+ turnStep: `${input.turnId}.${String(input.currentStep)}`,
47531
+ attempt: `${String(attempt)}/${String(maxAttempts)}`,
47532
+ model: input.llm.modelName,
47533
+ ...retryErrorFields(error)
47534
+ });
47535
+ }
47536
+ function paramsForAttempt(input, attempt, maxAttempts) {
47537
+ return {
47538
+ ...input.params,
47539
+ requestLogContext: {
47540
+ turnId: input.turnId,
47541
+ step: input.currentStep,
47542
+ stepUuid: input.stepUuid,
47543
+ attempt,
47544
+ maxAttempts
47545
+ }
47546
+ };
47547
+ }
47548
+ function retryBackoffDelays(maxAttempts) {
47549
+ const count = Math.max(maxAttempts - 1, 0);
47550
+ const delays = [];
47551
+ for (let i = 0; i < count; i += 1) {
47552
+ const base = Math.min(BASE_DELAY_MS * Math.pow(RETRY_FACTOR, i), MAX_DELAY_MS);
47553
+ delays.push(base + Math.random() * JITTER_FACTOR * base);
47554
+ }
47555
+ return delays;
47556
+ }
47557
+ async function sleepForRetry(delayMs, signal) {
47558
+ signal.throwIfAborted();
47559
+ await abortable(sleep$1(delayMs), signal);
47560
+ }
47561
+ function retryErrorFields(error) {
47562
+ return {
47563
+ errorName: error instanceof Error ? error.name : typeof error,
47564
+ errorMessage: error instanceof Error ? error.message : String(error),
47565
+ statusCode: maybeStatusCode(error)
47566
+ };
47567
+ }
47568
+ function maybeStatusCode(error) {
47569
+ if (typeof error !== "object" || error === null) return void 0;
47570
+ const statusCode = error.statusCode;
47571
+ return typeof statusCode === "number" ? statusCode : void 0;
47572
+ }
47573
+ //#endregion
47337
47574
  //#region ../../packages/agent-core/src/utils/tokens.ts
47338
47575
  /**
47339
47576
  * WeakMap cache for per-message token estimates. Messages are immutable once
@@ -47390,25 +47627,6 @@ function estimateTokensForContentPart(part) {
47390
47627
  return 0;
47391
47628
  }
47392
47629
  //#endregion
47393
- //#region ../../packages/agent-core/src/loop/errors.ts
47394
- /**
47395
- * Loop-local error helpers.
47396
- */
47397
- function createMaxStepsExceededError(maxSteps, message) {
47398
- return new NexumError(ErrorCodes.LOOP_MAX_STEPS_EXCEEDED, message ?? `Turn exceeded maxSteps=${maxSteps}`, { details: { maxSteps } });
47399
- }
47400
- function isMaxStepsExceededError(error) {
47401
- return isNexumError(error) && error.code === ErrorCodes.LOOP_MAX_STEPS_EXCEEDED;
47402
- }
47403
- function isAbortError$1(err) {
47404
- if (err instanceof Error) return err.name === "AbortError";
47405
- return false;
47406
- }
47407
- function errorMessage$4(err) {
47408
- if (err instanceof Error) return err.message;
47409
- return String(err);
47410
- }
47411
- //#endregion
47412
47630
  //#region ../../packages/agent-core/src/utils/per-id-json-store.ts
47413
47631
  /**
47414
47632
  * Per-id JSON record store — write each value as `<rootDir>/<subdir>/<id>.json`.
@@ -51667,80 +51885,6 @@ function normalizePath$1(path) {
51667
51885
  return folded;
51668
51886
  }
51669
51887
  //#endregion
51670
- //#region ../../packages/agent-core/src/utils/abort.ts
51671
- function abortError() {
51672
- const error = /* @__PURE__ */ new Error("Aborted");
51673
- error.name = "AbortError";
51674
- return error;
51675
- }
51676
- /**
51677
- * Marks an abort the user triggered deliberately (e.g. pressing ESC to
51678
- * interrupt the agent), as distinct from a timeout, an internal error, or any
51679
- * other programmatic abort. It travels as the AbortSignal's `reason`, so code
51680
- * that settles an interrupted operation can tell a user interruption apart from
51681
- * a failure and report it to the model accordingly instead of emitting a
51682
- * neutral "was aborted" that the model mistakes for a system problem.
51683
- *
51684
- * `name` stays 'AbortError' so existing `isAbortError()` checks (and
51685
- * `AbortSignal.throwIfAborted()`) keep treating it as an abort.
51686
- */
51687
- var UserCancellationError = class extends Error {
51688
- userCancelled = true;
51689
- constructor() {
51690
- super("Aborted by the user");
51691
- this.name = "AbortError";
51692
- }
51693
- };
51694
- function userCancellationReason() {
51695
- return new UserCancellationError();
51696
- }
51697
- function isUserCancellation(value) {
51698
- return value instanceof UserCancellationError;
51699
- }
51700
- function abortable(promise, signal) {
51701
- signal.throwIfAborted();
51702
- return new Promise((resolve, reject) => {
51703
- const onAbort = () => {
51704
- reject(abortError());
51705
- };
51706
- signal.addEventListener("abort", onAbort, { once: true });
51707
- promise.then(resolve, reject).finally(() => {
51708
- signal.removeEventListener("abort", onAbort);
51709
- });
51710
- });
51711
- }
51712
- function linkAbortSignal(source, target) {
51713
- const onAbort = () => {
51714
- target.abort(source.reason);
51715
- };
51716
- if (source.aborted) {
51717
- onAbort();
51718
- return () => {};
51719
- }
51720
- source.addEventListener("abort", onAbort, { once: true });
51721
- return () => {
51722
- source.removeEventListener("abort", onAbort);
51723
- };
51724
- }
51725
- function createDeadlineAbortSignal(source, timeoutMs) {
51726
- const controller = new AbortController();
51727
- const unlinkAbortSignal = linkAbortSignal(source, controller);
51728
- let didTimeout = false;
51729
- let timeout = setTimeout(() => {
51730
- didTimeout = true;
51731
- controller.abort(abortError());
51732
- }, timeoutMs);
51733
- return {
51734
- signal: controller.signal,
51735
- timedOut: () => didTimeout,
51736
- clear: () => {
51737
- if (timeout !== void 0) clearTimeout(timeout);
51738
- timeout = void 0;
51739
- unlinkAbortSignal();
51740
- }
51741
- };
51742
- }
51743
- //#endregion
51744
51888
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/agent-background-disabled.md
51745
51889
  var agent_background_disabled_default = "Background agent execution is disabled for this agent. Do not set `run_in_background=true`.";
51746
51890
  //#endregion
@@ -54956,7 +55100,7 @@ var LspClient = class {
54956
55100
  while (Date.now() - start < timeoutMs) {
54957
55101
  const collected = this.collectedDiagnostics.get(uri);
54958
55102
  if (collected !== void 0) return collected;
54959
- await sleep$1(100);
55103
+ await sleep(100);
54960
55104
  }
54961
55105
  return this.collectedDiagnostics.get(uri) ?? [];
54962
55106
  }
@@ -55058,7 +55202,7 @@ function uriToPath(uri) {
55058
55202
  if (process.platform === "win32" && filePath.startsWith("/") && /^[A-Za-z]:/.test(filePath.slice(1))) filePath = filePath.slice(1);
55059
55203
  return filePath;
55060
55204
  }
55061
- function sleep$1(ms) {
55205
+ function sleep(ms) {
55062
55206
  return new Promise((resolve) => {
55063
55207
  setTimeout(resolve, ms);
55064
55208
  });
@@ -59584,7 +59728,8 @@ const DOCUMENTATION_MARKDOWN_LOWER$1 = new Set([
59584
59728
  "code_of_conduct.md",
59585
59729
  "architecture.md",
59586
59730
  "design.md",
59587
- "notes.md"
59731
+ "notes.md",
59732
+ "agents.md"
59588
59733
  ]);
59589
59734
  async function resolveSkillRoots(options) {
59590
59735
  const isDir = options.isDir ?? defaultIsDir;
@@ -70217,7 +70362,23 @@ function renderPrompt(template, vars) {
70217
70362
  }
70218
70363
  //#endregion
70219
70364
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/skill-tool.md
70220
- var skill_tool_default = "Invoke a registered skill from the current skill listing. BLOCKING REQUIREMENT: when a skill from the listing matches the user's request, you MUST call this tool (not free-form text). Do NOT call the same skill repeatedly inside one turn — recursive depth is capped at {{ MAX_SKILL_QUERY_DEPTH }}.";
70365
+ var skill_tool_default = "Invoke a registered skill from the current skill listing. BLOCKING REQUIREMENT: when a skill from the listing matches the user's request, you MUST call this tool (not free-form text). Do NOT call the same skill repeatedly inside one turn — recursive depth is capped at {{ MAX_SKILL_QUERY_DEPTH }}.\r\n\r\n## Currently model-invocable skills\r\n{{ AVAILABLE_SKILLS }}\r\nThis list is a construction-time snapshot; for the live catalog inspect the skill registry.\r\n\r\n## Matching guide\r\n\r\n- A skill matches when the user's request involves the scenarios/trigger conditions listed in the skill's \"When to use\" line.\r\n- Look for: (a) keywords in the user's request that match the skill's trigger phrases, (b) the task type or scenario described in the skill's \"When to use\", (c) similar requests the skill was designed for.\r\n- If a skill seems relevant, invoke it first — if it doesn't fit, you can always fall back to doing it yourself.\r\n";
70366
+ /** Max skills to list inline in the tool description; rest are summarized. */
70367
+ const MAX_INLINE_SKILLS = 15;
70368
+ /** Max description length per skill line. */
70369
+ const MAX_SKILL_DESC_CHARS = 100;
70370
+ function buildSkillToolDescription(agent) {
70371
+ const skills = agent.skills?.registry.listInvocableSkills() ?? [];
70372
+ const lines = skills.slice(0, MAX_INLINE_SKILLS).map((s) => {
70373
+ const desc = s.description.trim().replaceAll("\n", " ").slice(0, MAX_SKILL_DESC_CHARS);
70374
+ return `- ${s.name}: ${desc}`;
70375
+ });
70376
+ if (skills.length > MAX_INLINE_SKILLS) lines.push(`…${String(skills.length - MAX_INLINE_SKILLS)} more (see skill registry)`);
70377
+ return renderPrompt(skill_tool_default, {
70378
+ MAX_SKILL_QUERY_DEPTH: 3,
70379
+ AVAILABLE_SKILLS: lines.length > 0 ? lines.join("\n") : "(none currently registered)"
70380
+ });
70381
+ }
70221
70382
  var NestedSkillTooDeepError = class extends Error {
70222
70383
  skillName;
70223
70384
  depth;
@@ -70237,11 +70398,12 @@ var SkillTool = class SkillTool {
70237
70398
  agent;
70238
70399
  options;
70239
70400
  name = "Skill";
70240
- description = renderPrompt(skill_tool_default, { MAX_SKILL_QUERY_DEPTH: 3 });
70401
+ description;
70241
70402
  parameters = toInputJsonSchema(SkillToolInputSchema);
70242
70403
  constructor(agent, options = {}) {
70243
70404
  this.agent = agent;
70244
70405
  this.options = options;
70406
+ this.description = buildSkillToolDescription(agent);
70245
70407
  }
70246
70408
  resolveExecution(args) {
70247
70409
  return {
@@ -71950,7 +72112,6 @@ const BARE_SKILL_PATH = "SKILL.md";
71950
72112
  const UNSUPPORTED_RUNTIME_FIELDS = [
71951
72113
  "tools",
71952
72114
  "commands",
71953
- "hooks",
71954
72115
  "apps",
71955
72116
  "inject",
71956
72117
  "configFile",
@@ -72047,7 +72208,10 @@ async function parseManifest(pluginRoot) {
72047
72208
  if (await isFile$1(path.join(pluginRoot, "SKILL.md"))) skills = [pluginRoot];
72048
72209
  }
72049
72210
  const skillInstructions = typeof raw["skillInstructions"] === "string" ? raw["skillInstructions"] : void 0;
72211
+ const config = typeof raw["config"] === "object" && raw["config"] !== null && !Array.isArray(raw["config"]) ? raw["config"] : void 0;
72050
72212
  recordUnsupportedRuntimeFields(raw, diagnostics);
72213
+ const entryPoint = await readEntryPoint(pluginRoot, raw["entryPoint"], diagnostics);
72214
+ const hooks = readHooks(pluginRoot, raw["hooks"], diagnostics);
72051
72215
  return {
72052
72216
  manifest: {
72053
72217
  name,
@@ -72061,7 +72225,10 @@ async function parseManifest(pluginRoot) {
72061
72225
  sessionStart: readSessionStart(raw["sessionStart"], diagnostics),
72062
72226
  mcpServers: await readMcpServers(pluginRoot, raw["mcpServers"], diagnostics),
72063
72227
  interface: readInterface(raw["interface"]),
72064
- skillInstructions
72228
+ skillInstructions,
72229
+ config,
72230
+ entryPoint,
72231
+ hooks
72065
72232
  },
72066
72233
  manifestKind,
72067
72234
  manifestPath,
@@ -72078,6 +72245,75 @@ function recordUnsupportedRuntimeFields(raw, diagnostics) {
72078
72245
  });
72079
72246
  }
72080
72247
  }
72248
+ async function readEntryPoint(pluginRoot, raw, diagnostics) {
72249
+ if (raw === void 0) return void 0;
72250
+ if (typeof raw !== "string") {
72251
+ diagnostics.push({
72252
+ severity: "warn",
72253
+ message: "\"entryPoint\" must be a string"
72254
+ });
72255
+ return;
72256
+ }
72257
+ return resolvePluginPathField({
72258
+ pluginRoot,
72259
+ field: "entryPoint",
72260
+ value: raw,
72261
+ diagnostics
72262
+ });
72263
+ }
72264
+ /**
72265
+ * Parse a plugin's declared hooks (external-command HookEngine channel). Each
72266
+ * entry mirrors {@link HookDef}: event, optional matcher, command (a `./`
72267
+ * relative command is resolved against the plugin root), optional timeout.
72268
+ * Unknown event names are kept (cast): they can never match a HookEngine
72269
+ * trigger, so they are inert rather than harmful.
72270
+ */
72271
+ function readHooks(pluginRoot, raw, diagnostics) {
72272
+ if (raw === void 0) return void 0;
72273
+ if (!Array.isArray(raw)) {
72274
+ diagnostics.push({
72275
+ severity: "warn",
72276
+ message: "\"hooks\" must be an array"
72277
+ });
72278
+ return;
72279
+ }
72280
+ const out = [];
72281
+ for (const entry of raw) {
72282
+ if (!isObject(entry)) {
72283
+ diagnostics.push({
72284
+ severity: "warn",
72285
+ message: "\"hooks\" entries must be objects"
72286
+ });
72287
+ continue;
72288
+ }
72289
+ const event = stringField$1(entry, "event");
72290
+ if (event === void 0) {
72291
+ diagnostics.push({
72292
+ severity: "warn",
72293
+ message: "\"hooks\" entry is missing \"event\""
72294
+ });
72295
+ continue;
72296
+ }
72297
+ let command = stringField$1(entry, "command");
72298
+ if (command === void 0) {
72299
+ diagnostics.push({
72300
+ severity: "warn",
72301
+ message: "\"hooks\" entry is missing \"command\""
72302
+ });
72303
+ continue;
72304
+ }
72305
+ if (command.startsWith("./")) command = path.resolve(pluginRoot, command);
72306
+ const timeout = typeof entry["timeout"] === "number" ? entry["timeout"] : void 0;
72307
+ const hook = {
72308
+ event,
72309
+ command,
72310
+ ...stringField$1(entry, "matcher") !== void 0 ? { matcher: stringField$1(entry, "matcher") } : {},
72311
+ ...timeout !== void 0 ? { timeout } : {}
72312
+ };
72313
+ out.push(hook);
72314
+ }
72315
+ return out.length > 0 ? out : void 0;
72316
+ }
72081
72317
  async function resolveSkillsField(pluginRoot, raw, diagnostics) {
72082
72318
  if (raw === void 0) return [];
72083
72319
  const entries = [];
@@ -73095,7 +73331,7 @@ Analyze the conversation transcript and the user's explicit guidance, then produ
73095
73331
  The package must contain:
73096
73332
  - name: kebab-case skill name. Prefer the user's nameHint if it is valid kebab-case; otherwise derive a concise name from the purpose.
73097
73333
  - description: one sentence describing when to use this skill.
73098
- - whenToUse: **required** — 1-2 sentences describing the specific situations or trigger conditions that should make the agent use this skill. Put the same guidance in the generated SKILL.md's \`when-to-use\` frontmatter. This drives the skill listing's "When to use" line. Never leave it empty.
73334
+ - when-to-use: **required** — 1-2 sentences describing the specific situations/trigger conditions that should make the agent use this skill. Must include concrete trigger phrases or keywords, the specific scenario or task type, and avoid vague terms like "when needed". Use "When the user [action/request]..." or "When [task type]..." format. Put the same guidance in the generated SKILL.md's \`when-to-use\` frontmatter. This drives the skill listing's "When to use" line. Never leave it empty.
73099
73335
  - content: the complete Markdown body of SKILL.md, following the MANDATORY structure below.
73100
73336
  - files: optional supporting files (e.g. scripts, data files) relative to the skill directory. Empty array if none.
73101
73337
 
@@ -73174,7 +73410,7 @@ var MakeSkillPlanTool = class {
73174
73410
  }
73175
73411
  async generatePlan(args) {
73176
73412
  const userPrompt = buildUserPrompt(args, buildTranscript(this.agent.context.history));
73177
- const response = await this.agent.generate(this.agent.config.provider, SYSTEM_PROMPT, [], [{
73413
+ const response = await this.agent.generateWithRetry(this.agent.config.provider, SYSTEM_PROMPT, [], [{
73178
73414
  role: "user",
73179
73415
  content: [{
73180
73416
  type: "text",
@@ -73226,7 +73462,19 @@ function parsePlanJson(rawText) {
73226
73462
  } catch (error) {
73227
73463
  throw new NexumError(ErrorCodes.REQUEST_INVALID, `The skill plan is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
73228
73464
  }
73229
- const result = z.object({
73465
+ const normalizeWhenToUse = (raw) => {
73466
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
73467
+ const object = raw;
73468
+ if (object["whenToUse"] === void 0) {
73469
+ const hyphenated = object["when-to-use"];
73470
+ const underscored = object["when_to_use"];
73471
+ if (typeof hyphenated === "string") object["whenToUse"] = hyphenated;
73472
+ else if (typeof underscored === "string") object["whenToUse"] = underscored;
73473
+ }
73474
+ }
73475
+ return raw;
73476
+ };
73477
+ const result = z.preprocess(normalizeWhenToUse, z.object({
73230
73478
  name: z.string(),
73231
73479
  description: z.string(),
73232
73480
  whenToUse: z.string(),
@@ -73235,7 +73483,7 @@ function parsePlanJson(rawText) {
73235
73483
  path: z.string(),
73236
73484
  content: z.string()
73237
73485
  })).default([])
73238
- }).safeParse(parsed);
73486
+ })).safeParse(parsed);
73239
73487
  if (!result.success) throw new NexumError(ErrorCodes.REQUEST_INVALID, `The skill plan has an invalid structure: ${result.error.message}`);
73240
73488
  return result.data;
73241
73489
  }
@@ -73245,7 +73493,7 @@ function validateSkillPlan(plan, nameHint) {
73245
73493
  const normalizedHint = sanitizeSkillName(nameHint);
73246
73494
  if (plan.name !== normalizedHint) throw new NexumError(ErrorCodes.REQUEST_INVALID, `Generated skill name "${plan.name}" does not match the user's requested name "${normalizedHint}". Please use the requested name.`);
73247
73495
  }
73248
- if (plan.whenToUse.trim().length === 0) throw new NexumError(ErrorCodes.REQUEST_INVALID, "Generated skill plan is missing the required \"whenToUse\" field. Describe the situations that should trigger this skill.");
73496
+ if (plan.whenToUse.trim().length === 0) throw new NexumError(ErrorCodes.REQUEST_INVALID, "Generated skill plan is missing the required \"whenToUse\" field. Describe the specific situations that should trigger this skill with concrete trigger conditions.");
73249
73497
  let contentWhenToUse;
73250
73498
  try {
73251
73499
  contentWhenToUse = parseSkillText({
@@ -73917,11 +74165,16 @@ var EditTool = class {
73917
74165
  await this.jian.writeText(safePath, materializeModelText(newContent, modelView.lineEndingStyle));
73918
74166
  scanCache.clear();
73919
74167
  const { notice, hasErrors } = await this.appendDiagnostics(safePath);
73920
- const output = `Replaced 1 occurrence in ${args.path}${notice}`;
74168
+ const output = `Replaced 1 occurrence in ${args.path}`;
74169
+ const message = notice.length > 0 ? notice : void 0;
73921
74170
  return hasErrors ? {
73922
74171
  isError: true,
73923
- output
73924
- } : { output };
74172
+ output,
74173
+ message
74174
+ } : {
74175
+ output,
74176
+ message
74177
+ };
73925
74178
  }
73926
74179
  const parts = content.split(args.old_string);
73927
74180
  const replacementCount = parts.length - 1;
@@ -73936,11 +74189,16 @@ var EditTool = class {
73936
74189
  await this.jian.writeText(safePath, materializeModelText(newContent, modelView.lineEndingStyle));
73937
74190
  scanCache.clear();
73938
74191
  const { notice, hasErrors } = await this.appendDiagnostics(safePath);
73939
- const output = `Replaced ${String(replacementCount)} occurrences in ${args.path}${notice}`;
74192
+ const output = `Replaced ${String(replacementCount)} occurrences in ${args.path}`;
74193
+ const message = notice.length > 0 ? notice : void 0;
73940
74194
  return hasErrors ? {
73941
74195
  isError: true,
73942
- output
73943
- } : { output };
74196
+ output,
74197
+ message
74198
+ } : {
74199
+ output,
74200
+ message
74201
+ };
73944
74202
  } catch (error) {
73945
74203
  if (error?.code === "EISDIR") return {
73946
74204
  isError: true,
@@ -79730,11 +79988,16 @@ var WriteTool = class {
79730
79988
  scanCache.clear();
79731
79989
  const bytesWritten = Buffer.byteLength(args.content, "utf8");
79732
79990
  const { notice, hasErrors } = await this.appendDiagnostics(safePath);
79733
- const output = `${mode === "append" ? "Appended" : "Wrote"} ${String(bytesWritten)} bytes to ${args.path}${notice}`;
79991
+ const output = `${mode === "append" ? "Appended" : "Wrote"} ${String(bytesWritten)} bytes to ${args.path}`;
79992
+ const message = notice.length > 0 ? notice : void 0;
79734
79993
  return hasErrors ? {
79735
79994
  isError: true,
79736
- output
79737
- } : { output };
79995
+ output,
79996
+ message
79997
+ } : {
79998
+ output,
79999
+ message
80000
+ };
79738
80001
  } catch (error) {
79739
80002
  if (error?.code === "ENOENT") return {
79740
80003
  isError: true,
@@ -82103,142 +82366,62 @@ function buildBackgroundTaskNotificationBody(info, isAgentTask) {
82103
82366
  ].join("\n")}`;
82104
82367
  }
82105
82368
  //#endregion
82106
- //#region ../../node_modules/.pnpm/@antfu+utils@9.3.0/node_modules/@antfu/utils/dist/index.mjs
82107
- function uniq(array) {
82108
- return Array.from(new Set(array));
82109
- }
82110
- function notNullish(v) {
82111
- return v != null;
82112
- }
82113
- function objectMap(obj, fn) {
82114
- return Object.fromEntries(Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish));
82115
- }
82116
- function sleep(ms, callback) {
82117
- return new Promise((resolve) => setTimeout(async () => {
82118
- await callback?.();
82119
- resolve();
82120
- }, ms));
82121
- }
82122
- function createControlledPromise() {
82123
- let resolve, reject;
82124
- const promise = new Promise((_resolve, _reject) => {
82125
- resolve = _resolve;
82126
- reject = _reject;
82127
- });
82128
- promise.resolve = resolve;
82129
- promise.reject = reject;
82130
- return promise;
82131
- }
82132
- const BASE_DELAY_MS = 500;
82133
- const MAX_DELAY_MS = 32e3;
82134
- const RETRY_FACTOR = 2;
82135
- const JITTER_FACTOR = .25;
82136
- async function chatWithRetry(input) {
82137
- const maxAttempts = input.maxAttempts ?? 10;
82138
- if (input.llm.isRetryableError === void 0 || maxAttempts <= 1) {
82139
- const effectiveMaxAttempts = Math.max(maxAttempts, 1);
82140
- try {
82141
- return await input.llm.chat(paramsForAttempt(input, 1, effectiveMaxAttempts));
82142
- } catch (error) {
82143
- logRequestFailure(input, error, 1, effectiveMaxAttempts);
82144
- throw error;
82145
- }
82146
- }
82147
- const delays = retryBackoffDelays(maxAttempts);
82148
- for (let attempt = 1;; attempt += 1) try {
82149
- return await input.llm.chat(paramsForAttempt(input, attempt, maxAttempts));
82150
- } catch (error) {
82151
- if (error instanceof APIContextOverflowError) {
82152
- logRequestFailure(input, error, attempt, maxAttempts);
82153
- throw error;
82154
- }
82155
- if (error instanceof APIProviderRateLimitError && error.reason === "QUOTA_EXHAUSTED") {
82156
- logRequestFailure(input, error, attempt, maxAttempts);
82157
- throw error;
82158
- }
82159
- if (attempt >= maxAttempts || !input.llm.isRetryableError(error)) {
82160
- logRequestFailure(input, error, attempt, maxAttempts);
82161
- throw error;
82162
- }
82163
- const delayMs = computeDelayMs(error, delays, attempt);
82164
- input.params.signal.throwIfAborted();
82165
- input.dispatchEvent({
82166
- type: "step.retrying",
82167
- turnId: input.turnId,
82168
- step: input.currentStep,
82169
- stepUuid: input.stepUuid,
82170
- failedAttempt: attempt,
82171
- nextAttempt: attempt + 1,
82172
- maxAttempts,
82173
- delayMs,
82174
- ...retryErrorFields(error)
82175
- });
82176
- await sleepForRetry(delayMs, input.params.signal);
82177
- }
82178
- }
82179
- function computeDelayMs(error, delays, attempt) {
82180
- const retryAfter = readRetryAfterMs(error);
82181
- if (retryAfter !== null) return retryAfter;
82182
- if (error instanceof APIProviderRateLimitError) return calculateRateLimitBackoffMs(error.reason);
82183
- return delays[attempt - 1] ?? 0;
82184
- }
82369
+ //#region ../../packages/agent-core/src/agent/events.ts
82185
82370
  /**
82186
- * Server-requested backoff carried on an `APIStatusError` (parsed from
82187
- * the `Retry-After` response header). When present and positive it
82188
- * overrides the computed backoff - a server `Retry-After` directive
82189
- * takes precedence over the local exponential delay.
82371
+ * In-process subscription bus for {@link AgentEvent}s.
82372
+ *
82373
+ * Mirrors the events the agent already broadcasts to the host via
82374
+ * `rpc.emitEvent`, so third-party extensions running inside the agent process
82375
+ * can subscribe without round-tripping through the host. This is the
82376
+ * read-side companion to {@link import('./index').Agent.emitEvent}.
82377
+ *
82378
+ * Lifecycle: extensions call `subscribe()` when activated and must call
82379
+ * `clear()` (or the returned unsubscribe) when deactivated to avoid leaking
82380
+ * handlers across sessions/restarts.
82190
82381
  */
82191
- function readRetryAfterMs(error) {
82192
- if (typeof error !== "object" || error === null) return null;
82193
- const value = error.retryAfterMs;
82194
- return typeof value === "number" && value > 0 ? value : null;
82195
- }
82196
- function logRequestFailure(input, error, attempt, maxAttempts) {
82197
- if (isAbortError$1(error) || input.params.signal.aborted) return;
82198
- input.log?.warn("llm request failed", {
82199
- turnStep: `${input.turnId}.${String(input.currentStep)}`,
82200
- attempt: `${String(attempt)}/${String(maxAttempts)}`,
82201
- model: input.llm.modelName,
82202
- ...retryErrorFields(error)
82203
- });
82204
- }
82205
- function paramsForAttempt(input, attempt, maxAttempts) {
82206
- return {
82207
- ...input.params,
82208
- requestLogContext: {
82209
- turnId: input.turnId,
82210
- step: input.currentStep,
82211
- stepUuid: input.stepUuid,
82212
- attempt,
82213
- maxAttempts
82382
+ var EventSubscriptionBus = class {
82383
+ byType = /* @__PURE__ */ new Map();
82384
+ wildcard = /* @__PURE__ */ new Set();
82385
+ /**
82386
+ * Subscribe to a specific event type (or `'*'` for all events).
82387
+ * Returns an unsubscribe function.
82388
+ */
82389
+ subscribe(type, handler) {
82390
+ if (type === "*") {
82391
+ this.wildcard.add(handler);
82392
+ return () => {
82393
+ this.wildcard.delete(handler);
82394
+ };
82214
82395
  }
82215
- };
82216
- }
82217
- function retryBackoffDelays(maxAttempts) {
82218
- const count = Math.max(maxAttempts - 1, 0);
82219
- const delays = [];
82220
- for (let i = 0; i < count; i += 1) {
82221
- const base = Math.min(BASE_DELAY_MS * Math.pow(RETRY_FACTOR, i), MAX_DELAY_MS);
82222
- delays.push(base + Math.random() * JITTER_FACTOR * base);
82396
+ let set = this.byType.get(type);
82397
+ if (set === void 0) {
82398
+ set = /* @__PURE__ */ new Set();
82399
+ this.byType.set(type, set);
82400
+ }
82401
+ set.add(handler);
82402
+ return () => {
82403
+ set.delete(handler);
82404
+ };
82223
82405
  }
82224
- return delays;
82225
- }
82226
- async function sleepForRetry(delayMs, signal) {
82227
- signal.throwIfAborted();
82228
- await abortable(sleep(delayMs), signal);
82229
- }
82230
- function retryErrorFields(error) {
82231
- return {
82232
- errorName: error instanceof Error ? error.name : typeof error,
82233
- errorMessage: error instanceof Error ? error.message : String(error),
82234
- statusCode: maybeStatusCode(error)
82235
- };
82236
- }
82237
- function maybeStatusCode(error) {
82238
- if (typeof error !== "object" || error === null) return void 0;
82239
- const statusCode = error.statusCode;
82240
- return typeof statusCode === "number" ? statusCode : void 0;
82241
- }
82406
+ /** Drop every subscriber (used on deactivate / session switch). */
82407
+ clear() {
82408
+ this.byType.clear();
82409
+ this.wildcard.clear();
82410
+ }
82411
+ /**
82412
+ * Deliver an event to matching handlers. A handler that throws is isolated
82413
+ * so a subscriber bug can never break the agent's event loop.
82414
+ */
82415
+ dispatch(event) {
82416
+ const typed = this.byType.get(event.type);
82417
+ if (typed !== void 0) for (const handler of typed) try {
82418
+ handler(event);
82419
+ } catch {}
82420
+ if (this.wildcard.size > 0) for (const handler of this.wildcard) try {
82421
+ handler(event);
82422
+ } catch {}
82423
+ }
82424
+ };
82242
82425
  //#endregion
82243
82426
  //#region ../../packages/agent-core/src/agent/context/projector.ts
82244
82427
  /** Synthetic error text used when a tool result is missing and must be
@@ -82362,10 +82545,10 @@ function stripContextMetadata(message) {
82362
82545
  }
82363
82546
  //#endregion
82364
82547
  //#region ../../packages/agent-core/src/agent/compaction/compaction-instruction.md
82365
- var compaction_instruction_default = "\r\n--- This message is a direct task, not part of the above conversation ---\r\n\r\nYou are now given a task to compact this conversation context according to specific priorities and output requirements.\r\n\r\nOutput text only. DO NOT CALL ANY TOOLS. Calling tools will be rejected and fails the task. You already have all the information you need in the conversation history. You have only one chance.\r\n\r\nThe goal of compaction is to keep essential code patterns, technical details, and architectural decisions for continuing development without losing context after the above messages are cleared work.\r\n\r\n{{ customInstruction }}\r\n\r\n<!-- Memory Memo Extraction (PRIORITY — do not skip) -->\r\n\r\n## 任务经验提取\r\n\r\nAFTER completing the compaction summary below, scan the messages being compacted for **task loops**. A task loop is \"completed\" when:\r\n- The user made a clear request or asked a specific question\r\n- You provided a solution or answer\r\n- The outcome is clear (success, partial success, or failure)\r\n\r\n**You MUST output at least one memory-memo block** (or the `{\"none\": true}` marker) at the very end of your response — omitting the section entirely is not allowed. Record completed task loops as full experience records; record **in-progress work** as a lower-priority record whose \"outcome\" is \"进行中\" (so the ongoing task survives compaction and can be resumed later).\r\n\r\nFor each task loop found, output a structured experience record **at the very end of your response**:\r\n\r\n```memory-memo\r\n{\r\n \"userNeed\": \"<the user's need or goal, one sentence>\",\r\n \"approach\": \"<what was done — the approach taken, 2-4 sentences>\",\r\n \"outcome\": \"<final result, e.g. '完成', '部分完成', '失败: reason', or '进行中' for in-progress work>\",\r\n \"whatFailed\": \"<dead ends tried — things that didn't work, or 'none'>\",\r\n \"whatWorked\": \"<key actions that ultimately worked, or 'none'>\",\r\n \"tags\": [\"<tag1>\", \"<tag2>\", \"<tag3>\"],\r\n \"note\": \"<optional: a soft, AI-readable note/suggestion that makes the record easier for future turns to understand — e.g. '这类任务先查接口可用性再写代码'. Omit if none>\"\r\n}\r\n```\r\n\r\nGuidelines:\r\n- Record important failed attempts in \"whatFailed\" to help avoid repeating mistakes.\r\n- Record key successful actions in \"whatWorked\" to help reuse effective approaches.\r\n- Include 3-5 semantic \"tags\" summarizing the task domain, tech stack, or action type (e.g. [\"react\", \"auth\", \"部署\"]).\r\n- \"note\" is optional: a one-sentence advisory note that helps future AI understand/reuse the record faster. It is a soft suggestion, not a user-enforced rule.\r\n- For in-progress work: record it with \"outcome\": \"进行中\" and describe where the task stands and what remains — this is what lets the agent resume seamlessly after compaction.\r\n- Merge closely related sub-tasks into a single record.\r\n- Use the exact field names and JSON format shown above (no extra fields beyond \"note\").\r\n\r\nIf no task loops (completed or in-progress) are found in the compacted messages, output:\r\n```memory-memo\r\n{\"none\": true}\r\n```\r\n\r\n<!-- Compression Priorities (in order) -->\r\n\r\n1. **Current Task State**: What is being worked on RIGHT NOW\r\n2. **Errors & Solutions**: All encountered errors and their resolutions\r\n3. **Code Evolution**: Final working versions only (remove intermediate attempts)\r\n4. **System Context**: Project structure, dependencies, environment setup\r\n5. **Design Decisions**: Architectural choices and their rationale\r\n6. **Next Steps**: The ordered, actionable plan going forward\r\n7. **TODO Items**: Unfinished tasks and known issues\r\n\r\n<!-- Required Output Structure -->\r\n\r\n## Current Focus\r\n\r\n[What we're working on now]\r\n\r\n## Environment\r\n\r\n- [Key setup/config points]\r\n- ...\r\n\r\n## Completed Tasks\r\n\r\n- [Task]: [Brief outcome]\r\n- ...\r\n\r\n## Active Issues\r\n\r\n- [Issue]: [Status/Next steps]\r\n- ...\r\n\r\n## Key Decisions\r\n\r\n- [Decision]: [rationale] — preserve architectural choices and why they were made\r\n- ...\r\n\r\n## Next Steps\r\n\r\n1. [The very next actionable step]\r\n2. [Then this]\r\n3. ...\r\n\r\n## Code State\r\n\r\n### [Critical file name]\r\n\r\n[Brief description of the file's purpose and current state]\r\n\r\n```\r\n[The latest version of critical code snippets in this file, <20 lines]\r\n```\r\n\r\n### [Critical file name]\r\n\r\n- [Useful classes/methods/functions]: [Brief description/usage]\r\n- ...\r\n\r\n<!-- Omit non-critical code, intermediate attempts, and resolved errors -->\r\n\r\n## Important Context\r\n\r\n- [Any crucial information not covered above]\r\n- ...\r\n\r\n## All User Messages\r\n\r\n- [Detailed non tool use user message]\r\n- ...\r\n\r\n## Skill candidates\r\n\r\nScan the compressed messages for reusable processes (project-specific build\r\nsteps, recurring debugging patterns, or tool workflows). If any is genuinely\r\nworth capturing as a reusable skill, output at the very end, at most one:\r\n\r\n[[skill-candidate: <name>|<one-line purpose>|<evidence>]]\r\n\r\n- The evidence must be concrete and verifiable: exact file paths, commands, or\r\n step sequences from the conversation (e.g. \"run `pnpm vitest run -t compaction`\r\n in packages/agent-core to reproduce the compaction snapshots\"). Vague evidence\r\n like \"used a script\" is not acceptable.\r\n- Only emit a candidate when the process is genuinely reusable beyond this one\r\n task; do not emit for one-off actions.\r\n\r\nOmit if none.\r\n";
82548
+ var compaction_instruction_default = "\r\n--- This message is a direct task, not part of the above conversation ---\r\n\r\nYou are now given a task to compact this conversation context according to specific priorities and output requirements.\r\n\r\nOutput text only. DO NOT CALL ANY TOOLS. Calling tools will be rejected and fails the task. You already have all the information you need in the conversation history. You have only one chance.\r\n\r\nThe goal of compaction is to keep essential code patterns, technical details, and architectural decisions for continuing development without losing context after the above messages are cleared work.\r\n\r\n{{ customInstruction }}\r\n\r\n<!-- Memory Memo Extraction (PRIORITY — do not skip) -->\r\n\r\n## 任务经验提取\r\n\r\nAFTER completing the compaction summary below, scan the messages being compacted for **task loops**. A task loop is \"completed\" when:\r\n- The user made a clear request or asked a specific question\r\n- You provided a solution or answer\r\n- The outcome is clear (success, partial success, or failure)\r\n\r\n**You MUST output at least one memory-memo block** (or the `{\"none\": true}` marker) after the summary — omitting the section entirely is not allowed. Record completed task loops as full experience records; record **in-progress work** as a lower-priority record whose \"outcome\" is \"进行中\" (so the ongoing task survives compaction and can be resumed later).\r\n\r\nFor each task loop found, output a structured experience record after the summary (the skill-candidate marker line described below comes after all memory-memo blocks):\r\n\r\n```memory-memo\r\n{\r\n \"userNeed\": \"<the user's need or goal, one sentence>\",\r\n \"approach\": \"<what was done — the approach taken, 2-4 sentences>\",\r\n \"outcome\": \"<final result, e.g. '完成', '部分完成', '失败: reason', or '进行中' for in-progress work>\",\r\n \"whatFailed\": \"<dead ends tried — things that didn't work, or 'none'>\",\r\n \"whatWorked\": \"<key actions that ultimately worked, or 'none'>\",\r\n \"tags\": [\"<tag1>\", \"<tag2>\", \"<tag3>\"],\r\n \"note\": \"<optional: a soft, AI-readable note/suggestion that makes the record easier for future turns to understand — e.g. '这类任务先查接口可用性再写代码'. Omit if none>\"\r\n}\r\n```\r\n\r\nGuidelines:\r\n- Record important failed attempts in \"whatFailed\" to help avoid repeating mistakes.\r\n- Record key successful actions in \"whatWorked\" to help reuse effective approaches.\r\n- Include 3-5 semantic \"tags\" summarizing the task domain, tech stack, or action type (e.g. [\"react\", \"auth\", \"部署\"]).\r\n- \"note\" is optional: a one-sentence advisory note that helps future AI understand/reuse the record faster. It is a soft suggestion, not a user-enforced rule.\r\n- For in-progress work: record it with \"outcome\": \"进行中\" and describe where the task stands and what remains — this is what lets the agent resume seamlessly after compaction.\r\n- Merge closely related sub-tasks into a single record.\r\n- Use the exact field names and JSON format shown above (no extra fields beyond \"note\").\r\n\r\nIf no task loops (completed or in-progress) are found in the compacted messages, output:\r\n```memory-memo\r\n{\"none\": true}\r\n```\r\n\r\n<!-- Compression Priorities (in order) -->\r\n\r\n1. **Current Task State**: What is being worked on RIGHT NOW\r\n2. **Errors & Solutions**: All encountered errors and their resolutions\r\n3. **Code Evolution**: Final working versions only (remove intermediate attempts)\r\n4. **System Context**: Project structure, dependencies, environment setup\r\n5. **Design Decisions**: Architectural choices and their rationale\r\n6. **Next Steps**: The ordered, actionable plan going forward\r\n7. **TODO Items**: Unfinished tasks and known issues\r\n\r\n<!-- Required Output Structure -->\r\n\r\n## Current Focus\r\n\r\n[What we're working on now]\r\n\r\n## Environment\r\n\r\n- [Key setup/config points]\r\n- ...\r\n\r\n## Completed Tasks\r\n\r\n- [Task]: [Brief outcome]\r\n- ...\r\n\r\n## Active Issues\r\n\r\n- [Issue]: [Status/Next steps]\r\n- ...\r\n\r\n## Key Decisions\r\n\r\n- [Decision]: [rationale] — preserve architectural choices and why they were made\r\n- ...\r\n\r\n## Next Steps\r\n\r\n1. [The very next actionable step]\r\n2. [Then this]\r\n3. ...\r\n\r\n## Code State\r\n\r\n### [Critical file name]\r\n\r\n[Brief description of the file's purpose and current state]\r\n\r\n```\r\n[The latest version of critical code snippets in this file, <20 lines]\r\n```\r\n\r\n### [Critical file name]\r\n\r\n- [Useful classes/methods/functions]: [Brief description/usage]\r\n- ...\r\n\r\n<!-- Omit non-critical code, intermediate attempts, and resolved errors -->\r\n\r\n## Important Context\r\n\r\n- [Any crucial information not covered above]\r\n- ...\r\n\r\n## All User Messages\r\n\r\n- [Detailed non tool use user message]\r\n- ...\r\n\r\n## Skill candidates\r\n\r\nScan the compressed messages for reusable processes (project-specific build\r\nsteps, recurring debugging patterns, or tool workflows). Then output exactly\r\none marker as the very LAST line of your response — after all memory-memo\r\nblocks:\r\n\r\n- If a process is genuinely worth capturing as a reusable skill (reusable\r\n beyond this one task — do not emit for one-off actions; the evidence must\r\n be concrete and verifiable: exact file paths, commands, or step sequences\r\n from the conversation, e.g. \"run `pnpm vitest run -t compaction` in\r\n packages/agent-core to reproduce the compaction snapshots\". Vague evidence\r\n like \"used a script\" is not acceptable):\r\n\r\n[[skill-candidate: <name>|<one-line purpose>|<evidence>]]\r\n\r\n- If none exists, output instead:\r\n\r\n[[skill-candidate: none]]\r\n\r\nThis marker line is MANDATORY — never omit it, and output at most one\r\ncandidate marker.\r\n";
82366
82549
  //#endregion
82367
82550
  //#region ../../packages/agent-core/src/agent/compaction/compaction-update-instruction.md
82368
- var compaction_update_instruction_default = "\r\n--- This message is a direct task, not part of the above conversation ---\r\n\r\nYou are now given a task to UPDATE an existing compaction summary with new messages that came in after the last compaction.\r\n\r\nA previous compaction summary already exists at the top of the conversation (the first assistant message). You must NOT discard it. Instead, merge the new information into the existing structure, keeping all previously captured state intact unless explicitly contradicted or resolved by the new messages.\r\n\r\nOutput text only. DO NOT CALL ANY TOOLS. Calling tools will be rejected and fails the task. You have only one chance.\r\n\r\n{{ customInstruction }}\r\n\r\n<!-- Previous Summary Reference -->\r\n\r\nThe first assistant message above is the PREVIOUS summary. Treat it as the source of truth for everything that happened before the new messages. Do not restate it verbatim — produce an updated, merged summary.\r\n\r\n<!-- Memory Memo Extraction (PRIORITY — do not skip) -->\r\n\r\n## 任务经验提取\r\n\r\nAFTER completing the updated summary below, scan ONLY the new messages being compacted (not those already covered by the previous summary) for **task loops**. A task loop is \"completed\" when:\r\n- The user made a clear request or asked a specific question\r\n- You provided a solution or answer\r\n- The outcome is clear (success, partial success, or failure)\r\n\r\n**You MUST output at least one memory-memo block** (or the `{\"none\": true}` marker) at the very end of your response — omitting the section entirely is not allowed. Record completed task loops as full experience records; record **in-progress work** as a lower-priority record whose \"outcome\" is \"进行中\" (so the ongoing task survives compaction and can be resumed later).\r\n\r\nFor each task loop found, output a structured experience record **at the very end of your response**:\r\n\r\n```memory-memo\r\n{\r\n \"userNeed\": \"<the user's need or goal, one sentence>\",\r\n \"approach\": \"<what was done — the approach taken, 2-4 sentences>\",\r\n \"outcome\": \"<final result, e.g. '完成', '部分完成', '失败: reason', or '进行中' for in-progress work>\",\r\n \"whatFailed\": \"<dead ends tried — things that didn't work, or 'none'>\",\r\n \"whatWorked\": \"<key actions that ultimately worked, or 'none'>\",\r\n \"tags\": [\"<tag1>\", \"<tag2>\", \"<tag3>\"],\r\n \"note\": \"<optional: a soft, AI-readable note/suggestion that makes the record easier for future turns to understand — e.g. '这类任务先查接口可用性再写代码'. Omit if none>\"\r\n}\r\n```\r\n\r\nGuidelines:\r\n- Record important failed attempts in \"whatFailed\" to help avoid repeating mistakes.\r\n- Record key successful actions in \"whatWorked\" to help reuse effective approaches.\r\n- Include 3-5 semantic \"tags\" summarizing the task domain, tech stack, or action type.\r\n- For in-progress work: record it with \"outcome\": \"进行中\" and describe where the task stands and what remains — this is what lets the agent resume seamlessly after compaction.\r\n- Merge closely related sub-tasks into a single record.\r\n- Use the exact field names and JSON format shown above.\r\n\r\nIf no task loops (completed or in-progress) are found in the new compacted messages, output:\r\n```memory-memo\r\n{\"none\": true}\r\n```\r\n\r\n<!-- Update Rules -->\r\n\r\n1. Preserve the section structure of the previous summary (Current Focus, Environment, Completed Tasks, Active Issues, Key Decisions, Next Steps, Code State, Important Context, All User Messages).\r\n2. Move newly-completed tasks from \"Current Focus\" / \"Active Issues\" into \"Completed Tasks\".\r\n3. Update \"Current Focus\" to reflect what is being worked on RIGHT NOW.\r\n4. Append new user messages to \"All User Messages\" — do not repeat those already captured.\r\n5. Refresh \"Code State\" code snippets only if newer versions exist in the new messages.\r\n6. Drop resolved issues from \"Active Issues\"; add newly-discovered ones.\r\n7. Merge new decisions into \"Key Decisions\" (keep prior decisions unless explicitly overturned); merge new steps into \"Next Steps\" (reorder if priorities changed).\r\n8. Do not invent new information. If the new messages say nothing about a section, carry the previous content forward unchanged.\r\n\r\n<!-- Required Output Structure -->\r\n\r\n## Current Focus\r\n\r\n[What we're working on now]\r\n\r\n## Environment\r\n\r\n- [Key setup/config points]\r\n- ...\r\n\r\n## Completed Tasks\r\n\r\n- [Task]: [Brief outcome]\r\n- ...\r\n\r\n## Active Issues\r\n\r\n- [Issue]: [Status/Next steps]\r\n- ...\r\n\r\n## Key Decisions\r\n\r\n- [Decision]: [rationale] — preserve architectural choices and why they were made\r\n- ...\r\n\r\n## Next Steps\r\n\r\n1. [The very next actionable step]\r\n2. [Then this]\r\n3. ...\r\n\r\n## Code State\r\n\r\n### [Critical file name]\r\n\r\n[Brief description of the file's purpose and current state]\r\n\r\n```\r\n[The latest version of critical code snippets in this file, <20 lines]\r\n```\r\n\r\n## Important Context\r\n\r\n- [Any crucial information not covered above]\r\n- ...\r\n\r\n## All User Messages\r\n\r\n- [Detailed non tool use user message]\r\n- ...\r\n";
82551
+ var compaction_update_instruction_default = "\r\n--- This message is a direct task, not part of the above conversation ---\r\n\r\nYou are now given a task to UPDATE an existing compaction summary with new messages that came in after the last compaction.\r\n\r\nA previous compaction summary already exists at the top of the conversation (the first assistant message). You must NOT discard it. Instead, merge the new information into the existing structure, keeping all previously captured state intact unless explicitly contradicted or resolved by the new messages.\r\n\r\nOutput text only. DO NOT CALL ANY TOOLS. Calling tools will be rejected and fails the task. You have only one chance.\r\n\r\n{{ customInstruction }}\r\n\r\n<!-- Previous Summary Reference -->\r\n\r\nThe first assistant message above is the PREVIOUS summary. Treat it as the source of truth for everything that happened before the new messages. Do not restate it verbatim — produce an updated, merged summary.\r\n\r\n<!-- Memory Memo Extraction (PRIORITY — do not skip) -->\r\n\r\n## 任务经验提取\r\n\r\nAFTER completing the updated summary below, scan ONLY the new messages being compacted (not those already covered by the previous summary) for **task loops**. A task loop is \"completed\" when:\r\n- The user made a clear request or asked a specific question\r\n- You provided a solution or answer\r\n- The outcome is clear (success, partial success, or failure)\r\n\r\n**You MUST output at least one memory-memo block** (or the `{\"none\": true}` marker) after the updated summary — omitting the section entirely is not allowed. Record completed task loops as full experience records; record **in-progress work** as a lower-priority record whose \"outcome\" is \"进行中\" (so the ongoing task survives compaction and can be resumed later).\r\n\r\nFor each task loop found, output a structured experience record after the updated summary (the skill-candidate marker line described below comes after all memory-memo blocks):\r\n\r\n```memory-memo\r\n{\r\n \"userNeed\": \"<the user's need or goal, one sentence>\",\r\n \"approach\": \"<what was done — the approach taken, 2-4 sentences>\",\r\n \"outcome\": \"<final result, e.g. '完成', '部分完成', '失败: reason', or '进行中' for in-progress work>\",\r\n \"whatFailed\": \"<dead ends tried — things that didn't work, or 'none'>\",\r\n \"whatWorked\": \"<key actions that ultimately worked, or 'none'>\",\r\n \"tags\": [\"<tag1>\", \"<tag2>\", \"<tag3>\"],\r\n \"note\": \"<optional: a soft, AI-readable note/suggestion that makes the record easier for future turns to understand — e.g. '这类任务先查接口可用性再写代码'. Omit if none>\"\r\n}\r\n```\r\n\r\nGuidelines:\r\n- Record important failed attempts in \"whatFailed\" to help avoid repeating mistakes.\r\n- Record key successful actions in \"whatWorked\" to help reuse effective approaches.\r\n- Include 3-5 semantic \"tags\" summarizing the task domain, tech stack, or action type.\r\n- For in-progress work: record it with \"outcome\": \"进行中\" and describe where the task stands and what remains — this is what lets the agent resume seamlessly after compaction.\r\n- Merge closely related sub-tasks into a single record.\r\n- Use the exact field names and JSON format shown above.\r\n\r\nIf no task loops (completed or in-progress) are found in the new compacted messages, output:\r\n```memory-memo\r\n{\"none\": true}\r\n```\r\n\r\n<!-- Skill Candidate Detection (after memory-memo) -->\r\n\r\n## Skill candidates\r\n\r\nAFTER the memory-memo block(s), scan ONLY the new messages being compacted\r\n(not the content already covered by the previous summary — candidates from\r\nolder messages were already considered) for reusable processes\r\n(project-specific build steps, recurring debugging patterns, or tool\r\nworkflows). Then output exactly one marker as the very LAST line of your\r\nresponse — after all memory-memo blocks:\r\n\r\n- If a process is genuinely worth capturing as a reusable skill (reusable\r\n beyond this one task — do not emit for one-off actions; the evidence must\r\n be concrete and verifiable: exact file paths, commands, or step sequences\r\n from the new messages):\r\n\r\n[[skill-candidate: <name>|<one-line purpose>|<evidence>]]\r\n\r\n- If none exists, output instead:\r\n\r\n[[skill-candidate: none]]\r\n\r\nThis marker line is MANDATORY — never omit it, and output at most one\r\ncandidate marker.\r\n\r\n<!-- Update Rules -->\r\n\r\n1. Preserve the section structure of the previous summary (Current Focus, Environment, Completed Tasks, Active Issues, Key Decisions, Next Steps, Code State, Important Context, All User Messages).\r\n2. Move newly-completed tasks from \"Current Focus\" / \"Active Issues\" into \"Completed Tasks\".\r\n3. Update \"Current Focus\" to reflect what is being worked on RIGHT NOW.\r\n4. Append new user messages to \"All User Messages\" — do not repeat those already captured.\r\n5. Refresh \"Code State\" code snippets only if newer versions exist in the new messages.\r\n6. Drop resolved issues from \"Active Issues\"; add newly-discovered ones.\r\n7. Merge new decisions into \"Key Decisions\" (keep prior decisions unless explicitly overturned); merge new steps into \"Next Steps\" (reorder if priorities changed).\r\n8. Do not invent new information. If the new messages say nothing about a section, carry the previous content forward unchanged.\r\n\r\n<!-- Required Output Structure -->\r\n\r\n## Current Focus\r\n\r\n[What we're working on now]\r\n\r\n## Environment\r\n\r\n- [Key setup/config points]\r\n- ...\r\n\r\n## Completed Tasks\r\n\r\n- [Task]: [Brief outcome]\r\n- ...\r\n\r\n## Active Issues\r\n\r\n- [Issue]: [Status/Next steps]\r\n- ...\r\n\r\n## Key Decisions\r\n\r\n- [Decision]: [rationale] — preserve architectural choices and why they were made\r\n- ...\r\n\r\n## Next Steps\r\n\r\n1. [The very next actionable step]\r\n2. [Then this]\r\n3. ...\r\n\r\n## Code State\r\n\r\n### [Critical file name]\r\n\r\n[Brief description of the file's purpose and current state]\r\n\r\n```\r\n[The latest version of critical code snippets in this file, <20 lines]\r\n```\r\n\r\n## Important Context\r\n\r\n- [Any crucial information not covered above]\r\n- ...\r\n\r\n## All User Messages\r\n\r\n- [Detailed non tool use user message]\r\n- ...\r\n";
82369
82552
  //#endregion
82370
82553
  //#region ../../packages/agent-core/src/agent/compaction/render-messages.ts
82371
82554
  const TOOL_RESULT_MAX_CHARS = 2e3;
@@ -82767,6 +82950,14 @@ var FullCompaction = class {
82767
82950
  get compactedHistory() {
82768
82951
  return this._compactedHistory;
82769
82952
  }
82953
+ /**
82954
+ * Restore the compaction debug trail from a `context.snapshot` record. During
82955
+ * snapshot replay the pre-fold history is skipped, so `markCompleted` can no
82956
+ * longer re-render it — the snapshot carries the trail instead.
82957
+ */
82958
+ restoreCompactedHistory(entries) {
82959
+ this._compactedHistory = [...entries];
82960
+ }
82770
82961
  /** One-shot: true if session memory summary should be injected at the next step. */
82771
82962
  shouldInjectSessionSummary() {
82772
82963
  if (this._shouldInjectSessionSummary) {
@@ -82805,7 +82996,7 @@ var FullCompaction = class {
82805
82996
  blockedByTurn: false
82806
82997
  };
82807
82998
  this.compacting = active;
82808
- active.promise = this.compactionWorker(abortController.signal, data, compactedCount);
82999
+ active.promise = this.compactionWorker(abortController.signal, data, compactedCount, active);
82809
83000
  }
82810
83001
  cancel() {
82811
83002
  this.markCanceled();
@@ -82834,6 +83025,13 @@ var FullCompaction = class {
82834
83025
  this.lowWaterMark = 0;
82835
83026
  this.reactiveAttempted = false;
82836
83027
  }
83028
+ /** The low-water mark is measured against the model's context window, so a
83029
+ * model switch (different max_context_tokens) invalidates it. Without a
83030
+ * reset, a stale mark from a large model can mask the overflow threshold
83031
+ * of a smaller model and suppress compaction until the provider overflows. */
83032
+ resetLowWaterMark() {
83033
+ this.lowWaterMark = 0;
83034
+ }
82837
83035
  async handleOverflowError(signal, error) {
82838
83036
  if (this.reactiveAttempted) throw error;
82839
83037
  if (!this.beginAutoCompaction(false) && !this.compacting) {
@@ -82845,6 +83043,12 @@ var FullCompaction = class {
82845
83043
  throw error;
82846
83044
  }
82847
83045
  this.reactiveAttempted = true;
83046
+ if (this.compacting) try {
83047
+ await this.block(signal);
83048
+ } catch (blockError) {
83049
+ if (signal.aborted || isAbortError$1(blockError)) throw blockError;
83050
+ throw error;
83051
+ }
82848
83052
  }
82849
83053
  async beforeStep(signal) {
82850
83054
  this.agent.microCompaction.detect();
@@ -82894,13 +83098,14 @@ var FullCompaction = class {
82894
83098
  async block(signal) {
82895
83099
  const active = this.compacting;
82896
83100
  if (!active) return;
83101
+ signal.throwIfAborted();
82897
83102
  active.blockedByTurn = true;
82898
83103
  const timeoutId = setTimeout(() => {
82899
83104
  if (this.compacting === active) {
82900
83105
  this.compactionTimedOut = true;
82901
- this.markCanceled("压缩超时(60秒),已取消。请使用 /compact 手动重试。");
83106
+ this.markCanceled("压缩超时(120秒),已取消。请使用 /compact 手动重试。");
82902
83107
  }
82903
- }, 6e4);
83108
+ }, 12e4);
82904
83109
  const onAbort = () => {
82905
83110
  clearTimeout(timeoutId);
82906
83111
  if (this.compacting === active) this.cancel();
@@ -82917,9 +83122,11 @@ var FullCompaction = class {
82917
83122
  signal.removeEventListener("abort", onAbort);
82918
83123
  }
82919
83124
  }
82920
- async compactionWorker(signal, data, compactedCount) {
83125
+ async compactionWorker(signal, data, compactedCount, owner) {
82921
83126
  const originalHistory = [...this.agent.context.history];
82922
- const tokensBefore = estimateTokensForMessages(originalHistory);
83127
+ const systemPromptTokens = estimateTokens$1(this.agent.getRuntimeSystemPrompt());
83128
+ const toolTokens = estimateTokensForTools(this.agent.tools.loopTools);
83129
+ const tokensBefore = systemPromptTokens + toolTokens + estimateTokensForMessages(originalHistory);
82923
83130
  const model = this.agent.config.model;
82924
83131
  const isUpdate = extractPreviousSummary(originalHistory) !== null;
82925
83132
  let retryCount = 0;
@@ -82955,24 +83162,27 @@ var FullCompaction = class {
82955
83162
  } catch (error) {
82956
83163
  if (error instanceof APIContextOverflowError || error instanceof TruncatedError) {
82957
83164
  const reduced = this.strategy.reduceCompactOnOverflow(messagesToCompact);
82958
- if (reduced < compactedCount) compactedCount = reduced;
82959
- else {
82960
- this.agent.log.warn("compaction overflow at minimum split, falling back to re-summarize", {
82961
- compactedCount,
82962
- tokensBefore: estimateTokensForMessages(messagesToCompact)
82963
- });
82964
- const result = await summarizeWithFallback(messagesToCompact, summarizeOnce);
82965
- summary = result.summary;
82966
- usage = result.usage;
82967
- break;
83165
+ if (reduced < compactedCount) {
83166
+ compactedCount = reduced;
83167
+ continue;
82968
83168
  }
82969
- } else if (!isRetryableGenerateError(error)) throw error;
83169
+ this.agent.log.warn("compaction overflow at minimum split, falling back to re-summarize", {
83170
+ compactedCount,
83171
+ tokensBefore: estimateTokensForMessages(messagesToCompact)
83172
+ });
83173
+ const result = await summarizeWithFallback(messagesToCompact, summarizeOnce);
83174
+ summary = result.summary;
83175
+ usage = result.usage;
83176
+ break;
83177
+ }
83178
+ if (!isRetryableGenerateError(error)) throw error;
82970
83179
  if (retryCount + 1 >= 5) throw error;
82971
- await sleepForRetry(delays[retryCount], signal);
83180
+ await sleepForRetry(computeDelayMs(error, delays, retryCount + 1), signal);
82972
83181
  retryCount += 1;
82973
83182
  }
82974
83183
  }
82975
83184
  if (usage !== null) this.agent.usage.record(model, usage);
83185
+ if (this.compacting !== owner) return void 0;
82976
83186
  const newHistory = this.agent.context.history;
82977
83187
  for (let i = 0; i < originalHistory.length; i++) if (newHistory[i] !== originalHistory[i]) {
82978
83188
  this.markCanceled("上下文已被更改(如 /revoke),压缩已取消");
@@ -82987,8 +83197,9 @@ var FullCompaction = class {
82987
83197
  } else this.lastCompactionFiles = void 0;
82988
83198
  for (const msg of messagesToCompactForOps) extractFileOpsFromMessage(msg, fileOps);
82989
83199
  const toolCallHistory = formatToolCallHistory(messagesToCompactForOps);
83200
+ const skillCandidateSummary = summary;
82990
83201
  const processedSummary = this.postProcessSummary(summary, fileOps, toolCallHistory, compactedCount);
82991
- const tokensAfter = estimateTokens$1(processedSummary) + estimateTokensForMessages(recent);
83202
+ const tokensAfter = systemPromptTokens + toolTokens + estimateTokens$1(processedSummary) + estimateTokensForMessages(recent);
82992
83203
  const fileLists = computeFileLists(fileOps);
82993
83204
  const MAX_PERSISTED_FILES = 100;
82994
83205
  const readFiles = fileLists.readFiles.slice(0, MAX_PERSISTED_FILES);
@@ -83012,20 +83223,23 @@ var FullCompaction = class {
83012
83223
  this.lowWaterMark = Math.floor(this.effectiveTokenCount * 1.1);
83013
83224
  await this.extractAndStoreMemos(processedSummary, messagesToCompactForOps);
83014
83225
  this.triggerPostCompactHook(data, result);
83015
- this.detectSkillCandidates(processedSummary);
83226
+ this.detectSkillCandidates(skillCandidateSummary);
83016
83227
  this.consecutiveCompactionFailures = 0;
83017
83228
  this._shouldInjectSessionSummary = true;
83018
83229
  } catch (error) {
83019
- const wasTimedOut = this.compactionTimedOut;
83020
- this.compactionTimedOut = false;
83230
+ const stale = this.compacting !== null && this.compacting !== owner;
83231
+ const wasTimedOut = stale ? false : this.compactionTimedOut;
83232
+ if (!stale) this.compactionTimedOut = false;
83021
83233
  if (!isAbortError$1(error) || wasTimedOut) {
83022
- const blockedByTurn = this.compacting?.blockedByTurn === true;
83023
- this.consecutiveCompactionFailures += 1;
83024
- if (this.consecutiveCompactionFailures >= MAX_CONSECUTIVE_FAILURES) this.agent.emitEvent({
83025
- type: "warning",
83026
- message: `压缩连续失败 ${String(this.consecutiveCompactionFailures)} 次,已自动暂停本回合的自动压缩。使用 /compact 手动重试。`,
83027
- code: "compaction_circuit_open"
83028
- });
83234
+ const blockedByTurn = stale || owner.blockedByTurn === true;
83235
+ if (!stale) {
83236
+ this.consecutiveCompactionFailures += 1;
83237
+ if (this.consecutiveCompactionFailures >= MAX_CONSECUTIVE_FAILURES) this.agent.emitEvent({
83238
+ type: "warning",
83239
+ message: `压缩连续失败 ${String(this.consecutiveCompactionFailures)} 次,已自动暂停本回合的自动压缩。使用 /compact 手动重试。`,
83240
+ code: "compaction_circuit_open"
83241
+ });
83242
+ }
83029
83243
  this.agent.log.error("compaction failed", {
83030
83244
  code: isNexumError(error) ? error.code : void 0,
83031
83245
  error,
@@ -83034,7 +83248,7 @@ var FullCompaction = class {
83034
83248
  compactedCount,
83035
83249
  tokensBefore
83036
83250
  });
83037
- this.markCanceled();
83251
+ if (!stale) this.markCanceled();
83038
83252
  if (!blockedByTurn) {
83039
83253
  const details = {
83040
83254
  model,
@@ -83046,7 +83260,7 @@ var FullCompaction = class {
83046
83260
  ...payload
83047
83261
  });
83048
83262
  }
83049
- if (blockedByTurn) {
83263
+ if (blockedByTurn && !stale) {
83050
83264
  if (isNexumError(error) && error.code === ErrorCodes.AUTH_LOGIN_REQUIRED) throw error;
83051
83265
  throw new NexumError(ErrorCodes.COMPACTION_FAILED, String(error), { cause: error });
83052
83266
  }
@@ -83137,27 +83351,41 @@ var FullCompaction = class {
83137
83351
  }
83138
83352
  /**
83139
83353
  * Detects [[skill-candidate: <name>|<purpose>|<evidence>]] markers in the
83140
- * compaction summary and emits a `skill_candidate` event for each one (at
83141
- * most one per compact). Best-effort and fully isolated: a parse failure or
83142
- * a missing marker never affects compaction or memory extraction — this
83143
- * method only reads the summary and emits an event.
83354
+ * compaction summary and emits a `skill_candidate` event (at most one per
83355
+ * compact). Best-effort and fully isolated: a parse failure or a missing
83356
+ * marker never affects compaction or memory extraction — this method only
83357
+ * reads the summary and emits an event.
83358
+ *
83359
+ * Tolerant parsing: the evidence segment may contain `|` characters and
83360
+ * newlines, and the explicit `[[skill-candidate: none]]` marker (emitted
83361
+ * when the model found nothing) is recognized and skipped. When several
83362
+ * markers appear (e.g. an old one carried over into an update summary),
83363
+ * the LAST valid candidate wins — the templates mandate the marker as the
83364
+ * final line of the response, so the trailing one is the model's verdict
83365
+ * for this round.
83144
83366
  */
83145
83367
  detectSkillCandidates(summary) {
83146
83368
  try {
83147
- const matches = summary.matchAll(/\[\[skill-candidate:\s*([^|\]]+)\|([^|\]]+)\|([^|\]]+)\]\]/g);
83369
+ const matches = summary.matchAll(/\[\[skill-candidate:\s*([^|\]]+?)(?:\|([^|\]]*)\|([\s\S]*?))?\]\]/g);
83370
+ let chosen;
83148
83371
  for (const m of matches) {
83149
- const name = m[1].trim();
83372
+ const name = m[1]?.trim() ?? "";
83150
83373
  if (name.length === 0) continue;
83151
- this.agent.emitEvent({
83152
- type: "skill_candidate",
83153
- candidate: {
83154
- name,
83155
- purpose: m[2].trim(),
83156
- evidence: m[3].trim()
83157
- }
83158
- });
83159
- break;
83374
+ if (name.toLowerCase() === "none") {
83375
+ chosen = void 0;
83376
+ continue;
83377
+ }
83378
+ if (m[2] === void 0) continue;
83379
+ chosen = {
83380
+ name,
83381
+ purpose: m[2].trim(),
83382
+ evidence: (m[3] ?? "").trim()
83383
+ };
83160
83384
  }
83385
+ if (chosen !== void 0) this.agent.emitEvent({
83386
+ type: "skill_candidate",
83387
+ candidate: chosen
83388
+ });
83161
83389
  } catch (error) {
83162
83390
  this.agent.log.warn("Skill candidate detection failed", { error: String(error) });
83163
83391
  }
@@ -83175,7 +83403,7 @@ var FullCompaction = class {
83175
83403
  */
83176
83404
  postProcessSummary(summary, fileOps, toolCallHistory, compactedCount) {
83177
83405
  const todos = this.agent.tools.storeData()["todo"] ?? [];
83178
- const base = summary.trim().replaceAll(/<files>[\s\S]*?<\/files>\s*/g, "").replace(/^> The conversation before this point was compacted:[\s\S]*?continue from here\.\s*\n+/m, "").trimEnd();
83406
+ const base = summary.trim().replaceAll(/<files>[\s\S]*?<\/files>\s*/g, "").replaceAll(/\[\[skill-candidate:[\s\S]*?\]\]\s*/g, "").replace(/^> The conversation before this point was compacted:[\s\S]*?continue from here\.\s*\n+/m, "").trimEnd();
83179
83407
  const sections = [];
83180
83408
  if (compactedCount > 0) sections.push(`> The conversation before this point was compacted: ${String(compactedCount)} earlier message(s) were omitted and are covered by this summary. Treat the summary below as working notes, not verbatim history — the messages after it continue from here.`);
83181
83409
  if (base.length > 0) sections.push(base);
@@ -84501,7 +84729,10 @@ var ConfigState = class {
84501
84729
  this._cwd = changed.cwd;
84502
84730
  this.agent.jian.chdir(changed.cwd);
84503
84731
  }
84504
- if (changed.modelAlias) this._modelAlias = changed.modelAlias;
84732
+ if (changed.modelAlias && changed.modelAlias !== this._modelAlias) {
84733
+ this._modelAlias = changed.modelAlias;
84734
+ this.agent.fullCompaction.resetLowWaterMark();
84735
+ }
84505
84736
  if (changed.profileName) this._profileName = changed.profileName;
84506
84737
  if (changed.thinkingLevel !== void 0) this._thinkingLevel = resolveThinkingEffort(changed.thinkingLevel, this.agent.nexumConfig?.thinking);
84507
84738
  if (changed.systemPrompt !== void 0) this._systemPrompt = changed.systemPrompt;
@@ -84705,6 +84936,42 @@ var ContextMemory = class {
84705
84936
  this.pendingToolResultIds = new Set(snapshot.pendingToolResultIds);
84706
84937
  this.deferredMessages = [...snapshot.deferredMessages];
84707
84938
  }
84939
+ /**
84940
+ * JSON-safe snapshot for wire persistence. `openSteps` values are recorded as
84941
+ * their index into `history` so restoring can rebuild the live reference
84942
+ * identity between history messages and open steps (see
84943
+ * {@link ContextMemoryJSONSnapshot}).
84944
+ */
84945
+ toJSONSnapshot() {
84946
+ return {
84947
+ history: [...this._history],
84948
+ tokenCount: this._tokenCount,
84949
+ tokenCountCoveredMessageCount: this.tokenCountCoveredMessageCount,
84950
+ openSteps: [...this.openSteps.entries()].map(([uuid, message]) => [uuid, this._history.indexOf(message)]),
84951
+ pendingToolResultIds: [...this.pendingToolResultIds],
84952
+ deferredMessages: [...this.deferredMessages]
84953
+ };
84954
+ }
84955
+ /**
84956
+ * Restore from a JSON-safe snapshot produced by {@link toJSONSnapshot}.
84957
+ * Open steps are re-attached to the exact history message objects they
84958
+ * pointed at, preserving reference identity: later `content.part`/`tool.call`
84959
+ * events and `applyCompaction` pruning operate on the same objects the
84960
+ * history array holds, exactly as they did in the live session.
84961
+ */
84962
+ restoreJSONSnapshot(snapshot) {
84963
+ this._history = [...snapshot.history];
84964
+ this._tokenCount = snapshot.tokenCount;
84965
+ this.tokenCountCoveredMessageCount = snapshot.tokenCountCoveredMessageCount;
84966
+ const openSteps = /* @__PURE__ */ new Map();
84967
+ for (const [uuid, historyIndex] of snapshot.openSteps) {
84968
+ const message = this._history[historyIndex];
84969
+ if (message !== void 0) openSteps.set(uuid, message);
84970
+ }
84971
+ this.openSteps = openSteps;
84972
+ this.pendingToolResultIds = new Set(snapshot.pendingToolResultIds);
84973
+ this.deferredMessages = [...snapshot.deferredMessages];
84974
+ }
84708
84975
  appendUserMessage(content, origin = USER_PROMPT_ORIGIN) {
84709
84976
  this.appendMessage({
84710
84977
  role: "user",
@@ -84818,6 +85085,11 @@ var ContextMemory = class {
84818
85085
  this.agent.injection.onContextCompacted(summary.compactedCount);
84819
85086
  this.agent.emitStatusUpdated();
84820
85087
  this.agent.microCompaction.reset();
85088
+ if (!this.agent.records.restoring) this.agent.records.logRecord({
85089
+ type: "context.snapshot",
85090
+ snapshot: this.toJSONSnapshot(),
85091
+ compactedHistory: [...this.agent.fullCompaction.compactedHistory]
85092
+ });
84821
85093
  }
84822
85094
  data() {
84823
85095
  return {
@@ -84875,7 +85147,16 @@ var ContextMemory = class {
84875
85147
  this.lastSentFingerprints = messages.map(messageFingerprint);
84876
85148
  if (prev.length === 0) return;
84877
85149
  const appended = messages.length - prev.length;
84878
- if (stable >= prev.length) return;
85150
+ if (stable >= prev.length) {
85151
+ if (appended > 0) this.agent.log.debug("prefix-stability: provider prompt cache prefix hit", {
85152
+ stablePrefixLength: stable,
85153
+ cachedPrefixTokens: estimateTokensForMessages(messages.slice(0, stable)),
85154
+ prevMessageCount: prev.length,
85155
+ currentMessageCount: messages.length,
85156
+ appendedSinceLast: appended
85157
+ });
85158
+ return;
85159
+ }
84879
85160
  this.agent.log.debug("prefix-stability: provider prompt cache prefix broke", {
84880
85161
  stablePrefixLength: stable,
84881
85162
  prevMessageCount: prev.length,
@@ -84934,6 +85215,7 @@ var ContextMemory = class {
84934
85215
  ...message,
84935
85216
  role: "tool",
84936
85217
  isError: event.result.isError,
85218
+ toolResultMessage: event.result.message,
84937
85219
  useless: event.result.isError !== true && event.result.useless === true ? true : void 0
84938
85220
  });
84939
85221
  this.pendingToolResultIds.delete(event.toolCallId);
@@ -84996,6 +85278,30 @@ var ContextMemory = class {
84996
85278
  });
84997
85279
  }
84998
85280
  }
85281
+ /**
85282
+ * Drop in-flight assistant messages that cannot be serialized into a valid
85283
+ * provider request. An interrupted or empty step leaves an open assistant
85284
+ * message whose content is either empty or only "think" parts; after
85285
+ * projection it serializes to a message with no content and no tool_calls,
85286
+ * which strict OpenAI-compatible gateways reject with a 400 on every later
85287
+ * request. Messages carrying any sendable part (text / image / audio / video)
85288
+ * or tool calls are kept.
85289
+ */
85290
+ dropVacuousOpenMessages() {
85291
+ for (const [uuid, message] of this.openSteps) {
85292
+ if (message.content.some((part) => part.type !== "think") || message.toolCalls.length > 0) continue;
85293
+ const index = this._history.indexOf(message);
85294
+ if (index !== -1) {
85295
+ this._history.splice(index, 1);
85296
+ this.agent.injection.onContextMessageRemoved(index);
85297
+ if (index < this.tokenCountCoveredMessageCount) {
85298
+ this.tokenCountCoveredMessageCount--;
85299
+ this._tokenCount = Math.max(0, this._tokenCount - estimateTokensForMessages([message]));
85300
+ }
85301
+ }
85302
+ this.openSteps.delete(uuid);
85303
+ }
85304
+ }
84999
85305
  };
85000
85306
  function toolResultOutputForModel(result) {
85001
85307
  const output = result.output;
@@ -85746,6 +86052,39 @@ var HookEngine = class {
85746
86052
  for (const [event, hooks] of this.byEvent.entries()) result[event] = hooks.length;
85747
86053
  return result;
85748
86054
  }
86055
+ /**
86056
+ * Register a hook at runtime (e.g. when a plugin activates). Returns an
86057
+ * unregister function for symmetric removal when the plugin deactivates.
86058
+ * The existing constructor-injected hooks are unaffected; the byEvent map
86059
+ * stays the single source of truth so trigger paths need no changes.
86060
+ */
86061
+ register(hook) {
86062
+ const entries = this.byEvent.get(hook.event) ?? [];
86063
+ entries.push(hook);
86064
+ this.byEvent.set(hook.event, entries);
86065
+ return () => {
86066
+ this.unregister(hook);
86067
+ };
86068
+ }
86069
+ /**
86070
+ * Register several hooks at once (e.g. a plugin's manifest hooks). Returns
86071
+ * a single function that unregisters all of them.
86072
+ */
86073
+ registerAll(hooks) {
86074
+ const unregisters = hooks.map((hook) => this.register(hook));
86075
+ return () => {
86076
+ for (const unregister of unregisters) unregister();
86077
+ };
86078
+ }
86079
+ unregister(hook) {
86080
+ const entries = this.byEvent.get(hook.event);
86081
+ if (entries === void 0) return;
86082
+ const index = entries.lastIndexOf(hook);
86083
+ if (index >= 0) {
86084
+ entries.splice(index, 1);
86085
+ if (entries.length === 0) this.byEvent.delete(hook.event);
86086
+ }
86087
+ }
85749
86088
  trigger(event, args = {}) {
85750
86089
  try {
85751
86090
  return this.triggerInner(event, args).catch(() => []);
@@ -88833,6 +89172,14 @@ const MISSING_MEDIA_PLACEHOLDER = "[media missing]";
88833
89172
  function isBlobRef(url) {
88834
89173
  return url.startsWith(BLOBREF_PROTOCOL);
88835
89174
  }
89175
+ /**
89176
+ * Blob storage for large message content (images, files, videos). Content above
89177
+ * the size threshold is offloaded to blobs in `blobsDir` and referenced from
89178
+ * wire records as `blobref:` URLs; `rehydrateParts` resolves them back to
89179
+ * inline data when a session is loaded. A single filesystem implementation is
89180
+ * used across the engine; the class boundary is what keeps blob details out of
89181
+ * the wire/records code.
89182
+ */
88836
89183
  var BlobStore = class {
88837
89184
  blobsDir;
88838
89185
  threshold;
@@ -88881,6 +89228,33 @@ var BlobStore = class {
88881
89228
  }
88882
89229
  };
88883
89230
  }
89231
+ case "context.snapshot": {
89232
+ const history = await Promise.all(record.snapshot.history.map(async (message) => {
89233
+ const content = await this.offloadParts(message.content);
89234
+ return content === message.content ? message : {
89235
+ ...message,
89236
+ content
89237
+ };
89238
+ }));
89239
+ const deferredMessages = await Promise.all(record.snapshot.deferredMessages.map(async (message) => {
89240
+ const content = await this.offloadParts(message.content);
89241
+ return content === message.content ? message : {
89242
+ ...message,
89243
+ content
89244
+ };
89245
+ }));
89246
+ const historyChanged = history.some((message, i) => message !== record.snapshot.history[i]);
89247
+ const deferredChanged = deferredMessages.some((message, i) => message !== record.snapshot.deferredMessages[i]);
89248
+ if (!historyChanged && !deferredChanged) return record;
89249
+ return {
89250
+ ...record,
89251
+ snapshot: {
89252
+ ...record.snapshot,
89253
+ history,
89254
+ deferredMessages
89255
+ }
89256
+ };
89257
+ }
88884
89258
  default: return record;
88885
89259
  }
88886
89260
  }
@@ -89024,6 +89398,28 @@ function asMediaContainer(value) {
89024
89398
  }
89025
89399
  //#endregion
89026
89400
  //#region ../../packages/agent-core/src/agent/records/index.ts
89401
+ /**
89402
+ * Record types whose state is fully captured by a `context.snapshot` record.
89403
+ * When a snapshot exists, every one of these that predates it is skipped during
89404
+ * replay because the snapshot already holds the folded context memory. Note
89405
+ * `micro_compaction.apply` is written with an `as never` cast (it is not part of
89406
+ * the AgentRecord union), so it is matched here by its literal type string.
89407
+ *
89408
+ * `full_compaction.complete` is included because its only lasting effect is
89409
+ * pushing onto `compactedHistory` — a debug trail rendered from the pre-fold
89410
+ * history. Snapshot replay skips that pre-fold history, so the trail would be
89411
+ * re-rendered as empty; the snapshot carries the trail itself instead.
89412
+ */
89413
+ const SNAPSHOT_FOLDED_CONTEXT_TYPES = new Set([
89414
+ "context.append_message",
89415
+ "context.append_loop_event",
89416
+ "context.apply_compaction",
89417
+ "micro_compaction.apply",
89418
+ "full_compaction.complete"
89419
+ ]);
89420
+ function isSnapshotFoldedContextRecord(type) {
89421
+ return SNAPSHOT_FOLDED_CONTEXT_TYPES.has(type);
89422
+ }
89027
89423
  function restoreAgentRecord(agent, input) {
89028
89424
  switch (input.type) {
89029
89425
  case "metadata": return;
@@ -89106,6 +89502,17 @@ function restoreAgentRecord(agent, input) {
89106
89502
  case "context.apply_compaction":
89107
89503
  agent.context.applyCompaction(input);
89108
89504
  return;
89505
+ case "context.snapshot":
89506
+ agent.context.restoreJSONSnapshot(input.snapshot);
89507
+ agent.fullCompaction.restoreCompactedHistory(input.compactedHistory);
89508
+ for (const message of agent.context.history) {
89509
+ if (message.origin?.kind === "background_task") agent.background.markDeliveredNotification(message.origin);
89510
+ agent.replayBuilder.push({
89511
+ type: "message",
89512
+ message
89513
+ });
89514
+ }
89515
+ return;
89109
89516
  case "tools.register_user_tool":
89110
89517
  agent.tools.registerUserTool(input);
89111
89518
  return;
@@ -89184,8 +89591,19 @@ var AgentRecords = class {
89184
89591
  protocol_version: "1.4"
89185
89592
  };
89186
89593
  replayedRecords.push(migratedRecord);
89187
- this.restore(migratedRecord);
89188
89594
  }
89595
+ let snapshotIndex = -1;
89596
+ for (let i = replayedRecords.length - 1; i >= 0; i--) if (replayedRecords[i]?.type === "context.snapshot") {
89597
+ snapshotIndex = i;
89598
+ break;
89599
+ }
89600
+ for (let i = 0; i < replayedRecords.length; i++) {
89601
+ const record = replayedRecords[i];
89602
+ if (!record) continue;
89603
+ if (i < snapshotIndex && isSnapshotFoldedContextRecord(record.type)) continue;
89604
+ this.restore(record);
89605
+ }
89606
+ this.agent.context.dropVacuousOpenMessages();
89189
89607
  if (shouldRewrite) {
89190
89608
  this.persistence.rewrite(replayedRecords);
89191
89609
  await this.persistence.flush();
@@ -102410,6 +102828,13 @@ var ToolManager = class {
102410
102828
  getTodos() {
102411
102829
  return cloneTodos(this.store.todo ?? []);
102412
102830
  }
102831
+ /**
102832
+ * Register a user/plugin tool. This is the public entry point for any
102833
+ * third-party extension (plugins, skills, future harness adapters) to expose
102834
+ * a tool — built-in tools use the internal `builtinTools` map and should not
102835
+ * route through here. Prefer `defineTool()` for the typed high-level API;
102836
+ * this method takes a hand-written registration.
102837
+ */
102413
102838
  registerUserTool(input) {
102414
102839
  this.agent.records.logRecord({
102415
102840
  type: "tools.register_user_tool",
@@ -102445,6 +102870,10 @@ var ToolManager = class {
102445
102870
  this.userTools.delete(name);
102446
102871
  this.enabledTools.delete(name);
102447
102872
  }
102873
+ /**
102874
+ * Register an MCP server (and its tools). Public entry point for third-party
102875
+ * extensions to expose MCP-backed tools; built-in tooling does not use it.
102876
+ */
102448
102877
  registerMcpServer(serverName, client, tools, enabledTools, options) {
102449
102878
  this.unregisterMcpServer(serverName);
102450
102879
  const qualifiedNames = [];
@@ -102834,7 +103263,8 @@ function mapLoopEvent(event, turnId) {
102834
103263
  toolCallId: event.toolCallId,
102835
103264
  output: event.result.output,
102836
103265
  isError: event.result.isError,
102837
- display: event.result.isError === true ? void 0 : event.result.display
103266
+ display: event.result.isError === true ? void 0 : event.result.display,
103267
+ message: event.result.message
102838
103268
  };
102839
103269
  case "turn.interrupted":
102840
103270
  if (event.activeStep === void 0) return void 0;
@@ -103547,6 +103977,11 @@ var TurnFlow = class {
103547
103977
  } catch (error) {
103548
103978
  this.agent.log.error("closeAbandonedToolExchange failed", error);
103549
103979
  }
103980
+ try {
103981
+ this.agent.context.dropVacuousOpenMessages();
103982
+ } catch (error) {
103983
+ console.error("dropVacuousOpenMessages failed", error);
103984
+ }
103550
103985
  if (this.currentId === turnId) this.agent.usage.endTurn();
103551
103986
  this.agent.emitEvent(ended);
103552
103987
  if (standalone && this.currentId === turnId) this.activeTurn = null;
@@ -104274,6 +104709,8 @@ var Agent = class {
104274
104709
  mcp;
104275
104710
  hooks;
104276
104711
  log;
104712
+ /** In-process event bus for extensions running inside the agent process. */
104713
+ eventBus;
104277
104714
  blobStore;
104278
104715
  records;
104279
104716
  fullCompaction;
@@ -104297,6 +104734,8 @@ var Agent = class {
104297
104734
  workingSet;
104298
104735
  dreamTracker;
104299
104736
  replayBuilder;
104737
+ /** Read-only manifest of the core engine subsystems (see {@link AgentServices}). */
104738
+ services;
104300
104739
  lastLlmConfigLogSignature;
104301
104740
  sharedEmbeddingEngine;
104302
104741
  resolveRuntimeSystemPrompt;
@@ -104315,6 +104754,7 @@ var Agent = class {
104315
104754
  this.subagentHost = options.subagentHost;
104316
104755
  this.mcp = options.mcp;
104317
104756
  this.hooks = options.hookEngine;
104757
+ this.eventBus = new EventSubscriptionBus();
104318
104758
  const embedCacheDir = options.nexumHomeDir !== void 0 ? join$1(options.nexumHomeDir, "cache", "fastembed") : void 0;
104319
104759
  this.sharedEmbeddingEngine = createFastEmbedEngine(embedCacheDir);
104320
104760
  this.log = options.log ?? log;
@@ -104349,6 +104789,25 @@ var Agent = class {
104349
104789
  this.workingSet = new WorkingSet();
104350
104790
  this.dreamTracker = new DreamTracker(nexumHomeDir ?? "");
104351
104791
  this.replayBuilder = new ReplayBuilder(this);
104792
+ this.services = {
104793
+ records: this.records,
104794
+ context: this.context,
104795
+ config: this.config,
104796
+ turn: this.turn,
104797
+ injection: this.injection,
104798
+ permission: this.permission,
104799
+ planMode: this.planMode,
104800
+ usage: this.usage,
104801
+ tools: this.tools,
104802
+ skills: this.skills,
104803
+ background: this.background,
104804
+ goal: this.goal,
104805
+ sessionMemory: this.sessionMemory,
104806
+ workingSet: this.workingSet,
104807
+ fullCompaction: this.fullCompaction,
104808
+ microCompaction: this.microCompaction,
104809
+ systemPrompt: () => this.getRuntimeSystemPrompt()
104810
+ };
104352
104811
  }
104353
104812
  /**
104354
104813
  * Promise that resolves once the shared memory store (and any legacy migration)
@@ -104515,6 +104974,26 @@ var Agent = class {
104515
104974
  });
104516
104975
  };
104517
104976
  }
104977
+ /**
104978
+ * Bounded-retry wrapper around `generate` for auxiliary LLM calls (exit
104979
+ * memory extraction, side questions, knowledge-base text generation, skill
104980
+ * plan generation). These call the model directly, outside the loop's
104981
+ * step-retry layer, and SDK-level retries are disabled — without this they
104982
+ * would hard-fail on any transient 429/5xx. Mirrors the main loop's policy:
104983
+ * only retryable errors, exponential backoff, bounded attempts.
104984
+ */
104985
+ async generateWithRetry(provider, systemPrompt, tools, messages, maxAttempts = 3) {
104986
+ const delays = retryBackoffDelays(maxAttempts);
104987
+ for (let attempt = 1;; attempt++) try {
104988
+ return await this.generate(provider, systemPrompt, [...tools], [...messages]);
104989
+ } catch (error) {
104990
+ if (attempt >= maxAttempts || !isRetryableGenerateError(error)) throw error;
104991
+ const delayMs = computeDelayMs(error, delays, attempt);
104992
+ await new Promise((resolve) => {
104993
+ setTimeout(resolve, delayMs);
104994
+ });
104995
+ }
104996
+ }
104518
104997
  get llm() {
104519
104998
  const model = this.config.model;
104520
104999
  const provider = this.config.provider.withThinking(this.config.thinkingLevel);
@@ -104766,7 +105245,7 @@ var Agent = class {
104766
105245
  }).join("\n");
104767
105246
  const userPrompt = buildExitExtractionPrompt(sessionId, history.length, sampleText);
104768
105247
  try {
104769
- const response = await this.generate(this.config.provider, EXIT_EXTRACTION_SYSTEM_PROMPT, [], [{
105248
+ const response = await this.generateWithRetry(this.config.provider, EXIT_EXTRACTION_SYSTEM_PROMPT, [], [{
104770
105249
  role: "user",
104771
105250
  content: [{
104772
105251
  type: "text",
@@ -104815,7 +105294,7 @@ var Agent = class {
104815
105294
  const conversationContext = contextParts.join("\n\n");
104816
105295
  const system = conversationContext ? `${SIDE_QUESTION_SYSTEM}\n\n<conversation_context>\n${conversationContext}\n</conversation_context>` : SIDE_QUESTION_SYSTEM;
104817
105296
  if (!this.config.hasModel) return "No model configured. Run `nexum config` or use `/model` to set a default model.";
104818
- return (await this.generate(this.config.provider, system, [], [{
105297
+ return (await this.generateWithRetry(this.config.provider, system, [], [{
104819
105298
  role: "user",
104820
105299
  content: [{
104821
105300
  type: "text",
@@ -104831,7 +105310,7 @@ var Agent = class {
104831
105310
  */
104832
105311
  async generateText(systemPrompt, userPrompt) {
104833
105312
  if (!this.config.hasModel) throw new Error("No model configured. Run `nexum config` or use `/model` to set a default model.");
104834
- return (await this.generate(this.config.provider, systemPrompt, [], [{
105313
+ return (await this.generateWithRetry(this.config.provider, systemPrompt, [], [{
104835
105314
  role: "user",
104836
105315
  content: [{
104837
105316
  type: "text",
@@ -104842,6 +105321,7 @@ var Agent = class {
104842
105321
  }
104843
105322
  emitEvent(event) {
104844
105323
  if (this.records.restoring) return;
105324
+ this.eventBus.dispatch(event);
104845
105325
  this.rpc?.emitEvent?.(event)?.catch(() => {});
104846
105326
  }
104847
105327
  emitStatusUpdated() {
@@ -109240,8 +109720,10 @@ var SessionSubagentHost = class {
109240
109720
  if (gitContext) childPrompt = `${gitContext}\n\n${childPrompt}`;
109241
109721
  }
109242
109722
  const origin = options.origin ?? {
109243
- kind: "system_trigger",
109244
- name: "subagent"
109723
+ kind: "subagent",
109724
+ parentAgentId: this.ownerAgentId,
109725
+ parentToolCallId: options.parentToolCallId,
109726
+ subagentName: profileName
109245
109727
  };
109246
109728
  child.turn.prompt([{
109247
109729
  type: "text",
@@ -109886,6 +110368,90 @@ function createRPC() {
109886
110368
  return [leftClient, rightClient];
109887
110369
  }
109888
110370
  //#endregion
110371
+ //#region ../../packages/agent-core/src/plugin/runtime/extension.ts
110372
+ /**
110373
+ * Loads and activates code-entry plugins inside the agent process.
110374
+ *
110375
+ * Responsibilities:
110376
+ * - `discover()` — pick plugins whose manifest declares an `entryPoint`
110377
+ * - `load()` — dynamic-import the entry point (cached per path)
110378
+ * - `activate()` — inject declared manifest hooks into the agent's HookEngine,
110379
+ * then call the plugin's `activate(context)`; tools are registered by the
110380
+ * plugin itself via `context.services.tools.registerUserTool`
110381
+ * - `deactivate()` — symmetric removal (hooks + deactivate hook), isolated so
110382
+ * a failing plugin never breaks the agent
110383
+ *
110384
+ * Activation is deliberately lazy (a `/plugin activate` command or explicit
110385
+ * config opt-in), so merely installing a plugin never executes its code.
110386
+ */
110387
+ var ExtensionRuntime = class {
110388
+ loaded = /* @__PURE__ */ new Map();
110389
+ activations = /* @__PURE__ */ new Map();
110390
+ /** Plugins that declare a code entry point, in installation order. */
110391
+ discover(plugins) {
110392
+ const result = [];
110393
+ for (const plugin of plugins) {
110394
+ if (plugin.manifest?.entryPoint === void 0) continue;
110395
+ result.push({
110396
+ pluginId: plugin.id,
110397
+ entryPoint: plugin.manifest.entryPoint,
110398
+ manifest: plugin.manifest
110399
+ });
110400
+ }
110401
+ return result;
110402
+ }
110403
+ /** Import (and cache) an entry point module. Rejects for non-conforming modules. */
110404
+ async load(entryPoint) {
110405
+ const cached = this.loaded.get(entryPoint);
110406
+ if (cached !== void 0) return cached;
110407
+ const module = normalizeExtensionModule(await import(entryPoint));
110408
+ this.loaded.set(entryPoint, module);
110409
+ return module;
110410
+ }
110411
+ /** Activate a discovered plugin against a live agent. */
110412
+ async activate(agent, extension) {
110413
+ if (this.activations.has(extension.pluginId)) throw new Error(`Plugin "${extension.pluginId}" is already active`);
110414
+ const module = await this.load(extension.entryPoint);
110415
+ let hooksUnregister;
110416
+ if (extension.manifest.hooks !== void 0 && extension.manifest.hooks.length > 0) hooksUnregister = agent.hooks?.registerAll(extension.manifest.hooks);
110417
+ const context = {
110418
+ services: agent.services,
110419
+ events: agent.eventBus,
110420
+ config: extension.manifest.config,
110421
+ pluginId: extension.pluginId
110422
+ };
110423
+ try {
110424
+ await module.activate(context);
110425
+ } catch (error) {
110426
+ hooksUnregister?.();
110427
+ throw error;
110428
+ }
110429
+ this.activations.set(extension.pluginId, {
110430
+ module,
110431
+ hooksUnregister
110432
+ });
110433
+ }
110434
+ /** Deactivate a plugin: remove its hooks and call its deactivate hook. */
110435
+ async deactivate(pluginId) {
110436
+ const activation = this.activations.get(pluginId);
110437
+ if (activation === void 0) return;
110438
+ activation.hooksUnregister?.();
110439
+ this.activations.delete(pluginId);
110440
+ await activation.module.deactivate?.();
110441
+ }
110442
+ isActive(pluginId) {
110443
+ return this.activations.has(pluginId);
110444
+ }
110445
+ activePluginIds() {
110446
+ return [...this.activations.keys()];
110447
+ }
110448
+ };
110449
+ function normalizeExtensionModule(mod) {
110450
+ const candidate = mod?.default ?? mod;
110451
+ if (candidate === void 0 || typeof candidate.activate !== "function") throw new Error("Plugin entry point must export an activate(context) function");
110452
+ return candidate;
110453
+ }
110454
+ //#endregion
109889
110455
  //#region ../../packages/agent-core/src/tools/providers/fetch-cache.ts
109890
110456
  /**
109891
110457
  * Simple in-memory LRU cache for URL fetch results.
@@ -126208,6 +126774,8 @@ var NexumCore = class {
126208
126774
  subagentModelBindings;
126209
126775
  sessionStore;
126210
126776
  plugins;
126777
+ /** Loads/activates code-entry plugins (manifest `entryPoint`). */
126778
+ extensionRuntime = new ExtensionRuntime();
126211
126779
  pluginsReady;
126212
126780
  pluginsLoadError;
126213
126781
  constructor(rpcClient, options = {}) {
@@ -126500,6 +127068,37 @@ var NexumCore = class {
126500
127068
  registerTool({ sessionId, ...payload }) {
126501
127069
  return this.sessionApi(sessionId).registerTool(payload);
126502
127070
  }
127071
+ /**
127072
+ * Activate a code plugin (one with a manifest `entryPoint`) on the session's
127073
+ * main agent: injects declared manifest hooks into the agent's HookEngine and
127074
+ * calls the plugin's `activate(context)`.
127075
+ */
127076
+ async activatePlugin({ sessionId, pluginId }) {
127077
+ await this.pluginsReady;
127078
+ const session = this.sessions.get(sessionId);
127079
+ if (session === void 0) throw new NexumError(ErrorCodes.SESSION_NOT_FOUND, `Session "${sessionId}" was not found`, { details: { sessionId } });
127080
+ const agent = session.agents.get("main");
127081
+ if (agent === void 0) throw new NexumError(ErrorCodes.AGENT_NOT_FOUND, `Session "${sessionId}" has no main agent`, { details: { sessionId } });
127082
+ const plugin = this.plugins.list().find((record) => record.id === pluginId);
127083
+ if (plugin === void 0) throw new NexumError(ErrorCodes.PLUGIN_NOT_FOUND, `Plugin "${pluginId}" was not found`, { details: { pluginId } });
127084
+ const [extension] = this.extensionRuntime.discover([plugin]);
127085
+ if (extension === void 0) throw new NexumError(ErrorCodes.PLUGIN_NOT_FOUND, `Plugin "${pluginId}" has no code entry point`, { details: { pluginId } });
127086
+ await this.extensionRuntime.activate(agent, extension);
127087
+ }
127088
+ /** Deactivate a code plugin (removes its hooks and runs its deactivate). */
127089
+ async deactivatePlugin({ pluginId }) {
127090
+ await this.pluginsReady;
127091
+ await this.extensionRuntime.deactivate(pluginId);
127092
+ }
127093
+ /** Code plugins the runtime can load, with their activation state. */
127094
+ async pluginExtensionStatus() {
127095
+ await this.pluginsReady;
127096
+ return this.extensionRuntime.discover(this.plugins.list()).map((extension) => ({
127097
+ pluginId: extension.pluginId,
127098
+ entryPoint: extension.entryPoint,
127099
+ active: this.extensionRuntime.isActive(extension.pluginId)
127100
+ }));
127101
+ }
126503
127102
  unregisterTool({ sessionId, ...payload }) {
126504
127103
  return this.sessionApi(sessionId).unregisterTool(payload);
126505
127104
  }
@@ -127391,6 +127990,18 @@ var SDKRpcClient = class {
127391
127990
  args: input.args
127392
127991
  });
127393
127992
  }
127993
+ async activatePlugin(input) {
127994
+ return (await this.getRpc()).activatePlugin({
127995
+ sessionId: input.sessionId,
127996
+ pluginId: input.pluginId
127997
+ });
127998
+ }
127999
+ async deactivatePlugin(input) {
128000
+ return (await this.getRpc()).deactivatePlugin({ pluginId: input.pluginId });
128001
+ }
128002
+ async pluginExtensionStatus(input) {
128003
+ return (await this.getRpc()).pluginExtensionStatus({ sessionId: input.sessionId });
128004
+ }
127394
128005
  async undoHistory(input) {
127395
128006
  return (await this.getRpc()).undoHistory({
127396
128007
  sessionId: input.sessionId,
@@ -127860,6 +128471,30 @@ var Session = class {
127860
128471
  });
127861
128472
  }
127862
128473
  /**
128474
+ * Activate a code-entry plugin (manifest `entryPoint`) on the session's main
128475
+ * agent. Lazy and isolated: the plugin's code runs only after this call.
128476
+ */
128477
+ async activatePlugin(pluginId) {
128478
+ this.ensureOpen();
128479
+ await this.rpc.activatePlugin({
128480
+ sessionId: this.id,
128481
+ pluginId
128482
+ });
128483
+ }
128484
+ /** Deactivate a code-entry plugin (removes its hooks, runs its deactivate). */
128485
+ async deactivatePlugin(pluginId) {
128486
+ this.ensureOpen();
128487
+ await this.rpc.deactivatePlugin({
128488
+ sessionId: this.id,
128489
+ pluginId
128490
+ });
128491
+ }
128492
+ /** Code plugins the runtime can load, with their activation state. */
128493
+ async pluginExtensionStatus() {
128494
+ this.ensureOpen();
128495
+ return this.rpc.pluginExtensionStatus({ sessionId: this.id });
128496
+ }
128497
+ /**
127863
128498
  * Remove the last N user-prompt turns from the conversation history.
127864
128499
  * The TUI is responsible for cleaning up the corresponding transcript
127865
128500
  * entries and UI components after this call succeeds.
@@ -128290,7 +128925,7 @@ function applyCatalogProvider(config, options) {
128290
128925
  config.thinking = {
128291
128926
  ...config.thinking,
128292
128927
  mode: thinkingLevel === "off" ? "off" : "on",
128293
- effort: thinkingLevel
128928
+ effort: thinkingLevel === "off" ? config.thinking?.effort ?? "low" : thinkingLevel
128294
128929
  };
128295
128930
  return { defaultModel };
128296
128931
  }
@@ -128812,16 +129447,20 @@ const BUILTIN_SLASH_COMMANDS = [
128812
129447
  availability: "always"
128813
129448
  },
128814
129449
  {
128815
- name: "skill",
128816
- aliases: [
128817
- "skills",
128818
- "plugin",
128819
- "plugins"
128820
- ],
128821
- description: "registry.skill_desc",
129450
+ name: "plugin",
129451
+ aliases: ["skills", "plugins"],
129452
+ hiddenAliases: ["skill"],
129453
+ description: "registry.plugin_desc",
128822
129454
  priority: 202,
128823
129455
  availability: "always"
128824
129456
  },
129457
+ {
129458
+ name: "extension",
129459
+ aliases: ["extensions"],
129460
+ description: "registry.extension_desc",
129461
+ priority: 203,
129462
+ availability: "always"
129463
+ },
128825
129464
  {
128826
129465
  name: "fork",
128827
129466
  aliases: [],
@@ -128998,7 +129637,7 @@ const BUILTIN_SLASH_COMMANDS = [
128998
129637
  }
128999
129638
  ];
129000
129639
  function findBuiltInSlashCommand(commandName) {
129001
- return BUILTIN_SLASH_COMMANDS.find((command) => command.name === commandName || command.aliases.includes(commandName));
129640
+ return BUILTIN_SLASH_COMMANDS.find((command) => command.name === commandName || command.aliases.includes(commandName) || command.hiddenAliases?.includes(commandName) === true);
129002
129641
  }
129003
129642
  function resolveSlashCommandAvailability(command, args) {
129004
129643
  const availability = command.availability ?? "idle-only";
@@ -129180,6 +129819,7 @@ function isManagedUsageProvider(providerKey) {
129180
129819
  const STREAMING_ARGS_FIELD_RE = /"(path|file_path|command|pattern|query|url|description|title|name)"\s*:\s*"((?:\\.|[^"\\])*)"/g;
129181
129820
  const STREAMING_ARGS_PREVIEW_MAX_CHARS = 8 * 1024;
129182
129821
  const STREAMING_ARGS_BUFFER_MAX_CHARS = 1024 * 1024;
129822
+ const CHARS_PER_TOKEN = 2.5;
129183
129823
  //#endregion
129184
129824
  //#region src/tui/utils/event-payload.ts
129185
129825
  function appendStreamingArgsPreview(current, next) {
@@ -129659,6 +130299,7 @@ const DEFAULT_THINKING_LEVELS = [
129659
130299
  "low",
129660
130300
  "medium",
129661
130301
  "high",
130302
+ "xhigh",
129662
130303
  "max"
129663
130304
  ];
129664
130305
  function modelDisplayName$1(alias, model) {
@@ -129920,15 +130561,23 @@ function runModelSelector(host, modelDict) {
129920
130561
  });
129921
130562
  }
129922
130563
  function getWireTypeOptions() {
129923
- return [{
129924
- value: "openai",
129925
- label: t("prompts.wire_openai"),
129926
- description: t("prompts.wire_openai_desc")
129927
- }, {
129928
- value: "anthropic",
129929
- label: t("prompts.wire_anthropic"),
129930
- description: t("prompts.wire_anthropic_desc")
129931
- }];
130564
+ return [
130565
+ {
130566
+ value: "openai",
130567
+ label: t("prompts.wire_openai"),
130568
+ description: t("prompts.wire_openai_desc")
130569
+ },
130570
+ {
130571
+ value: "openai_responses",
130572
+ label: t("prompts.wire_openai_responses"),
130573
+ description: t("prompts.wire_openai_responses_desc")
130574
+ },
130575
+ {
130576
+ value: "anthropic",
130577
+ label: t("prompts.wire_anthropic"),
130578
+ description: t("prompts.wire_anthropic_desc")
130579
+ }
130580
+ ];
129932
130581
  }
129933
130582
  function getThinkingOptions() {
129934
130583
  return [
@@ -129947,6 +130596,14 @@ function getThinkingOptions() {
129947
130596
  {
129948
130597
  value: "high",
129949
130598
  label: t("prompts.thinking_high")
130599
+ },
130600
+ {
130601
+ value: "xhigh",
130602
+ label: t("prompts.thinking_xhigh")
130603
+ },
130604
+ {
130605
+ value: "max",
130606
+ label: t("prompts.thinking_max")
129950
130607
  }
129951
130608
  ];
129952
130609
  }
@@ -130223,16 +130880,29 @@ async function handleDiyConfig(host) {
130223
130880
  if (wire === void 0) return;
130224
130881
  const baseUrl = await promptTextInput$2(host, t("auth.input_api_url"), { subtitle: t("auth.api_url_hint") });
130225
130882
  if (baseUrl === void 0) return;
130883
+ if (!baseUrl.trim()) {
130884
+ host.showError(t("auth.error_empty_base_url"));
130885
+ return;
130886
+ }
130226
130887
  const apiKey = await promptTextInput$2(host, t("auth.input_api_key"), { subtitle: t("auth.api_key_hint") });
130227
130888
  if (apiKey === void 0) return;
130228
130889
  const modelId = await promptTextInput$2(host, t("auth.input_model"), { subtitle: t("auth.model_hint") });
130229
130890
  if (modelId === void 0) return;
130891
+ if (!modelId.trim()) {
130892
+ host.showError(t("auth.error_empty_model_id"));
130893
+ return;
130894
+ }
130230
130895
  const maxContextStr = await promptTextInput$2(host, t("auth.input_context"), {
130231
130896
  subtitle: t("auth.context_hint"),
130232
130897
  placeholder: "131072"
130233
130898
  });
130234
130899
  if (maxContextStr === void 0) return;
130235
- const maxContextTokens = parseInt(maxContextStr, 10) || 131072;
130900
+ const parsed = Number(maxContextStr.trim());
130901
+ if (!Number.isSafeInteger(parsed) || parsed < 4096) {
130902
+ host.showError(t("auth.error_invalid_context_size"));
130903
+ return;
130904
+ }
130905
+ const maxContextTokens = parsed;
130236
130906
  const thinkingLevel = await promptThinkingMode(host);
130237
130907
  if (thinkingLevel === void 0) return;
130238
130908
  const imageEnabled = await promptImageMode(host);
@@ -130257,28 +130927,22 @@ async function handleDiyConfig(host) {
130257
130927
  maxOutputSize: wire === "anthropic" ? 32e3 : void 0
130258
130928
  };
130259
130929
  if ((await host.harness.getConfig()).providers[providerId] !== void 0) await host.harness.removeProvider(providerId);
130260
- const config = await host.harness.getConfig();
130261
- config.providers[providerId] = {
130262
- type: wire,
130930
+ const freshConfig = await host.harness.getConfig();
130931
+ applyCatalogProvider(freshConfig, {
130932
+ providerId,
130933
+ wire,
130263
130934
  baseUrl,
130264
- apiKey
130265
- };
130266
- const models = config.models ?? {};
130267
- models[`${providerId}/${modelId}`] = catalogModelToAlias(providerId, catalogModel);
130268
- config.models = models;
130269
- config.defaultModel = `${providerId}/${modelId}`;
130270
- config.defaultThinking = thinkingLevel !== "off";
130271
- config.thinking = {
130272
- ...config.thinking,
130273
- mode: thinkingLevel === "off" ? "off" : "on",
130274
- effort: thinkingLevel
130275
- };
130935
+ apiKey,
130936
+ models: [catalogModel],
130937
+ selectedModelId: modelId,
130938
+ thinkingLevel
130939
+ });
130276
130940
  await host.harness.setConfig({
130277
- providers: config.providers,
130278
- models: config.models,
130279
- defaultModel: config.defaultModel,
130280
- defaultThinking: config.defaultThinking,
130281
- thinking: config.thinking
130941
+ providers: freshConfig.providers,
130942
+ models: freshConfig.models,
130943
+ defaultModel: freshConfig.defaultModel,
130944
+ defaultThinking: freshConfig.defaultThinking,
130945
+ thinking: freshConfig.thinking
130282
130946
  });
130283
130947
  await host.authFlow.refreshConfigAfterLogin();
130284
130948
  host.showStatus(t("auth.connected", { name: `${providerId} · ${modelId} (${wire})` }));
@@ -133315,6 +133979,7 @@ function getModelCycleLevel(models, alias, current) {
133315
133979
  "low",
133316
133980
  "medium",
133317
133981
  "high",
133982
+ "xhigh",
133318
133983
  "max"
133319
133984
  ];
133320
133985
  const currentIndex = levels.indexOf(current);
@@ -134650,7 +135315,7 @@ async function guidedGoalSetup(host) {
134650
135315
  host.showNotice(t("goal.storm_breaker"), t("goal.conflict_loop"));
134651
135316
  return;
134652
135317
  }
134653
- const { TextInputDialogComponent } = await import("./text-input-dialog-B5DB64Yp.mjs");
135318
+ const { TextInputDialogComponent } = await import("./text-input-dialog-BXXydm0u.mjs");
134654
135319
  const initialDesc = await promptText(host, TextInputDialogComponent, {
134655
135320
  title: t("goal.setup_title_initial"),
134656
135321
  subtitle: t("goal.setup_desc_hint"),
@@ -134671,7 +135336,7 @@ async function guidedGoalSetup(host) {
134671
135336
  await showGoalConfigWizard(host, session, confirmed.trim() || objective, false);
134672
135337
  }
134673
135338
  async function showGoalConfigWizard(host, session, objective, replace) {
134674
- const { TextInputDialogComponent } = await import("./text-input-dialog-B5DB64Yp.mjs");
135339
+ const { TextInputDialogComponent } = await import("./text-input-dialog-BXXydm0u.mjs");
134675
135340
  const turnInput = await promptNumber(host, TextInputDialogComponent, {
134676
135341
  title: t("goal.wizard_title", { objective }),
134677
135342
  subtitle: t("goal.budget_turns_hint"),
@@ -135139,6 +135804,52 @@ var WelcomeComponent = class {
135139
135804
  }
135140
135805
  };
135141
135806
  //#endregion
135807
+ //#region src/tui/utils/sanitize.ts
135808
+ /** Replace tabs with spaces, keeping column alignment. Default tab width 4. */
135809
+ function replaceTabs(text, tabWidth = 4) {
135810
+ return text.replaceAll(" ", " ".repeat(tabWidth));
135811
+ }
135812
+ /** Replace home directory occurrences, including inline paths, with ~. */
135813
+ function shortenPath(fullPath) {
135814
+ const home = nodeOs.homedir();
135815
+ if (home.length === 0) return fullPath;
135816
+ const variants = new Set([
135817
+ home,
135818
+ home.replaceAll("\\", "/"),
135819
+ home.replaceAll("/", "\\")
135820
+ ]);
135821
+ let shortened = fullPath;
135822
+ for (const variant of [...variants].toSorted((a, b) => b.length - a.length)) {
135823
+ const escaped = variant.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
135824
+ const flags = /^[A-Za-z]:[\\/]/.test(variant) ? "gi" : "g";
135825
+ shortened = shortened.replace(new RegExp(`${escaped}(?=$|[\\\\/])`, flags), "~");
135826
+ }
135827
+ return shortened;
135828
+ }
135829
+ /** Shared truncation length constants — no ad-hoc numbers in render paths. */
135830
+ const TRUNCATE_LENGTHS = {
135831
+ /** Approval panel file content previews */
135832
+ FILE_CONTENT: 300,
135833
+ /** Error messages (may embed file content) */
135834
+ ERROR: 200,
135835
+ /** Notice / informational text */
135836
+ NOTICE: 120,
135837
+ /** Status bar / one-liners */
135838
+ STATUS: 80
135839
+ };
135840
+ /** Strip escape sequences and non-printing terminal control characters. */
135841
+ function stripTerminalControlSequences(text) {
135842
+ return text.replaceAll(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").replaceAll(/\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "").replaceAll(/\u001B[P^_][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "").replaceAll(/\u001B[()][0-9A-Za-z]/g, "").replaceAll(/\u001B[=>78DEFHMc]/g, "").replaceAll(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g, "");
135843
+ }
135844
+ /** Sanitize untrusted human-readable metadata for safe TUI rendering. */
135845
+ function sanitizeHumanMetadata(text) {
135846
+ return shortenPath(replaceTabs(stripTerminalControlSequences(text))).split("\n").map((line) => truncateToWidth(line, TRUNCATE_LENGTHS.NOTICE));
135847
+ }
135848
+ /** Strip terminal control sequences from captured shell output. */
135849
+ function sanitizeShellOutput(output) {
135850
+ return stripTerminalControlSequences(output);
135851
+ }
135852
+ //#endregion
135142
135853
  //#region src/tui/components/messages/wrapped-line.ts
135143
135854
  var WrappedLine = class {
135144
135855
  firstPrefix;
@@ -135178,7 +135889,43 @@ var WrappedLine = class {
135178
135889
  }
135179
135890
  };
135180
135891
  //#endregion
135892
+ //#region src/tui/components/messages/tool-result-message.ts
135893
+ /** Safely renders human-only tool-result metadata using the live theme palette. */
135894
+ var ToolResultMessageComponent = class {
135895
+ colors;
135896
+ indent;
135897
+ linePrefix;
135898
+ lines;
135899
+ constructor(message, colors, indent, linePrefix) {
135900
+ this.colors = colors;
135901
+ this.indent = indent;
135902
+ this.linePrefix = linePrefix;
135903
+ this.lines = sanitizeHumanMetadata(message);
135904
+ }
135905
+ render(width) {
135906
+ const tone = chalk.hex(this.colors.textMuted);
135907
+ return this.lines.flatMap((line) => this.linePrefix === void 0 ? new Text(tone(line), this.indent, 0).render(width) : new WrappedLine(this.linePrefix, this.linePrefix, tone(line)).render(width));
135908
+ }
135909
+ invalidate() {}
135910
+ };
135911
+ //#endregion
135181
135912
  //#region src/tui/components/messages/agent-group.ts
135913
+ /**
135914
+ * AgentGroupComponent renders 2+ Agent tool calls from the same step as one group.
135915
+ *
135916
+ * Design:
135917
+ * - State container: each child Agent keeps its real state in its
135918
+ * `ToolCallComponent` (subagent meta, phase, sub-tool calls, tokens, text).
135919
+ * AgentGroup only stores references and does not copy state. Event handlers
135920
+ * still route through `state.pendingToolComponents.get(parent_tool_call_id)`.
135921
+ * - Subscription: `attach` registers a snapshot listener on each child so the
135922
+ * group can refresh when child state changes.
135923
+ * - Throttling: normal changes are coalesced into one render every 200ms.
135924
+ * Phase transitions (spawning -> running -> done/failed) flush immediately.
135925
+ * - Mounting: `NexumTUI` attaches the group to the transcript at the
135926
+ * right time; the group handles `invalidate` plus `ui.requestRender`.
135927
+ * - Ungrouping is not implemented. Once formed, a group stays grouped.
135928
+ */
135182
135929
  const THROTTLE_MS$1 = 200;
135183
135930
  var AgentGroupComponent = class extends Container {
135184
135931
  colors;
@@ -135322,6 +136069,7 @@ var AgentGroupComponent = class extends Container {
135322
136069
  const branchContinuation = isLast ? " " : " │ ";
135323
136070
  this.bodyContainer.addChild(new WrappedLine(branchPrefix, branchContinuation, `${namePart} ${descPart}${stats}${tail}`, { truncate: true }));
135324
136071
  const childPrefix = ` ${isLast ? " " : "│ "} `;
136072
+ for (const message of snap.resultMessages) this.bodyContainer.addChild(new ToolResultMessageComponent(message, colors, 0, childPrefix));
135325
136073
  if (snap.phase === "failed") {
135326
136074
  const errLine = (snap.errorText ?? t("agentgroup.failed")).split(/\r\n|\r|\n/).at(0) ?? t("agentgroup.failed");
135327
136075
  const errStr = chalk.hex(colors.error)(`${t("agentgroup.error")}${errLine}`);
@@ -135858,25 +136606,32 @@ var SpeedTracker = class {
135858
136606
  while (this.observations.length > 0 && this.observations[0].time < threshold) this.observations.shift();
135859
136607
  }
135860
136608
  /**
135861
- * Record one instantaneous tok/s reading, clamped to {@link SPEED_MAX} so a
135862
- * single oversized delta can't poison the windowed average. Non-finite or
135863
- * negative rates are ignored.
136609
+ * Record one delta and its inter-delta duration. Long gaps are stalls and
136610
+ * are ignored so they do not read as a false generation slow-down.
135864
136611
  */
135865
- observe(rate, now = performance.now()) {
135866
- if (!Number.isFinite(rate) || rate < 0) return;
136612
+ observe(tokens, elapsedMs, now = performance.now()) {
136613
+ if (!Number.isFinite(tokens) || tokens < 0) return;
136614
+ if (!Number.isFinite(elapsedMs) || elapsedMs <= 0) return;
136615
+ if (elapsedMs > 3e3) return;
135867
136616
  this.observations.push({
135868
136617
  time: now,
135869
- rate: Math.min(rate, 200)
136618
+ tokens,
136619
+ elapsedMs
135870
136620
  });
135871
136621
  this.prune(now);
135872
136622
  }
135873
- /** Windowed-average tok/s; 0 once observations age out of the window. */
136623
+ /** Windowed generation speed, computed as total tokens / total seconds. */
135874
136624
  getSpeed(now = performance.now()) {
135875
136625
  this.prune(now);
135876
136626
  if (this.observations.length === 0) return 0;
135877
- let sum = 0;
135878
- for (const o of this.observations) sum += o.rate;
135879
- return sum / this.observations.length;
136627
+ let totalTokens = 0;
136628
+ let totalElapsedMs = 0;
136629
+ for (const observation of this.observations) {
136630
+ totalTokens += observation.tokens;
136631
+ totalElapsedMs += observation.elapsedMs;
136632
+ }
136633
+ if (totalElapsedMs <= 0) return 0;
136634
+ return totalTokens / totalElapsedMs * 1e3;
135880
136635
  }
135881
136636
  reset() {
135882
136637
  this.observations = [];
@@ -135898,7 +136653,7 @@ function getSharedSpeedTracker() {
135898
136653
  * from a dim gray toward the theme accent as tok/s rises.
135899
136654
  */
135900
136655
  function lerpHex(from, to, t) {
135901
- const k = t < 0 ? 0 : t > 1 ? 1 : t;
136656
+ const k = t < 0 ? 0 : Math.min(1, t);
135902
136657
  const fr = Number.parseInt(from.slice(1, 3), 16);
135903
136658
  const fg = Number.parseInt(from.slice(3, 5), 16);
135904
136659
  const fb = Number.parseInt(from.slice(5, 7), 16);
@@ -135925,7 +136680,7 @@ function estimateTokens(delta) {
135925
136680
  * makes the color jump toward accent as soon as any tokens flow.
135926
136681
  */
135927
136682
  function easeSpeedRatio(ratio) {
135928
- const t = ratio < 0 ? 0 : ratio > 1 ? 1 : ratio;
136683
+ const t = ratio < 0 ? 0 : Math.min(1, ratio);
135929
136684
  return t * t * (3 - 2 * t);
135930
136685
  }
135931
136686
  //#endregion
@@ -135999,7 +136754,7 @@ var ThinkingComponent = class {
135999
136754
  if (this.mode === "live") {
136000
136755
  const visibleLines = contentLines.length > 2 ? contentLines.slice(contentLines.length - 2) : contentLines;
136001
136756
  const spinner = chalk.hex(this.color)(`${BRAILLE_SPINNER_FRAMES[this.spinnerFrame] ?? BRAILLE_SPINNER_FRAMES[0]} `);
136002
- const rate = Math.min(200, getSharedSpeedTracker().getSpeed());
136757
+ const rate = getSharedSpeedTracker().getSpeed();
136003
136758
  const rateSuffix = rate > .05 ? chalk.hex(lerpHex(this.dimColor, this.accentColor, easeSpeedRatio(rate / 200)))(` · ${rate.toFixed(1)} toks/s`) : "";
136004
136759
  return [
136005
136760
  "",
@@ -136021,7 +136776,7 @@ var ThinkingComponent = class {
136021
136776
  }
136022
136777
  const truncated = rendered.slice(0, 3);
136023
136778
  const remaining = contentLines.length - 2;
136024
- const hint = `... (${String(remaining)} more lines, ctrl+o to expand)`;
136779
+ const hint = t("thinking.more_lines", { count: String(remaining) });
136025
136780
  const hintWidth = Math.max(0, width - 2);
136026
136781
  truncated.push(" " + chalk.dim(truncateToWidth(hint, hintWidth, "…")));
136027
136782
  if (isRenderCacheEnabled()) {
@@ -136096,7 +136851,7 @@ var CachedContainer = class extends Container {
136096
136851
  //#region src/tui/theme/code-highlight-theme.ts
136097
136852
  function createCodeHighlightTheme(colors) {
136098
136853
  const keyword = chalk.hex(colors.mdCodeBlock);
136099
- const str = chalk.hex(colors.error);
136854
+ const str = chalk.hex(colors.mdLink);
136100
136855
  const num = chalk.hex(colors.primary);
136101
136856
  const fn = chalk.hex(colors.warning);
136102
136857
  const builtin = chalk.hex(colors.planMode);
@@ -136715,12 +137470,10 @@ var TruncatedOutputComponent = class {
136715
137470
  expanded;
136716
137471
  maxLines;
136717
137472
  hintFormatter;
136718
- collapseHintFormatter;
136719
137473
  constructor(output, options) {
136720
137474
  this.expanded = options.expanded;
136721
137475
  this.maxLines = options.maxLines ?? PREVIEW_LINES;
136722
137476
  this.hintFormatter = options.hintFormatter;
136723
- this.collapseHintFormatter = options.collapseHintFormatter;
136724
137477
  const tint = options.isError ? chalk.hex(options.colors.error) : chalk.dim;
136725
137478
  const cleaned = trimTrailingEmptyLines(output.split("\n")).join("\n");
136726
137479
  const stripped = options.isError ? cleaned.replaceAll(/\u001B\[[0-9;]*m/g, "") : cleaned;
@@ -136732,15 +137485,11 @@ var TruncatedOutputComponent = class {
136732
137485
  }
136733
137486
  render(width) {
136734
137487
  const contentLines = this.textComponent.render(width);
136735
- if (contentLines.length <= this.maxLines) return contentLines;
136736
- if (this.expanded) {
136737
- const collapseHint = this.collapseHintFormatter ? this.collapseHintFormatter() : t("shell.collapse_hint");
136738
- return [chalk.dim(collapseHint), ...contentLines];
136739
- }
137488
+ if (this.expanded || contentLines.length <= this.maxLines) return contentLines;
136740
137489
  const remaining = contentLines.length - this.maxLines;
136741
- const tail = contentLines.slice(-this.maxLines);
137490
+ const tail = this.maxLines <= 0 ? [] : contentLines.slice(-this.maxLines);
136742
137491
  const expandHint = this.hintFormatter ? this.hintFormatter(remaining) : t("shell.more_lines", { count: String(remaining) });
136743
- return [chalk.dim(expandHint), ...tail];
137492
+ return [...new Text(chalk.dim(expandHint), 2, 0).render(width), ...tail];
136744
137493
  }
136745
137494
  };
136746
137495
  const renderTruncated = (_toolCall, result, ctx) => {
@@ -136756,16 +137505,16 @@ const renderTruncated = (_toolCall, result, ctx) => {
136756
137505
  var ShellExecutionComponent = class extends Container {
136757
137506
  constructor(options) {
136758
137507
  super();
136759
- if (options.showCommand === true) this.addCommandPreview(options.command ?? "", options.commandPreviewLines);
137508
+ if (options.showCommand === true) this.addCommandPreview(options.command ?? "", options.commandPreviewLines, options.colors);
136760
137509
  if (options.result !== void 0) this.addResultPreview(options.result, options.colors, options.expanded ?? false, options.resultPreviewLines ?? 15);
136761
137510
  }
136762
- addCommandPreview(command, previewLines) {
137511
+ addCommandPreview(command, previewLines, colors) {
136763
137512
  if (command.length === 0) return;
136764
- const allLines = command.split("\n");
137513
+ const allLines = highlightLines(command, "bash", colors);
136765
137514
  const lines = previewLines === void 0 ? allLines : allLines.slice(0, previewLines);
136766
137515
  for (const [i, line] of lines.entries()) {
136767
137516
  const prefix = i === 0 ? "$ " : " ";
136768
- this.addChild(new Text(chalk.dim(prefix + line), 2, 0));
137517
+ this.addChild(new Text(`${chalk.dim(prefix)}${line}`, 2, 0));
136769
137518
  }
136770
137519
  }
136771
137520
  addResultPreview(result, colors, expanded, previewLines) {
@@ -136776,8 +137525,7 @@ var ShellExecutionComponent = class extends Container {
136776
137525
  colors,
136777
137526
  maxLines: previewLines,
136778
137527
  maxBytes: MAX_SHELL_OUTPUT_BYTES,
136779
- hintFormatter: (remaining) => t("shell.more_lines", { count: String(remaining) }),
136780
- collapseHintFormatter: () => t("shell.collapse_hint")
137528
+ hintFormatter: (remaining) => t("shell.more_lines", { count: String(remaining) })
136781
137529
  }));
136782
137530
  }
136783
137531
  };
@@ -136786,8 +137534,9 @@ const shellExecutionResultRenderer = (toolCall, result, ctx) => [new ShellExecut
136786
137534
  result,
136787
137535
  colors: ctx.colors,
136788
137536
  expanded: ctx.expanded,
136789
- showCommand: ctx.expanded,
136790
- commandPreviewLines: void 0
137537
+ showCommand: true,
137538
+ commandPreviewLines: ctx.expanded ? void 0 : 3,
137539
+ resultPreviewLines: ctx.expanded ? void 0 : result.is_error ? void 0 : ctx.isLive ? void 0 : 0
136791
137540
  })];
136792
137541
  //#endregion
136793
137542
  //#region src/tui/components/media/image-thumbnail.ts
@@ -137066,6 +137815,20 @@ function pickChip(toolName) {
137066
137815
  return REGISTRY[toolName];
137067
137816
  }
137068
137817
  //#endregion
137818
+ //#region src/tui/components/messages/tool-renderers/glance-lines.ts
137819
+ /** Render pre-styled glance lines without allowing terminal wrapping. */
137820
+ var GlanceLinesComponent = class {
137821
+ lines;
137822
+ constructor(lines) {
137823
+ this.lines = lines;
137824
+ }
137825
+ invalidate() {}
137826
+ render(width) {
137827
+ const safeWidth = Math.max(width, 1);
137828
+ return this.lines.map((line) => truncateToWidth(` ${line}`, safeWidth, "…"));
137829
+ }
137830
+ };
137831
+ //#endregion
137069
137832
  //#region src/tui/components/messages/tool-renderers/summary.ts
137070
137833
  const GLANCE_SAMPLES = 3;
137071
137834
  const MAX_EXTENSION_COUNTS = 4;
@@ -137075,11 +137838,11 @@ function withGlance(glance) {
137075
137838
  if (result.is_error) return renderTruncated(toolCall, result, ctx);
137076
137839
  const out = [];
137077
137840
  if (glance !== null) {
137078
- const line = glance(toolCall, result, ctx.colors);
137079
- if (line.length > 0) {
137080
- const indented = line.split("\n").map((l) => ` ${l}`).join("\n");
137841
+ const glanceOut = glance(toolCall, result, ctx.colors);
137842
+ if (typeof glanceOut === "string" && glanceOut.length > 0) {
137843
+ const indented = glanceOut.split("\n").map((l) => ` ${l}`).join("\n");
137081
137844
  out.push(new Text(indented, 0, 0));
137082
- }
137845
+ } else if (typeof glanceOut !== "string") out.push(glanceOut);
137083
137846
  }
137084
137847
  if (ctx.expanded && result.output.length > 0) out.push(new Text(chalk.dim(result.output), 4, 0));
137085
137848
  return out;
@@ -137102,29 +137865,35 @@ function readSearchResultsMatches(result) {
137102
137865
  if (display.kind !== "search_results") return void 0;
137103
137866
  return display.matches;
137104
137867
  }
137105
- function truncateMatchText(text, max = 80) {
137106
- if (text.length <= max) return text;
137107
- return `${text.slice(0, max - 1)}…`;
137868
+ function styleFilePath(path) {
137869
+ const index = path.lastIndexOf("/");
137870
+ if (index < 0) return path;
137871
+ return `${chalk.dim(path.slice(0, index + 1))}${path.slice(index + 1)}`;
137108
137872
  }
137109
137873
  const grepGlance = (_toolCall, result, colors) => {
137110
137874
  const matches = readSearchResultsMatches(result);
137111
137875
  if (matches !== void 0 && matches.length > 0) {
137112
- const fileColor = chalk.hex(colors.roleTool);
137113
- const lines = matches.slice(0, GLANCE_SAMPLES).map((m) => {
137114
- return `${m.line > 0 ? `${fileColor(m.file)}${chalk.dim(":")}${chalk.hex(colors.primary)(String(m.line))}` : fileColor(m.file)}${chalk.dim(` ${truncateMatchText(m.text.trim())}`)}`;
137876
+ const samples = matches.slice(0, GLANCE_SAMPLES);
137877
+ const plainLocations = samples.map((match) => match.line > 0 ? `${match.file}:${String(match.line)}` : match.file);
137878
+ const columnWidth = Math.max(...plainLocations.map((location) => visibleWidth(location)));
137879
+ const lineNumberColor = chalk.hex(colors.roleTool);
137880
+ const lines = samples.map((match, index) => {
137881
+ const location = match.line > 0 ? `${styleFilePath(match.file)}${chalk.dim(":")}${lineNumberColor(String(match.line))}` : styleFilePath(match.file);
137882
+ const padding = " ".repeat(Math.max(0, columnWidth - visibleWidth(plainLocations[index] ?? "")));
137883
+ const text = match.text.trim();
137884
+ return text.length > 0 ? `${location}${padding} ${chalk.dim(text)}` : `${location}${padding}`;
137115
137885
  });
137116
137886
  const remaining = matches.length - GLANCE_SAMPLES;
137117
137887
  if (remaining > 0) lines.push(chalk.dim(`+${String(remaining)} more`));
137118
- return lines.join("\n");
137888
+ return new GlanceLinesComponent(lines);
137119
137889
  }
137120
137890
  const lines = nonEmptyLines(result.output);
137121
137891
  if (lines.length === 0) return "";
137122
137892
  const samples = lines.slice(0, GLANCE_SAMPLES).map(pathFromGrepLine);
137123
137893
  const remaining = lines.length - samples.length;
137124
- const fileColor = chalk.hex(colors.roleTool);
137125
- const out = samples.map((s) => fileColor(s));
137894
+ const out = samples.map((sample) => styleFilePath(sample));
137126
137895
  if (remaining > 0) out.push(chalk.dim(`+${String(remaining)} more`));
137127
- return out.join("\n");
137896
+ return new GlanceLinesComponent(out);
137128
137897
  };
137129
137898
  function fileBasename(path) {
137130
137899
  const idx = path.lastIndexOf("/");
@@ -137772,9 +138541,10 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
137772
138541
  args: call.args,
137773
138542
  output: call.result.output,
137774
138543
  isError: call.result.is_error ?? false,
137775
- display: call.result.display
138544
+ display: call.result.display,
138545
+ message: call.result.message
137776
138546
  });
137777
- this.upsertSubToolActivity(call.id, call.name, call.args, call.result.is_error === true ? "failed" : "done");
138547
+ this.upsertSubToolActivity(call.id, call.name, call.args, call.result.is_error === true ? "failed" : "done", call.result.message);
137778
138548
  }
137779
138549
  while (this.finishedSubCalls.length > MAX_SUB_TOOL_CALLS_SHOWN) {
137780
138550
  this.finishedSubCalls.shift();
@@ -137817,7 +138587,8 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
137817
138587
  tokens,
137818
138588
  isError: derivedPhase === "failed",
137819
138589
  errorText,
137820
- latestActivity
138590
+ latestActivity,
138591
+ resultMessages: this.finishedSubCalls.flatMap((call) => call.message === void 0 || call.message.length === 0 ? [] : [call.message])
137821
138592
  };
137822
138593
  }
137823
138594
  /**
@@ -137856,12 +138627,13 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
137856
138627
  notifySnapshotChange() {
137857
138628
  this.onSnapshotChange?.();
137858
138629
  }
137859
- upsertSubToolActivity(id, name, args, phase) {
138630
+ upsertSubToolActivity(id, name, args, phase, message) {
137860
138631
  const existing = this.subToolActivities.get(id);
137861
138632
  if (existing !== void 0) {
137862
138633
  existing.name = name;
137863
138634
  existing.args = args;
137864
138635
  existing.phase = phase;
138636
+ if (message !== void 0) existing.message = message;
137865
138637
  return;
137866
138638
  }
137867
138639
  this.subToolActivities.set(id, {
@@ -137869,7 +138641,8 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
137869
138641
  name,
137870
138642
  args,
137871
138643
  phase,
137872
- orderSeq: ++this.subToolOrderSeq
138644
+ orderSeq: ++this.subToolOrderSeq,
138645
+ message
137873
138646
  });
137874
138647
  }
137875
138648
  getCombinedSubagentText() {
@@ -138111,9 +138884,10 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
138111
138884
  args: ongoing.args,
138112
138885
  output: result.output,
138113
138886
  isError: result.is_error ?? false,
138114
- display: result.display
138887
+ display: result.display,
138888
+ message: result.message
138115
138889
  });
138116
- this.upsertSubToolActivity(result.tool_call_id, ongoing.name, ongoing.args, result.is_error === true ? "failed" : "done");
138890
+ this.upsertSubToolActivity(result.tool_call_id, ongoing.name, ongoing.args, result.is_error === true ? "failed" : "done", result.message);
138117
138891
  while (this.finishedSubCalls.length > MAX_SUB_TOOL_CALLS_SHOWN) {
138118
138892
  this.finishedSubCalls.shift();
138119
138893
  this.hiddenSubCallCount += 1;
@@ -138228,7 +139002,8 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
138228
139002
  is_error: false
138229
139003
  }, {
138230
139004
  expanded: this.expanded,
138231
- colors: this.colors
139005
+ colors: this.colors,
139006
+ isLive: true
138232
139007
  });
138233
139008
  for (const component of components) this.addChild(component);
138234
139009
  }
@@ -138252,6 +139027,7 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
138252
139027
  const nameCol = chalk.hex(this.colors.primary)(sub.name);
138253
139028
  const argCol = keyArg ? dim(` (${keyArg})`) : "";
138254
139029
  this.addChild(new Text(` ${mark} ${t("toolcall.used")} ${nameCol}${argCol}`, 0, 0));
139030
+ if (sub.message !== void 0 && sub.message.length > 0) this.addChild(new ToolResultMessageComponent(sub.message, this.colors, 6));
138255
139031
  }
138256
139032
  for (const [id, call] of this.ongoingSubCalls) {
138257
139033
  const keyArg = extractKeyArgument(call.name, call.args, this.workspaceDir);
@@ -138369,6 +139145,7 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
138369
139145
  const mark = activity.phase === "failed" ? chalk.hex(this.colors.error)("✗") : activity.phase === "done" ? chalk.hex(this.colors.success)("•") : chalk.hex(this.colors.text)("•");
138370
139146
  const verb = activity.phase === "ongoing" ? t("toolcall.in_use") : t("toolcall.used");
138371
139147
  this.addChild(new Text(` ${mark} ${this.formatSubToolActivity(verb, activity)}`, 0, 0));
139148
+ if (activity.message !== void 0 && activity.message.length > 0) this.addChild(new ToolResultMessageComponent(activity.message, this.colors, 4));
138372
139149
  }
138373
139150
  if (this.getDerivedSubagentPhase() === "failed" && this.subagentError !== void 0) {
138374
139151
  const errorLine = tailNonEmptyLines(this.subagentError, 1).at(-1);
@@ -138586,6 +139363,7 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
138586
139363
  colors: this.colors
138587
139364
  });
138588
139365
  for (const component of components) this.addChild(component);
139366
+ if (result.message !== void 0 && result.message.length > 0) this.addChild(new ToolResultMessageComponent(result.message, this.colors, 2));
138589
139367
  }
138590
139368
  /**
138591
139369
  * Render AskUserQuestion's JSON payload as a friendly Q/A list.
@@ -139264,7 +140042,7 @@ async function findCcConnectResidualPaths(excludePath) {
139264
140042
  existing.push(p);
139265
140043
  } catch {}
139266
140044
  }
139267
- return existing.sort();
140045
+ return existing.toSorted();
139268
140046
  }
139269
140047
  async function handleCcCommand(host) {
139270
140048
  const daemon = resolveDaemonMode();
@@ -139304,7 +140082,7 @@ function runLifecycleAction(host, daemon, action) {
139304
140082
  host.refreshCcStatus();
139305
140083
  } else host.showError(t("cc.start_failed", {
139306
140084
  label,
139307
- output: output || "未知错误"
140085
+ output: output || t("cc.unknown_error")
139308
140086
  }));
139309
140087
  })();
139310
140088
  }
@@ -139314,7 +140092,7 @@ function buildUninstallSummary(daemon, install, residualPaths = []) {
139314
140092
  t("cc.will_clean"),
139315
140093
  t("cc.clean_daemon", { label: daemon.method }),
139316
140094
  t("cc.clean_config", { detail: t("cc.clean_config.detail") }),
139317
- "· 执行 npm uninstall -g cc-connect"
140095
+ t("cc.uninstall_step_npm")
139318
140096
  ];
139319
140097
  if (install.version) lines.push(t("cc.current_version", { version: install.version }));
139320
140098
  if (install.entry) lines.push(t("cc.install_path", { path: install.entry }));
@@ -139480,6 +140258,28 @@ function confirmCcConnectUninstall(host, summary) {
139480
140258
  });
139481
140259
  }
139482
140260
  //#endregion
140261
+ //#region src/cli/update/prefix.ts
140262
+ /** Derive the npm global prefix that contains the running Nexum Code entrypoint. */
140263
+ function globalPrefixForNexum() {
140264
+ const entry = process.argv[1];
140265
+ if (!entry) return void 0;
140266
+ const separator = entry.includes("\\") ? "\\" : "/";
140267
+ const parts = entry.split(/[\\/]/);
140268
+ const index = parts.lastIndexOf("node_modules");
140269
+ if (index < 2 || parts[index - 1] !== "lib") return void 0;
140270
+ return parts.slice(0, index - 1).join(separator);
140271
+ }
140272
+ /** Build npm arguments while preserving the prefix used by this installation. */
140273
+ function installLatestArgs() {
140274
+ const prefix = globalPrefixForNexum();
140275
+ return [
140276
+ "install",
140277
+ "-g",
140278
+ "nexum-code@latest",
140279
+ ...prefix !== void 0 ? ["--prefix", prefix] : []
140280
+ ];
140281
+ }
140282
+ //#endregion
139483
140283
  //#region src/utils/persistence.ts
139484
140284
  /**
139485
140285
  * Small persistence helpers for CLI-owned data files.
@@ -139742,11 +140542,7 @@ async function handleUpdateCommand(host) {
139742
140542
  }
139743
140543
  host.showStatus(t("update.updating", { version: target.version }));
139744
140544
  host.showStatus(t("update.npm_install"));
139745
- const result = await runInstallStep(npmExecutable(), [
139746
- "install",
139747
- "-g",
139748
- "nexum-code@latest"
139749
- ], void 0, t("update.install_label"));
140545
+ const result = await runInstallStep(npmExecutable(), installLatestArgs(), void 0, t("update.install_label"));
139750
140546
  if (!result.ok) {
139751
140547
  host.showError(`❌ ${result.message}`);
139752
140548
  return;
@@ -140229,9 +141025,87 @@ function getPlatforms() {
140229
141025
  type: "wecom",
140230
141026
  setupCmd: "wecom setup --project default",
140231
141027
  note: t("ccconnect.note_wecom")
141028
+ },
141029
+ {
141030
+ name: "QQ 官方 bot",
141031
+ type: "qqbot",
141032
+ setupCmd: "qqbot setup --project default"
141033
+ },
141034
+ {
141035
+ name: "LINE",
141036
+ type: "line",
141037
+ setupCmd: "line setup --project default"
141038
+ },
141039
+ {
141040
+ name: "微博",
141041
+ type: "weibo",
141042
+ setupCmd: "weibo setup --project default"
141043
+ },
141044
+ {
141045
+ name: "WPS 协作",
141046
+ type: "wps-xiezuo",
141047
+ setupCmd: "wps-xiezuo setup --project default"
141048
+ },
141049
+ {
141050
+ name: "Matrix",
141051
+ type: "matrix",
141052
+ setupCmd: "matrix setup --project default",
141053
+ note: t("ccconnect.note_matrix")
141054
+ },
141055
+ {
141056
+ name: "Cisco Webex",
141057
+ type: "webex",
141058
+ setupCmd: "webex setup --project default",
141059
+ note: t("ccconnect.note_webex")
141060
+ },
141061
+ {
141062
+ name: "MAX",
141063
+ type: "max",
141064
+ setupCmd: "max setup --project default",
141065
+ note: t("ccconnect.note_max")
141066
+ },
141067
+ {
141068
+ name: "Google Chat",
141069
+ type: "googlechat",
141070
+ setupCmd: "googlechat setup --project default",
141071
+ note: t("ccconnect.note_googlechat")
141072
+ },
141073
+ {
141074
+ name: "Cloud Web",
141075
+ type: "cloud_web",
141076
+ setupCmd: "cloud_web setup --project default",
141077
+ note: t("ccconnect.note_cloud_web")
141078
+ },
141079
+ {
141080
+ name: "腾讯元宝",
141081
+ type: "yuanbao",
141082
+ setupCmd: "yuanbao setup --project default",
141083
+ note: t("ccconnect.note_yuanbao")
141084
+ },
141085
+ {
141086
+ name: "Tuitui",
141087
+ type: "tuitui",
141088
+ setupCmd: "tuitui setup --project default",
141089
+ note: t("ccconnect.note_tuitui")
141090
+ },
141091
+ {
141092
+ name: "WPS 数字员工",
141093
+ type: "wps-agentspace",
141094
+ setupCmd: "wps-agentspace setup --project default",
141095
+ note: t("ccconnect.note_wps_agentspace")
140232
141096
  }
140233
141097
  ];
140234
141098
  }
141099
+ const NEW_PLATFORM_TYPES = new Set([
141100
+ "matrix",
141101
+ "webex",
141102
+ "max",
141103
+ "googlechat",
141104
+ "cloud_web",
141105
+ "yuanbao",
141106
+ "tuitui",
141107
+ "wps-agentspace"
141108
+ ]);
140235
141109
  const CONFIG_PATH = join(homedir(), ".cc-connect", "config.toml");
140236
141110
  function checkCcConnect() {
140237
141111
  try {
@@ -140247,42 +141121,66 @@ function checkCcConnect() {
140247
141121
  }
140248
141122
  }
140249
141123
  function detectNexumPath() {
141124
+ const execBase = process.execPath.toLowerCase();
141125
+ if (execBase.endsWith("/nexum") || execBase.endsWith("\\nexum") || execBase.endsWith("nexum.exe")) return `${quoteShellPath(process.execPath)} stream-json`;
141126
+ if (execBase.includes("node") && process.argv[1]) {
141127
+ const arg1 = process.argv[1];
141128
+ if (arg1.includes("nexum-code") || arg1.includes("nexum")) return `node ${quoteShellPath(arg1)} stream-json`;
141129
+ }
140250
141130
  try {
140251
141131
  const first = execSync(process.platform === "win32" ? "where nexum" : "which nexum 2>/dev/null", {
140252
141132
  encoding: "utf-8",
140253
141133
  timeout: 3e3
140254
141134
  }).trim().split(/[\r\n]+/)[0]?.trim() ?? "";
140255
- if (first) return `${first} stream-json`;
141135
+ if (first) return `${quoteShellPath(first)} stream-json`;
140256
141136
  } catch {}
140257
141137
  return "nexum stream-json";
140258
141138
  }
140259
- function readConfiguredType() {
140260
- if (!existsSync(CONFIG_PATH)) return void 0;
140261
- try {
140262
- const content = readFileSync(CONFIG_PATH, "utf-8");
140263
- let inPlatforms = false;
140264
- for (const line of content.split("\n")) {
140265
- const trimmed = line.trim();
140266
- if (trimmed === "[[projects.platforms]]") {
140267
- inPlatforms = true;
140268
- continue;
140269
- }
140270
- if (trimmed.startsWith("[[") && trimmed !== "[[projects.platforms]]") {
140271
- inPlatforms = false;
140272
- continue;
140273
- }
140274
- if (inPlatforms) {
140275
- const m = line.match(/^type\s*=\s*"(\S+)"/);
140276
- if (m) return m[1];
140277
- }
141139
+ function quoteShellPath(path) {
141140
+ return `"${path.replaceAll("\"", "\\\"")}"`;
141141
+ }
141142
+ function parseConfiguredTypes(content) {
141143
+ const types = [];
141144
+ let inPlatforms = false;
141145
+ for (const line of content.split("\n")) {
141146
+ const trimmed = line.trim();
141147
+ if (trimmed.startsWith("[[projects.platforms]]")) {
141148
+ inPlatforms = true;
141149
+ continue;
140278
141150
  }
140279
- return;
141151
+ if (trimmed.startsWith("[")) {
141152
+ inPlatforms = false;
141153
+ continue;
141154
+ }
141155
+ if (inPlatforms) {
141156
+ const match = trimmed.match(/^type\s*=\s*["']([^"']+)["']/);
141157
+ if (match?.[1]) types.push(match[1]);
141158
+ }
141159
+ }
141160
+ return types;
141161
+ }
141162
+ function readConfiguredTypes() {
141163
+ if (!existsSync(CONFIG_PATH)) return [];
141164
+ try {
141165
+ return parseConfiguredTypes(readFileSync(CONFIG_PATH, "utf-8"));
140280
141166
  } catch {
140281
- return;
141167
+ return [];
140282
141168
  }
140283
141169
  }
140284
- function escapeSingleQuotes(str) {
140285
- return str.replaceAll("'", "\\'");
141170
+ function hasPlatformConfigured(content, type) {
141171
+ const escaped = type.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
141172
+ return new RegExp(`^\\s*type\\s*=\\s*["']${escaped}["']`, "m").test(content);
141173
+ }
141174
+ function isVersionAtLeast(version, min) {
141175
+ if (!version) return false;
141176
+ const parse = (value) => value.split(".").map((part) => Number.parseInt(part, 10) || 0);
141177
+ const [a = 0, b = 0, c = 0] = parse(version);
141178
+ const [x = 0, y = 0, z = 0] = parse(min);
141179
+ return a > x || a === x && (b > y || b === y && c >= z);
141180
+ }
141181
+ function tomlString(value) {
141182
+ if (!value.includes("'")) return `'${value}'`;
141183
+ return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
140286
141184
  }
140287
141185
  function generateConfig(platform) {
140288
141186
  const dir = dirname$1(CONFIG_PATH);
@@ -140290,11 +141188,14 @@ function generateConfig(platform) {
140290
141188
  const platformBlock = `\n[[projects.platforms]]\ntype = "${platform.type}"\n`;
140291
141189
  if (existsSync(CONFIG_PATH)) {
140292
141190
  const existing = readFileSync(CONFIG_PATH, "utf-8");
140293
- if (existing.includes(`type = "${platform.type}"`)) return;
141191
+ if (hasPlatformConfigured(existing, platform.type)) return;
140294
141192
  writeFileSync(CONFIG_PATH, existing + platformBlock, "utf-8");
140295
141193
  return;
140296
141194
  }
140297
- writeFileSync(CONFIG_PATH, [
141195
+ writeFileSync(CONFIG_PATH, buildConfigContent(platform, detectNexumPath(), process.cwd()), "utf-8");
141196
+ }
141197
+ function buildConfigContent(platform, nexumCmd, cwd) {
141198
+ return [
140298
141199
  t("ccconnect.config_comment_attachment"),
140299
141200
  "attachment_send = \"on\"",
140300
141201
  "",
@@ -140305,21 +141206,22 @@ function generateConfig(platform) {
140305
141206
  "type = \"claudecode\"",
140306
141207
  "",
140307
141208
  "[projects.agent.options]",
140308
- `cmd = '${escapeSingleQuotes(detectNexumPath())}'`,
140309
- `work_dir = '${escapeSingleQuotes(process.cwd())}'`,
140310
- "mode = \"default\"",
141209
+ `cmd = ${tomlString(nexumCmd)}`,
141210
+ `work_dir = ${tomlString(cwd)}`,
141211
+ "# Permission mode: default (confirm each tool) | acceptEdits | plan | auto | bypassPermissions (yolo) | dontAsk",
141212
+ "mode = \"auto\"",
140311
141213
  "",
140312
141214
  "[[projects.platforms]]",
140313
141215
  `type = "${platform.type}"`,
140314
141216
  ""
140315
- ].join("\n"), "utf-8");
141217
+ ].join("\n");
140316
141218
  }
140317
141219
  const SEP = "──".repeat(20);
140318
141220
  /**
140319
141221
  * Build the full notice text shown after platform selection.
140320
141222
  * Common management commands come first; detailed setup steps follow.
140321
141223
  */
140322
- function buildNoticeText(platform, isReconfigure) {
141224
+ function buildNoticeText(platform, isReconfigure, installedVersion) {
140323
141225
  const daemon = getDaemonInstructions(dirname$1(CONFIG_PATH));
140324
141226
  const parts = [];
140325
141227
  if (isReconfigure) {
@@ -140331,6 +141233,10 @@ function buildNoticeText(platform, isReconfigure) {
140331
141233
  parts.push("");
140332
141234
  parts.push(t("ccconnect.config_written", { path: CONFIG_PATH }));
140333
141235
  }
141236
+ if (NEW_PLATFORM_TYPES.has(platform.type) && !isVersionAtLeast(installedVersion, "1.5.0")) {
141237
+ parts.push("");
141238
+ parts.push(t("ccconnect.new_platform_version_hint"));
141239
+ }
140334
141240
  parts.push("");
140335
141241
  parts.push(t("ccconnect.quick_ref"));
140336
141242
  parts.push("");
@@ -140384,13 +141290,14 @@ function buildNoticeText(platform, isReconfigure) {
140384
141290
  return parts.join("\n");
140385
141291
  }
140386
141292
  async function handleChannelCommand(host, _args) {
140387
- if (!checkCcConnect().installed) {
141293
+ const cc = checkCcConnect();
141294
+ if (!cc.installed) {
140388
141295
  host.showNotice(t("ccconnect.not_installed"), t("ccconnect.install_guide"));
140389
141296
  return;
140390
141297
  }
140391
- const configuredType = readConfiguredType();
141298
+ const configuredTypes = readConfiguredTypes();
140392
141299
  const options = getPlatforms().map((p) => {
140393
- const isConfigured = configuredType === p.type;
141300
+ const isConfigured = configuredTypes.includes(p.type);
140394
141301
  return {
140395
141302
  value: p.type,
140396
141303
  label: isConfigured ? t("ccconnect.already_configured", { name: p.name }) : p.name,
@@ -140401,7 +141308,7 @@ async function handleChannelCommand(host, _args) {
140401
141308
  title: t("ccconnect.picker_title"),
140402
141309
  hint: t("ccconnect.picker_hint"),
140403
141310
  options,
140404
- currentValue: configuredType,
141311
+ currentValue: configuredTypes[0],
140405
141312
  colors: host.state.theme.colors,
140406
141313
  onSelect: (value) => {
140407
141314
  host.restoreEditor();
@@ -140410,12 +141317,12 @@ async function handleChannelCommand(host, _args) {
140410
141317
  host.showError(t("error.internal"));
140411
141318
  return;
140412
141319
  }
140413
- if (configuredType === value) {
140414
- host.showNotice(t("ccconnect.reconfigured", { name: platform.name }), buildNoticeText(platform, true));
141320
+ if (configuredTypes.includes(value)) {
141321
+ host.showNotice(t("ccconnect.reconfigured", { name: platform.name }), buildNoticeText(platform, true, cc.version));
140415
141322
  return;
140416
141323
  }
140417
141324
  generateConfig(platform);
140418
- host.showNotice(t("ccconnect.config_done", { name: platform.name }), buildNoticeText(platform, false));
141325
+ host.showNotice(t("ccconnect.config_done", { name: platform.name }), buildNoticeText(platform, false, cc.version));
140419
141326
  },
140420
141327
  onCancel: () => {
140421
141328
  host.restoreEditor();
@@ -140786,13 +141693,13 @@ function disposeChildren(container) {
140786
141693
  const SKILL_DESC_MAX = 60;
140787
141694
  async function handleSkillCommand(host, _args) {
140788
141695
  if (!host.session) {
140789
- host.showError(t("skill.no_session"));
141696
+ host.showError(t("plugin.no_session"));
140790
141697
  return;
140791
141698
  }
140792
141699
  await openSkillCenter(host);
140793
141700
  }
140794
141701
  async function openSkillCenter(host) {
140795
- const loading = new SkillCenterLoadingComponent(host, t("skill.loading"));
141702
+ const loading = new SkillCenterLoadingComponent(host, t("plugin.loading"));
140796
141703
  host.mountEditorReplacement(loading);
140797
141704
  const [skillsResult, pluginsResult, marketplaceResult] = await Promise.allSettled([
140798
141705
  loadActivatableSkills(host),
@@ -140807,12 +141714,12 @@ async function openSkillCenter(host) {
140807
141714
  const options = buildOptions(host, skills, plugins, marketplace);
140808
141715
  if (options.length === 0) {
140809
141716
  host.restoreEditor();
140810
- host.showNotice(t("skill.center_title"), t("skill.no_skills"));
141717
+ host.showNotice(t("plugin.center_title"), t("plugin.no_plugins"));
140811
141718
  return;
140812
141719
  }
140813
141720
  const picker = new ChoicePickerComponent({
140814
- title: t("skill.center_title"),
140815
- hint: t("skill.footer_hint"),
141721
+ title: t("plugin.center_title"),
141722
+ hint: t("plugin.footer_hint"),
140816
141723
  options,
140817
141724
  colors: host.state.theme.colors,
140818
141725
  searchable: true,
@@ -140892,7 +141799,7 @@ function buildOptions(host, skills, plugins, marketplace) {
140892
141799
  if (skills.length > 0) {
140893
141800
  options.push({
140894
141801
  value: "__section__installed",
140895
- label: "── " + t("skill.installed") + " ──"
141802
+ label: "── " + t("plugin.installed") + " ──"
140896
141803
  });
140897
141804
  for (const skill of skills) {
140898
141805
  const actionKeys = {};
@@ -140919,12 +141826,12 @@ function buildOptions(host, skills, plugins, marketplace) {
140919
141826
  if (installable.length > 0) {
140920
141827
  options.push({
140921
141828
  value: "__section__installable",
140922
- label: "── " + t("skill.installable") + " ──"
141829
+ label: "── " + t("plugin.installable") + " ──"
140923
141830
  });
140924
141831
  for (const entry of installable) options.push({
140925
141832
  value: `install:${entry.source}`,
140926
141833
  label: entry.displayName,
140927
- description: entry.description ? `${truncate(entry.description, SKILL_DESC_MAX)} [${t("skill.not_installed")}]` : `[${t("skill.not_installed")}]`,
141834
+ description: entry.description ? `${truncate(entry.description, SKILL_DESC_MAX)} [${t("plugin.not_installed")}]` : `[${t("plugin.not_installed")}]`,
140928
141835
  actionKeys: { i: () => {
140929
141836
  host.restoreEditor();
140930
141837
  installInjectActivate(host, entry.source);
@@ -140951,12 +141858,12 @@ async function handleSelect(host, value, skills, _plugins, _marketplace) {
140951
141858
  async function activateSkillByName(host, name, skills) {
140952
141859
  const session = host.session;
140953
141860
  if (!session) {
140954
- host.showError(t("skill.no_session_activate"));
141861
+ host.showError(t("plugin.no_session_activate"));
140955
141862
  return;
140956
141863
  }
140957
141864
  const skill = skills.find((s) => s.name === name);
140958
141865
  if (!skill) {
140959
- host.showError(t("skill.not_found"));
141866
+ host.showError(t("plugin.not_found"));
140960
141867
  return;
140961
141868
  }
140962
141869
  host.sendSkillActivation(session, skill.name, "");
@@ -140964,20 +141871,20 @@ async function activateSkillByName(host, name, skills) {
140964
141871
  async function installInjectActivate(host, source) {
140965
141872
  const session = host.session;
140966
141873
  if (!session) {
140967
- host.showError(t("skill.no_session_activate"));
141874
+ host.showError(t("plugin.no_session_activate"));
140968
141875
  return;
140969
141876
  }
140970
- const spinner = host.showProgressSpinner(t("skill.installing_package"));
141877
+ const spinner = host.showProgressSpinner(t("plugin.installing_package"));
140971
141878
  try {
140972
141879
  const summary = await session.installPlugin(source);
140973
141880
  await session.injectPlugin(summary.id);
140974
141881
  spinner.stop({
140975
141882
  ok: true,
140976
- label: `"${summary.displayName}" ${t("skill.installed_injected")}`
141883
+ label: `"${summary.displayName}" ${t("plugin.installed_injected")}`
140977
141884
  });
140978
141885
  const pluginSkills = (await session.listSkills()).filter((s) => s.pluginId === summary.id && isUserActivatableSkill(s));
140979
141886
  if (pluginSkills.length === 0) {
140980
- host.showNotice(t("skill.plugin_installed"), `${summary.displayName} ${t("skill.no_manual_skill")}`);
141887
+ host.showNotice(t("plugin.plugin_installed"), `${summary.displayName} ${t("plugin.no_manual_plugin")}`);
140981
141888
  return;
140982
141889
  }
140983
141890
  if (pluginSkills.length === 1) {
@@ -140989,9 +141896,9 @@ async function installInjectActivate(host, source) {
140989
141896
  } catch (error) {
140990
141897
  spinner.stop({
140991
141898
  ok: false,
140992
- label: t("skill.install_failed")
141899
+ label: t("plugin.install_failed")
140993
141900
  });
140994
- host.showError(t("skill.install_failed_msg", { msg: error instanceof Error ? error.message : String(error) }));
141901
+ host.showError(t("plugin.install_failed_msg", { msg: error instanceof Error ? error.message : String(error) }));
140995
141902
  }
140996
141903
  }
140997
141904
  async function pickAndActivateSkill(host, skills, plugins = []) {
@@ -141003,8 +141910,8 @@ async function pickAndActivateSkill(host, skills, plugins = []) {
141003
141910
  description: formatSkillDescription(skill, plugins)
141004
141911
  }));
141005
141912
  const picker = new ChoicePickerComponent({
141006
- title: t("skill.select_activate"),
141007
- hint: t("skill.select_hint"),
141913
+ title: t("plugin.select_activate"),
141914
+ hint: t("plugin.select_hint"),
141008
141915
  options,
141009
141916
  colors: host.state.theme.colors,
141010
141917
  searchable: true,
@@ -141022,7 +141929,7 @@ async function pickAndActivateSkill(host, skills, plugins = []) {
141022
141929
  async function uninstallByPluginId(host, pluginId, plugin) {
141023
141930
  const session = host.session;
141024
141931
  if (!session) {
141025
- host.showError(t("skill.no_session_activate"));
141932
+ host.showError(t("plugin.no_session_activate"));
141026
141933
  return;
141027
141934
  }
141028
141935
  if (plugin === void 0) try {
@@ -141030,24 +141937,24 @@ async function uninstallByPluginId(host, pluginId, plugin) {
141030
141937
  } catch {}
141031
141938
  const label = plugin?.displayName ?? pluginId;
141032
141939
  const skillCount = plugin?.skillCount;
141033
- if (!await confirmUninstall(host, label, skillCount !== void 0 && skillCount > 0 ? t("skill.uninstall_whole_pkg", { count: skillCount }) : t("skill.uninstall_single"))) {
141940
+ if (!await confirmUninstall(host, label, skillCount !== void 0 && skillCount > 0 ? t("plugin.uninstall_whole_pkg", { count: skillCount }) : t("plugin.uninstall_single"))) {
141034
141941
  await openSkillCenter(host);
141035
141942
  return;
141036
141943
  }
141037
- const spinner = host.showProgressSpinner(`${t("skill.uninstalling")} "${label}"…`);
141944
+ const spinner = host.showProgressSpinner(`${t("plugin.uninstalling")} "${label}"…`);
141038
141945
  try {
141039
141946
  await session.removePlugin(pluginId);
141040
141947
  spinner.stop({
141041
141948
  ok: true,
141042
- label: `"${label}" ${t("skill.uninstalled")}`
141949
+ label: `"${label}" ${t("plugin.uninstalled")}`
141043
141950
  });
141044
- host.showNotice(t("skill.plugin_uninstalled"), t("skill.plugin_removed"));
141951
+ host.showNotice(t("plugin.plugin_uninstalled"), t("plugin.plugin_removed"));
141045
141952
  } catch (error) {
141046
141953
  spinner.stop({
141047
141954
  ok: false,
141048
- label: t("skill.uninstall_failed")
141955
+ label: t("plugin.uninstall_failed")
141049
141956
  });
141050
- host.showError(t("skill.uninstall_failed_msg", { msg: error instanceof Error ? error.message : String(error) }));
141957
+ host.showError(t("plugin.uninstall_failed_msg", { msg: error instanceof Error ? error.message : String(error) }));
141051
141958
  } finally {
141052
141959
  await openSkillCenter(host);
141053
141960
  }
@@ -141055,27 +141962,27 @@ async function uninstallByPluginId(host, pluginId, plugin) {
141055
141962
  async function uninstallManualSkill(host, skill) {
141056
141963
  const session = host.session;
141057
141964
  if (!session) {
141058
- host.showError(t("skill.no_session_activate"));
141965
+ host.showError(t("plugin.no_session_activate"));
141059
141966
  return;
141060
141967
  }
141061
- if (!await confirmUninstall(host, skill.name, t("skill.deleting_skill"))) {
141968
+ if (!await confirmUninstall(host, skill.name, t("plugin.deleting_plugin"))) {
141062
141969
  await openSkillCenter(host);
141063
141970
  return;
141064
141971
  }
141065
- const spinner = host.showProgressSpinner(`${t("skill.deleting")} "${skill.name}"…`);
141972
+ const spinner = host.showProgressSpinner(`${t("plugin.deleting")} "${skill.name}"…`);
141066
141973
  try {
141067
141974
  await session.removeSkill(skill.name);
141068
141975
  spinner.stop({
141069
141976
  ok: true,
141070
- label: `"${skill.name}" ${t("skill.deleted")}`
141977
+ label: `"${skill.name}" ${t("plugin.deleted")}`
141071
141978
  });
141072
- host.showNotice(t("skill.skill_deleted"), t("skill.skill_removed"));
141979
+ host.showNotice(t("plugin.plugin_deleted"), t("plugin.skill_removed"));
141073
141980
  } catch (error) {
141074
141981
  spinner.stop({
141075
141982
  ok: false,
141076
- label: t("skill.delete_failed")
141983
+ label: t("plugin.delete_failed")
141077
141984
  });
141078
- host.showError(t("skill.delete_failed_msg", { msg: error instanceof Error ? error.message : String(error) }));
141985
+ host.showError(t("plugin.delete_failed_msg", { msg: error instanceof Error ? error.message : String(error) }));
141079
141986
  } finally {
141080
141987
  await openSkillCenter(host);
141081
141988
  }
@@ -141083,14 +141990,14 @@ async function uninstallManualSkill(host, skill) {
141083
141990
  async function confirmUninstall(host, label, description) {
141084
141991
  return new Promise((resolve) => {
141085
141992
  const picker = new ChoicePickerComponent({
141086
- title: t("skill.confirm_uninstall", { label }),
141087
- hint: t("skill.uninstall_reversible"),
141993
+ title: t("plugin.confirm_uninstall", { label }),
141994
+ hint: t("plugin.uninstall_reversible"),
141088
141995
  options: [{
141089
141996
  value: "no",
141090
141997
  label: t("common.cancel")
141091
141998
  }, {
141092
141999
  value: "yes",
141093
- label: t("skill.uninstall_yes"),
142000
+ label: t("plugin.uninstall_yes"),
141094
142001
  tone: "danger",
141095
142002
  description
141096
142003
  }],
@@ -141109,10 +142016,10 @@ async function confirmUninstall(host, label, description) {
141109
142016
  }
141110
142017
  function formatSkillDescription(skill, plugins = []) {
141111
142018
  const parts = [];
141112
- if (skill.source) parts.push(`${t("skill.source_label")} ${skill.source}`);
142019
+ if (skill.source) parts.push(`${t("plugin.source_label")} ${skill.source}`);
141113
142020
  if (skill.pluginId !== void 0) {
141114
142021
  const label = plugins.find((p) => p.id === skill.pluginId)?.displayName ?? skill.pluginId;
141115
- parts.push(`${t("skill.plugin_label")} ${label}`);
142022
+ parts.push(`${t("plugin.plugin_label")} ${label}`);
141116
142023
  }
141117
142024
  if (skill.description) parts.push(truncate(skill.description, SKILL_DESC_MAX));
141118
142025
  return parts.join(" · ");
@@ -141121,6 +142028,67 @@ function truncate(value, max) {
141121
142028
  return value.length > max ? `${value.slice(0, max)}…` : value;
141122
142029
  }
141123
142030
  //#endregion
142031
+ //#region src/tui/commands/extension.ts
142032
+ /** Activate, deactivate, or list code-entry plugin extensions. */
142033
+ async function handleExtensionCommand(host, args) {
142034
+ const session = host.session;
142035
+ if (!session) {
142036
+ host.showError(t("extension.no_session"));
142037
+ return;
142038
+ }
142039
+ const [action, ...rest] = args.trim().split(/\s+/);
142040
+ const pluginId = rest.join(" ").trim();
142041
+ switch (action === "" || action === void 0 ? "status" : action) {
142042
+ case "activate":
142043
+ if (!pluginId) {
142044
+ host.showError(t("extension.missing_id", { action: "activate" }));
142045
+ return;
142046
+ }
142047
+ try {
142048
+ await session.activatePlugin(pluginId);
142049
+ host.showStatus(t("extension.activated", { pluginId }));
142050
+ } catch (error) {
142051
+ host.showError(getErrorMessage(error));
142052
+ }
142053
+ return;
142054
+ case "deactivate":
142055
+ if (!pluginId) {
142056
+ host.showError(t("extension.missing_id", { action: "deactivate" }));
142057
+ return;
142058
+ }
142059
+ try {
142060
+ await session.deactivatePlugin(pluginId);
142061
+ host.showStatus(t("extension.deactivated", { pluginId }));
142062
+ } catch (error) {
142063
+ host.showError(getErrorMessage(error));
142064
+ }
142065
+ return;
142066
+ case "status":
142067
+ try {
142068
+ const extensions = await session.pluginExtensionStatus();
142069
+ if (extensions.length === 0) {
142070
+ host.showStatus(t("extension.no_extensions"));
142071
+ return;
142072
+ }
142073
+ for (const extension of extensions) host.showStatus(`${extension.active ? "●" : "○"} ${extension.pluginId}`);
142074
+ } catch (error) {
142075
+ host.showError(getErrorMessage(error));
142076
+ }
142077
+ return;
142078
+ default: host.showError(t("extension.usage"));
142079
+ }
142080
+ }
142081
+ function getErrorMessage(error) {
142082
+ if (error === null || error === void 0) return String(error);
142083
+ const value = typeof error === "object" && "message" in error ? error.message : error;
142084
+ if (value === null || typeof value !== "object") return String(value);
142085
+ try {
142086
+ return JSON.stringify(value) ?? "Unknown error";
142087
+ } catch {
142088
+ return "Unknown error";
142089
+ }
142090
+ }
142091
+ //#endregion
141124
142092
  //#region src/tui/commands/btw.ts
141125
142093
  /**
141126
142094
  * /btw — Fast side question without interrupting the main conversation.
@@ -141317,7 +142285,7 @@ function buildRoleAdditionalText(prefs) {
141317
142285
  lines.push("", ...items);
141318
142286
  if (doNot !== void 0 && doNot.length > 0) lines.push("", "## Do NOT (explicit prohibitions — NEVER do these)", doNot);
141319
142287
  if (hasToolPriority) {
141320
- const instruction = prefs.toolPriority === "skill" ? "For every user request, first analyze the intent, then check all installed skills and try to solve the problem with a matching one. Only when no installed skill fits should you fall back to MCP tools or decide on your own how to solve it." : "For every user request, first analyze the intent, then check all available MCP tools and try to solve the problem with one. Only when no MCP tool fits should you fall back to the Skill tool or decide on your own how to solve it.";
142288
+ const instruction = prefs.toolPriority === "skill" ? "For every user request: (1) first analyze the intent, (2) then identify whether any installed skill matches THIS request, (3) if one matches, invoke the Skill tool with it as your FIRST action — before MCP tools or doing it yourself, (4) if none matches, proceed with MCP tools or solve it yourself. Consult the skill list shown in the Skill tool description whenever you are unsure what is installed." : "For every user request: (1) first analyze the intent, (2) then identify whether any available MCP tool matches THIS request, (3) if one matches, use it as your FIRST action — before the Skill tool or doing it yourself, (4) if none matches, proceed with the Skill tool or solve it yourself.";
141321
142289
  lines.push("", "## Tool priority (set via /like — HIGHEST PRIORITY)", instruction);
141322
142290
  }
141323
142291
  lines.push("", t("like.priority"));
@@ -144141,13 +145109,16 @@ async function handleBuiltInSlashCommand(host, name, args) {
144141
145109
  case "make-skill":
144142
145110
  await handleMakeSkillCommand(host, args);
144143
145111
  return;
144144
- case "skill":
145112
+ case "plugin":
144145
145113
  await handleSkillCommand(host, args);
144146
145114
  return;
145115
+ case "extension":
145116
+ await handleExtensionCommand(host, args);
145117
+ return;
144147
145118
  default:
144148
145119
  host.showError(`Unknown slash command: /${String(name)}`);
144149
145120
  return;
144150
145121
  }
144151
145122
  }
144152
145123
  //#endregion
144153
- export { handleTitleCommand as $, isTodoItemShape as $t, highlightLines as A, CLI_UI_MODE as An, ENABLE_TERMINAL_FOCUS_REPORTING as At, AssistantMessageComponent as B, flushDiagnosticLogs as Bn, TERMINAL_THEME_LIGHT as Bt, UserMessageComponent as C, saveTuiConfig as Cn, createThemeStyles as Ct, ToolCallComponent as D, getLogDir as Dn, parseOsc11BackgroundTheme as Dt, toggleEmptySessionHint as E, getInputHistoryFile as En, detectTerminalTheme as Et, getSharedSpeedTracker as F, saveCatalogCache as Fn, OSC11_RESPONSE_PREFIX_NO_ESC as Ft, getBreathingFrame as G, ErrorCodes as Gn, handleSearchCommand as Gt, WelcomeComponent as H, resolveGlobalLogPath as Hn, isStreaming as Ht, SkillActivationComponent as I, NexumHarness as In, QUERY_TERMINAL_THEME as It, refineGoal as J, printableChar as Jt, resetBreathingClock as K, NEXUM_ERROR_INFO as Kn, handleConnectCommand as Kt, ReadGroupComponent as L, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE as Ln, TERMINAL_FOCUS_IN as Lt, CachedContainer as M, PRODUCT_NAME as Mn, OSC11_QUERY as Mt, ThinkingComponent as N, DEFAULT_CATALOG_URL as Nn, OSC11_RESPONSE as Nt, renderDiffLines as O, detectInstallSource as On, DISABLE_TERMINAL_FOCUS_REPORTING as Ot, estimateTokens as P, fetchCatalog as Pn, OSC11_RESPONSE_PREFIX as Pt, handleInitCommand as Q, formatErrorMessage as Qt, parseReadGroupOutput as R, resolveNexumHome as Rn, TERMINAL_FOCUS_OUT as Rt, handleRevokeCommand as S, loadTuiConfig as Sn, createMarkdownTheme as St, isTurnElapsedEnabled as T, getDataDir as Tn, getColorPalette as Tt, NEXUM_CODE_LOGO as U, isNexumError as Un, FooterComponent as Ut, AgentGroupComponent as V, log as Vn, isBusy as Vt, BREATHE_CYCLE_MS as W, isOrphanedToolCallError as Wn, handleTraceCommand as Wt, handleExportMdCommand as X, appendStreamingArgsPreview as Xt, handleExportDebugZipCommand as Y, STATUS_BULLET as Yt, handleForkCommand as Z, argsRecord as Zt, readUpdateCache as _, setExperimentalFlags as _n, clearInfoPanelState as _t, handleSkillCommand as a, EXIT_CONFIRM_WINDOW_MS as an, handleEditorCommand as at, handleCcCommand as b, TuiConfigParseError as bn, resolveThemeSync as bt, isPlanExpandable as c, TIP_ROTATION_INTERVAL_MS as cn, handlePlanCommand as ct, handleMemoryCommand as d, getLlmNotSetMessage as dn, handleYoloCommand as dt, parseStreamingArgs as en, toTerminalHyperlink as et, handleChannelCommand as f, getNoActiveSessionMessage as fn, showModelPicker as ft, refreshUpdateCache as g, isExperimentalFlagEnabled as gn, supportsBalance as gt, selectUpdateTarget as h, sortSlashCommands as hn, refreshProviderBalance as ht, buildRoleAdditionalText as i, EMPTY_SESSION_HINT_URL as in, handleCompactCommand as it, langFromPath as j, CLI_USER_AGENT_PRODUCT as jn, ENABLE_TERMINAL_THEME_REPORTING as jt, renderDiffLinesClustered as k, CLI_COMMAND_NAME as kn, DISABLE_TERMINAL_THEME_REPORTING as kt, MoonLoader as l, getCtrlCHint as ln, handleThemeCommand as lt, handleUpdateCommand as m, BUILTIN_SLASH_COMMANDS as mn, showSettingsSelector as mt, clearEvalPanelState as n, stringValue as nn, getModelCycleLevel as nt, disposeChildren as o, MAIN_AGENT_ID$1 as on, handleFusionPlanCommand as ot, handleMcpCommand as p, buildSkillSlashCommands as pn, showPermissionPicker as pt, clearGoalState as q, handleLogoutCommand as qt, openUrl as r, truncateErrorMessage as rn, handleAutoCommand as rt, hasDispose as s, SESSION_TIPS as sn, handleModelCommand as st, dispatchInput as t, serializeToolResultOutput as tn, changeThinkingLevel as tt, formatMemoryMemoForInjection as u, getCtrlDHint as un, handleWolfpackCommand as ut, appendJsonlLine as v, PIXEL_PULSE_FRAMES as vn, showStatusReport as vt, isEmptySessionHintDismissed as w, detectShellEnvironment as wn, contrastTextHex as wt, getDaemonInstructions as x, TuiLikePreferencesSchema as xn, createEditorTheme as xt, readJsonlFile as y, PULSE_WAVE_FRAMES as yn, showUsage as yt, BackgroundAgentStatusComponent as z, MemoryMemoStore as zn, TERMINAL_THEME_DARK as zt };
145124
+ export { handleExportMdCommand as $, appendStreamingArgsPreview as $t, renderDiffLinesClustered as A, getInputHistoryFile as An, parseOsc11BackgroundTheme as At, BackgroundAgentStatusComponent as B, NexumHarness as Bn, TERMINAL_FOCUS_IN as Bt, handleRevokeCommand as C, PULSE_WAVE_FRAMES as Cn, resolveThemeSync as Ct, toggleEmptySessionHint as D, saveTuiConfig as Dn, contrastTextHex as Dt, isTurnElapsedEnabled as E, loadTuiConfig as En, createThemeStyles as Et, estimateTokens as F, CLI_USER_AGENT_PRODUCT as Fn, OSC11_QUERY as Ft, WelcomeComponent as G, log as Gn, isStreaming as Gt, AgentGroupComponent as H, resolveNexumHome as Hn, TERMINAL_THEME_DARK as Ht, getSharedSpeedTracker as I, PRODUCT_NAME as In, OSC11_RESPONSE as It, getBreathingFrame as J, isOrphanedToolCallError as Jn, handleSearchCommand as Jt, NEXUM_CODE_LOGO as K, resolveGlobalLogPath as Kn, FooterComponent as Kt, SkillActivationComponent as L, DEFAULT_CATALOG_URL as Ln, OSC11_RESPONSE_PREFIX as Lt, langFromPath as M, detectInstallSource as Mn, DISABLE_TERMINAL_THEME_REPORTING as Mt, CachedContainer as N, CLI_COMMAND_NAME as Nn, ENABLE_TERMINAL_FOCUS_REPORTING as Nt, ToolCallComponent as O, detectShellEnvironment as On, getColorPalette as Ot, ThinkingComponent as P, CLI_UI_MODE as Pn, ENABLE_TERMINAL_THEME_REPORTING as Pt, handleExportDebugZipCommand as Q, STATUS_BULLET as Qt, ReadGroupComponent as R, fetchCatalog as Rn, OSC11_RESPONSE_PREFIX_NO_ESC as Rt, getDaemonInstructions as S, PIXEL_PULSE_FRAMES as Sn, showUsage as St, isEmptySessionHintDismissed as T, TuiLikePreferencesSchema as Tn, createMarkdownTheme as Tt, replaceTabs as U, MemoryMemoStore as Un, TERMINAL_THEME_LIGHT as Ut, AssistantMessageComponent as V, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE as Vn, TERMINAL_FOCUS_OUT as Vt, sanitizeShellOutput as W, flushDiagnosticLogs as Wn, isBusy as Wt, clearGoalState as X, NEXUM_ERROR_INFO as Xn, handleLogoutCommand as Xt, resetBreathingClock as Y, ErrorCodes as Yn, handleConnectCommand as Yt, refineGoal as Z, printableChar as Zt, refreshUpdateCache as _, buildSkillSlashCommands as _n, showSettingsSelector as _t, handleExtensionCommand as a, stringValue as an, getModelCycleLevel as at, readJsonlFile as b, isExperimentalFlagEnabled as bn, clearInfoPanelState as bt, hasDispose as c, EMPTY_SESSION_HINT_URL as cn, handleEditorCommand as ct, formatMemoryMemoForInjection as d, SESSION_TIPS as dn, handlePlanCommand as dt, argsRecord as en, handleForkCommand as et, handleMemoryCommand as f, TIP_ROTATION_INTERVAL_MS as fn, handleThemeCommand as ft, selectUpdateTarget as g, getNoActiveSessionMessage as gn, showPermissionPicker as gt, handleUpdateCommand as h, getLlmNotSetMessage as hn, showModelPicker as ht, buildRoleAdditionalText as i, serializeToolResultOutput as in, changeThinkingLevel as it, highlightLines as j, getLogDir as jn, DISABLE_TERMINAL_FOCUS_REPORTING as jt, renderDiffLines as k, getDataDir as kn, detectTerminalTheme as kt, isPlanExpandable as l, EXIT_CONFIRM_WINDOW_MS as ln, handleFusionPlanCommand as lt, handleMcpCommand as m, getCtrlDHint as mn, handleYoloCommand as mt, clearEvalPanelState as n, isTodoItemShape as nn, handleTitleCommand as nt, handleSkillCommand as o, truncateErrorMessage as on, handleAutoCommand as ot, handleChannelCommand as p, getCtrlCHint as pn, handleWolfpackCommand as pt, BREATHE_CYCLE_MS as q, isNexumError as qn, handleTraceCommand as qt, openUrl as r, parseStreamingArgs as rn, toTerminalHyperlink as rt, disposeChildren as s, CHARS_PER_TOKEN as sn, handleCompactCommand as st, dispatchInput as t, formatErrorMessage as tn, handleInitCommand as tt, MoonLoader as u, MAIN_AGENT_ID$1 as un, handleModelCommand as ut, readUpdateCache as v, BUILTIN_SLASH_COMMANDS as vn, refreshProviderBalance as vt, UserMessageComponent as w, TuiConfigParseError as wn, createEditorTheme as wt, handleCcCommand as x, setExperimentalFlags as xn, showStatusReport as xt, appendJsonlLine as y, sortSlashCommands as yn, supportsBalance as yt, parseReadGroupOutput as z, saveCatalogCache as zn, QUERY_TERMINAL_THEME as zt };