@sayknow-cli/coding-agent 0.7.13 → 0.7.15

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.
@@ -3595,14 +3595,30 @@ export class TelegramBotTransport implements BotApi {
3595
3595
  }
3596
3596
 
3597
3597
  type PairedChatPrivacy = "private" | "non-private" | "indeterminate";
3598
+ const PAIRED_CHAT_PRIVACY_RETRY_BASE_MS = 15_000;
3599
+ const PAIRED_CHAT_PRIVACY_RETRY_MAX_MS = 10 * 60_000;
3600
+ // A rejected bot token (401 revoked / 404 deleted) does not heal by retrying;
3601
+ // re-pairing swaps the token and replaces this daemon. Pause polling with a
3602
+ // long exponential backoff instead of hitting the Bot API every second.
3603
+ const AUTH_REJECTED_RETRY_BASE_MS = 60_000;
3604
+ const AUTH_REJECTED_RETRY_MAX_MS = 30 * 60_000;
3605
+ // Bound one paused wait so the run loop still reaches its idle-exit/stop checks.
3606
+ const AUTH_REJECTED_WAIT_STEP_MS = 25_000;
3607
+
3608
+ export interface TelegramAuthRejection {
3609
+ errorCode: number;
3610
+ description: string;
3611
+ }
3598
3612
 
3599
3613
  export type TelegramUpdateOutcome = "consumed" | "retry";
3600
3614
 
3601
3615
  export type TelegramPollResult =
3602
3616
  | { kind: "success"; updateCount: number }
3603
3617
  | { kind: "aborted" }
3618
+ | { kind: "auth_paused" }
3604
3619
  | { kind: "getUpdates_failed"; error: string }
3605
3620
  | { kind: "api_failure"; errorCode?: number; description: string }
3621
+ | ({ kind: "auth_rejected"; retryInMs: number } & TelegramAuthRejection)
3606
3622
  | { kind: "conflict"; description: string; backoffMs: number };
3607
3623
 
3608
3624
  export interface TelegramUpdatePollerOptions {
@@ -3611,16 +3627,18 @@ export interface TelegramUpdatePollerOptions {
3611
3627
  backoff: { next(): number; reset(): void };
3612
3628
  processUpdate: (update: unknown) => Promise<TelegramUpdateOutcome>;
3613
3629
  health?: TelegramPollHealth;
3630
+ /** Called on each transition into (rejection) or out of (undefined) the auth-rejected state. */
3631
+ onAuthRejected?: (rejection: TelegramAuthRejection | undefined) => void;
3614
3632
  }
3615
3633
 
3616
- type TelegramPollHealthStatus = "healthy" | "getUpdates_failed" | "api_failure" | "conflict";
3634
+ type TelegramPollHealthStatus = "healthy" | "getUpdates_failed" | "api_failure" | "auth_rejected" | "conflict";
3617
3635
 
3618
3636
  export class TelegramPollHealth {
3619
3637
  #status: TelegramPollHealthStatus = "healthy";
3620
3638
  #suppressedCount = 0;
3621
3639
 
3622
3640
  record(result: TelegramPollResult): void {
3623
- if (result.kind === "aborted") return;
3641
+ if (result.kind === "aborted" || result.kind === "auth_paused") return;
3624
3642
  if (result.kind === "success") {
3625
3643
  if (this.#status !== "healthy") {
3626
3644
  logger.info("notifications daemon: Telegram getUpdates recovered", {
@@ -3652,6 +3670,19 @@ export class TelegramPollHealth {
3652
3670
  });
3653
3671
  return;
3654
3672
  }
3673
+ if (result.kind === "auth_rejected") {
3674
+ logger.error(
3675
+ "notifications daemon: Telegram rejected the bot token; polling paused. Re-pair with `skc notify setup`",
3676
+ {
3677
+ errorCode: result.errorCode,
3678
+ description: result.description,
3679
+ retryInMs: result.retryInMs,
3680
+ previousStatus,
3681
+ suppressedCount,
3682
+ },
3683
+ );
3684
+ return;
3685
+ }
3655
3686
  if (result.kind === "api_failure") {
3656
3687
  logger.error("notifications daemon: Telegram getUpdates API failed", {
3657
3688
  errorCode: result.errorCode,
@@ -3689,6 +3720,10 @@ export class TelegramUpdatePoller {
3689
3720
  #offset = 0;
3690
3721
  #opts: TelegramUpdatePollerOptions;
3691
3722
  #health: TelegramPollHealth;
3723
+ #authFailures = 0;
3724
+ #authRetryAt = 0;
3725
+ /** Last state passed to onAuthRejected; undefined until the first verdict so a stale marker is cleared. */
3726
+ #authReported: boolean | undefined;
3692
3727
 
3693
3728
  constructor(opts: TelegramUpdatePollerOptions) {
3694
3729
  this.#opts = opts;
@@ -3708,6 +3743,13 @@ export class TelegramUpdatePoller {
3708
3743
  description?: string;
3709
3744
  result?: Array<{ update_id: number } & Record<string, unknown>>;
3710
3745
  };
3746
+ if (this.#authRetryAt > 0) {
3747
+ const remainingMs = this.#authRetryAt - this.#opts.runtime.now();
3748
+ if (remainingMs > 0) {
3749
+ await this.#opts.runtime.sleep(Math.min(remainingMs, AUTH_REJECTED_WAIT_STEP_MS), signal);
3750
+ return { kind: "auth_paused" };
3751
+ }
3752
+ }
3711
3753
  try {
3712
3754
  body = (await this.#opts.botApi.call(
3713
3755
  "getUpdates",
@@ -3728,6 +3770,23 @@ export class TelegramUpdatePoller {
3728
3770
  await this.#opts.runtime.sleep(backoffMs, signal);
3729
3771
  return { kind: "conflict", description: sanitizeDiagnostic(body.description ?? "no description"), backoffMs };
3730
3772
  }
3773
+ if (body?.ok === false && (body.error_code === 401 || body.error_code === 404)) {
3774
+ this.#authFailures += 1;
3775
+ const retryInMs = Math.min(
3776
+ AUTH_REJECTED_RETRY_MAX_MS,
3777
+ AUTH_REJECTED_RETRY_BASE_MS * 2 ** (this.#authFailures - 1),
3778
+ );
3779
+ this.#authRetryAt = this.#opts.runtime.now() + retryInMs;
3780
+ const rejection = {
3781
+ errorCode: body.error_code,
3782
+ description: sanitizeDiagnostic(body.description ?? "Unauthorized"),
3783
+ };
3784
+ if (this.#authReported !== true) {
3785
+ this.#authReported = true;
3786
+ this.#opts.onAuthRejected?.(rejection);
3787
+ }
3788
+ return { kind: "auth_rejected", retryInMs, ...rejection };
3789
+ }
3731
3790
  if (body?.ok !== true || !Array.isArray(body.result)) {
3732
3791
  await this.#opts.runtime.sleep(POLL_BACKOFF_MS, signal);
3733
3792
  return {
@@ -3737,6 +3796,12 @@ export class TelegramUpdatePoller {
3737
3796
  };
3738
3797
  }
3739
3798
  this.#opts.backoff.reset();
3799
+ this.#authFailures = 0;
3800
+ this.#authRetryAt = 0;
3801
+ if (this.#authReported !== false) {
3802
+ this.#authReported = false;
3803
+ this.#opts.onAuthRejected?.(undefined);
3804
+ }
3740
3805
  let malformedSeen = false;
3741
3806
  for (const update of body.result) {
3742
3807
  // A single malformed update_id must not wedge the poller. Skip the
@@ -4173,6 +4238,8 @@ export class TelegramNotificationDaemon {
4173
4238
  readonly #deliveryAbort = new AbortController();
4174
4239
  private readonly pool: RateLimitPool<TelegramQueuePayload>;
4175
4240
  private readonly poller: TelegramUpdatePoller;
4241
+ /** Serializes auth-rejected marker writes so a quick reject→recover cannot reorder. */
4242
+ private authMarkerWrite: Promise<void> = Promise.resolve();
4176
4243
  private readonly dispatchState = new TelegramEventDispatchState();
4177
4244
  /** Bot-wide flood-control window; inbound polling remains eligible during it. */
4178
4245
  private botCooldownUntil = 0;
@@ -4200,6 +4267,15 @@ export class TelegramNotificationDaemon {
4200
4267
  private readonly flatIdentitySent = new Set<string>();
4201
4268
  /** Cached result of whether the paired chat is a private chat (flat-fallback gate). */
4202
4269
  private pairedChatPrivate: boolean | undefined;
4270
+ /**
4271
+ * Backoff for indeterminate privacy checks. A rejected bot token or a deleted
4272
+ * chat fails the same way on every attempt; re-asking on every delivery tick
4273
+ * flooded the log (one warning per 4s) and the Bot API. Retry with backoff and
4274
+ * warn only when the failure changes.
4275
+ */
4276
+ private pairedChatPrivacyRetryAt = 0;
4277
+ private pairedChatPrivacyFailures = 0;
4278
+ private pairedChatPrivacyLastWarning: string | undefined;
4203
4279
  /** Bot username from getMe, cached once at owner startup for group/forum command targeting. */
4204
4280
  private botUsername: string | undefined;
4205
4281
  /** Sessions whose agent loop is currently busy (drives the typing indicator). */
@@ -4680,9 +4756,38 @@ export class TelegramNotificationDaemon {
4680
4756
  runtime: this.runtime,
4681
4757
  backoff: this.pollConflictBackoff,
4682
4758
  processUpdate: update => this.processTelegramUpdate(update),
4759
+ onAuthRejected: rejection => this.recordAuthRejected(rejection),
4683
4760
  });
4684
4761
  }
4685
4762
 
4763
+ /**
4764
+ * Persist the auth-rejected verdict for offline `notify health`, keyed by the
4765
+ * token fingerprint so a re-paired config ignores a predecessor's marker.
4766
+ */
4767
+ private recordAuthRejected(rejection: TelegramAuthRejection | undefined): void {
4768
+ const file = daemonPaths(this.opts.settings.getAgentDir()).authRejected;
4769
+ this.authMarkerWrite = this.authMarkerWrite
4770
+ .then(async () => {
4771
+ if (rejection) {
4772
+ await writeJsonAtomic(this.fsImpl, file, {
4773
+ tokenFingerprint: tokenFingerprint(this.opts.botToken),
4774
+ errorCode: rejection.errorCode,
4775
+ description: rejection.description,
4776
+ since: this.runtime.now(),
4777
+ });
4778
+ } else {
4779
+ await this.fsImpl.unlink(file).catch(error => {
4780
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
4781
+ });
4782
+ }
4783
+ })
4784
+ .catch(error => {
4785
+ logger.warn("notifications daemon: failed to update Telegram auth-rejected marker", {
4786
+ error: sanitizeDiagnostic(String(error), this.opts.botToken),
4787
+ });
4788
+ });
4789
+ }
4790
+
4686
4791
  private createSessionRouter(): OperatorEventRouter<SessionSocket> {
4687
4792
  return new OperatorEventRouter<SessionSocket>()
4688
4793
  .add({
@@ -7859,15 +7964,23 @@ export class TelegramNotificationDaemon {
7859
7964
  */
7860
7965
  private async resolvePairedChatPrivacy(): Promise<PairedChatPrivacy> {
7861
7966
  if (this.pairedChatPrivate !== undefined) return this.pairedChatPrivate ? "private" : "non-private";
7967
+ const now = this.opts.now?.() ?? Date.now();
7968
+ if (now < this.pairedChatPrivacyRetryAt) return "indeterminate";
7862
7969
  try {
7863
7970
  const res = (await this.botApi.call("getChat", { chat_id: this.opts.chatId })) as {
7864
7971
  ok?: unknown;
7972
+ error_code?: unknown;
7973
+ description?: unknown;
7865
7974
  result?: { type?: unknown };
7866
7975
  };
7867
- if (res === undefined) return "indeterminate";
7976
+ if (res === undefined) return this.deferPairedChatPrivacy(now, undefined);
7868
7977
  if (res?.ok !== true) {
7869
- logger.warn("notifications: getChat privacy check indeterminate (non-success response)");
7870
- return "indeterminate";
7978
+ const code = typeof res?.error_code === "number" ? ` ${res.error_code}` : "";
7979
+ const description = typeof res?.description === "string" ? `: ${res.description}` : "";
7980
+ return this.deferPairedChatPrivacy(
7981
+ now,
7982
+ `notifications: getChat privacy check indeterminate (non-success response${code}${description})`,
7983
+ );
7871
7984
  }
7872
7985
  if (res.result?.type === "private") {
7873
7986
  this.pairedChatPrivate = true;
@@ -7877,12 +7990,35 @@ export class TelegramNotificationDaemon {
7877
7990
  this.pairedChatPrivate = false;
7878
7991
  return "non-private";
7879
7992
  }
7880
- logger.warn("notifications: getChat privacy check indeterminate (missing or invalid chat type)");
7881
- return "indeterminate";
7993
+ return this.deferPairedChatPrivacy(
7994
+ now,
7995
+ "notifications: getChat privacy check indeterminate (missing or invalid chat type)",
7996
+ );
7882
7997
  } catch {
7883
- logger.warn("notifications: getChat privacy check indeterminate (request failed)");
7884
- return "indeterminate";
7998
+ return this.deferPairedChatPrivacy(now, "notifications: getChat privacy check indeterminate (request failed)");
7999
+ }
8000
+ }
8001
+
8002
+ /**
8003
+ * Fail closed for now and schedule the next check. A single failure retries on
8004
+ * the next attempt (transient errors clear quickly); repeated failures back off
8005
+ * exponentially. Warn once per distinct failure.
8006
+ */
8007
+ private deferPairedChatPrivacy(now: number, warning: string | undefined): PairedChatPrivacy {
8008
+ this.pairedChatPrivacyFailures += 1;
8009
+ const delayMs =
8010
+ this.pairedChatPrivacyFailures < 2
8011
+ ? 0
8012
+ : Math.min(
8013
+ PAIRED_CHAT_PRIVACY_RETRY_MAX_MS,
8014
+ PAIRED_CHAT_PRIVACY_RETRY_BASE_MS * 2 ** (this.pairedChatPrivacyFailures - 2),
8015
+ );
8016
+ this.pairedChatPrivacyRetryAt = now + delayMs;
8017
+ if (warning && warning !== this.pairedChatPrivacyLastWarning) {
8018
+ this.pairedChatPrivacyLastWarning = warning;
8019
+ logger.warn(warning, { retryInMs: delayMs });
7885
8020
  }
8021
+ return "indeterminate";
7886
8022
  }
7887
8023
 
7888
8024
  /** Keep existing outbound callers fail-closed for indeterminate privacy. */
@@ -66,6 +66,7 @@ import {
66
66
  prepareCompaction,
67
67
  type RemoteCompactionFallbackHealthEvent,
68
68
  type RemoteCompactionFallbackHealthHooks,
69
+ resolveMidRunThresholdTokens,
69
70
  resolveThresholdTokens,
70
71
  type SummaryOptions,
71
72
  shouldCompact,
@@ -1006,6 +1007,8 @@ function assistantMessageHasVisibleOrToolContent(message: AssistantMessage): boo
1006
1007
  /** Serializers with a verified projection of a failed plain-text assistant prefix. */
1007
1008
  const VISIBLE_CONTINUATION_APIS: ReadonlySet<string> = new Set(["openai-completions", "anthropic-messages"]);
1008
1009
  const RECOVERY_CHECKPOINT_CUSTOM_TYPE = "recovery_checkpoint";
1010
+ /** Re-attached workflow skill instructions after compaction summarized the original prompt away. */
1011
+ const WORKFLOW_SKILL_CONTEXT_CUSTOM_TYPE = "workflow-skill-context";
1009
1012
  const VISIBLE_CONTINUATION_PROMPT =
1010
1013
  "The connection was interrupted while you were answering. Your answer above is preserved exactly as the user saw it. Continue directly from where it stops: do not repeat any of it and do not redo completed work.";
1011
1014
 
@@ -1017,6 +1020,11 @@ function isTextVisibleTail(message: AssistantMessage): boolean {
1017
1020
  );
1018
1021
  }
1019
1022
 
1023
+ /** The model ended its turn normally with no pending tool calls: the answer is complete. */
1024
+ function isFinishedAnswer(message: AssistantMessage): boolean {
1025
+ return message.stopReason === "stop" && !message.content.some(block => block.type === "toolCall");
1026
+ }
1027
+
1020
1028
  function isLocalModelEndpoint(model: Model | undefined): boolean {
1021
1029
  if (!model) return false;
1022
1030
  if (model.provider === "ollama" || model.provider === "lm-studio" || model.provider === "llama.cpp") {
@@ -4194,7 +4202,22 @@ export class AgentSession {
4194
4202
  maintenanceGeneration !== undefined &&
4195
4203
  this.#promptGeneration === maintenanceGeneration
4196
4204
  ) {
4197
- this.#scheduleAgentContinue({ generation: maintenanceGeneration, skipCompactionCheck: true });
4205
+ // Compaction may have summarized away the active workflow's instructions;
4206
+ // re-attach them inside the tracked continuation (registered synchronously,
4207
+ // so the run never looks idle) before the loop's first model call.
4208
+ const invokedWorkflowSkills = outcome === "compacted" ? this.#invokedWorkflowSkillArgs() : undefined;
4209
+ this.#scheduleAgentContinue({
4210
+ generation: maintenanceGeneration,
4211
+ skipCompactionCheck: true,
4212
+ beforeContinue:
4213
+ invokedWorkflowSkills && invokedWorkflowSkills.size > 0
4214
+ ? async () => {
4215
+ const workflowSkillMessage =
4216
+ await this.#buildWorkflowSkillContextMessage(invokedWorkflowSkills);
4217
+ if (workflowSkillMessage) this.agent.steer(workflowSkillMessage);
4218
+ }
4219
+ : undefined,
4220
+ });
4198
4221
  }
4199
4222
  return;
4200
4223
  }
@@ -4404,6 +4427,8 @@ export class AgentSession {
4404
4427
  onError?: (error: unknown) => void;
4405
4428
  /** Run on the current model only: no managed chain, no fallback switch. */
4406
4429
  pinnedModel?: boolean;
4430
+ /** Runs inside the tracked task after the continue checks pass, before agent.continue. */
4431
+ beforeContinue?: () => Promise<void>;
4407
4432
  }): Promise<void> {
4408
4433
  const predecessorAgentEndHold = options?.suppressPredecessorAgentEnd
4409
4434
  ? this.#reserveDeferredAgentEndForContinuation()
@@ -4472,6 +4497,10 @@ export class AgentSession {
4472
4497
  skip("handoff_in_progress");
4473
4498
  return;
4474
4499
  }
4500
+ if (options?.beforeContinue) {
4501
+ await options.beforeContinue();
4502
+ if (!canContinue()) return;
4503
+ }
4475
4504
  const predecessorAgentEnd = this.#claimDeferredAgentEndForContinuation(predecessorAgentEndHold);
4476
4505
  const startsQueuedSuccessor =
4477
4506
  this.agent.state.messages.at(-1)?.role === "assistant" && this.agent.hasQueuedMessages();
@@ -7843,6 +7872,70 @@ export class AgentSession {
7843
7872
  return message;
7844
7873
  }
7845
7874
 
7875
+ /**
7876
+ * The active workflow skill's instructions, when compaction has summarized the
7877
+ * original skill prompt out of live context. A workflow (ralplan, ultragoal, ...)
7878
+ * spans many turns and follows its SKILL.md step by step; a summary of it is not
7879
+ * enough to keep following it, and the model otherwise re-reads the file.
7880
+ * Returns null while the skill prompt (or a restored copy) is still in context.
7881
+ */
7882
+ /**
7883
+ * Workflow skills this branch actually invoked, with their latest args. Sync and
7884
+ * in-memory so sessions that never ran a workflow skill pay no state-file IO.
7885
+ * A leftover state row from another session or an abandoned run must not inject
7886
+ * instructions, so only branch-invoked skills are restore candidates.
7887
+ */
7888
+ #invokedWorkflowSkillArgs(): Map<string, string> {
7889
+ const invoked = new Map<string, string>();
7890
+ for (const entry of this.sessionManager.getBranch()) {
7891
+ if (entry.type !== "custom_message" || entry.customType !== SKILL_PROMPT_MESSAGE_TYPE) continue;
7892
+ const details = entry.details as { name?: unknown; args?: unknown } | undefined;
7893
+ if (typeof details?.name !== "string" || !isCanonicalSkcWorkflowSkill(details.name)) continue;
7894
+ invoked.set(details.name, typeof details.args === "string" ? details.args : "");
7895
+ }
7896
+ return invoked;
7897
+ }
7898
+
7899
+ async #buildWorkflowSkillContextMessage(invoked: Map<string, string>): Promise<CustomMessage | null> {
7900
+ const sessionId = this.sessionManager.getSessionId();
7901
+ let activeSkill: string | undefined;
7902
+ try {
7903
+ const activeState = await readVisibleSkillActiveState(this.sessionManager.getCwd(), sessionId);
7904
+ activeSkill = activeState?.active_skills
7905
+ ?.filter(entry => entry.active !== false && entry.session_id === sessionId)
7906
+ .filter(entry => isCanonicalSkcWorkflowSkill(entry.skill))
7907
+ .sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""))[0]?.skill;
7908
+ } catch (error) {
7909
+ logger.warn("Failed to read workflow skill state for post-compaction restore", {
7910
+ error: error instanceof Error ? error.message : String(error),
7911
+ });
7912
+ return null;
7913
+ }
7914
+ if (!activeSkill || this.#isDisposed || this.sessionManager.getSessionId() !== sessionId) return null;
7915
+ const skillNameOf = (message: AgentMessage): string | undefined =>
7916
+ message.role === "custom" &&
7917
+ (message.customType === SKILL_PROMPT_MESSAGE_TYPE || message.customType === WORKFLOW_SKILL_CONTEXT_CUSTOM_TYPE)
7918
+ ? ((message.details as { name?: unknown } | undefined)?.name as string | undefined)
7919
+ : undefined;
7920
+ if (this.agent.state.messages.some(message => skillNameOf(message) === activeSkill)) return null;
7921
+ const skill = this.skills.find(candidate => candidate.name === activeSkill);
7922
+ const args = invoked.get(activeSkill);
7923
+ if (!skill || args === undefined) return null;
7924
+ const built = await buildSkillPromptMessage(skill, args, {
7925
+ cwd: this.sessionManager.getCwd(),
7926
+ sessionId,
7927
+ });
7928
+ return {
7929
+ role: "custom",
7930
+ customType: WORKFLOW_SKILL_CONTEXT_CUSTOM_TYPE,
7931
+ content: `The conversation was compacted. The active ${activeSkill} workflow's instructions are restored below; keep following them from the current step recorded in its state.\n\n${built.message}`,
7932
+ display: false,
7933
+ details: { name: activeSkill, args: args || undefined },
7934
+ attribution: "agent",
7935
+ timestamp: Date.now(),
7936
+ };
7937
+ }
7938
+
7846
7939
  /**
7847
7940
  * Clear the goal/plan static-once injection signatures so the next prompt
7848
7941
  * re-injects the active mode context once. MUST be called whenever the live
@@ -8539,6 +8632,12 @@ export class AgentSession {
8539
8632
  if (goalModeMessage) {
8540
8633
  messages.push(goalModeMessage);
8541
8634
  }
8635
+ const invokedWorkflowSkills = this.#invokedWorkflowSkillArgs();
8636
+ const workflowSkillMessage =
8637
+ invokedWorkflowSkills.size > 0 ? await this.#buildWorkflowSkillContextMessage(invokedWorkflowSkills) : null;
8638
+ if (workflowSkillMessage) {
8639
+ messages.push(workflowSkillMessage);
8640
+ }
8542
8641
  const volatileProjectContextMessage = await this.#buildVolatileProjectContextMessage();
8543
8642
  if (!this.#isLatestRetainedEphemeralCopy(volatileProjectContextMessage)) {
8544
8643
  messages.push(volatileProjectContextMessage);
@@ -12194,7 +12293,11 @@ export class AgentSession {
12194
12293
  // Try promotion first — if a larger model is available, switch instead of compacting
12195
12294
  const promoted = await this.#tryContextPromotion(assistantMessage);
12196
12295
  if (!promoted) {
12197
- await this.#runAutoCompaction("threshold", false);
12296
+ // A finished answer has nothing to resume; prompting the model to continue
12297
+ // would start an extra turn that can redo the work it just reported.
12298
+ await this.#runAutoCompaction("threshold", false, false, {
12299
+ promptContinuation: !isFinishedAnswer(assistantMessage),
12300
+ });
12198
12301
  }
12199
12302
  }
12200
12303
  return true;
@@ -12249,13 +12352,20 @@ export class AgentSession {
12249
12352
  // A compaction already in flight (overflow recovery, manual, idle) owns the
12250
12353
  // context; never double-compact underneath it.
12251
12354
  if (this.isCompacting) return "not-needed";
12355
+ // The configured threshold is enforced at answer boundaries; inside a run
12356
+ // only the ceiling/window limit applies, so work is not summarized away
12357
+ // and redone mid-task.
12358
+ const runSettings = {
12359
+ ...compactionSettings,
12360
+ thresholdTokens: resolveMidRunThresholdTokens(contextWindow, compactionSettings),
12361
+ };
12252
12362
 
12253
12363
  // Model maxTokens is a capability ceiling, not a per-turn reservation;
12254
12364
  // track actual context fullness (mirrors the agent_end / pre-prompt checks).
12255
12365
  const autoCompactionOutputReserveTokens = 0;
12256
12366
  const anchor = this.#findMidRunUsageAnchor(context.messages);
12257
12367
  let contextTokens = this.#estimateMidRunContextTokens(context.messages);
12258
- if (!shouldCompact(contextTokens, contextWindow, compactionSettings, autoCompactionOutputReserveTokens)) {
12368
+ if (!shouldCompact(contextTokens, contextWindow, runSettings, autoCompactionOutputReserveTokens)) {
12259
12369
  return "not-needed";
12260
12370
  }
12261
12371
  // Anti-loop (#1662): a given provider response anchors at most one
@@ -12288,7 +12398,7 @@ export class AgentSession {
12288
12398
  !shouldCompact(
12289
12399
  Math.max(0, contextTokens - pruneEstimate.tokensSaved),
12290
12400
  contextWindow,
12291
- compactionSettings,
12401
+ runSettings,
12292
12402
  autoCompactionOutputReserveTokens,
12293
12403
  )
12294
12404
  ) {
@@ -12296,7 +12406,7 @@ export class AgentSession {
12296
12406
  if (isAborted()) return "aborted";
12297
12407
  if (pruneResult) contextTokens = Math.max(0, contextTokens - pruneResult.tokensSaved);
12298
12408
  }
12299
- if (!shouldCompact(contextTokens, contextWindow, compactionSettings, autoCompactionOutputReserveTokens)) {
12409
+ if (!shouldCompact(contextTokens, contextWindow, runSettings, autoCompactionOutputReserveTokens)) {
12300
12410
  return pruneResult?.prunedCount ? "pruned" : "not-needed";
12301
12411
  }
12302
12412
 
@@ -13588,6 +13698,7 @@ export class AgentSession {
13588
13698
  deferred = false,
13589
13699
  options?: {
13590
13700
  continueAfterMaintenance?: boolean;
13701
+ promptContinuation?: boolean;
13591
13702
  deferHandoffMaintenance?: boolean;
13592
13703
  force?: boolean;
13593
13704
  signal?: AbortSignal;
@@ -13606,6 +13717,7 @@ export class AgentSession {
13606
13717
  deferred = false,
13607
13718
  options?: {
13608
13719
  continueAfterMaintenance?: boolean;
13720
+ promptContinuation?: boolean;
13609
13721
  deferHandoffMaintenance?: boolean;
13610
13722
  force?: boolean;
13611
13723
  signal?: AbortSignal;
@@ -13640,6 +13752,7 @@ export class AgentSession {
13640
13752
  let action: "context-full" | "handoff" =
13641
13753
  compactionSettings.strategy === "handoff" && reason !== "overflow" ? "handoff" : "context-full";
13642
13754
  const continueAfterMaintenance = options?.continueAfterMaintenance !== false;
13755
+ const promptContinuation = continueAfterMaintenance && options?.promptContinuation !== false;
13643
13756
  // Register the controller before the observable start event so an abort from
13644
13757
  // a local subscriber, extension, dispose, or caller signal owns this run.
13645
13758
  this.#autoCompactionAbortController?.abort();
@@ -13703,7 +13816,7 @@ export class AgentSession {
13703
13816
  willRetry: false,
13704
13817
  });
13705
13818
  if (autoCompactionSignal.aborted) return { kind: "aborted", source: "signal" };
13706
- if (continueAfterMaintenance && reason !== "idle" && compactionSettings.autoContinue !== false) {
13819
+ if (promptContinuation && reason !== "idle" && compactionSettings.autoContinue !== false) {
13707
13820
  this.#scheduleAutoContinuePrompt(generation);
13708
13821
  }
13709
13822
  if (autoCompactionSignal.aborted) return { kind: "aborted", source: "signal" };
@@ -13804,7 +13917,7 @@ export class AgentSession {
13804
13917
  onSkip: skipReason => this.#logCompactionContinuationSkipped("queued_continue", skipReason),
13805
13918
  onError: error => this.#logCompactionContinuationError("queued_continue", error),
13806
13919
  });
13807
- } else if (continueAfterMaintenance && reason !== "idle" && compactionSettings.autoContinue !== false) {
13920
+ } else if (promptContinuation && reason !== "idle" && compactionSettings.autoContinue !== false) {
13808
13921
  this.#scheduleAutoContinuePrompt(generation);
13809
13922
  }
13810
13923
  return { kind: "skipped" };
@@ -14048,7 +14161,7 @@ export class AgentSession {
14048
14161
  onSkip: reason => this.#logCompactionContinuationSkipped("queued_continue", reason),
14049
14162
  onError: error => this.#logCompactionContinuationError("queued_continue", error),
14050
14163
  });
14051
- } else if (continueAfterMaintenance && reason !== "idle" && compactionSettings.autoContinue !== false) {
14164
+ } else if (promptContinuation && reason !== "idle" && compactionSettings.autoContinue !== false) {
14052
14165
  this.#scheduleAutoContinuePrompt(generation);
14053
14166
  }
14054
14167
  return { kind: "compacted" };
@@ -7,6 +7,7 @@ import * as path from "node:path";
7
7
  import { canContinuePersistedHistory } from "@sayknow-cli/agent-core";
8
8
  import { getAgentDir } from "@sayknow-cli/utils";
9
9
  import { withFileLock } from "../config/file-lock";
10
+ import { canonicalizeTrustedPath } from "../session/internal/managed-session-scope";
10
11
  import { type SessionDestinationInput, SessionManager } from "../session/session-manager";
11
12
  import { FileSessionStorage, type SessionStorageSnapshot } from "../session/session-storage";
12
13
  import { parseClaudeCodeTranscript, parseClaudeExport } from "./claude";
@@ -548,7 +549,8 @@ function findExistingWorkspaceImport(
548
549
  }
549
550
  return {
550
551
  targetSessionId: candidate.id,
551
- targetPath: candidate.path,
552
+ // Same canonical form SessionManager gives a freshly materialized import (macOS /var -> /private/var).
553
+ targetPath: canonicalizeTrustedPath(candidate.path),
552
554
  title:
553
555
  typeof header.title === "string" && header.title.trim()
554
556
  ? truncateText(header.title, MAX_TITLE_CHARS)
package/src/tools/ask.ts CHANGED
@@ -867,8 +867,11 @@ export class AskTool implements AgentTool<AskParametersSchema, AskToolDetails> {
867
867
  activeRemoteReceipt = undefined;
868
868
  if (receipt) await receipt.settle(settlement);
869
869
  };
870
- const checkedPrefix = `${theme.checkbox.checked} `;
871
- const uncheckedPrefix = `${theme.checkbox.unchecked} `;
870
+ // Headless/SDK sessions never initialize the TUI theme and never render
871
+ // checkbox-decorated labels, so any non-matching prefix is correct there.
872
+ const checkbox = theme?.checkbox ?? { checked: "[x]", unchecked: "[ ]" };
873
+ const checkedPrefix = `${checkbox.checked} `;
874
+ const uncheckedPrefix = `${checkbox.unchecked} `;
872
875
  /** The option a displayed label stands for, without checkbox, numbering, or recommendation decoration. */
873
876
  const semanticLabel = (label: string): string =>
874
877
  stripRecommendedSuffix(