omp-superagent 0.1.17 → 0.1.19

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.
Files changed (82) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +205 -59
  4. package/docs/OPERATIONS.md +173 -47
  5. package/docs/design/execution.md +119 -37
  6. package/docs/design/messaging.md +160 -45
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/docs/releases/0.1.19.md +10 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +6 -5
  19. package/skills/head/references/model-selection.md +8 -22
  20. package/skills/head/references/routing.md +36 -17
  21. package/skills/lane/SKILL.md +24 -76
  22. package/skills/lane/references/workflow.md +7 -94
  23. package/src/cli.ts +36 -16
  24. package/src/config/config.ts +21 -2
  25. package/src/contracts.ts +66 -7
  26. package/src/cron/cron-jobs.ts +135 -92
  27. package/src/cron/cron-pr-intake.ts +18 -11
  28. package/src/extension.ts +25 -10
  29. package/src/gateway/gateway-client.ts +3 -1
  30. package/src/host-extension.ts +76 -8
  31. package/src/lane/lane-report.ts +1 -1
  32. package/src/lane/lane-rows.ts +2 -1
  33. package/src/lane/workflow.ts +12 -6
  34. package/src/lane-extension.ts +4 -21
  35. package/src/managed-super-probe.ts +21 -15
  36. package/src/messaging/messenger-command-catalog.json +1 -1
  37. package/src/messaging/messenger-commands.ts +8 -3
  38. package/src/messaging/result-attachment.ts +77 -19
  39. package/src/messaging/slack-context.ts +50 -0
  40. package/src/messaging/written-directives.ts +56 -0
  41. package/src/omp/exit-record.ts +27 -0
  42. package/src/omp/host-protocol.ts +20 -0
  43. package/src/omp/host.ts +73 -20
  44. package/src/omp/installed-omp.ts +15 -12
  45. package/src/omp/managed-super.ts +135 -65
  46. package/src/omp/superkit-skills.ts +15 -2
  47. package/src/pr/pr-intake-order.ts +62 -0
  48. package/src/pr/pr-intake-review.ts +49 -31
  49. package/src/pr/pr-intake-work.ts +3 -2
  50. package/src/routing/message-order.ts +22 -1
  51. package/src/routing/topic-request.ts +48 -4
  52. package/src/runtime/controller.ts +968 -338
  53. package/src/runtime/deferred-routing.ts +12 -4
  54. package/src/runtime/dm-timeline.ts +3 -3
  55. package/src/runtime/inbound-attachments.ts +70 -0
  56. package/src/runtime/local-host-fence.ts +85 -0
  57. package/src/runtime/model-journal.ts +14 -9
  58. package/src/runtime/native-frames.ts +5 -1
  59. package/src/runtime/result-attachments.ts +151 -24
  60. package/src/runtime/worker-result-download.ts +36 -0
  61. package/src/storage/deferred-routing.ts +25 -4
  62. package/src/storage/store.ts +445 -75
  63. package/src/worker/worker-checkout.ts +89 -9
  64. package/src/worker/worker-destination.ts +8 -7
  65. package/src/worker/worker-doctor.ts +29 -9
  66. package/src/worker/worker-enrollment.ts +44 -12
  67. package/src/worker/worker-git-startup.ts +157 -0
  68. package/src/worker/worker-host.ts +16 -26
  69. package/src/worker/worker-ledger.ts +42 -18
  70. package/src/worker/worker-placement-intent.ts +13 -0
  71. package/src/worker/worker-placement.ts +204 -28
  72. package/src/worker/worker-profile.ts +18 -65
  73. package/src/worker/worker-project-startup.ts +106 -0
  74. package/src/worker/worker-registration.ts +85 -30
  75. package/src/worker/worker-repository.ts +55 -6
  76. package/src/worker/worker-request.ts +13 -6
  77. package/src/worker/worker-result-attachments.ts +185 -0
  78. package/src/worker/worker-result-wire.ts +12 -0
  79. package/src/worker/worker-service.ts +51 -23
  80. package/src/worker/worker-trust.ts +19 -4
  81. package/src/worker/worker-wire.ts +47 -14
  82. package/upstream/super.json +2 -3
@@ -1,12 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import { constants, existsSync, lstatSync, realpathSync, statSync } from "node:fs";
3
- import { mkdir, open } from "node:fs/promises";
2
+ import { existsSync, lstatSync } from "node:fs";
3
+ import { mkdir } from "node:fs/promises";
4
4
  import { basename, dirname, isAbsolute, join } from "node:path";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { readSessionInfo } from "@oh-my-pi/pi-coding-agent/session/session-listing";
7
7
  import { untilAborted } from "@oh-my-pi/pi-utils";
8
8
  import type { MemoryRuntimeContext } from "@oh-my-pi/pi-coding-agent/memory-backend";
9
- import type { Approval, ApprovalResolution, DialogResponse, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartNotice, GatewayRestartRecord, GatewayRestartRequest, HistoryPlatform, Inbound, InputRecord, Lane, LaneModel, LaneModelChoice, LanePresetSnapshot, ResolvedLanePreset, ModelPreset, Messenger, OutputRecord, Route, StorePort, ThreadInfo, ThreadUpdate, WorkflowChoice } from "../contracts";
9
+ import type { Approval, ApprovalResolution, DialogResponse, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartNotice, GatewayRestartRecord, GatewayRestartRequest, HistoryPlatform, Inbound, InboundAttachmentReceipt, InputRecord, Lane, LaneModel, LaneModelChoice, LanePresetSnapshot, LocalHostIdentity, ResolvedLanePreset, ModelPreset, Messenger, OutputRecord, Route, SlackContext, SlackPurposeNote, StorePort, ThreadInfo, ThreadUpdate, WorkflowChoice } from "../contracts";
10
10
  import { authorizeDiscordPurpose, discordPurposeRequest } from "../messaging/discord-context";
11
11
  import { discordWorkThreadKey, discordWorkThreadOwnerKey, discordWorkThreadSource, guildThreadParent } from "../messaging/discord-work-thread";
12
12
  import { isObservationRequest } from "./observation-request";
@@ -16,16 +16,20 @@ import { authorizeRoute, credentialEnvNames, DEFAULT_HEAD_IDLE_MS, type Config,
16
16
  import { DeliveryError } from "../messaging/delivery";
17
17
  import { GroupAccess } from "../group/group-access";
18
18
  import { groupRoom } from "../group/group-policy";
19
- import { ResultAttachmentError, type ResultAttachmentIntent } from "../messaging/result-attachment";
19
+ import { presentSlackResultAttachment, ResultAttachmentError, type ResultAttachmentIntent } from "../messaging/result-attachment";
20
20
  import { ResultAttachments } from "./result-attachments";
21
+ import { readAttachmentBytes, stageWorkerAttachments } from "./inbound-attachments";
21
22
  import { assistantProgress, assistantText, headJobResults, nativePromptResult, record, restartPromptReceipt, successful,
22
23
  type NativePromptResult, type RuntimeHost, type RuntimeState } from "./native-frames";
23
24
  import { HostConnection, type HostOptions, PR_REVIEW_INPUT_PREFIX, startHost } from "../omp/host";
24
- import type { FastModeState } from "../omp/host-protocol";
25
+ import { inspectLocalOrphan, quarantinedSlotFree } from "./local-host-fence";
26
+ import { workerDispatchRefusal, type FastModeState, type WorkerDispatchRefusal } from "../omp/host-protocol";
25
27
  import { nativeDefaultModelEvidence, recordedFallbackEvidence } from "./model-journal";
26
28
  import { DmTimeline, eventOrderId, newLogicalTopicId } from "./dm-timeline";
27
- import { compareMessageIds } from "../routing/message-order";
28
- import { matchesWrittenCommand, messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
29
+ import { compareMessageIds, slackWorkspaceQuestionTimestamp } from "../routing/message-order";
30
+ import { decodeSlackMrkdwn, matchesWrittenCommand, messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
31
+ import { hasWorkerCurrentHeader, readWorkerCurrentDirective } from "../messaging/written-directives";
32
+ import { matchesWorkerCurrentPlacement, type WorkerCurrentIntent } from "../worker/worker-placement-intent";
29
33
  import { acceptsRestrictedModelSelector, codingModels, isLaneModel, laneModelArgument, resolveLaneModelChoice, sameLaneModel, type LaneModelCandidate } from "../lane/lane-models";
30
34
  import { advertisedLegacyWorkflow, advertisedWorkflow, headWorkflow, ownerWorkflowRequest, workflowChoice, workflowContext, workflowPrompt } from "../lane/workflow";
31
35
  import { admitHeadSuperstack, advertisesSuperstack, headSuperstackTaskPrefix, headSuperstackTaskText, recordedHeadSuperstack,
@@ -34,7 +38,7 @@ import type { NativePresetInspection } from "../omp/native-presets";
34
38
  import { PresetRoleSync, type PresetRoleSyncAdapters } from "./preset-sync";
35
39
  import type { HeadInitialization } from "../gateway/gateway-wire";
36
40
  import { repositoryRoot } from "../operator/repository";
37
- import { discordThreadSplit, editsTopicPlacement, existingWorkspace, inferredWorkspace, namedWorkspaces, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
41
+ import { discordThreadSplit, editsTopicPlacement, existingWorkspace, inferredWorkspace, matchingSlackHistoryChoice, namedWorkspaces, slackWorkspaceAnswer, slackWorkspacePlacement, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
38
42
  import { findPastTopic, findRoutingTopics, joinedTopicProvenance, pastTopicQuery, readPastTopic, routingExcerpt, routingSubject, transportRoutingProse } from "../routing/topic-history";
39
43
  import { parseLaneReportResult } from "../lane/lane-report";
40
44
  import { isLaneWatchNotice, LaneWatcher, type LaneWatchCommand } from "../lane/lane-watch";
@@ -45,7 +49,8 @@ import { isPrObservation, PrWatcher, type PrWatchCommand } from "../pr/pr-watch"
45
49
  import { CRON_RUN_PREFIX, CronJobs, type CronCreate } from "../cron/cron-jobs";
46
50
  import { CronPrIntake, isPrIntakeOffer, type IntakeScan } from "../cron/cron-pr-intake";
47
51
  import { prModeArgument } from "../pr/pr-intake-mode";
48
- import { intakeStatusKey, intakeThreadKey, intakeWorkId, intakeWorkPrefix, prThreadTitle, unattendedSource } from "../pr/pr-intake-work";
52
+ import { isPrMessageId } from "../pr/pr-intake-order";
53
+ import { intakeStatusKey, intakeThreadKey, intakeWorkId, intakeWorkPrefix, prCronCommand, prThreadTitle, unattendedSource } from "../pr/pr-intake-work";
49
54
  import { readIntakePulls } from "../pr/pr-intake-github";
50
55
  import { isPrReviewLane, prAction, PrControlError, PrReviews, prReviewApis, type ReviewRound } from "../pr/pr-intake-review";
51
56
  import { prReviewModelChoices } from "../pr/pr-review-models";
@@ -54,11 +59,12 @@ import type { readPrSnapshot } from "../pr/pr-github";
54
59
  import { acknowledgeDecision, decisionRequest, decisionViews, validateDecisionResponse, type DecisionView } from "../lane/decisions";
55
60
  import { HEAD_ROTATION_KEY, HEAD_SESSION_FILE_KEY, MIN_HEAD_IDLE_MS, activeHeadSessionFile, hasBoundNativeProfile, readHeadRotation,
56
61
  type HeadLifecycleMode, type HeadRotation, type RotationAttestation, type RotationNative, type RotationResident } from "./head-rotation";
57
- import { selectWorkerPlacement, workerPlacementReady } from "../worker/worker-placement";
62
+ import { selectWorkerPlacement, workerPlacementReady, type WorkerAssignment } from "../worker/worker-placement";
58
63
  import { DeferredRoutingDrain, type RecoveryControl } from "./deferred-routing";
59
64
  import { pullWorkerMemory, verifyMemoryCheckout, workerMemoryStatus, type MemoryDestination } from "./worker-memory";
60
65
  import { lookupWorker, remoteLanePaths, workerConnect, workerOpen, workerProbe, workerRef } from "../worker/worker-wire";
61
66
  import type { RemotePlacement, WorkerProbe, WorkerRegistration, WorkerSelector } from "../worker/worker-wire";
67
+ import type { WorkerResultSource } from "../worker/worker-result-wire";
62
68
  import { applySoulUpdate, replyVoiceProfile, soulSourceId, soulUpdateIntent } from "../omp/soul";
63
69
 
64
70
  const key = (value: string) => createHash("sha256").update(value).digest("hex").slice(0, 24);
@@ -109,6 +115,22 @@ function discordWorkThread(route: Route): boolean {
109
115
  return route.platform === "discord" && route.guildId !== null && route.threadId !== null;
110
116
  }
111
117
 
118
+ function nativeWorkThread(route: Route): boolean {
119
+ return discordWorkThread(route) || route.platform === "slack" && route.threadId !== null;
120
+ }
121
+
122
+ function supportsHeadFollowups(route?: Route): boolean {
123
+ return route?.platform === "discord" || route?.platform === "slack";
124
+ }
125
+
126
+ function routingReply(input: Inbound) {
127
+ const slackRoot = !input.reply && input.route.platform === "slack" ? input.route.threadId : null;
128
+ return {
129
+ replyId: input.reply?.messageId ?? slackRoot,
130
+ replyRoute: slackRoot ? { ...physicalRoute(input.route), threadId: null } : input.route,
131
+ };
132
+ }
133
+
112
134
  function catchupBoundaryKey(route: Route): string | null {
113
135
  return route.platform === "discord" || route.platform === "slack"
114
136
  ? `${route.platform}:catchup-boundary:${physicalRouteKey(route)}` : null;
@@ -120,16 +142,51 @@ function inertContext(text: string): string {
120
142
  }
121
143
 
122
144
  function placementText(input: Inbound): string {
123
- if (!discordWorkThread(input.route) || input.text.trimStart().startsWith("/")) return messengerCommandText(input);
124
- const { text } = topicRequest(input.text);
125
- const split = discordThreadSplit(text);
126
- if (split === null) return input.text;
145
+ // Only a proven Slack address can expose a workspace header or a natural
146
+ // split. The projected prose cannot supply a command or workflow selector.
147
+ let text = input.text;
148
+ let addressedProse: string | undefined;
149
+ let addressedWorkspace = false;
150
+ if (input.route.platform === "slack" && input.messageId !== null && !input.reply && !input.unresolvedReply && !input.attachments.length) {
151
+ text = slackWorkspacePlacement(input.text, input.routingText);
152
+ addressedWorkspace = input.routingText !== undefined && /^cwd:/iu.test(input.routingText);
153
+ addressedProse = input.routingText;
154
+ }
155
+ if (!nativeWorkThread(input.route) || input.text.trimStart().startsWith("/")
156
+ || input.route.platform === "slack" && (input.reply || input.unresolvedReply || input.attachments.length))
157
+ return messengerCommandText(text === input.text ? input : { ...input, text });
158
+ // A legacy routing view is useful data, but it never grants a new split.
159
+ if (input.route.platform === "slack" && input.slackVerifiedRoutingBody !== true) return text;
160
+ const request = topicRequest(text);
161
+ const split = discordThreadSplit(addressedWorkspace ? request.text : addressedProse ?? request.text);
162
+ if (split === null) return text;
127
163
  if (!split) return "/new";
128
164
  // Replace only the split directive. Rebuilding the cwd header loses quoted path bytes.
129
- const header = input.text.slice(0, input.text.length - text.length);
130
- return `/new ${header}${split}`;
165
+ const header = text.slice(0, text.length - request.text.length);
166
+ // The workspace path has already been decoded; normalize just the task.
167
+ const body = input.route.platform === "slack" && (addressedWorkspace || addressedProse === undefined)
168
+ ? decodeSlackMrkdwn(split) : split;
169
+ return `/new ${header}${body}`;
170
+ }
171
+
172
+ /** A Slack routing wrapper can select placement without attesting a workflow selector. */
173
+ function unverifiedSlackWorkspaceTask(input: Inbound, placement: string): boolean {
174
+ return input.route.platform === "slack" && input.messageId !== null && input.slackVerifiedRoutingBody !== true
175
+ && topicRequest(placement).cwd !== null;
131
176
  }
132
177
 
178
+ function topicWorkspaceMetadata(id: string, cwd: string, requested = cwd) {
179
+ // Routing comparisons use the admitted physical cwd. New placement also
180
+ // needs the owner's spelling to recognize the authority of a named default.
181
+ return { [`topic-cwd:${id}`]: cwd, [`topic-requested-cwd:${id}`]: requested };
182
+ }
183
+
184
+ function ownerPlacementWorkflow(input: Inbound, placement: string, task: string) {
185
+ const unverifiedTask = input.route.platform === "slack" && input.messageId !== null && (
186
+ /^\/new(?:\s|$)/u.test(placement.trimStart()) && !/^\/new(?:\s|$)/u.test(input.text.trimStart())
187
+ || unverifiedSlackWorkspaceTask(input, placement));
188
+ return ownerWorkflowRequest(input, task, unverifiedTask);
189
+ }
133
190
  function messengerEdit(input: Inbound): boolean {
134
191
  if (input.messageId === null) return false;
135
192
  const { platform, accountId, channelId } = input.route;
@@ -139,7 +196,7 @@ function messengerEdit(input: Inbound): boolean {
139
196
 
140
197
  function matchHeadControl(text: string, platform: Route["platform"]): HeadCommand | null {
141
198
  const match = headControlPattern.exec(text.trim());
142
- if (!match || match[1] === "usage-reset" && platform !== "discord") return null;
199
+ if (!match || match[1] === "usage-reset" && platform !== "discord" && platform !== "slack") return null;
143
200
  const name = match[1] as HeadCommand["name"];
144
201
  const argument = (match[2] ?? "").trim();
145
202
  // PR actions contain only identifiers. Use the same tokens for admission receipts,
@@ -159,11 +216,17 @@ function fastModeStatus({ mode, active }: FastModeState): string {
159
216
  return `Fast mode: ${mode}; native fast tier ${active ? "active" : "inactive"} for the current model.`;
160
217
  }
161
218
 
219
+ interface CapacityHold {
220
+ readonly resident: number;
221
+ readonly maxHosts: number;
222
+ readonly unverifiedLocalLaneIds: readonly string[];
223
+ }
224
+
162
225
  export interface RuntimeAdapters extends PresetRoleSyncAdapters {
163
226
  topicMemory?: Pick<MemoryRuntimeContext, "status" | "search">;
164
227
  workerMemoryDestination?: MemoryDestination;
165
228
  connect(path: string): Promise<RuntimeHost>;
166
- startHost(options: HostOptions): Promise<{ pid: number }>;
229
+ startHost(options: HostOptions): Promise<{ pid: number; localIdentity?: LocalHostIdentity }>;
167
230
  selectWorkerPlacement: typeof selectWorkerPlacement;
168
231
  workerPlacementReady: typeof workerPlacementReady;
169
232
  lookupWorker: typeof lookupWorker;
@@ -182,15 +245,32 @@ export interface RuntimeAdapters extends PresetRoleSyncAdapters {
182
245
  readHeadQuota?: (failure: HeadQuotaFailure, sessionId: string, signal: AbortSignal) => Promise<boolean>;
183
246
  }
184
247
 
248
+ interface PromptAdmission {
249
+ input: InputRecord;
250
+ result?: NativePromptResult;
251
+ followupEnteredAt?: number;
252
+ workerResult?: WorkerResultSource;
253
+ worker?: {
254
+ readonly command: "prompt" | "goal";
255
+ readonly attachments?: true;
256
+ readonly holdOnRefusal?: true;
257
+ response?: Promise<void>;
258
+ outcome?: "acknowledged" | WorkerDispatchRefusal;
259
+ };
260
+ }
261
+
185
262
  interface Live {
186
263
  id: string;
187
264
  generation: number;
188
265
  sessionId: string;
189
266
  readonly journalCursorVersion?: 1;
267
+ readonly nativeModelAvailability: boolean;
190
268
  connection: RuntimeHost;
191
269
  input?: InputRecord;
192
270
  result?: NativePromptResult;
193
- admitted: Map<string, { input: InputRecord; result?: NativePromptResult; discordFollowupEnteredAt?: number }>;
271
+ admitted: Map<string, PromptAdmission>;
272
+ /** Uncertain paused submissions can still receive exact receipts on this connection. */
273
+ pausedWorkerAdmissions?: Map<string, PromptAdmission>;
194
274
  running: boolean;
195
275
  preparing: number;
196
276
  ownedRuns: number;
@@ -212,17 +292,18 @@ interface Live {
212
292
  headJobPromptSeen?: boolean;
213
293
  headJobBatch?: Map<string, string>;
214
294
  headJobMixed?: boolean;
215
- headJobCleanAnswer?: { text: string; discordFollowupProofAt?: number };
216
- discordNonCohortJobSeen?: boolean;
217
- discordJobContinuation?: boolean;
218
- discordContinuationJobIds?: Set<string>;
219
- discordJoinedAnswer?: { text: string; observedAt: number };
295
+ headJobCleanAnswer?: { text: string; followupProofAt?: number };
296
+ nonCohortJobSeen?: boolean;
297
+ headJobContinuation?: boolean;
298
+ headContinuationJobIds?: Set<string>;
299
+ joinedAnswer?: { text: string; observedAt: number };
220
300
  releasing?: boolean;
221
301
  lostDuringRelease?: boolean;
222
302
  nextReleaseProbe?: number;
223
303
  memoryWorker?: WorkerRegistration;
224
304
  nextMemoryPull?: number;
225
305
  finalMemoryVersion?: number;
306
+ workerAttachmentReceipt?: { readonly inputId: string; readonly attachments: InputRecord["attachments"]; readonly data: AttachmentData };
226
307
  recovery?: RotationResident;
227
308
  goalId?: string;
228
309
  observationCursor?: string | null;
@@ -247,8 +328,14 @@ interface LanePlacementReceipt {
247
328
  readonly platform?: WorkerSelector["platform"];
248
329
  }
249
330
  interface AttachmentData {
250
- descriptions: string[];
251
- images: Array<{ type: "image"; data: string; mimeType: string }>;
331
+ readonly descriptions: readonly string[];
332
+ readonly images: ReadonlyArray<{ readonly type: "image"; readonly data: string; readonly mimeType: string }>;
333
+ readonly workerFiles?: InboundAttachmentReceipt["files"];
334
+ }
335
+ interface WorkerInboundPreparation {
336
+ readonly inputId: string;
337
+ readonly cancel: AbortController;
338
+ readonly done: Promise<void>;
252
339
  }
253
340
  const laneDecisionReview = "lane-decision-review:";
254
341
  interface HeadCommand {
@@ -258,8 +345,9 @@ interface HeadCommand {
258
345
  }
259
346
 
260
347
  function matchesUsageReset(command: HeadCommand, platform: Route["platform"]): boolean {
261
- return platform === "discord" ? command.name === "usage-reset" && !command.argument
262
- : command.name === "usage" && command.argument === "reset";
348
+ return command.name === "usage-reset"
349
+ ? (platform === "discord" || platform === "slack") && !command.argument
350
+ : platform !== "discord" && command.name === "usage" && command.argument === "reset";
263
351
  }
264
352
 
265
353
  function usageResetHint(platform: Route["platform"]): string {
@@ -308,7 +396,7 @@ export interface LaneStart extends LaneModelChoice {
308
396
  title: string;
309
397
  cwd: string;
310
398
  kickoff: string;
311
- modelReason: string;
399
+ modelReason?: string;
312
400
  brief?: string;
313
401
  acceptance?: string[];
314
402
  destination?: Route;
@@ -399,13 +487,14 @@ export class Superagent {
399
487
  private readonly live = new Map<string, Live>();
400
488
  private readonly connecting = new Set<string>();
401
489
  private readonly blocked = new Set<string>();
490
+ private capacityHolds = new Map<string, CapacityHold>(); // Last completed admission pass, keyed by pending input.
402
491
  private readonly modelHolds = new Map<string, string>();
403
492
  private readonly cards = new Set<string>();
404
493
  private readonly callbacks = new Set<string>();
405
494
  private readonly controls = new Set<string>();
406
495
  private readonly routingHints = new Map<string, HeadRoutingHint>();
407
496
  private readonly operations = new Map<string, Promise<Lane>>();
408
- private readonly placingWorkers = new Map<string, string>();
497
+ private readonly placingWorkers = new Map<string, RemotePlacement>();
409
498
  private readonly pauseRevisions = new Map<string, number>();
410
499
  private readonly modelChanges = new Map<string, Promise<unknown>>();
411
500
  private readonly tasks = new Set<Promise<unknown>>();
@@ -423,6 +512,7 @@ export class Superagent {
423
512
  private laneMutations = 0;
424
513
  private headStopTail: Promise<void> = Promise.resolve();
425
514
  private restartActive?: string;
515
+ private restartAckWaiting?: string;
426
516
  private headActivityAt = performance.now();
427
517
  private headCoordinationActivityAt = this.headActivityAt;
428
518
  private sleepProof?: { readonly activityAt: number; readonly attestation: RotationAttestation };
@@ -466,6 +556,7 @@ export class Superagent {
466
556
  private readonly resultAttachments: ResultAttachments;
467
557
  private readonly remoteReconnect = new Map<string, RemoteRetry>();
468
558
  private readonly remoteAttaching = new Map<string, Promise<Live>>();
559
+ private readonly workerInbound = new Map<string, WorkerInboundPreparation>();
469
560
  private memoryPull?: { readonly live: Live; readonly deadline: number; readonly done: Promise<void>; readonly cancel: AbortController };
470
561
  private readonly routingDrain: DeferredRoutingDrain;
471
562
 
@@ -482,6 +573,7 @@ export class Superagent {
482
573
  stopped: () => this.stopped,
483
574
  fenced: () => this.restartFence() !== null || this.headRotationHeld("hibernate"),
484
575
  recovery: input => this.deferredRecoveryControl(input),
576
+ awaitingReceipt: input => this.awaitingSlackChoiceReceipt(input),
485
577
  admit: id => this.intake(() => {
486
578
  const input = store.deferredRouting.input(id);
487
579
  if (!input) throw new Error(`Deferred receipt ${id} disappeared before admission`);
@@ -571,6 +663,10 @@ export class Superagent {
571
663
  && rotation.sessionFile === this.headSessionFile() && rotation.attestation.generation === generation
572
664
  && process.ppid > 1 && rotation.replacementOwnerPid === process.ppid;
573
665
  for (const lane of this.store.lanes()) {
666
+ if (lane.localOwner?.journalHeld) {
667
+ this.blocked.add(lane.id);
668
+ continue;
669
+ }
574
670
  if (!this.mayOwnHost(lane)) {
575
671
  if (this.remoteOpenPending(lane)) {
576
672
  this.blocked.add(lane.id);
@@ -1338,6 +1434,7 @@ export class Superagent {
1338
1434
 
1339
1435
  private verify(live: Pick<Live, "id" | "generation" | "sessionId">, state: RuntimeState): void {
1340
1436
  const lane = live.id === "main" ? null : this.requireLane(live.id);
1437
+ if (lane?.localOwner?.journalHeld) throw new Error(`Lane ${live.id}: the original local Host journal is unverified`);
1341
1438
  const expected = lane?.sessionFile ?? this.headSessionFile();
1342
1439
  const expectedId = live.sessionId || (lane ? lane.sessionId : this.store.getMeta("main:sessionId"));
1343
1440
  if (state.sessionFile !== expected || !state.sessionId || (expectedId && state.sessionId !== expectedId)
@@ -1353,6 +1450,8 @@ export class Superagent {
1353
1450
  const state = await live.connection.client.getState();
1354
1451
  if (!this.current(live)) throw new Error(`Obsolete host connection: ${live.id}`);
1355
1452
  this.verify(live, state);
1453
+ if (live.nativeModelAvailability && state.laneModelAvailable === undefined)
1454
+ throw new Error(`Lane ${live.id} did not report its native model availability`);
1356
1455
  return state;
1357
1456
  }
1358
1457
 
@@ -1369,11 +1468,10 @@ export class Superagent {
1369
1468
  return leafId;
1370
1469
  }
1371
1470
 
1372
- private async nativeModelCatalog(): Promise<unknown[]> {
1373
- const head = this.live.get("main");
1374
- if (!head || !this.current(head)) throw new Error("The authoritative head model catalog is unavailable");
1375
- const data = successful(await head.connection.request({ type: "get_available_models" }), "get_available_models");
1376
- if (!this.current(head)) throw new Error("The authoritative head changed while reading its model catalog");
1471
+ private async nativeModelCatalog(owner = this.live.get("main")): Promise<unknown[]> {
1472
+ if (!owner || !this.current(owner)) throw new Error("The authoritative native model catalog is unavailable");
1473
+ const data = successful(await owner.connection.request({ type: "get_available_models" }), "get_available_models");
1474
+ if (!this.current(owner)) throw new Error("The authoritative native owner changed while reading its model catalog");
1377
1475
  if (!Array.isArray(data.models)) throw new Error("Native available-model response is missing its model list");
1378
1476
  return data.models;
1379
1477
  }
@@ -1539,6 +1637,7 @@ export class Superagent {
1539
1637
 
1540
1638
  private nativeSelectionMatches(state: RuntimeState, intent: Pick<ModelChangeIntent, "model" | "preset" | "snapshot">): boolean {
1541
1639
  return state.settingsScope === "session" && sameLaneModel(state.model, intent.model)
1640
+ && (state.laneModelAvailable === undefined || sameLaneModel(state.laneModelAvailable, intent.model))
1542
1641
  && (intent.preset === null || !!intent.snapshot && this.samePresetSettings(intent.snapshot, state.modelSettings));
1543
1642
  }
1544
1643
 
@@ -1558,9 +1657,9 @@ export class Superagent {
1558
1657
  return restored?.generation === live.generation && this.modelIntent(live.id, "apply") !== null;
1559
1658
  }
1560
1659
 
1561
- private async nativeDefaultProof(live: Live, catalog: unknown[], model: LaneModel): Promise<string | null> {
1660
+ private async nativeDefaultProof(live: Live, readCatalog: () => Promise<unknown[]>, model: LaneModel): Promise<string | null> {
1562
1661
  const result = successful(await live.connection.request({ type: "get_entries" }), "read native default model journal");
1563
- const { leaf, selected } = nativeDefaultModelEvidence(result, catalog, live.id);
1662
+ const { leaf, selected } = await nativeDefaultModelEvidence(result, readCatalog, live.id);
1564
1663
  if (await this.readJournalCursor(live, "confirm native default model journal") !== leaf)
1565
1664
  throw new Error(`Lane ${live.id} native model journal changed during selection readback`);
1566
1665
  return typeof leaf === "string" && sameLaneModel(selected, model) ? leaf : null;
@@ -1701,11 +1800,11 @@ export class Superagent {
1701
1800
  if (lane.remote && preset === null && !acceptsRestrictedModelSelector(requested))
1702
1801
  throw new Error("Remote worker model changes require a provider and model ID without whitespace or control characters");
1703
1802
  const reviewOnly = isPrReviewLane(this.store, id);
1704
- const catalog = reviewOnly ? await this.nativeModelCatalog() : await this.requireAvailableModel(requested);
1705
- if (reviewOnly) {
1803
+ const reviewCatalog = reviewOnly ? await this.nativeModelCatalog() : undefined;
1804
+ if (reviewCatalog) {
1706
1805
  // A retry can prove the exact model by native readback without calling
1707
1806
  // set_pr_review_model again. That still requires a current eligible pair.
1708
- const choices = prReviewModelChoices(catalog);
1807
+ const choices = prReviewModelChoices(reviewCatalog);
1709
1808
  if (!choices.some(candidate => sameLaneModel(candidate, requested)))
1710
1809
  throw new PrControlError("Static PR review model selection requires a unique, currently available tool-less inference model");
1711
1810
  }
@@ -1755,7 +1854,7 @@ export class Superagent {
1755
1854
  },
1756
1855
  };
1757
1856
  }
1758
- live = await this.ensureLane(lane, readback) ?? undefined;
1857
+ live = await this.ensureLane(lane, { modelReadback: readback }) ?? undefined;
1759
1858
  if (!live) throw new Error(`Lane ${id} could not restore its native owner within the host budget; durable intent remains held`);
1760
1859
  lane = this.requireLane(id);
1761
1860
  }
@@ -1763,6 +1862,10 @@ export class Superagent {
1763
1862
  if (!live?.connection.assertPrReviewOnly) throw new PrControlError("Native review policy is unavailable");
1764
1863
  await live.connection.assertPrReviewOnly(lane.cwd);
1765
1864
  }
1865
+ // An attached managed Host validates the target pair in its own setter;
1866
+ // a no-op still needs exact readback of the active available pair.
1867
+ const legacyCatalog = !reviewOnly && (live ? !live.nativeModelAvailability : !lane.remote)
1868
+ ? await this.requireAvailableModel(requested) : undefined;
1766
1869
  const nativeVersion = live?.nativeVersion;
1767
1870
  if (scoped && operatorSource) {
1768
1871
  const selected = this.scopedLaneModelSelection(operatorSource, this.requireLane(id));
@@ -1773,7 +1876,10 @@ export class Superagent {
1773
1876
  // An ambiguous attempt is complete only if its default change, not just
1774
1877
  // the currently serving model, is on the active native journal branch.
1775
1878
  const persistedDefault = live && intent?.native && this.requiresNativeDefault(live, intent)
1776
- ? await this.nativeDefaultProof(live, catalog, intent.model) : null;
1879
+ ? await this.nativeDefaultProof(live, () => {
1880
+ const catalog = reviewCatalog ?? legacyCatalog;
1881
+ return catalog ? Promise.resolve(catalog) : this.nativeModelCatalog(lane.remote ? undefined : live);
1882
+ }, intent.model) : null;
1777
1883
  // HEAD identity is independent of target idleness. Read the target last:
1778
1884
  // goals, owned work and UI can become active without a run/version event.
1779
1885
  const idleVersion = live?.modelIdleVersion;
@@ -1869,7 +1975,7 @@ export class Superagent {
1869
1975
  }
1870
1976
  }
1871
1977
 
1872
- private async confirmRecordedFallback(live: Live, lane: Lane, state: RuntimeState, actual: LaneModel, catalog: unknown[], after?: string):
1978
+ private async confirmRecordedFallback(live: Live, lane: Lane, state: RuntimeState, actual: LaneModel, readCatalog: () => Promise<unknown[]>, after?: string):
1873
1979
  Promise<RuntimeState | null> {
1874
1980
  if (!lane.model || lane.modelPreset !== null || this.modelChanges.has(lane.id)
1875
1981
  || typeof state.hostPid !== "number" || !Number.isSafeInteger(state.hostPid) || state.hostPid <= 0
@@ -1879,7 +1985,7 @@ export class Superagent {
1879
1985
  // The Rust worker relay allows this query on the attached owner only.
1880
1986
  // A remote lane's journal path must never be opened on the controller.
1881
1987
  const evidence = successful(await live.connection.request({ type: "get_entries" }), "read native lane model evidence");
1882
- const fallback = recordedFallbackEvidence(evidence, { configured: lane.model, actual, catalog }, after);
1988
+ const fallback = await recordedFallbackEvidence(evidence, { configured: lane.model, actual, readCatalog }, after);
1883
1989
  if (!fallback) return null;
1884
1990
  const { leaf, entryId } = fallback;
1885
1991
  const receipt = { sessionId: live.sessionId, generation: live.generation, hostPid: state.hostPid, entryId };
@@ -1897,6 +2003,7 @@ export class Superagent {
1897
2003
  || this.stopped || this.restartFence()
1898
2004
  || confirmedLeaf !== leaf || confirmed.settingsScope !== "session" || confirmed.hostPid !== state.hostPid
1899
2005
  || !sameLaneModel(actual, confirmed.model) || this.modelChanges.has(lane.id) || this.modelIntent(lane.id)
2006
+ || live.nativeModelAvailability && !sameLaneModel(actual, confirmed.laneModelAvailable)
1900
2007
  || this.modelIntent(lane.id, "apply") || current.modelPreset !== null || current.modelReason !== lane.modelReason
1901
2008
  || !sameLaneModel(current.model, lane.model) || this.store.getMeta(laneFallbackKey(lane.id)) !== saved
1902
2009
  || !this.workRoute(current.route)) return null;
@@ -1925,20 +2032,23 @@ export class Superagent {
1925
2032
  };
1926
2033
  try {
1927
2034
  assertCurrentSelection();
1928
- const catalog = await this.nativeModelCatalog();
2035
+ let lane = this.requireLane(live.id);
2036
+ const catalogOwner = live.nativeModelAvailability && !lane.remote ? live : undefined;
2037
+ let catalog: Promise<unknown[]> | undefined;
2038
+ const readCatalog = () => catalog ??= this.nativeModelCatalog(catalogOwner);
2039
+ const available = live.nativeModelAvailability ? undefined : codingModels(await readCatalog());
1929
2040
  assertCurrentSelection();
1930
- const available = codingModels(catalog);
1931
2041
  let state = await this.state(live);
1932
2042
  assertCurrentSelection();
1933
2043
  if (this.restartFence()) return state;
1934
2044
  if (state.settingsScope !== "session") throw new Error(`Lane ${live.id} is not using a session-isolated owned native configuration overlay; restart it before managed execution`);
1935
- let lane = this.requireLane(live.id);
2045
+ lane = this.requireLane(live.id);
1936
2046
  const intent = this.modelIntent(live.id);
1937
2047
  if (intent) {
1938
2048
  this.assertPassiveModelReconciliation(live.id, intent);
1939
- if (!available.some(candidate => sameLaneModel(candidate, intent.model))) throw new Error(`Lane ${live.id} intended model is no longer available; model change remains held`);
2049
+ if (available && !available.some(candidate => sameLaneModel(candidate, intent.model))) throw new Error(`Lane ${live.id} intended model is no longer available; model change remains held`);
1940
2050
  if (this.requiresNativeDefault(live, intent)) {
1941
- const proof = await this.nativeDefaultProof(live, catalog, intent.model);
2051
+ const proof = await this.nativeDefaultProof(live, readCatalog, intent.model);
1942
2052
  if (!proof)
1943
2053
  throw new Error(`Lane ${live.id} native default journal has not confirmed its durable intent; explicitly retry source ${intent.sourceId} after inspecting the session`);
1944
2054
  state = await this.state(live);
@@ -1958,7 +2068,7 @@ export class Superagent {
1958
2068
  if (!intent && deferred) {
1959
2069
  if (!sameLaneModel(lane.model, deferred.model) || lane.modelPreset !== deferred.preset
1960
2070
  || !isDeepStrictEqual(lane.modelPresetSnapshot, deferred.snapshot)) throw new Error(`Lane ${live.id} deferred model change no longer matches its committed choice`);
1961
- if (!available.some(candidate => sameLaneModel(candidate, deferred.model))) throw new Error(`Lane ${live.id} deferred model is no longer available`);
2071
+ if (available && !available.some(candidate => sameLaneModel(candidate, deferred.model))) throw new Error(`Lane ${live.id} deferred model is no longer available`);
1962
2072
  this.assertModelChangeIdle(lane, live, state);
1963
2073
  const { quotaHold: _releasedQuota, ...prior } = deferred;
1964
2074
  const applying: ModelChangeIntent = {
@@ -1980,7 +2090,7 @@ export class Superagent {
1980
2090
  if (!isLaneModel(state.model)) throw new Error(`Lane ${live.id} has no authoritative native model; inspect its native session before resuming`);
1981
2091
  const actual = { provider: state.model.provider, id: state.model.id };
1982
2092
  const expected = lane.model ?? actual;
1983
- if (!available.some(candidate => sameLaneModel(candidate, expected))) {
2093
+ if (available ? !available.some(candidate => sameLaneModel(candidate, expected)) : !sameLaneModel(state.laneModelAvailable, actual)) {
1984
2094
  throw new Error(`Selected lane model ${laneModelArgument(expected)} is not an available native chat model; restore its availability before resuming`);
1985
2095
  }
1986
2096
  if (!this.current(live)) throw new Error(`Lane ${live.id} generation changed during model validation`);
@@ -1996,8 +2106,8 @@ export class Superagent {
1996
2106
  const boundary = JSON.parse(savedRestore ?? "null") as RestoreModelBoundary | null;
1997
2107
  const restored = boundary?.generation === live.generation ? boundary : null;
1998
2108
  if (!sameLaneModel(lane.model, actual)) {
1999
- const fallback = (!restored || typeof restored.leaf === "string") && available.some(candidate => sameLaneModel(candidate, actual))
2000
- ? await this.confirmRecordedFallback(live, lane, state, actual, catalog, restored?.leaf || undefined) : null;
2109
+ const fallback = (!restored || typeof restored.leaf === "string")
2110
+ ? await this.confirmRecordedFallback(live, lane, state, actual, readCatalog, restored?.leaf || undefined) : null;
2001
2111
  assertCurrentSelection();
2002
2112
  if (!fallback) {
2003
2113
  throw new Error(`Lane ${live.id} model drift: expected ${laneModelArgument(lane.model!)}, actual ${laneModelArgument(actual)}; reconcile the native session or start a new explicitly selected lane. No model was reset and no prompt was sent`);
@@ -2019,6 +2129,7 @@ export class Superagent {
2019
2129
  assertCurrentSelection();
2020
2130
  if (version !== live.nativeVersion || this.restartFence() || confirmed.settingsScope !== "session"
2021
2131
  || confirmed.hostPid !== state.hostPid || !sameLaneModel(confirmed.model, actual)
2132
+ || live.nativeModelAvailability && !sameLaneModel(confirmed.laneModelAvailable, actual)
2022
2133
  || !sameLaneModel(this.requireLane(live.id).model, actual)
2023
2134
  || this.modelIntent(live.id) || this.modelIntent(live.id, "apply")) {
2024
2135
  throw new Error(`Lane ${live.id} model or owner changed while recording its restored journal boundary`);
@@ -2034,7 +2145,7 @@ export class Superagent {
2034
2145
  const snapshot = this.frozenPreset(lane.modelPresetSnapshot, state);
2035
2146
  if (!this.samePresetSettings(snapshot, state.modelSettings)) throw new Error(`Lane ${live.id} native preset roles/thinking drift from its frozen snapshot; explicitly select a preset after reconciling native settings`);
2036
2147
  if (!isDeepStrictEqual(snapshot, lane.modelPresetSnapshot)) {
2037
- if (!this.store.changeLaneModel(lane.id, live.generation, lane.model, lane.model!, lane.modelReason!, lane.modelPreset, snapshot)) throw new Error(`Lane ${live.id} preset snapshot readback raced with another state change`);
2148
+ if (!this.store.changeLaneModel(lane.id, live.generation, lane.model, lane.model!, lane.modelReason, lane.modelPreset, snapshot)) throw new Error(`Lane ${live.id} preset snapshot readback raced with another state change`);
2038
2149
  }
2039
2150
  }
2040
2151
  this.modelHolds.delete(live.id);
@@ -2055,7 +2166,9 @@ export class Superagent {
2055
2166
  }
2056
2167
 
2057
2168
  private recordLocalExit(lane: Lane): boolean {
2058
- if (lane.pid !== null && this.pidAlive(lane.pid) || this.localSocketMayExist(lane.socketPath)) return false;
2169
+ if (lane.localOwner?.journalHeld) return false;
2170
+ if (lane.pid !== null && (this.pidAlive(lane.pid) || lane.localOwner && this.pidAlive(lane.localOwner.ownerPid))
2171
+ || this.localSocketMayExist(lane.socketPath)) return false;
2059
2172
  // Forget the verified dead owner before releasing its budget slot. Otherwise
2060
2173
  // reuse of its numeric PID by an unrelated process can claim the slot again.
2061
2174
  return lane.pid === null || this.store.retireLocalLaneHost(lane);
@@ -2093,11 +2206,13 @@ export class Superagent {
2093
2206
  }
2094
2207
 
2095
2208
  private async workerLaneReady(lane: Lane, { probe, registration }: RemoteInspection): Promise<boolean> {
2096
- // An authenticated, exact released lane may reuse its original checkout
2097
- // after ordinary edits. A first placement still requires the clean preflight.
2098
- return (lane.sessionId !== null && probe.sessionId === lane.sessionId && probe.sealedGeneration === lane.generation
2099
- && probe.reopenActive !== undefined && probe.reopenActive < registration.description.capacity)
2100
- || await this.adapters.workerPlacementReady(registration, workerRef(lane));
2209
+ const reopen = lane.sessionId !== null && probe.sessionId === lane.sessionId && probe.sealedGeneration === lane.generation
2210
+ && probe.reopenActive !== undefined && probe.reopenActive < registration.description.capacity;
2211
+ if (reopen) return true;
2212
+ // A worker-current describe only proves the checkout, not custody of a
2213
+ // prior session. It cannot stand in for the worker's exact reopen receipt.
2214
+ if (lane.remote?.workerCheckout && lane.sessionId !== null) return false;
2215
+ return await this.adapters.workerPlacementReady(registration, workerRef(lane));
2101
2216
  }
2102
2217
 
2103
2218
  private remoteOpenKey(lane: Pick<Lane, "id" | "generation">): string {
@@ -2132,6 +2247,7 @@ export class Superagent {
2132
2247
  }
2133
2248
 
2134
2249
  private async attachLane(lane: Lane, inspected?: RemoteInspection): Promise<Live> {
2250
+ if (lane.localOwner?.journalHeld) throw new Error(`Lane ${lane.id}: the original local Host journal is unverified`);
2135
2251
  if (!lane.remote) return this.attach(lane.id, lane.generation, () => this.adapters.connect(lane.socketPath));
2136
2252
  this.requireRemoteCommandPolicy();
2137
2253
  const existing = this.live.get(lane.id);
@@ -2181,12 +2297,21 @@ export class Superagent {
2181
2297
  const state = await connection.client.getState();
2182
2298
  if (this.stopped) throw new Error("Controller stopped during connection");
2183
2299
  this.verify({ id, generation, sessionId: "" }, state);
2300
+ const localOwner = connection.localIdentity;
2301
+ if (id !== "main" && localOwner) {
2302
+ const lane = this.requireLane(id);
2303
+ if (lane.remote || localOwner.sessionFile !== lane.sessionFile || localOwner.sessionId !== state.sessionId
2304
+ || localOwner.pid !== state.hostPid || lane.pid !== null && lane.pid !== localOwner.pid
2305
+ || lane.localOwner && !isDeepStrictEqual(lane.localOwner, localOwner))
2306
+ throw new Error(`Refusing changed local Host identity for ${id}`);
2307
+ }
2184
2308
  if (owner && (state.hostPid !== owner.pid || state.sessionId !== owner.sessionId))
2185
2309
  throw new Error(`Refusing a remote Host ${id} that differs from its verified worker owner`);
2186
2310
  if (state.journalCursorVersion !== undefined && state.journalCursorVersion !== 1)
2187
2311
  throw new Error(`Host ${id} reported an unsupported native journal cursor version`);
2188
2312
  live = {
2189
2313
  id, generation, sessionId: state.sessionId, journalCursorVersion: state.journalCursorVersion,
2314
+ nativeModelAvailability: state.laneModelAvailable !== undefined,
2190
2315
  connection, busy: !state.isSettled,
2191
2316
  lastActivity: Date.now(), text: "", ownedRuns: 0, nativeVersion: 0, modelIdleVersion: 0, modelSelectionVersion: 0,
2192
2317
  admitted: new Map(), running: false, preparing: 0, unsubscribe,
@@ -2245,6 +2370,7 @@ export class Superagent {
2245
2370
  }
2246
2371
  else if (!this.store.updateLane(id, generation, {
2247
2372
  sessionId: state.sessionId, ...(state.hostPid ? { pid: state.hostPid } : {}),
2373
+ ...(localOwner && { localOwner }),
2248
2374
  runtimeState: live.busy ? "running" : "idle",
2249
2375
  })) throw new Error(`Host ${id} generation changed during attachment`);
2250
2376
  if (owner) this.store.setMeta(this.remoteOpenKey(live), "attached");
@@ -2295,6 +2421,7 @@ export class Superagent {
2295
2421
  private disconnected(live: Live, transportClosed = false): void {
2296
2422
  if (!this.current(live)) return;
2297
2423
  if (live.releasing) { live.lostDuringRelease = true; return; }
2424
+ this.workerInbound.get(live.id)?.cancel.abort();
2298
2425
  const lane = live.id === "main" ? null : this.requireLane(live.id);
2299
2426
  const lostAttachment = transportClosed && lane?.remote && !this.blocked.has(live.id)
2300
2427
  && !this.connecting.has(lane.id) && !this.remoteAttaching.has(lane.id)
@@ -2306,6 +2433,7 @@ export class Superagent {
2306
2433
  && this.remoteExitCanReleaseConnectionHold(lane)
2307
2434
  ? { generation: live.generation, sessionId: live.sessionId, pauseRevision: this.pauseRevisions.get(lane.id) } : undefined;
2308
2435
  live.unsubscribe();
2436
+ live.pausedWorkerAdmissions?.clear();
2309
2437
  this.live.delete(live.id);
2310
2438
  this.blocked.add(live.id);
2311
2439
  if (live.id === "main" && this.bootstrapActive) {
@@ -2557,7 +2685,7 @@ export class Superagent {
2557
2685
  const questionId = `${prior.id}:workspace`;
2558
2686
  if (this.store.output(questionId)?.state !== "sent") return false;
2559
2687
  if (routeKey(prior.route) === routeKey(followup.route)) {
2560
- if (!followup.reply) return discordWorkThread(followup.route) || this.isDm(followup.route);
2688
+ if (!followup.reply) return nativeWorkThread(followup.route) || this.isDm(followup.route);
2561
2689
  return this.store.sentOutputForMessage(followup.route, followup.reply.messageId)?.id === questionId
2562
2690
  || prior.messageId === followup.reply.messageId;
2563
2691
  }
@@ -2631,7 +2759,7 @@ export class Superagent {
2631
2759
  if (!lane || lane.sessionId !== ref.sessionId || lane.cwd !== ref.cwd || existingWorkspace(ref.cwd) !== ref.cwd
2632
2760
  || !authorizeRoute(this.config, lane.route) || lane.route.platform === source.platform && lane.route.accountId !== source.accountId
2633
2761
  || lane.workState === "paused" || lane.workState === "cancelled" || lane.runtimeState === "interrupted" || this.blocked.has(lane.id)) return null;
2634
- if (lane.id === owner && discordWorkThread(source) && routeKey(source) === routeKey(lane.route)) {
2762
+ if (lane.id === owner && nativeWorkThread(source) && routeKey(source) === routeKey(lane.route)) {
2635
2763
  return lane.workState === "open" ? lane : null;
2636
2764
  }
2637
2765
  if (lane.runtimeState === "running" || lane.runtimeState === "starting"
@@ -2644,7 +2772,7 @@ export class Superagent {
2644
2772
  if (!lane) return null;
2645
2773
  // The destination can consult a pinned entry in its own active journal.
2646
2774
  // A different lane must be quiescent; its running work is never transferred.
2647
- if (lane.id !== owner || !discordWorkThread(source.route) || routeKey(source.route) !== routeKey(lane.route)) {
2775
+ if (lane.id !== owner || !nativeWorkThread(source.route) || routeKey(source.route) !== routeKey(lane.route)) {
2648
2776
  const previous = this.live.get(lane.id);
2649
2777
  if (previous) {
2650
2778
  const state = await this.state(previous);
@@ -2673,8 +2801,9 @@ export class Superagent {
2673
2801
  const conversation = routingConversation(input.route);
2674
2802
  const waiting = queue.head(conversation) !== null;
2675
2803
  const recovery = waiting ? this.deferredRecoveryControl(intake) : null;
2676
- const bypass = recovery?.priority === "immediate" || recovery?.priority === "retry" && this.routingDrain.retrying(conversation);
2677
- if (waiting ? bypass || this.store.input(input.id) !== null : this.routingIntent(intake).query === null) {
2804
+ const bypass = recovery?.priority === "immediate" || recovery?.priority === "retry" && this.routingDrain.blocked(conversation);
2805
+ if (waiting ? bypass || this.store.input(input.id) !== null
2806
+ : this.routingIntent(intake).query === null && !this.awaitingSlackChoiceReceipt(intake)) {
2678
2807
  await this.admit(input);
2679
2808
  return;
2680
2809
  }
@@ -2683,6 +2812,59 @@ export class Superagent {
2683
2812
  this.remember(input);
2684
2813
  }
2685
2814
 
2815
+ private awaitingSlackChoiceReceipt(input: Inbound): boolean {
2816
+ const { messageId, route } = input;
2817
+ const { threadId } = route;
2818
+ if (route.platform !== "slack" || threadId === null || messageId === null
2819
+ || input.pickerSelection || input.reply || input.unresolvedReply || input.attachments.length || messengerEdit(input)) return false;
2820
+ const bareStop = input.text.trim() === "/stop";
2821
+ const answer = bareStop ? null : slackWorkspaceAnswer(input.text, input.routingText, input.slackVerifiedRoutingBody);
2822
+ if (!bareStop && (!answer || codeHandledControl(input.text, route.platform))) return false;
2823
+ const explicit = answer?.source ?? null;
2824
+ const parent = { ...physicalRoute(route), threadId: null };
2825
+ if (bareStop) {
2826
+ const root = this.store.repliedStop(parent, threadId);
2827
+ // A bound lane is a definite target unless the root carries conflicting
2828
+ // evidence. An unrelated in-flight channel post cannot override it.
2829
+ if (root.kind === "lane" || root.kind === "sources" || root.kind === "workspace"
2830
+ || root.kind === "unknown" && this.boundLane(route)) return false;
2831
+ }
2832
+ const rootPost = !bareStop && !explicit && this.store.sentOutputForMessage(parent, threadId);
2833
+ if (rootPost && rootPost.id === `${rootPost.sourceId}:workspace`) return false;
2834
+ const threadKey = routeKey(route);
2835
+ const parentKey = routeKey(parent);
2836
+ const explicitSource = explicit && this.store.firstAdmittedMessage(route, explicit);
2837
+ const pending = explicit ? explicitSource ? [explicitSource] : [] : this.store.inputs(undefined, "pending");
2838
+ const possibleRoot = !explicit && compareMessageIds("slack", messageId, threadId) === 1;
2839
+ const candidates = pending.filter(prior => prior.state === "pending"
2840
+ && this.store.getMeta(`user-source:${prior.id}`) === "true" && this.workspaceChoiceOpen(prior.id));
2841
+ const couldAnswer = (source: InputRecord) => {
2842
+ if (this.store.output(`${source.id}:workspace`)?.state !== "sending") return false;
2843
+ if (bareStop || explicit) return true;
2844
+ if (!answer) return false;
2845
+ const choices: PastTopicRef[] = JSON.parse(this.store.getMeta(`topic-history:${source.id}`) ?? "[]");
2846
+ if (choices.length) return matchingSlackHistoryChoice(answer.text, answer.cwd, choices) !== undefined;
2847
+ return existingWorkspace(answer.cwd ?? answer.text) !== null || answer.cwd === null
2848
+ && namedWorkspaces(answer.text, this.store.lanes().filter(lane => this.sameConversation(lane.route, route)), true).size === 1;
2849
+ };
2850
+ const sameThread = candidates.filter(source => routeKey(source.route) === threadKey && source.messageId !== null
2851
+ && compareMessageIds("slack", messageId, source.messageId) === 1);
2852
+ if (!bareStop && sameThread.length === 1 && couldAnswer(sameThread[0])) return true;
2853
+ // A channel-root question publishes before its send receipt reaches HEAD.
2854
+ // A plausible reply to that new root can wait, but only the exact posted
2855
+ // thread timestamp authorizes selecting the original question at admission.
2856
+ return possibleRoot && candidates.some(source => physicalRouteKey(source.route) === parentKey
2857
+ && (source.messageId === null ? !!source.invocationId : compareMessageIds("slack", threadId, source.messageId) === 1)
2858
+ && couldAnswer(source));
2859
+ }
2860
+
2861
+ private workspaceChoiceOpen(id: string): boolean {
2862
+ if (this.store.getMeta(`topic-confirm:${id}`) !== null || this.store.getMeta(`topic-previous:${id}`) !== null) return false;
2863
+ const history = this.store.getMeta(`topic-history:${id}`);
2864
+ if (this.store.getMeta(`topic-choice-auto:${id}`) !== null && history !== "[]") return false;
2865
+ return this.store.getMeta(`topic-creator:${id}`) ? !this.store.getMeta(`topic-cwd:${id}`) : Boolean(history);
2866
+ }
2867
+
2686
2868
  private deferredRecoveryControl(input: Inbound): RecoveryControl | null {
2687
2869
  const candidate = deferredRecoveryCandidate(input.text);
2688
2870
  if (!candidate || telegramCommandBlocked(input) || input.pickerSelection
@@ -2694,10 +2876,17 @@ export class Superagent {
2694
2876
  const lane = this.explicitLaneStop(candidate.laneId);
2695
2877
  return lane && this.workRoute(lane.route) ? { priority: "immediate", laneId: lane.id } : null;
2696
2878
  }
2697
- // Only an unquoted command on a directly bound physical Discord thread
2698
- // has a bare-stop target that queued topics, placement or replies cannot change.
2699
- const lane = !input.reply && discordWorkThread(input.route) ? this.store.laneForRoute(input.route) : null;
2700
- return lane && authorizeRoute(this.config, lane.route) ? { priority: "retry", laneId: lane.id } : null;
2879
+ // A Slack root can point to an outstanding placement rather than the
2880
+ // bound lane. Reply-relative stops keep ordinary admission order.
2881
+ if (input.reply || input.route.topicId !== undefined || !nativeWorkThread(input.route)
2882
+ || this.awaitingSlackChoiceReceipt(input)) return null;
2883
+ const lane = this.store.laneForRoute(input.route);
2884
+ if (!lane || !authorizeRoute(this.config, lane.route)) return null;
2885
+ const { replyId, replyRoute } = routingReply(input);
2886
+ const receipt = replyId ? this.store.repliedStop(replyRoute, replyId) : null;
2887
+ if (receipt?.kind === "workspace" || receipt?.kind === "unverified"
2888
+ || receipt?.kind === "lane" && (receipt.lane.id !== lane.id || receipt.unplaced.length > 0)) return null;
2889
+ return { priority: "retry", laneId: lane.id };
2701
2890
  }
2702
2891
 
2703
2892
  /** Admit queued inputs of each conversation in order; resumes after restart and after a failed admission's backoff. */
@@ -2731,7 +2920,7 @@ export class Superagent {
2731
2920
  || typeof selection.cardId !== "string" || !selection.cardId
2732
2921
  || input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined || input.attachments.length) return null;
2733
2922
  if (picker.kind === "model" && picker.modelTargets !== undefined) {
2734
- if (input.route.platform !== "discord" || input.reply || input.discordOriginalText !== undefined
2923
+ if ((input.route.platform !== "discord" && input.route.platform !== "slack") || input.reply || input.discordOriginalText !== undefined
2735
2924
  || !picker.modelTargets || !source || source.state !== "done"
2736
2925
  || routeKey(source.route) !== routeKey(output.route) || output.id !== `${source.id}:head-control`
2737
2926
  || !this.originalOwnerControl(source) || (selection.target !== "head" && (selection.target !== "lane" || !picker.modelTargets.lane))) return null;
@@ -2772,24 +2961,24 @@ export class Superagent {
2772
2961
  && (prModeArgument(input.text) !== null || /^\/head(?:\s|$)/.test(input.text.trimStart()));
2773
2962
  const request = topicRequest(placement);
2774
2963
  const historyText = commandBlocked ? "" : this.routingRequestText(input);
2775
- const candidate = request.cwd === null ? pastTopicQuery(historyText) : null;
2776
- const slackRoot = !input.reply && input.route.platform === "slack" ? input.route.threadId : null;
2777
- const replyRoute = slackRoot ? { ...physicalRoute(input.route), threadId: null } : input.route;
2778
- const replyId = input.reply?.messageId ?? slackRoot;
2964
+ const slackChoice = input.route.platform === "slack" && /^!choose(?:\s|$)/u.test(input.text.trim());
2965
+ const candidate = !slackChoice && request.cwd === null ? pastTopicQuery(historyText) : null;
2966
+ const { replyId, replyRoute } = routingReply(input);
2779
2967
  const discordEdit = input.route.platform === "discord" && editEvent;
2780
- const query = !selection && !discordEdit && !headAddressed && !codeHandledControl(input.text, input.route.platform)
2968
+ const slackEdit = input.route.platform === "slack" && editEvent;
2969
+ const query = !selection && !discordEdit && !slackEdit && !headAddressed && !codeHandledControl(input.text, input.route.platform)
2781
2970
  && candidate && !this.store.input(input.id)
2782
2971
  && !(input.messageId && this.store.firstAdmittedMessage(input.route, input.messageId))
2783
2972
  && !(input.reply && this.store.repliedTopicWorkspace(input.route, input.reply.messageId))
2784
2973
  && !(replyId && this.store.sentOutputForMessage(replyRoute, replyId)?.id.endsWith(":workspace")) ? candidate : null;
2785
- return { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, query };
2974
+ return { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, slackEdit, slackChoice, query };
2786
2975
  }
2787
2976
 
2788
2977
  private async admit(original: Inbound, deferred = false): Promise<void> {
2789
2978
  let input = this.intakeInput(original);
2790
2979
  const selection = input.pickerSelection;
2791
2980
  const eventId = selection ? null : eventOrderId(input);
2792
- const { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, query } = this.routingIntent(input);
2981
+ const { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, slackEdit, slackChoice, query } = this.routingIntent(input);
2793
2982
  let history: PastTopicRef[] | null = null;
2794
2983
  let historyUnavailable = false;
2795
2984
  if (query !== null) {
@@ -2857,10 +3046,15 @@ export class Superagent {
2857
3046
  } else if (discordEdit && discordWorkThread(input.route) && (/^\/new(?:\s|$)/.test(placement.trimStart()) || /^\d+$/.test(placement.trim())
2858
3047
  || (replyId && this.store.sentOutputForMessage(replyRoute, replyId)?.id.endsWith(":workspace")))) {
2859
3048
  metadata = { [`dm:control-edit:${input.id}`]: "true" };
2860
- } else if (!selection && this.isDm(input.route)) {
2861
- const admission = this.dmTimeline.admit(input, eventId, commandBlocked);
2862
- input = admission.input;
2863
- metadata = admission.metadata;
3049
+ } else {
3050
+ const editedPlacement = slackEdit && (editsTopicPlacement("", placement)
3051
+ || (replyId && this.store.sentOutputForMessage(replyRoute, replyId)?.id.endsWith(":workspace")));
3052
+ if (!selection && this.isDm(input.route)) {
3053
+ const admission = this.dmTimeline.admit(input, eventId, commandBlocked || Boolean(editedPlacement));
3054
+ input = admission.input;
3055
+ metadata = admission.metadata;
3056
+ }
3057
+ if (editedPlacement) metadata = { ...metadata, [`dm:control-edit:${input.id}`]: "true" };
2864
3058
  }
2865
3059
  if (!commandBlocked && !priorRevision && editEvent && codeHandledControl(input.text, input.route.platform)) {
2866
3060
  metadata = { ...metadata, [`dm:control-edit:${input.id}`]: "command" };
@@ -2892,21 +3086,22 @@ export class Superagent {
2892
3086
  const ordinary = !headAddressed && !selection && !metadata[`dm:control-edit:${input.id}`]
2893
3087
  && !codeHandledControl(commandText, input.route.platform) && !["/main", "/new"].includes(commandText);
2894
3088
  if (ordinary && (priorRevision?.target !== "main" || priorOwner)) {
2895
- const keepThread = discordWorkThread(input.route) && !newTopic && Boolean(bound || opening);
3089
+ const keepThread = nativeWorkThread(input.route) && !newTopic && Boolean(bound || opening);
2896
3090
  const sibling = !keepThread && !this.isDm(input.route) && !!input.route.threadId
2897
3091
  && (newTopic || changesWorkspace || separateHistory && Boolean(bound || opening));
2898
3092
  const newPlacement = sibling || !keepThread && (changesWorkspace || separateHistory);
2899
3093
  const owner = priorOwner ?? (newPlacement ? null : bound?.id ?? (!commandBlocked && opening ? this.store.getMeta(`topic-owner:${opening.id}`) : null));
2900
3094
  const selectedTopic = !commandBlocked && !owner && this.dmTimeline.isExplicitTopic(input.route);
2901
- // On a bound Discord thread the prior session supplies evidence, not a
3095
+ // In a bound thread the prior session supplies evidence, not a
2902
3096
  // destination or cwd. A lookup with no match leaves local context alone.
2903
- const consultHistory = history !== null && (!owner || keepThread && history.length > 1);
3097
+ const unavailableInSlackThread = keepThread && input.route.platform === "slack" && historyUnavailable;
3098
+ const consultHistory = history !== null && (!owner || keepThread && history.length > 1 || unavailableInSlackThread);
2904
3099
  metadata = { ...metadata,
2905
- ...(workspace ? { [`topic-cwd:${input.id}`]: workspace } : {}),
3100
+ ...(workspace && request.cwd !== null ? topicWorkspaceMetadata(input.id, workspace, request.cwd) : {}),
2906
3101
  ...(consultHistory ? { [`topic-history:${input.id}`]: JSON.stringify(history) } : {}),
2907
- ...(historyUnavailable && !owner ? { [`topic-history-unavailable:${input.id}`]: "true" } : {}),
3102
+ ...(historyUnavailable && (!owner || unavailableInSlackThread) ? { [`topic-history-unavailable:${input.id}`]: "true" } : {}),
2908
3103
  ...(past && (!owner || keepThread) ? { [`topic-previous:${input.id}`]: JSON.stringify(past),
2909
- ...(!owner ? { [`topic-cwd:${input.id}`]: past.cwd } : {}) } : {}),
3104
+ ...(!owner ? topicWorkspaceMetadata(input.id, past.cwd) : {}) } : {}),
2910
3105
  };
2911
3106
  if (!priorRevision && !commandBlocked) {
2912
3107
  const headerOnly = request.cwd !== null && !request.text.trim();
@@ -2916,7 +3111,11 @@ export class Superagent {
2916
3111
  const referenceRoute = slackRoot ? { ...physicalRoute(input.route), threadId: null } : input.route;
2917
3112
  const output = reference ? this.store.sentOutputForMessage(referenceRoute, reference) : null;
2918
3113
  const question = output && output.id === `${output.sourceId}:workspace` ? output : null;
2919
- const text = request.text.trim();
3114
+ const slack = input.route.platform === "slack";
3115
+ const slackAnswer = slack && input.messageId !== null && !input.reply && !input.unresolvedReply && !input.attachments.length
3116
+ ? slackWorkspaceAnswer(input.text, input.routingText, input.slackVerifiedRoutingBody) : null;
3117
+ const explicitSource = slackAnswer?.source && this.store.firstAdmittedMessage(input.route, slackAnswer.source);
3118
+ const text = slackAnswer?.text ?? request.text.trim();
2920
3119
  const numberReply = /^\d+$/.test(text);
2921
3120
  const repliedOriginal = discordWorkThread(input.route) && input.reply && !question
2922
3121
  ? this.store.firstAdmittedMessage(input.route, input.reply.messageId) : null;
@@ -2925,15 +3124,14 @@ export class Superagent {
2925
3124
  const referencedOptions: PastTopicRef[] = offered ? JSON.parse(offered) : [];
2926
3125
  const replyingToHistory = referencedOptions.length > 0 && (numberReply || headerOnly || referencedOptions.some(ref =>
2927
3126
  ref.cwd === text || basename(ref.cwd).toLowerCase() === text.toLowerCase()));
2928
- const waiting = headerOnly || request.cwd === null && (opening || reference || !owner || keepThread && numberReply) ?
3127
+ const waiting = slackChoice || headerOnly || request.cwd === null && (opening || reference || !owner || keepThread && numberReply) ?
2929
3128
  this.store.inputs(undefined, "pending").filter(prior =>
2930
- (question ? prior.id === question.sourceId && (slackRoot || routeKey(prior.route) === routeKey(input.route))
3129
+ (slackChoice ? explicitSource && explicitSource.id === prior.id && routeKey(prior.route) === routeKey(input.route)
3130
+ : question ? prior.id === question.sourceId && (slackRoot || routeKey(prior.route) === routeKey(input.route))
2931
3131
  : routeKey(prior.route) === routeKey(input.route) && (!input.reply || prior.messageId === input.reply.messageId))
2932
- && this.store.getMeta(`topic-confirm:${prior.id}`) === null
2933
- && this.store.getMeta(`topic-previous:${prior.id}`) === null
2934
- && this.store.getMeta(`topic-choice-auto:${prior.id}`) === null
2935
- && (this.store.getMeta(`topic-creator:${prior.id}`) && !this.store.getMeta(`topic-cwd:${prior.id}`)
2936
- || this.store.getMeta(`topic-history:${prior.id}`) && !this.store.getMeta(`topic-creator:${prior.id}`))
3132
+ && (!slackChoice || this.store.getMeta(`user-source:${prior.id}`) === "true"
3133
+ && this.store.output(`${prior.id}:workspace`)?.state === "sent")
3134
+ && this.workspaceChoiceOpen(prior.id)
2937
3135
  ) : [];
2938
3136
  const lanes = request.cwd === null && (newTopic || selectedTopic || waiting.length > 0 || reference && !owner)
2939
3137
  ? this.store.lanes().filter(lane => this.sameConversation(lane.route, input.route)) : [];
@@ -2946,32 +3144,53 @@ export class Superagent {
2946
3144
  const heldContext = original && !owner && !newTopic && request.cwd === null && history === null
2947
3145
  && this.heldPlacementMatches(original, input) ? original : null;
2948
3146
  const choices: PastTopicRef[] = original ? JSON.parse(this.store.getMeta(`topic-history:${original.id}`) ?? "[]") : [];
2949
- if (original && choices.length && !newTopic && (headerOnly || answeringQuestion || replyingToHistory || bareNames.size || barePath || numberReply)) {
2950
- const number = request.cwd === null && numberReply ? Number(text) : null;
2951
- const matches = number === null ? choices.filter(ref => headerOnly || barePath
2952
- ? ref.cwd === (workspace ?? barePath) : basename(ref.cwd).toLowerCase() === text.toLowerCase())
2953
- : /^[1-9]\d*$/.test(text) ? choices.slice(number - 1, number) : [];
3147
+ const slackHistoryMatch = slackAnswer ? matchingSlackHistoryChoice(slackAnswer.text, slackAnswer.cwd, choices) : undefined;
3148
+ const ambiguousSlackNumber = !!slackAnswer && !slackChoice && /^[1-9]\d*$/u.test(text)
3149
+ && this.store.hasSlackHistoryChoice(input.route, Number(text), input.receivedAt, original?.id);
3150
+ const questionId = slack && original && slackWorkspaceQuestionTimestamp(this.store, original);
3151
+ const afterSlackPost = Boolean(questionId && input.messageId
3152
+ && compareMessageIds("slack", input.messageId, questionId) === 1);
3153
+ const authorizedChoice = !slackEdit && !ambiguousSlackNumber
3154
+ && (!slack || !!slackAnswer && input.route.threadId !== null && afterSlackPost);
3155
+ if (original && choices.length && !newTopic && (slackChoice || headerOnly || answeringQuestion || replyingToHistory || bareNames.size || barePath || numberReply || slackHistoryMatch)) {
3156
+ let selected = slackHistoryMatch;
3157
+ if (!slack) {
3158
+ const number = request.cwd === null && numberReply ? Number(text) : null;
3159
+ const matches = number === null ? choices.filter(ref => headerOnly || barePath
3160
+ ? ref.cwd === (workspace ?? barePath) : basename(ref.cwd).toLowerCase() === text.toLowerCase())
3161
+ : /^[1-9]\d*$/.test(text) ? choices.slice(number - 1, number) : [];
3162
+ selected = matches.length === 1 ? matches[0] : undefined;
3163
+ }
2954
3164
  const placedChoice = !this.store.getMeta(`topic-creator:${original.id}`);
2955
3165
  const deadline = this.store.getMeta(`topic-choice-deadline:${original.id}`);
2956
3166
  const inTime = !placedChoice || deadline !== null && input.receivedAt <= Number(deadline)
2957
- && (question !== null || input.receivedAt >= Number(deadline) - TOPIC_CHOICE_WAIT_MS);
2958
- const selected = !discordEdit && inTime && matches.length === 1 ? matches[0] : undefined;
3167
+ && (afterSlackPost || question !== null || input.receivedAt >= Number(deadline) - TOPIC_CHOICE_WAIT_MS);
3168
+ if (discordEdit || !authorizedChoice || !inTime) selected = undefined;
3169
+ const requested = slackAnswer ? slackAnswer.cwd ?? slackAnswer.text : headerOnly ? request.cwd : barePath ? text : null;
2959
3170
  metadata = { ...metadata, [`topic-confirm:${input.id}`]: selected ? original.id : "",
2960
3171
  ...(selected ? { [`topic-previous:${original.id}`]: JSON.stringify(selected),
2961
- ...(placedChoice ? {} : { [`topic-cwd:${original.id}`]: selected.cwd }) } : {}) };
3172
+ ...(placedChoice ? {} : topicWorkspaceMetadata(original.id, selected.cwd,
3173
+ requested && isAbsolute(requested) ? requested : selected.cwd)) } : {}) };
2962
3174
  } else if (replyingToHistory || keepThread && numberReply && waiting.length > 1
3175
+ || ambiguousSlackNumber
2963
3176
  || numberReply && input.reply && !output && this.store.isDiscordWorkspaceQuestion(input.route, input.reply.messageId)) {
2964
3177
  metadata = { ...metadata, [`topic-confirm:${input.id}`]: "" };
2965
- } else if (headerOnly || barePath || bareNames.size || answeringQuestion && !heldContext) {
3178
+ } else if (slackChoice || headerOnly || barePath || bareNames.size || answeringQuestion && !heldContext) {
2966
3179
  const selected = workspace ?? barePath ?? (bareNames.size === 1 ? [...bareNames][0]! : null);
2967
- const original = waiting.length === 1 && selected && existingWorkspace(selected) === selected ? waiting[0] : null;
2968
- metadata = { ...metadata, [`topic-confirm:${input.id}`]: original?.id ?? "",
2969
- ...(original && selected ? { [`topic-cwd:${original.id}`]: selected } : {}) };
3180
+ const originalLane = original && this.store.getMeta(`topic-owner:${original.id}`);
3181
+ const fixedWorkspace = originalLane && original && !this.store.getMeta(`topic-creator:${original.id}`)
3182
+ ? this.store.lane(originalLane)?.cwd : undefined;
3183
+ const confirmed = original && authorizedChoice && selected && existingWorkspace(selected) === selected
3184
+ && (!slack || fixedWorkspace === undefined || selected === fixedWorkspace) ? original : null;
3185
+ metadata = { ...metadata, [`topic-confirm:${input.id}`]: confirmed?.id ?? "",
3186
+ ...(confirmed && selected
3187
+ ? topicWorkspaceMetadata(confirmed.id, selected, workspace && request.cwd !== null ? request.cwd : barePath ? text : selected)
3188
+ : {}) };
2970
3189
  } else if (!owner && request.cwd === null && history === null) {
2971
3190
  const replied = reference ? this.store.repliedTopicWorkspace(referenceRoute, reference) : null;
2972
3191
  const selected = newTopic || selectedTopic || replied
2973
3192
  ? inferredWorkspace(text, lanes, replied, newTopic ? previousWorkspace ?? null : null) : null;
2974
- if (selected) metadata = { ...metadata, [`topic-cwd:${input.id}`]: selected };
3193
+ if (selected) metadata = { ...metadata, ...topicWorkspaceMetadata(input.id, selected.cwd, selected.requested) };
2975
3194
  else if (heldContext) metadata = { ...metadata, [`head-routing-context:${input.id}`]: heldContext.id };
2976
3195
  }
2977
3196
  }
@@ -3045,9 +3264,10 @@ export class Superagent {
3045
3264
  }
3046
3265
  }
3047
3266
  const task = this.requestText(input, placement);
3048
- const workflow = commandBlocked || metadata[`dm:control-edit:${input.id}`] ? null : ownerWorkflowRequest(input, task).name;
3267
+ const workflow = commandBlocked || metadata[`dm:control-edit:${input.id}`] ? null : ownerPlacementWorkflow(input, placement, task).name;
3049
3268
  const target = ordinary && metadata[`topic-owner:${input.id}`] ? null : "main";
3050
3269
  const stack = target === "main" && !commandBlocked && !metadata[`dm:control-edit:${input.id}`] && !editEvent && !selection
3270
+ && !unverifiedSlackWorkspaceTask(input, placement)
3051
3271
  ? admitHeadSuperstack(input, task) : undefined;
3052
3272
  if (stack) metadata = { ...metadata, [`head-superstack:${input.id}`]: JSON.stringify(stack) };
3053
3273
  if (ordinary && target === "main") metadata = { ...metadata, [`head-routing:${input.id}`]: "true" };
@@ -3095,6 +3315,10 @@ export class Superagent {
3095
3315
  const restart = this.restartFence();
3096
3316
  if (restart && target === "main"
3097
3317
  && !["handoff", "accepted", "uncertain"].includes(restart.state)) {
3318
+ if (this.restartAckWaiting === restart.ackOutputId) {
3319
+ this.restartAckWaiting = undefined;
3320
+ this.restartActive = undefined;
3321
+ }
3098
3322
  this.store.settle(restart.inputId, "cancelled");
3099
3323
  this.saveRestart({ ...restart, state: "refused" }, false);
3100
3324
  this.restartResult(restart, "Explicit HEAD stop superseded restart before lifecycle handoff. No successor was authorized.");
@@ -3129,6 +3353,11 @@ export class Superagent {
3129
3353
  return route.guildId === null && route.threadId === null;
3130
3354
  }
3131
3355
 
3356
+ private editProgressInPlace(route: Route): boolean {
3357
+ return route.platform === "discord" ? this.config.discord?.editProgressInPlace === true
3358
+ : route.platform === "slack" && this.config.slack?.editProgressInPlace === true;
3359
+ }
3360
+
3132
3361
  private hasPlacementIntent(input: InputRecord): boolean {
3133
3362
  if (telegramCommandBlocked(input)) return false;
3134
3363
  const placement = placementText(input);
@@ -3166,18 +3395,23 @@ export class Superagent {
3166
3395
 
3167
3396
  /**
3168
3397
  * Structural shape of an opted-in cross-channel parent: an explicit native
3169
- * Discord guild parent in the same bot account, owner and guild as the source,
3398
+ * Discord guild or Slack workspace parent in the same bot account and owner,
3170
3399
  * but a different channel. The policy opt-in is checked separately so a later
3171
3400
  * config change can never make an interrupted creation replayable.
3172
3401
  */
3173
3402
  private crossChannelParent(source: Route, parent: Route): boolean {
3174
- return source.platform === "discord" && parent.platform === "discord"
3403
+ return (source.platform === "discord" || source.platform === "slack") && parent.platform === source.platform
3175
3404
  && source.guildId !== null && parent.guildId === source.guildId
3176
3405
  && parent.accountId === source.accountId && parent.authorityId === source.authorityId
3177
3406
  && parent.threadId === null && parent.topicId === undefined
3178
3407
  && !this.sameConversation(source, parent);
3179
3408
  }
3180
3409
 
3410
+ private allowsCrossChannelThreads(platform: Route["platform"]): boolean {
3411
+ return platform === "slack" ? this.config.slack?.allowCrossChannelThreads === true
3412
+ : platform === "discord" && this.config.discord?.allowCrossChannelThreads === true;
3413
+ }
3414
+
3181
3415
  /**
3182
3416
  * Repair only the exact thread the adapter journaled as its native result for
3183
3417
  * the journaled cross-channel parent. A thread in the source parent, or any
@@ -3210,6 +3444,10 @@ export class Superagent {
3210
3444
  }
3211
3445
 
3212
3446
  private routingRequestText(input: Inbound): string {
3447
+ if (input.route.platform === "slack" && input.routingText !== undefined) {
3448
+ const placement = placementText(input);
3449
+ return placement === input.text && !/^cwd:/iu.test(input.routingText) ? input.routingText : this.requestText(input, placement);
3450
+ }
3213
3451
  const routingInput = { ...input, text: transportRoutingProse(input) };
3214
3452
  return this.requestText(routingInput, placementText(routingInput));
3215
3453
  }
@@ -3295,8 +3533,8 @@ export class Superagent {
3295
3533
  const isNew = /^\/new(?:\s|$)/.test(command);
3296
3534
  if (!isNew && command !== "/main") return false;
3297
3535
  if (isNew && this.requestText(input)) return false;
3298
- const text = isNew && discordWorkThread(input.route)
3299
- ? "어떤 작업을 새 스레드에서 시작할까요? `/new 작업 내용`으로 알려 주세요. 지금 스레드의 작업은 그대로 둡니다."
3536
+ const text = isNew && nativeWorkThread(input.route)
3537
+ ? `어떤 작업을 새 스레드에서 시작할까요? \`${input.route.platform === "slack" ? "!" : "/"}new 작업 내용\`으로 알려 주세요. 지금 스레드의 작업은 그대로 둡니다.`
3300
3538
  : !this.isDm(input.route)
3301
3539
  ? "독립 주제는 새 스레드·포럼 주제에서 시작해 주세요. DM에서는 /new 요청으로 새 주제를 만들고 /main으로 메인 대화에 돌아갈 수 있습니다."
3302
3540
  : isNew ? "새 DM 주제를 열었습니다. 이 주제에서 처리할 요청이나 질문을 보내 주세요. 저장소는 요청을 확인한 뒤 선택합니다."
@@ -3668,9 +3906,9 @@ export class Superagent {
3668
3906
  const original = this.store.ownerSource(sourceId);
3669
3907
  if (this.store.getMeta(`topic-owner:${original?.id ?? sourceId}`)) throw new Error("Topic-owned intake cannot authorize a manager handoff; use an explicit HEAD request");
3670
3908
  if (original) this.assertFirstDmHandoffSource(original, sourceId);
3671
- if (destination && original && discordWorkThread(original.route) && this.store.getMeta(`head-routing:${original.id}`) === "true"
3909
+ if (destination && original && nativeWorkThread(original.route) && this.store.getMeta(`head-routing:${original.id}`) === "true"
3672
3910
  && routeKey(original.route) !== routeKey(destination)) {
3673
- throw new Error("Work from this Discord thread stays in the original thread unless the owner explicitly requests a split");
3911
+ throw new Error("Work from this thread stays in the original thread unless the owner explicitly requests a split");
3674
3912
  }
3675
3913
  this.assertCronDelegationOpen(sourceId);
3676
3914
  return null;
@@ -3698,13 +3936,31 @@ export class Superagent {
3698
3936
  throw new Error("Remote lanes cannot inherit custom head OMP command flags safely; use local placement");
3699
3937
  }
3700
3938
 
3939
+ private ownerWorkerCurrent(original: InputRecord | null, selector?: WorkerSelector): WorkerCurrentIntent | null {
3940
+ if (!selector?.currentWorkspace && !(original && hasWorkerCurrentHeader(original.text))) return null;
3941
+ const directive = original && readWorkerCurrentDirective(original);
3942
+ const first = original?.messageId ? this.store.firstAdmittedMessage(original.route, original.messageId) : null;
3943
+ const requested = selector?.currentWorkspace;
3944
+ if (!original || !directive || original.target !== "main" || !authorizeRoute(this.config, original.route)
3945
+ || this.store.getMeta(`user-source:${original.id}`) !== "true"
3946
+ || (original.messageId !== null && (!first || first.id !== original.id || routeKey(first.route) !== routeKey(original.route)))
3947
+ || selector?.target === "local" || (selector?.worker !== undefined && selector.worker !== directive.worker)
3948
+ || (requested && (requested.repoId !== directive.repoId || requested.subdir !== directive.subdir))) {
3949
+ throw new Error("Worker-current placement requires the matching original owner directive: /head worker-current: WORKER_ID REPO_ID [SUBDIR]");
3950
+ }
3951
+ return directive;
3952
+ }
3953
+
3701
3954
  private async assertLanePlacement(receipt: LanePlacementReceipt, selector?: WorkerSelector): Promise<void> {
3702
3955
  if (receipt.remote) this.requireRemoteCommandPolicy();
3703
3956
  if (!selector) return;
3704
3957
  const { remote, platform } = receipt;
3705
- if (selector.target === "local" && (remote || selector.worker !== undefined || selector.platform !== undefined)
3706
- || (selector.target === "remote" || selector.worker !== undefined || selector.platform !== undefined) && !remote
3707
- || selector.worker !== undefined && selector.worker !== remote?.workerId) {
3958
+ const remoteRequested = selector.target === "remote" || selector.worker !== undefined || selector.platform !== undefined;
3959
+ if (selector.target === "local" && (remote || selector.worker !== undefined || selector.platform !== undefined || selector.currentWorkspace)
3960
+ || (remoteRequested || selector.currentWorkspace) && !remote
3961
+ || remoteRequested && remote?.workerCheckout && !selector.currentWorkspace
3962
+ || selector.worker !== undefined && selector.worker !== remote?.workerId
3963
+ || selector.currentWorkspace && (!selector.worker || !matchesWorkerCurrentPlacement({ ...selector.currentWorkspace, worker: selector.worker }, remote))) {
3708
3964
  throw new Error("Worker selector conflicts with the lane's durable placement");
3709
3965
  }
3710
3966
  if (remote && selector.platform !== undefined) {
@@ -3721,21 +3977,23 @@ export class Superagent {
3721
3977
  }
3722
3978
  }
3723
3979
 
3724
- private async admitLane(input: LaneStart): Promise<Lane> {
3980
+ private async admitLane(input: LaneStart, admittedCwd?: string): Promise<Lane> {
3725
3981
  this.assertRestartOpen();
3726
3982
  if (input.appliedTags !== undefined && (!Array.isArray(input.appliedTags) || input.appliedTags.length > 5
3727
3983
  || input.appliedTags.some(tag => typeof tag !== "string" || !/^\d{1,20}$/.test(tag))
3728
3984
  || new Set(input.appliedTags).size !== input.appliedTags.length)) {
3729
3985
  throw new Error("appliedTags must contain at most five unique Discord tag IDs");
3730
3986
  }
3731
- if (typeof input.modelReason !== "string" || !input.modelReason.trim()) {
3732
- throw new Error("lane_start requires a nonempty modelReason");
3733
- }
3734
3987
  if (typeof input.kickoff !== "string" || !input.kickoff.trim()) throw new Error("lane_start requires a concise user-language kickoff");
3735
3988
  // Preset objects belong to the caller. Snapshot the resolved identity before
3736
3989
  // the first asynchronous catalog read so later preset edits cannot retarget it.
3737
3990
  const selectedWorkflow = workflowChoice(input.workflow);
3738
- const placement = input.placement ? { ...input.placement } : undefined;
3991
+ const proposed = input.placement ? structuredClone(input.placement) : undefined;
3992
+ const original = this.store.input(input.sourceId);
3993
+ const current = this.ownerWorkerCurrent(original, proposed);
3994
+ // The physical message selects the worker; the model need not transcribe its ID or path.
3995
+ const placement = current ? { ...proposed, worker: current.worker,
3996
+ currentWorkspace: { repoId: current.repoId, subdir: current.subdir } } : proposed;
3739
3997
  const source = this.store.input(`handoff:${input.sourceId}:lane`) ?? this.store.input(input.sourceId);
3740
3998
  const bound = source?.target && source.target !== "main" ? this.store.lane(source.target) : null;
3741
3999
  const resolvePreset = bound?.model && bound.modelPreset === input.preset && bound.modelPresetSnapshot
@@ -3749,7 +4007,7 @@ export class Superagent {
3749
4007
  if (inFlight) {
3750
4008
  const lane = await inFlight;
3751
4009
  if (!sameLaneModel(lane.model, selected.model) || lane.modelPreset !== selected.modelPreset
3752
- || !isDeepStrictEqual(lane.modelPresetSnapshot, selected.modelPresetSnapshot) || realpathSync(input.cwd) !== lane.cwd) {
4010
+ || !isDeepStrictEqual(lane.modelPresetSnapshot, selected.modelPresetSnapshot) || existingWorkspace(input.cwd) !== lane.cwd) {
3753
4011
  throw new Error("Concurrent lane selection conflicts with the source's existing model or repository");
3754
4012
  }
3755
4013
  const original = this.store.input(input.sourceId)!;
@@ -3769,7 +4027,7 @@ export class Superagent {
3769
4027
  await this.assertLanePlacement(receipt, selected.placement);
3770
4028
  return lane;
3771
4029
  }
3772
- const operation = this.createLane(selected);
4030
+ const operation = this.createLane(selected, admittedCwd);
3773
4031
  this.operations.set(input.sourceId, operation);
3774
4032
  try { return await operation; } finally {
3775
4033
  this.operations.delete(input.sourceId);
@@ -3777,22 +4035,28 @@ export class Superagent {
3777
4035
  }
3778
4036
  }
3779
4037
 
3780
- private queuedWorkerAssignments(): Map<string, number> {
3781
- const queued = new Map<string, number>();
3782
- const count = (id: string) => queued.set(id, (queued.get(id) ?? 0) + 1);
3783
- for (const id of this.placingWorkers.values()) count(id);
4038
+ private queuedWorkerAssignments(): readonly WorkerAssignment[] {
4039
+ const queued: WorkerAssignment[] = [...this.placingWorkers.values()];
3784
4040
  for (const lane of this.store.lanes()) {
3785
- if (lane.remote && lane.workState === "open" && lane.runtimeState === "unloaded" && lane.pid === null
3786
- && this.store.hasInput(lane.id, "pending")) count(lane.remote.workerId);
4041
+ // A not-yet-acknowledged open may not have appeared in the worker's
4042
+ // capacity receipt. Reconcile by exact open identity, but keep its checkout reserved.
4043
+ if (!lane.remote || lane.pid !== null) continue;
4044
+ if (this.remoteOpenPending(lane)) {
4045
+ queued.push({ ...lane.remote, ...workerRef(lane) });
4046
+ } else if (lane.workState === "open" && (lane.runtimeState === "starting"
4047
+ || lane.runtimeState === "unloaded" && this.store.hasInput(lane.id, "pending"))) {
4048
+ queued.push(lane.remote);
4049
+ }
3787
4050
  }
3788
4051
  return queued;
3789
4052
  }
3790
4053
 
3791
- private async createLane(input: ResolvedLaneStart): Promise<Lane> {
4054
+ private async createLane(input: ResolvedLaneStart, admittedCwd?: string): Promise<Lane> {
3792
4055
  this.assertRestartOpen();
3793
4056
  if (!isAbsolute(input.cwd)) throw new Error("cwd must be absolute");
3794
- const cwd = realpathSync(input.cwd);
3795
- if (!statSync(cwd).isDirectory()) throw new Error("cwd must be an existing directory");
4057
+ const cwd = existingWorkspace(input.cwd);
4058
+ if (!cwd) throw new Error("cwd must be an existing directory");
4059
+ if (admittedCwd !== undefined && admittedCwd !== cwd) throw new Error("Topic workspace changed before placement");
3796
4060
  if (!input.title.trim()) throw new Error("Lane title is required");
3797
4061
  const original = this.store.input(input.sourceId);
3798
4062
  if (!original) throw new Error("Unknown source request");
@@ -3807,8 +4071,6 @@ export class Superagent {
3807
4071
  if (workflow && this.store.getMeta(`user-source:${original.id}`) !== "true") {
3808
4072
  throw new Error("Workflow selection requires an original authorized user source, not internal data");
3809
4073
  }
3810
- await this.requireAvailableModel(input.model);
3811
- this.assertRestartOpen();
3812
4074
  if (this.store.input(original.id)?.state === "cancelled") throw new Error("A cancelled main request cannot create new delegated work");
3813
4075
  let source = original;
3814
4076
  let handoff: Inbound | undefined;
@@ -3850,7 +4112,7 @@ export class Superagent {
3850
4112
  if (requestedParent && !this.sameConversation(original.route, requestedParent)) {
3851
4113
  // The destination was authorized above (same owner, allowed guild and
3852
4114
  // channel). Only the opt-in owner policy widens the source parent.
3853
- if (this.config.discord?.allowCrossChannelThreads !== true || !this.crossChannelParent(original.route, requestedParent))
4115
+ if (!this.allowsCrossChannelThreads(original.route.platform) || !this.crossChannelParent(original.route, requestedParent))
3854
4116
  throw new Error("A new sibling topic must use the source conversation's authorized parent");
3855
4117
  }
3856
4118
  // A read-only capability rejection has created nothing. Let the head select
@@ -3872,14 +4134,21 @@ export class Superagent {
3872
4134
  // retargeting retries after a native topic creation or a lost kickoff.
3873
4135
  const receipt: LanePlacementReceipt = savedPlacement ? JSON.parse(savedPlacement)
3874
4136
  : { cwd, remote: existingBinding ? existingBinding.remote ?? null
3875
- : await this.adapters.selectWorkerPlacement(this.config, cwd, input.placement, {
3876
- queued: () => this.queuedWorkerAssignments(), reserve: id => this.placingWorkers.set(original.id, id),
4137
+ : await this.adapters.selectWorkerPlacement(this.config, input.cwd, input.placement, {
4138
+ queued: () => this.queuedWorkerAssignments(), reserve: assignment => this.placingWorkers.set(original.id, assignment),
3877
4139
  }),
3878
4140
  ...(input.placement?.platform !== undefined && !existingBinding ? { platform: input.placement.platform } : {}) };
3879
- if (receipt.cwd !== cwd || existingBinding && !isDeepStrictEqual(existingBinding.remote ?? null, receipt.remote))
4141
+ if (receipt.cwd !== cwd || existingWorkspace(input.cwd) !== cwd
4142
+ || existingBinding && !isDeepStrictEqual(existingBinding.remote ?? null, receipt.remote))
3880
4143
  throw new Error("Lane placement conflicts with the original source workspace or binding");
3881
- if (savedPlacement && receipt.remote && !existingBinding) this.placingWorkers.set(original.id, receipt.remote.workerId);
4144
+ if (savedPlacement && receipt.remote && !existingBinding) this.placingWorkers.set(original.id, receipt.remote);
3882
4145
  await this.assertLanePlacement(receipt, input.placement);
4146
+ if (!existingBinding) {
4147
+ if (receipt.remote) {
4148
+ if (!acceptsRestrictedModelSelector(input.model))
4149
+ throw new Error("Remote worker models require a provider and model ID without whitespace or control characters");
4150
+ } else await this.requireAvailableModel(input.model);
4151
+ }
3883
4152
  this.assertRestartOpen();
3884
4153
  if (this.stopped || this.store.input(original.id)?.state === "cancelled") throw new Error("Source is no longer available for delegated work");
3885
4154
  if (!savedPlacement) this.store.setMeta(placementKey, JSON.stringify(receipt));
@@ -3951,7 +4220,7 @@ export class Superagent {
3951
4220
  this.authorized(destination, "work");
3952
4221
  if (!destination.threadId && !destination.topicId) throw new Error("Delegation needs an independent destination topic");
3953
4222
  if (destination.threadId && routeKey(destination) !== routeKey(original.route)
3954
- && this.sameConversation(original.route, destination) && (!input.destination || requestedParent)) {
4223
+ && (requestedParent !== null || !input.destination && this.sameConversation(original.route, destination))) {
3955
4224
  this.store.setMeta(nativeKey, "true");
3956
4225
  }
3957
4226
  this.store.setMeta(destinationKey, JSON.stringify(destination));
@@ -4000,7 +4269,7 @@ export class Superagent {
4000
4269
  const lane = this.store.createLane({
4001
4270
  id, title: input.title, route: source.route, cwd, repoRoot,
4002
4271
  brief: input.brief ?? this.requestText(original), acceptance: input.acceptance ?? [],
4003
- model: { provider: input.model.provider, id: input.model.id }, modelReason: input.modelReason,
4272
+ model: { provider: input.model.provider, id: input.model.id }, modelReason: input.modelReason ?? null,
4004
4273
  modelPreset: input.modelPreset,
4005
4274
  modelPresetSnapshot: input.modelPresetSnapshot,
4006
4275
  ...(remote ? { remote } : {}),
@@ -4042,7 +4311,11 @@ export class Superagent {
4042
4311
  this.store.queueOutput({ id: kickoffId, sourceId: source.id, route: lane.route, text: input.kickoff });
4043
4312
  this.wakeOutputs(original.route);
4044
4313
  await this.flushOutputs(physicalRouteKey(lane.route));
4045
- if (this.store.output(kickoffId)?.state !== "sent") {
4314
+ const kickoff = this.store.output(kickoffId);
4315
+ // Binding is durable, but a route-ordered retry can still hold its
4316
+ // kickoff. The existing kickoff fence prevents native dispatch.
4317
+ if (kickoff?.state === "pending") return lane;
4318
+ if (kickoff?.state !== "sent") {
4046
4319
  throw new Error("Kickoff delivery is not confirmed; lane execution is held without retrying the message");
4047
4320
  }
4048
4321
  void this.kick().catch(this.report);
@@ -4073,6 +4346,10 @@ export class Superagent {
4073
4346
  if (!original) throw new Error("sourceId must name a received authorized request");
4074
4347
  if (original.state === "cancelled") throw new Error("A cancelled request cannot delegate new work");
4075
4348
  this.authorizeLaneManagerSource(original, recovery);
4349
+ const current = this.ownerWorkerCurrent(original);
4350
+ if (current && !matchesWorkerCurrentPlacement(current, lane.remote)) {
4351
+ throw new Error("Original worker-current request conflicts with the lane's durable placement");
4352
+ }
4076
4353
  this.authorized(lane.route, "work");
4077
4354
  const scopedThread = !authorizeRoute(this.config, lane.route) && discordWorkThreadSource(this.config, this.store, lane.route);
4078
4355
  const scopedOwner = scopedThread && this.store.ownerSource(sourceId);
@@ -4097,7 +4374,7 @@ export class Superagent {
4097
4374
  // Do not rebind the inbound message, topic, or source of native callbacks.
4098
4375
  const reportInThread = original.target === "main" && !original.pickerSelection
4099
4376
  && this.store.getMeta(`user-source:${original.id}`) === "true"
4100
- && discordWorkThread(lane.route) && lane.route.topicId === undefined
4377
+ && nativeWorkThread(lane.route) && lane.route.topicId === undefined
4101
4378
  && routeKey(original.route) === routeKey({ ...lane.route, threadId: null });
4102
4379
  const queued = this.store.receive({
4103
4380
  id: handoffId, route: lane.route, messageId: original.messageId,
@@ -4300,8 +4577,8 @@ export class Superagent {
4300
4577
  }
4301
4578
  const route = physicalRoute(laneId ? this.requireLane(laneId).route : source.route);
4302
4579
  this.authorized(route, laneId ? "work" : undefined);
4303
- if (route.platform !== "discord" || !route.guildId || !this.messenger.inspectThread)
4304
- throw new Error("Thread inspection requires a supported Discord guild conversation");
4580
+ if (!this.messenger.inspectThread || !nativeWorkThread(route) && !(route.platform === "discord" && route.guildId))
4581
+ throw new Error("Thread inspection requires a Slack thread or Discord guild conversation");
4305
4582
  return this.messenger.inspectThread(route);
4306
4583
  }
4307
4584
 
@@ -4315,6 +4592,31 @@ export class Superagent {
4315
4592
  return this.messenger.inspectDiscordContext(physicalRoute(source.route));
4316
4593
  }
4317
4594
 
4595
+ async inspectSlackContext(sourceId: string): Promise<SlackContext> {
4596
+ const source = this.observationSource(sourceId, "Slack context");
4597
+ if (source.route.platform !== "slack" || !this.messenger.inspectSlackContext)
4598
+ throw new Error("Slack context inspection requires a supported Slack source");
4599
+ return this.messenger.inspectSlackContext({ sourceId, route: physicalRoute(source.route) });
4600
+ }
4601
+
4602
+ async slackPurpose(input: { sourceId: string; scope?: "channel" | "thread" } & (
4603
+ { action: "list" | "clear" } | { action: "set"; purpose: string }
4604
+ )): Promise<readonly SlackPurposeNote[]> {
4605
+ if (input.action !== "list") this.assertLaneRecoveryMutation(input.sourceId);
4606
+ this.assertRestartOpen();
4607
+ if (this.stopped) throw new Error("Controller is stopped");
4608
+ const source = this.observationSource(input.sourceId, "Slack purpose");
4609
+ if (source.route.platform !== "slack" || !this.messenger.slackPurpose)
4610
+ throw new Error("Slack purpose requires a supported Slack source");
4611
+ if (input.scope !== undefined && input.scope !== "channel" && input.scope !== "thread")
4612
+ throw new Error("Invalid Slack purpose scope");
4613
+ if (input.scope === "thread" && !source.route.threadId) throw new Error("The original source has no Slack thread");
4614
+ const route = { ...physicalRoute(source.route), ...(input.scope === "channel" ? { threadId: null } : {}) };
4615
+ return this.messenger.slackPurpose(input.action === "set"
4616
+ ? { sourceId: input.sourceId, route, action: input.action, purpose: input.purpose }
4617
+ : { sourceId: input.sourceId, route, action: input.action });
4618
+ }
4619
+
4318
4620
  async messengerPresence(sourceId: string, action: PresenceAction, platform?: Route["platform"]) {
4319
4621
  const source = this.observationSource(sourceId, "Messenger presence");
4320
4622
  if (platform !== undefined && platform !== source.route.platform)
@@ -4368,8 +4670,8 @@ export class Superagent {
4368
4670
  const lane = this.requireLane(input.id);
4369
4671
  this.authorized(lane.route, "work");
4370
4672
  const { messenger } = this;
4371
- if (lane.route.platform !== "discord" || !lane.route.guildId || !lane.route.threadId || !messenger.updateThread)
4372
- throw new Error("Thread changes require a managed Discord guild thread");
4673
+ if (!nativeWorkThread(lane.route) || !messenger.updateThread)
4674
+ throw new Error("Thread changes require a managed Discord or Slack thread");
4373
4675
  const changes = structuredClone(input.changes);
4374
4676
  const request = { route: physicalRoute(lane.route), changes };
4375
4677
  const receiptKey = `lane-thread:${lane.id}:${input.sourceId}`;
@@ -4378,7 +4680,7 @@ export class Superagent {
4378
4680
  const receipt: { request: typeof request; result?: ThreadInfo; error?: string; certainty?: "rejected" | "uncertain" } = JSON.parse(saved);
4379
4681
  if (!isDeepStrictEqual(receipt.request, request)) throw new Error("Thread-change source identity conflict");
4380
4682
  if (receipt.result) return receipt.result;
4381
- throw new DeliveryError(receipt.error ?? "Thread change is pending or uncertain; inspect Discord before a new explicit request",
4683
+ throw new DeliveryError(receipt.error ?? "Thread change is pending or uncertain; inspect the messenger before a new explicit request",
4382
4684
  receipt.certainty ?? "uncertain");
4383
4685
  }
4384
4686
  // Persist intent before IPC. A lost receipt must not repeat a remote edit.
@@ -4415,7 +4717,7 @@ export class Superagent {
4415
4717
  private async syncLaneThreadTitle(lane: Lane): Promise<void> {
4416
4718
  const { messenger } = this;
4417
4719
  const route = physicalRoute(lane.route);
4418
- if (route.platform !== "discord" || !route.guildId || !route.threadId || !messenger.inspectThread || !messenger.updateThread) return;
4720
+ if (!nativeWorkThread(route) || !messenger.inspectThread || !messenger.updateThread) return;
4419
4721
  const inspect = messenger.inspectThread.bind(messenger);
4420
4722
  const update = messenger.updateThread.bind(messenger);
4421
4723
  const active = () => {
@@ -4432,8 +4734,8 @@ export class Superagent {
4432
4734
  const thread = await inspect(route);
4433
4735
  if (physicalRouteKey(thread.route) !== physicalRouteKey(route))
4434
4736
  throw new DeliveryError("Work thread title lookup returned a different destination", "rejected");
4435
- if (thread.archived !== false || !active()) return;
4436
- // Re-read after the Discord lookup so an older settle cannot clear a
4737
+ if ((route.platform === "slack" ? !thread.editableTitle : thread.archived !== false) || !active()) return;
4738
+ // Re-read after the lookup so an older settle cannot clear a
4437
4739
  // newer run or a surviving input/approval hold. Open is not active.
4438
4740
  let current = this.store.lane(lane.id);
4439
4741
  if (!current) return;
@@ -4452,7 +4754,7 @@ export class Superagent {
4452
4754
  }
4453
4755
  const base = thread.title.replace(/^(?:⏳|✅) /u, "");
4454
4756
  if (prefix === null || !base.trim()) return;
4455
- // Keep the title within Discord's name limit without splitting a surrogate pair.
4757
+ // Keep the work title within its limit without splitting a surrogate pair.
4456
4758
  const title = (prefix + base).slice(0, 100).replace(/[\uD800-\uDBFF]$/, "").trimEnd();
4457
4759
  if (title === thread.title) return;
4458
4760
  this.laneMutations++;
@@ -4465,7 +4767,7 @@ export class Superagent {
4465
4767
  if (!(error instanceof DeliveryError && error.certainty === "rejected" && error.retryAfterMs !== undefined)) throw error;
4466
4768
  if (!active()) return;
4467
4769
  // Retry only a confirmed rate-limit rejection; recompute the desired
4468
- // prefix when Discord permits a new change, never replay a stale write.
4770
+ // prefix when the messenger permits a new change, never replay a stale write.
4469
4771
  const retry = setTimeout(() => {
4470
4772
  this.threadTitleRetries.delete(lane.id);
4471
4773
  this.background(this.syncLaneThreadTitle(lane));
@@ -4508,6 +4810,44 @@ export class Superagent {
4508
4810
  this.pauseRevisions.set(lane.id, (this.pauseRevisions.get(lane.id) ?? 0) + 1);
4509
4811
  if (lane.workState === "open" && this.store.updateLane(lane.id, lane.generation, { workState: "paused" }))
4510
4812
  this.background(this.syncLaneThreadTitle(lane));
4813
+ this.workerInbound.get(lane.id)?.cancel.abort();
4814
+ }
4815
+
4816
+ private observeWorkerDispatch(live: Live, frame: Record<string, unknown>): void {
4817
+ if (live.id === "main" || typeof frame.id !== "string") return;
4818
+ const admission = live.admitted.get(frame.id) ?? live.pausedWorkerAdmissions?.get(frame.id);
4819
+ const worker = admission?.worker;
4820
+ if (!admission || !worker || worker.outcome || admission.result || worker.command !== frame.command) return;
4821
+ const lane = this.store.lane(live.id);
4822
+ const input = this.store.input(admission.input.id);
4823
+ if (!lane?.remote || lane.sessionId !== live.sessionId || lane.generation !== live.generation
4824
+ || input?.target !== live.id || input.generation !== live.generation || input.requestId !== frame.id
4825
+ || input.state !== "submitted" && input.state !== "uncertain") return;
4826
+ if (frame.success === true && frame.workerDispatch === undefined) {
4827
+ worker.outcome = "acknowledged";
4828
+ return;
4829
+ }
4830
+ const refusal = workerDispatchRefusal(frame);
4831
+ if (!refusal || refusal === "worker_attachments_rejected" && !worker.attachments
4832
+ || refusal === "worker_checkout_unverified" && !lane.remote.workerCheckout) return;
4833
+ worker.outcome = refusal;
4834
+ live.pausedWorkerAdmissions?.delete(frame.id);
4835
+ // A failed checkout stops the rest of the queue. A refused resume of a
4836
+ // previously paused lane must not leave the durable lane reopened.
4837
+ if (refusal === "worker_checkout_unverified" || worker.holdOnRefusal && lane.workState === "open")
4838
+ this.holdLanePause(lane);
4839
+ this.activity(input, false);
4840
+ this.store.settle(input.id, "cancelled", {
4841
+ id: `${input.id}:${refusal === "worker_attachments_rejected" ? "attachments" : "admission"}`,
4842
+ text: refusal === "worker_checkout_unverified"
4843
+ ? "워커의 작업 디렉터리 또는 기준 커밋을 확인할 수 없어 실행하지 않았습니다. 원래 체크아웃을 확인한 뒤 레인을 재개하세요."
4844
+ : refusal === "worker_attachments_rejected"
4845
+ ? "원격 레인에서 첨부 파일을 안전하게 준비할 수 없어 요청을 실행하지 않았습니다."
4846
+ : "원격 레인 Host가 실행 전에 요청을 거절했습니다. 요청을 실행하거나 다시 시도하지 않았습니다.",
4847
+ });
4848
+ // Invalidate a settlement read already in flight on this same connection.
4849
+ live.nativeVersion++;
4850
+ this.background(this.finish(live));
4511
4851
  }
4512
4852
 
4513
4853
  async pause(id: string): Promise<void> {
@@ -4515,6 +4855,19 @@ export class Superagent {
4515
4855
  return this.pauseLane(id);
4516
4856
  }
4517
4857
 
4858
+ private retirePausedAdmission(live: Live, requestId: string, receipt: PromptAdmission, stopped: boolean): void {
4859
+ if (live.admitted.get(requestId) !== receipt) return;
4860
+ live.admitted.delete(requestId);
4861
+ const input = this.store.input(receipt.input.id);
4862
+ if (!input || input.state !== "submitted" && input.state !== "uncertain") return;
4863
+ const worker = this.requireLane(live.id).remote;
4864
+ const uncertain = worker && (input.state === "uncertain" || !stopped && !receipt.result);
4865
+ if (uncertain && receipt.result?.status !== "aborted") {
4866
+ this.store.settle(input.id, "uncertain");
4867
+ if (!receipt.result && receipt.worker) (live.pausedWorkerAdmissions ??= new Map()).set(requestId, receipt);
4868
+ } else this.store.settle(input.id, "cancelled");
4869
+ }
4870
+
4518
4871
  private async pauseLane(id: string): Promise<void> {
4519
4872
  this.assertRestartOpen();
4520
4873
  this.holdLanePause(this.requireLane(id));
@@ -4523,17 +4876,28 @@ export class Superagent {
4523
4876
 
4524
4877
  private async stopPausedLane(id: string): Promise<void> {
4525
4878
  this.assertRestartOpen();
4879
+ const inbound = this.workerInbound.get(id);
4880
+ const cleanup = inbound && this.store.input(inbound.inputId)?.state === "pending" ? inbound.done : undefined;
4881
+ const live = this.live.get(id);
4882
+ const pendingResponses = new Map<string, PromptAdmission>();
4883
+ let stopped = false;
4526
4884
  this.laneMutations++;
4527
4885
  try {
4528
4886
  const lane = this.requireLane(id);
4529
- const live = this.live.get(id);
4530
4887
  const failures: unknown[] = [];
4531
4888
  if (live) {
4532
- for (const { input } of live.admitted.values()) {
4889
+ for (const [requestId, receipt] of live.admitted) {
4890
+ const { input } = receipt;
4533
4891
  this.activity(input, false);
4534
- this.store.settle(input.id, "cancelled");
4892
+ if (receipt.worker?.response && !receipt.result) {
4893
+ // Keep the exact receipt for both the outstanding RPC and any
4894
+ // concurrent native prompt_result. Neither a pause nor an idle
4895
+ // snapshot proves whether this command crossed the SSH boundary.
4896
+ pendingResponses.set(requestId, receipt);
4897
+ continue;
4898
+ }
4899
+ this.retirePausedAdmission(live, requestId, receipt, true);
4535
4900
  }
4536
- live.admitted.clear();
4537
4901
  live.input = undefined;
4538
4902
  live.result = undefined;
4539
4903
  live.running = false;
@@ -4557,6 +4921,7 @@ export class Superagent {
4557
4921
  // State reads share stock RPC's serial tail. Interrupt maintenance before
4558
4922
  // querying it, just as the priority HEAD stop path does.
4559
4923
  try { await live.connection.client.abortAndRestoreQueue(); } catch (error) { failures.push(error); }
4924
+ await Promise.all([...pendingResponses.values()].map(receipt => receipt.worker?.response));
4560
4925
  const state = await this.state(live);
4561
4926
  if (state.goal?.enabled) {
4562
4927
  try { successful(await live.connection.request({ type: "goal", op: "pause" }), "pause goal"); }
@@ -4575,7 +4940,13 @@ export class Superagent {
4575
4940
  || paused.goal?.enabled || paused.pendingUiRequests?.length))
4576
4941
  throw new Error("Lane is paused durably, but native work has not fully stopped");
4577
4942
  if (failures.length) throw new AggregateError(failures, "Pause cleanup incomplete; lane remains paused");
4578
- } finally { this.laneMutations--; }
4943
+ stopped = true;
4944
+ } finally {
4945
+ if (live) for (const [requestId, receipt] of pendingResponses)
4946
+ this.retirePausedAdmission(live, requestId, receipt, stopped);
4947
+ await cleanup;
4948
+ this.laneMutations--;
4949
+ }
4579
4950
  }
4580
4951
 
4581
4952
  async resume(id: string, sourceId?: string): Promise<void> {
@@ -4594,6 +4965,7 @@ export class Superagent {
4594
4965
  try {
4595
4966
  let lane = this.requireLane(id);
4596
4967
  if (lane.workState === "cancelled") throw new Error("Cancelled work requires an explicit new/reopened request");
4968
+ if (lane.localOwner?.journalHeld) throw new Error(`Lane ${id}: the original local Host journal is unverified; resume is held`);
4597
4969
  this.authorized(lane.route, "work");
4598
4970
  const source = sourceId ? this.store.input(sourceId) : null;
4599
4971
  if (sourceId && (!source || source.state === "cancelled")) throw new Error("Resume requires a received uncancelled sourceId");
@@ -4631,12 +5003,10 @@ export class Superagent {
4631
5003
  || this.store.inputs(id).some(input => input.state === "submitted" || input.state === "uncertain")) {
4632
5004
  throw new Error("Resolve kickoff delivery and uncertain submissions before restoring the goal");
4633
5005
  }
4634
- live = await this.ensureLane(lane, undefined, pauseRevision) ?? undefined;
5006
+ live = await this.ensureLane(lane, { authorizedResume: pauseRevision }) ?? undefined;
4635
5007
  if (!live) throw new Error("The native session could not be restored within existing ownership and host limits");
4636
5008
  }
4637
5009
  if (live) await this.checkLaneModel(live);
4638
- else if (this.modelIntent(id)) await this.requireAvailableModel(this.modelIntent(id)!.model);
4639
- else if (lane.model !== null) await this.requireAvailableModel(lane.model);
4640
5010
  const state = live ? await this.state(live) : null;
4641
5011
  if ((this.pauseRevisions.get(id) ?? 0) !== pauseRevision) throw new Error("A later pause superseded this resume");
4642
5012
  if (source && this.store.input(source.id)?.state === "cancelled") throw new Error("The resume source was cancelled");
@@ -4686,6 +5056,10 @@ export class Superagent {
4686
5056
  const pauseRevision = this.pauseRevisions.get(live.id);
4687
5057
  const priorWorkState = live.id === "main" ? undefined : this.requireLane(live.id).workState;
4688
5058
  let submitted = false;
5059
+ const workerResponse = live.id !== "main" && this.requireLane(live.id).remote ? Promise.withResolvers<void>() : undefined;
5060
+ const worker: PromptAdmission["worker"] = workerResponse ? {
5061
+ command: "goal", response: workerResponse.promise, ...(priorWorkState === "paused" && { holdOnRefusal: true }),
5062
+ } : undefined;
4689
5063
  live.preparing++;
4690
5064
  try {
4691
5065
  const cursor = await this.readJournalCursor(live, "capture native goal resume owner");
@@ -4725,7 +5099,8 @@ export class Superagent {
4725
5099
  submitted = true;
4726
5100
  live.input = input;
4727
5101
  live.result = undefined;
4728
- live.admitted.set(requestId, { input });
5102
+ const admission: PromptAdmission = { input, worker };
5103
+ live.admitted.set(requestId, admission);
4729
5104
  live.recovery = undefined;
4730
5105
  live.ownedRuns = 0;
4731
5106
  live.running = false;
@@ -4736,20 +5111,31 @@ export class Superagent {
4736
5111
  this.blocked.delete(live.id);
4737
5112
  this.modelHolds.delete(live.id);
4738
5113
  }
4739
- successful(await live.connection.request({ type: "goal", op: "resume" }, requestId), "resume native goal");
5114
+ const reply = await live.connection.request({ type: "goal", op: "resume" }, requestId);
5115
+ if (worker?.outcome && worker.outcome !== "acknowledged") {
5116
+ throw new Error(worker.outcome === "worker_checkout_unverified"
5117
+ ? "Worker checkout was not verified; the native goal was not resumed"
5118
+ : "Worker refused the native goal resume before dispatch");
5119
+ }
5120
+ successful(reply, "resume native goal");
4740
5121
  if (live.input === input && live.admitted.has(requestId)
4741
5122
  && (live.id === "main" || this.requireLane(live.id).workState === "open")) {
4742
5123
  const result: Live["result"] = { status: "accepted", agentInvoked: false, goalResume: true };
4743
5124
  live.result = result;
4744
- live.admitted.set(requestId, { input, result });
5125
+ admission.result = result;
4745
5126
  }
4746
5127
  } catch (error) {
4747
- if (submitted && this.store.input(inputId)?.state === "submitted") this.store.settle(inputId, "uncertain", {
5128
+ if (submitted && (!worker || this.current(live)) && this.store.input(inputId)?.state === "submitted") this.store.settle(inputId, "uncertain", {
4748
5129
  id: `${inputId}:admission`, ...(live.id === "main" ? {} : { laneFailure: "recover" as const }),
4749
5130
  text: "Native goal resume outcome is uncertain; it was not replayed.",
4750
5131
  });
4751
5132
  throw error;
4752
- } finally { live.preparing--; }
5133
+ } finally {
5134
+ live.preparing--;
5135
+ if (worker) delete worker.response;
5136
+ workerResponse?.resolve();
5137
+ if (submitted && this.store.input(inputId)?.state === "cancelled") this.background(this.finish(live));
5138
+ }
4753
5139
  await this.finish(live);
4754
5140
  }
4755
5141
 
@@ -4863,7 +5249,12 @@ export class Superagent {
4863
5249
  const remoteShutdown = lane !== null && this.remoteShutdownPending(lane);
4864
5250
  const remoteOpen = lane !== null && this.remoteOpenPending(lane);
4865
5251
  const quota = this.store.getMeta(`lane-quota-hold:${id}`);
4866
- return { runtimeBlocked: this.blocked.has(id) || remoteShutdown || remoteOpen, uncertainInputIds, ...(quota ? { quota } : {}),
5252
+ const waiting = lane?.workState === "open" && !live && !this.blocked.has(id) && !quota && !kickoff
5253
+ ? inputs.find(input => input.state === "pending" && (!beforeInputId || input.id === beforeInputId) && this.capacityHolds.has(input.id)) : null;
5254
+ const capacity = waiting && this.capacityHolds.get(waiting.id);
5255
+ return { runtimeBlocked: this.blocked.has(id) || remoteShutdown || remoteOpen || !!lane?.localOwner?.journalHeld,
5256
+ uncertainInputIds, ...(quota ? { quota } : {}), ...(capacity && { capacity }),
5257
+ ...(lane?.localOwner?.journalHeld && { localFence: "journal-unverified" }),
4867
5258
  ...(remoteShutdown ? { remoteShutdown: "awaiting verified exit" } : {}),
4868
5259
  ...(remoteOpen ? { remoteOpen: "awaiting verified owner or explicit reconciliation" } : {}), ...(kickoff ? { kickoff } : {}) };
4869
5260
  }
@@ -4885,8 +5276,12 @@ export class Superagent {
4885
5276
  };
4886
5277
  }
4887
5278
 
4888
- private async ensureLane(lane: Lane, modelReadback?: ModelChangeIntent | "review-readback" | ScopedLaneModelReadback, authorizedResume?: number): Promise<Live | null> {
4889
- if (this.restartFence()) return null;
5279
+ private async ensureLane(lane: Lane, { modelReadback, authorizedResume, onCapacityHold }: {
5280
+ modelReadback?: ModelChangeIntent | "review-readback" | ScopedLaneModelReadback;
5281
+ authorizedResume?: number;
5282
+ onCapacityHold?: (hold: CapacityHold) => void;
5283
+ } = {}): Promise<Live | null> {
5284
+ if (this.restartFence() || lane.localOwner?.journalHeld) return null;
4890
5285
  const scopedReadback = modelReadback && typeof modelReadback === "object" && "pickerSourceId" in modelReadback ? modelReadback : undefined;
4891
5286
  const explicitRetry = scopedReadback?.intent
4892
5287
  ?? (modelReadback && typeof modelReadback === "object" && "request" in modelReadback ? modelReadback : undefined);
@@ -4895,17 +5290,22 @@ export class Superagent {
4895
5290
  const existing = this.live.get(lane.id);
4896
5291
  if (existing) return existing.releasing || this.remoteShutdownPending(lane) ? null : existing;
4897
5292
  if ((this.blocked.has(lane.id) && !modelReadback && authorizedResume === undefined) || this.connecting.has(lane.id)) return null;
4898
- const resident = this.residentHosts();
5293
+ let resident = this.residentHosts();
4899
5294
  if (!resident.has(lane.id) && resident.size + Number(this.groups?.running ?? false) >= this.config.maxHosts) {
4900
5295
  const candidates = [...this.live.values()].filter(host => host.id !== "main" && !host.input && !host.busy)
4901
5296
  .sort((left, right) => left.lastActivity - right.lastActivity);
4902
- let released = false;
4903
- for (const candidate of candidates) if (await this.release(candidate, "capacity")) { released = true; break; }
4904
- if (!released) return null;
4905
- if (this.residentHosts().size + Number(this.groups?.running ?? false) >= this.config.maxHosts) return null;
5297
+ for (const candidate of candidates) if (await this.release(candidate, "capacity")) break;
5298
+ if (candidates.length) resident = this.residentHosts();
5299
+ const count = resident.size + Number(this.groups?.running ?? false);
5300
+ if (!resident.has(lane.id) && count >= this.config.maxHosts) {
5301
+ onCapacityHold?.({ resident: count, maxHosts: this.config.maxHosts, unverifiedLocalLaneIds: this.store.lanes()
5302
+ .filter(other => !other.remote && resident.has(other.id) && !this.connecting.has(other.id)
5303
+ && (!this.live.has(other.id) || this.live.get(other.id)?.lostDuringRelease)).map(other => other.id) });
5304
+ return null;
5305
+ }
4906
5306
  }
4907
5307
  const checked = this.requireLane(lane.id);
4908
- if (checked.generation !== lane.generation || this.live.has(lane.id) || this.connecting.has(lane.id)) return null;
5308
+ if (checked.localOwner?.journalHeld || checked.generation !== lane.generation || this.live.has(lane.id) || this.connecting.has(lane.id)) return null;
4909
5309
  lane = checked; // Capacity reconciliation may have retired the recorded local PID.
4910
5310
  this.connecting.add(lane.id);
4911
5311
  const restoringResumed = (workState: Lane["workState"]) => (workState === "paused" || workState === "completed")
@@ -4941,17 +5341,16 @@ export class Superagent {
4941
5341
  || pendingModelChange.request !== explicitRetry.request || !isDeepStrictEqual(pendingModelChange.snapshot, explicitRetry.snapshot))) {
4942
5342
  throw new Error(`Lane ${lane.id} explicit retry no longer matches its durable model-change intent`);
4943
5343
  }
5344
+ if ((pendingModelChange && pendingModelChange.native !== false || reviewReadback) && !hasTranscript)
5345
+ throw new Error(`Lane ${lane.id} has no transcript for the requested native readback`);
5346
+ const unstartedModel = pendingModelChange?.native === false ? pendingModelChange.model : lane.model;
5347
+ if (!remote && !hasTranscript && unstartedModel !== null) await this.requireAvailableModel(unstartedModel);
4944
5348
  if (pendingModelChange?.native === false) {
4945
- await this.requireAvailableModel(pendingModelChange.model);
4946
5349
  this.commitModelChange(lane, pendingModelChange);
4947
5350
  lane = this.requireLane(lane.id);
4948
5351
  pendingModelChange = null;
4949
5352
  }
4950
- if ((pendingModelChange || reviewReadback) && !hasTranscript)
4951
- throw new Error(`Lane ${lane.id} has no transcript for the requested native readback`);
4952
- if (pendingModelChange) await this.requireAvailableModel(pendingModelChange.model);
4953
- else if (lane.model !== null && !reviewReadback) await this.requireAvailableModel(lane.model);
4954
- else if (!hasTranscript) {
5353
+ if (lane.model === null && !hasTranscript) {
4955
5354
  if (lane.sessionId !== null) throw new Error(`Legacy lane ${lane.id} has a recorded session but no transcript; restore it before resuming`);
4956
5355
  const head = this.live.get("main");
4957
5356
  if (!head) throw new Error("Cannot adopt a legacy lane model without the authoritative head");
@@ -4983,7 +5382,7 @@ export class Superagent {
4983
5382
  if (restoring) this.store.setMeta(restoreModelKey(lane.id), JSON.stringify({ generation: lane.generation }));
4984
5383
  preflight = false;
4985
5384
  if (!remote) await mkdir(dirname(lane.sessionFile), { recursive: true, mode: 0o700 });
4986
- const memoryCheckout = remote && !restoring && remote.probe.memoryLaunchVersion === 1
5385
+ const memoryCheckout = remote && !lane.remote?.workerCheckout && !restoring && remote.probe.memoryLaunchVersion === 1
4987
5386
  && this.config.remoteMemorySync && lane.cwd === this.config.headCwd && this.memoryDestination(lane)
4988
5387
  ? await verifyMemoryCheckout(lane) : undefined;
4989
5388
  const beforeLaunch = this.requireLane(lane.id);
@@ -5003,14 +5402,22 @@ export class Superagent {
5003
5402
  const memorySync = memoryCheckout?.() && !!this.memoryDestination(beforeLaunch);
5004
5403
  if (memorySync) this.store.setMeta(`worker-memory:requested:${lane.id}`, "1");
5005
5404
  if (remote) this.store.setMeta(this.remoteOpenKey(lane), "pending");
5006
- const { pid } = remote ? await this.adapters.workerOpen(remote.registration, workerRef(lane), { ...launch, ...(memorySync && { memorySync: true }) })
5405
+ const started: { pid: number; localIdentity?: LocalHostIdentity } = remote
5406
+ ? await this.adapters.workerOpen(remote.registration, workerRef(lane), { ...launch, ...(memorySync && { memorySync: true }) })
5007
5407
  : await this.adapters.startHost({
5008
5408
  ...launch, command: this.config.command, cwd: lane.cwd, sessionFile: lane.sessionFile,
5009
5409
  ...(isPrReviewLane(this.store, lane.id) ? { prReviewOnly: true } : {}),
5010
5410
  socketPath: lane.socketPath, extensionPath: this.extensionPath, env: this.childEnvironment(lane.id),
5011
5411
  logPath: hostPaths(this.config, lane.id).logPath,
5012
5412
  });
5013
- if (!this.store.updateLane(lane.id, lane.generation, { pid })) throw new Error(`Lane ${lane.id} generation changed during launch`);
5413
+ const { pid, localIdentity } = started;
5414
+ const matches = localIdentity && !remote && localIdentity.pid === pid && localIdentity.sessionFile === lane.sessionFile
5415
+ && !!localIdentity.sessionId && (lane.sessionId === null || localIdentity.sessionId === lane.sessionId);
5416
+ // Even a rejected session has a launched process. Keep its PID against capacity
5417
+ // without adopting its journal, including if the public endpoint disappears.
5418
+ if (!this.store.updateLane(lane.id, lane.generation, { pid, ...(matches && { localOwner: localIdentity, sessionId: localIdentity.sessionId }) }))
5419
+ throw new Error(`Lane ${lane.id} generation changed during launch`);
5420
+ if (localIdentity && !matches) throw new Error(`Lane ${lane.id} launch did not match the expected local session`);
5014
5421
  const live = await this.attachLane({ ...lane, pid });
5015
5422
  if (remote) {
5016
5423
  await this.reconcileUi(live);
@@ -5039,7 +5446,16 @@ export class Superagent {
5039
5446
 
5040
5447
  private residentHosts(): Set<string> {
5041
5448
  return new Set(["main", ...this.live.keys(), ...this.connecting, ...this.store.lanes()
5042
- .filter(lane => this.mayOwnHost(lane)).map(lane => lane.id)]);
5449
+ .filter(lane => !quarantinedSlotFree(this.config, lane) && this.mayOwnHost(lane)).map(lane => lane.id)]);
5450
+ }
5451
+
5452
+ private async quarantineLocalOrphan(lane: Lane, releasing?: Live): Promise<boolean> {
5453
+ if (lane.remote || lane.pid === null || this.connecting.has(lane.id) || this.live.get(lane.id) !== releasing) return false;
5454
+ const orphan = await inspectLocalOrphan(this.config, lane);
5455
+ if (!orphan || this.stopped || this.restartFence() || this.connecting.has(lane.id) || this.live.get(lane.id) !== releasing
5456
+ || !this.store.retireLocalLaneHost(lane, orphan)) return false;
5457
+ this.blocked.add(lane.id);
5458
+ return true;
5043
5459
  }
5044
5460
 
5045
5461
  private memoryDestination(lane: Lane) {
@@ -5139,11 +5555,17 @@ export class Superagent {
5139
5555
  const { probe } = await this.inspectRemote(lane);
5140
5556
  if (!this.current(live) || !this.recordRemoteExit(lane, probe)) return false;
5141
5557
  } catch (error) { this.report(error); return false; }
5142
- } else if (this.pidAlive(lane.pid) || this.localSocketMayExist(lane.socketPath)) return false;
5558
+ } else {
5559
+ if (this.pidAlive(lane.pid) || lane.localOwner && this.pidAlive(lane.localOwner.ownerPid)) return false;
5560
+ if (this.localSocketMayExist(lane.socketPath)) {
5561
+ if (!await this.quarantineLocalOrphan(lane, live)) return false;
5562
+ } else if (!this.store.retireLocalLaneHost(lane)) return false;
5563
+ }
5143
5564
  this.live.delete(live.id);
5144
5565
  live.unsubscribe();
5145
5566
  await live.connection.close();
5146
- if (!lane.remote) this.store.updateLane(live.id, live.generation, { runtimeState: "unloaded", pid: null });
5567
+ if (!lane.remote && !this.requireLane(lane.id).localOwner?.journalHeld)
5568
+ this.store.updateLane(live.id, live.generation, { runtimeState: "unloaded", pid: null });
5147
5569
  return true;
5148
5570
  }
5149
5571
  if (live.id === "main" || live.preparing || this.modelChanges.has(live.id) || this.modelIntent(live.id) || this.modelHolds.has(live.id) || live.input || this.store.approvals(live.id).length
@@ -5446,16 +5868,21 @@ export class Superagent {
5446
5868
  let handedOff = false;
5447
5869
  try {
5448
5870
  this.assertRestartCurrent(restart);
5449
- restart = { ...restart, state: "acknowledging" };
5450
- this.saveRestart(restart);
5451
- this.store.settle(input.id, "done", { id: restart.ackOutputId,
5452
- text: "Preparing to replace Gateway AND HEAD and restore the same native session and transcript. Independent lanes stay running. This is an ACK, not restart completion; new work is held until replacement readiness is verified." });
5453
- // Joining an already-finishing drain is not proof this newly queued ACK
5454
- // was included. Only a durable sent receipt authorizes the Gateway RPC.
5455
- do { await this.flushOutputs(physicalRouteKey(input.route)); }
5456
- while (!this.stopped && this.store.output(restart.ackOutputId)?.state === "pending");
5871
+ if (!this.store.output(restart.ackOutputId)) {
5872
+ restart = { ...restart, state: "acknowledging" };
5873
+ this.saveRestart(restart);
5874
+ this.store.settle(input.id, "done", { id: restart.ackOutputId,
5875
+ text: "Preparing to replace Gateway AND HEAD and restore the same native session and transcript. Independent lanes stay running. This is an ACK, not restart completion; new work is held until replacement readiness is verified." });
5876
+ }
5877
+ await this.flushOutputs(physicalRouteKey(input.route));
5457
5878
  const ack = this.store.output(restart.ackOutputId);
5458
5879
  this.assertRestartCurrent(restart);
5880
+ if (ack?.state === "pending") {
5881
+ // In particular, a same-route Retry-After can keep the ACK ineligible.
5882
+ // Release the control drain; its own terminal receipt wakes this request.
5883
+ this.restartAckWaiting = ack.id;
5884
+ return;
5885
+ }
5459
5886
  if (ack?.state !== "sent") {
5460
5887
  if (ack?.state === "failed") this.refuseRestart(restart, "The required ACK was rejected; no restart handoff was attempted.");
5461
5888
  else {
@@ -5523,7 +5950,7 @@ export class Superagent {
5523
5950
  JSON.stringify({ ...current, state: "failed" }), output)) this.report(error);
5524
5951
  }
5525
5952
  } finally {
5526
- if (this.restartActive === input.id) this.restartActive = undefined;
5953
+ if (this.restartActive === input.id && this.restartAckWaiting !== restart.ackOutputId) this.restartActive = undefined;
5527
5954
  }
5528
5955
  }
5529
5956
 
@@ -5890,15 +6317,16 @@ export class Superagent {
5890
6317
  "Supported owner commands (Slack uses ! instead of /, e.g. !status):",
5891
6318
  "/help; /status; /context — read current shared HEAD, even while busy; no model turn.",
5892
6319
  "/usage — view account quotas and reset times from the configured OMP profile; no model turn.",
5893
- `${usageResetHint(input.route.platform)}${input.route.platform === "slack" ? " or /superagent-usage reset" : ""} — list usable saved reset tickets. Choose an account and use Confirm to spend one ticket on it.`,
5894
- ...(input.route.platform === "discord" ? ["/model — choose HEAD or the current lane, then choose a provider and model."] : []),
6320
+ `${usageResetHint(input.route.platform)}${input.route.platform === "slack" ? ", !usage-reset or /superagent-usage-reset" : ""} — list usable saved reset tickets. Choose an account and use Confirm to spend one ticket on it.`,
6321
+ ...(input.route.platform === "slack" ? ["!model — choose HEAD or the current lane, then choose a provider and model."]
6322
+ : input.route.platform === "discord" ? ["/model — choose HEAD or the current lane, then choose a provider and model."] : []),
5895
6323
  "/model and /effort open selection menus. HEAD text commands: /model list; /model <exact provider/id>; /model preset; /model preset list; /model preset <exact-name>; /effort <advertised-level>. HEAD changes require idle, unambiguous state.",
5896
6324
  `${input.route.platform === "slack" ? "!fast or /superagent-fast" : "/fast"} — show the current HEAD fast tier and open the menu. Select off, on or ultra, then press Confirm. Changes require idle HEAD; faster tiers may cost more.`,
5897
6325
  "/model --lane <exact provider/id> — select the bound lane's model, not the HEAD model. Requires an idle lane and never replays a failed prompt.",
5898
6326
  "/model preset <exact-name> --global — first apply and verify the shared HEAD session, then save those exact roles/thinking as future/default settings. Existing lanes remain unchanged. --global is only supported for named preset selection, not queries/lists, direct models or effort; duplicate/unknown flags are rejected. A failed/unconfirmed global save does not undo the session change and is never automatically replayed.",
5899
6327
  "/compact [instructions] — native shared HEAD compaction; multiline instructions allowed; requires idle, unambiguous state.",
5900
6328
  "/cron [help] — schedule and manage one-time or recurring jobs in this conversation.",
5901
- '/cron pr-add "every 5m" OWNER/REPO — 외부 PR 자동 리뷰와 GitHub 코멘트를 시작합니다. 부모 채널에서 “무인으로 리뷰만”, “무인으로 리뷰 후 수정커밋까지”, “무인으로 수정커밋후 머지까지” 또는 /cron pr-mode JOB review|fix|merge 로 단계를 선택하세요.',
6329
+ `${input.route.platform === "slack" ? '!cron' : '/cron'} pr-add "every 5m" OWNER/REPO — 외부 PR 자동 리뷰와 GitHub 코멘트를 시작합니다. 등록한 부모 채널에서 단계(review, fix, merge)를 선택하세요.`,
5902
6330
  "/stop [head|lane-id] — pause the bound lane or reply to the original request or placement question. Ambiguous targets are not stopped. Use /stop head for the global HEAD stop, or /stop <lane-id> for one managed lane.",
5903
6331
  "/restart — durably fence intake, confirm the original-route ACK, checkpoint/interrupt busy HEAD and cancel its original approval cards, then safely replace BOTH Gateway AND HEAD. Restore the same native session/model/effort and resume eligible previously active goals without prompt replay. Independent lanes stay running. Uncertain effects or unreconciled owned resources remain held; no forced kill. ACK/acceptance is not completion; explicit stop wins.",
5904
6332
  "/resolve [input-id] — close ONE already-uncertain HEAD input as cancelled so later HEAD work is no longer held. Requires the exact ID when several are held; never replays the original work and never claims its native outcome. Send a new request if that work is still wanted.",
@@ -6097,7 +6525,7 @@ export class Superagent {
6097
6525
  };
6098
6526
  this.store.setMeta("head:stop-boundary", JSON.stringify({
6099
6527
  inputId: input.id,
6100
- prDiscordOrder: this.cronJobs.prStopOrder(boundary, input),
6528
+ prOrder: this.cronJobs.prStopOrder(boundary, input),
6101
6529
  cancelledInputIds: [...new Set([...previousBoundary.cancelledInputIds, ...cancelledInputIds])],
6102
6530
  deferredStoppedIds: [...new Set([...(previousBoundary.deferredStoppedIds ?? []), ...deferredStoppedIds])],
6103
6531
  }));
@@ -6295,7 +6723,11 @@ export class Superagent {
6295
6723
  return;
6296
6724
  }
6297
6725
  const live = this.live.get(lane.id);
6298
- if (live) this.background(this.finish(live));
6726
+ if (live) {
6727
+ const requestId = this.store.input(target)?.requestId;
6728
+ if (requestId) live.pausedWorkerAdmissions?.delete(requestId);
6729
+ this.background(this.finish(live));
6730
+ }
6299
6731
  this.background(this.syncLaneThreadTitle(lane));
6300
6732
  this.wakeOutputs(control.route);
6301
6733
  this.background(this.kick().catch(this.report));
@@ -6324,6 +6756,10 @@ export class Superagent {
6324
6756
  this.controlReply(input, `Invalid syntax. Use /usage or ${resetInput}. A ticket can only be spent from the confirmation card.`, "cancelled");
6325
6757
  return;
6326
6758
  }
6759
+ if (input.route.platform === "slack" && !input.pickerSelection && !this.originalOwnerControl(input)) {
6760
+ this.controlReply(input, `Open ${resetCommand} as a new owner command without attachments.`, "cancelled");
6761
+ return;
6762
+ }
6327
6763
  const savedKey = this.store.getMeta("usage-reset:identity-key");
6328
6764
  const identityKey = savedKey ?? crypto.randomUUID();
6329
6765
  if (savedKey === null) this.store.setMeta("usage-reset:identity-key", identityKey);
@@ -6460,7 +6896,8 @@ export class Superagent {
6460
6896
  return;
6461
6897
  }
6462
6898
  const presetCommand = this.headPresetCommand(command);
6463
- const scopedOpening = input.route.platform === "discord" && command.name === "model" && !command.argument && !command.picker;
6899
+ const scopedOpening = (input.route.platform === "discord" || input.route.platform === "slack")
6900
+ && command.name === "model" && !command.argument && !command.picker;
6464
6901
  const reply = (text: string, outcome: "done" | "cancelled" | "uncertain" = "done", picker?: HeadPicker) => {
6465
6902
  const scope = presetCommand?.global ? "HEAD preset command (existing lanes unchanged)." : "HEAD session only (not lanes or global defaults).";
6466
6903
  this.store.settle(input.id, outcome, { id: `${input.id}:head-control`, text: scopedOpening ? text : `${scope} ${text}`, ...(picker ? { picker } : {}) });
@@ -6529,7 +6966,7 @@ export class Superagent {
6529
6966
  } : undefined);
6530
6967
  } else if (command.name === "model") {
6531
6968
  if (scopedOpening && !this.originalOwnerControl(input)) {
6532
- reply("Open /model from an original owner command in this conversation.", "cancelled");
6969
+ reply(`Open ${prefix}model from an original owner command in this conversation.`, "cancelled");
6533
6970
  return;
6534
6971
  }
6535
6972
  const catalog = await this.nativeModelCatalog().catch(() => null);
@@ -6788,7 +7225,8 @@ export class Superagent {
6788
7225
  }
6789
7226
 
6790
7227
  private originalOwnerControl(input: InputRecord): boolean {
6791
- if (input.pickerSelection || input.attachments.length || messengerEdit(input) || !authorizeRoute(this.config, input.route)) return false;
7228
+ if (input.pickerSelection || input.attachments.length || input.route.platform === "slack" && input.unresolvedReply
7229
+ || messengerEdit(input) || !authorizeRoute(this.config, input.route)) return false;
6792
7230
  return matchesWrittenCommand(input);
6793
7231
  }
6794
7232
 
@@ -6981,8 +7419,11 @@ export class Superagent {
6981
7419
  if (!isLaneModel(model)) throw new PrControlError("현재 HEAD 모델을 확인할 수 없습니다.");
6982
7420
  if (source.route.threadId) {
6983
7421
  const actual = await this.messenger.inspectThread?.(source.route);
6984
- if (!actual || actual.archived !== false || routeKey(actual.route) !== routeKey(source.route))
6985
- throw new PrControlError("원래 메시지에서 열린 활성 스레드임을 Discord에서 확인할 수 없습니다.");
7422
+ const slack = source.route.platform === "slack";
7423
+ const offerAnchor = this.store.getMeta(intakeThreadKey(round.job, round.number));
7424
+ if (!actual || routeKey(actual.route) !== routeKey(source.route)
7425
+ || (slack ? actual.botStarter !== (source.route.threadId === offerAnchor) : actual.archived !== false))
7426
+ throw new PrControlError("원래 메시지에서 열린 검토 스레드임을 확인할 수 없습니다.");
6986
7427
  }
6987
7428
  const cwd = join(this.config.stateDir, "pr-reviews", round.laneId);
6988
7429
  privateDirectory(cwd);
@@ -6991,7 +7432,7 @@ export class Superagent {
6991
7432
  await this.admitLane({ sourceId: source.id, cwd, destination: physicalRoute(source.route), placement: { target: "local" },
6992
7433
  title: prThreadTitle(round.repository, round.number), model, modelReason: "Inherit the verified HEAD model for this static PR review.",
6993
7434
  brief: `Static review of ${round.repository}#${round.number}; do not execute contributor code.`,
6994
- kickoff: `PR #${round.number} 정적 검토 전용 스레드입니다. 검토 상태와 다음 명령: /cron pr-status ${round.job} ${round.number}` });
7435
+ kickoff: `PR #${round.number} 정적 검토 전용 스레드입니다. 검토 상태와 다음 명령: ${source.route.platform === "slack" ? "!" : "/"}cron pr-status ${round.job} ${round.number}` });
6995
7436
  }
6996
7437
 
6997
7438
  private async drivePrScan({ job, entries }: IntakeScan): Promise<void> {
@@ -7017,11 +7458,13 @@ export class Superagent {
7017
7458
  verify();
7018
7459
  const previous = this.prReviews.saved(job.id, number);
7019
7460
  if (previous && !previous.automation) continue; // A real per-PR owner action took ownership.
7020
- if (!/^[1-9]\d{0,19}$/.test(anchor)) throw new PrControlError("Discord 알림의 실제 메시지 ID가 없어 자동 검토를 시작하지 않았습니다.");
7461
+ const slack = route.platform === "slack";
7462
+ if (!isPrMessageId(route.platform, anchor))
7463
+ throw new PrControlError("PR 알림의 실제 메시지 ID가 없어 자동 검토를 시작하지 않았습니다.");
7021
7464
  if (!head && !previous) continue;
7022
7465
  const threadKey = intakeThreadKey(job.id, number);
7023
7466
  const claimed = this.store.getMeta(threadKey);
7024
- if (claimed === null) {
7467
+ if (claimed === null && !slack) {
7025
7468
  if (!this.messenger.inspectThread || !await this.messenger.canCreateThread?.(offer.route))
7026
7469
  throw new PrControlError("원래 Discord 알림에 스레드를 만들고 확인할 권한이 없습니다.");
7027
7470
  verify();
@@ -7036,12 +7479,15 @@ export class Superagent {
7036
7479
  if (routeKey(created) !== routeKey(route))
7037
7480
  throw new PrControlError("Discord 스레드와 원래 알림 메시지 ID가 다릅니다. 생성 요청을 반복하지 않습니다.");
7038
7481
  } else if (claimed === `rejected:${anchor}`) continue;
7039
- else if (claimed !== anchor) throw new PrControlError("원래 알림과 스레드 영수증이 일치하지 않습니다.");
7482
+ else if (claimed !== null && claimed !== anchor) throw new PrControlError("원래 알림과 스레드 영수증이 일치하지 않습니다.");
7040
7483
  verify();
7041
7484
  const thread = await this.messenger.inspectThread?.(route);
7042
- if (!thread || thread.archived !== false || routeKey(thread.route) !== routeKey(route))
7485
+ if (!thread || routeKey(thread.route) !== routeKey(route) || (slack ? thread.botStarter !== true : thread.archived !== false))
7043
7486
  throw new PrControlError("원래 알림에 연결된 활성 스레드가 확인되지 않습니다. 두 번째 스레드를 만들지 않습니다.");
7044
7487
  verify();
7488
+ // Slack replies use the verified alert itself as their root. There is
7489
+ // no remote create operation to claim or repeat before binding it.
7490
+ if (slack && claimed === null) this.store.setMeta(threadKey, anchor);
7045
7491
  let next = head;
7046
7492
  if (previous) {
7047
7493
  const lane = this.store.lane(previous.laneId);
@@ -7068,14 +7514,14 @@ export class Superagent {
7068
7514
  const sourceId = intakeWorkId(job.id, number, policy.revision, next);
7069
7515
  const laneId = previous?.laneId ?? `lane-${key(`handoff:${sourceId}:lane`)}`;
7070
7516
  const bound = this.store.laneForRoute(route);
7071
- if (bound && (!previous || bound.id !== laneId)) throw new PrControlError("원래 Discord 스레드가 다른 작업에 배정됐습니다.");
7517
+ if (bound && (!previous || bound.id !== laneId)) throw new PrControlError("원래 스레드가 다른 작업에 배정됐습니다.");
7072
7518
  const round = this.prReviews.startAutomated(job, candidate, next, route, laneId, policy.revision);
7073
7519
  const source = this.store.input(round.source);
7074
7520
  if (!source) throw new PrControlError("자동 검토 작업 영수증을 확인하지 못했습니다.");
7075
7521
  try {
7076
7522
  await this.placePrReview(round, source, !previous, verify);
7077
7523
  this.store.settle(source.id, "done");
7078
- this.store.setMeta(slot, `PR #${number} 검토 접수: ${next}. <#${anchor}>`);
7524
+ this.store.setMeta(slot, `PR #${number} 검토 접수: ${next}. ${slack ? `스레드 ${anchor}` : `<#${anchor}>`}`);
7079
7525
  this.background(this.kick());
7080
7526
  } catch (error) {
7081
7527
  // Only the native lane input may have reached OMP. Placement/outbox
@@ -7085,7 +7531,7 @@ export class Superagent {
7085
7531
  }
7086
7532
  } catch (error) {
7087
7533
  this.store.setMeta(slot, error instanceof PrControlError ? error.message
7088
- : `PR #${number} 자동 처리 보류. /cron pr-status ${job.id} ${number} 및 원래 알림·스레드의 실제 상태를 확인하세요.`);
7534
+ : `PR #${number} 자동 처리 보류. ${prCronCommand(offer.route.platform)} pr-status ${job.id} ${number} 및 원래 알림·스레드의 실제 상태를 확인하세요.`);
7089
7535
  } finally { this.activePrs.delete(slot); }
7090
7536
  }
7091
7537
  }
@@ -7110,9 +7556,15 @@ export class Superagent {
7110
7556
  this.prControlActive = true;
7111
7557
  try {
7112
7558
  verify();
7113
- if (!this.messenger.assertRoute) throw new PrControlError("인증된 Discord 경로를 확인할 수 없습니다.");
7559
+ if (!this.messenger.assertRoute) throw new PrControlError("인증된 메신저 경로를 확인할 수 없습니다.");
7114
7560
  try { await this.messenger.assertRoute(input.route); }
7115
- catch { throw new PrControlError("원래 Discord 봇 계정·채널·스레드의 접근을 확인할 수 없습니다."); }
7561
+ catch { throw new PrControlError("원래 봇 계정·채널·스레드의 접근을 확인할 수 없습니다."); }
7562
+ if (input.route.platform === "slack" && input.route.threadId) {
7563
+ const root = await this.messenger.inspectThread?.(input.route);
7564
+ if (!root || routeKey(root.route) !== routeKey(input.route) || typeof root.botStarter !== "boolean")
7565
+ throw new PrControlError("원래 Slack PR 스레드의 시작 메시지를 확인할 수 없습니다.");
7566
+ }
7567
+ verify();
7116
7568
  const id = `lane-${key(`handoff:${input.id}:lane`)}`;
7117
7569
  const text = await this.prReviews.control(input, argument, { verify, newLaneId: id, signal: this.stopSignal.signal,
7118
7570
  place: (round, first) => this.placePrReview(round, input, first, verify) });
@@ -7120,7 +7572,7 @@ export class Superagent {
7120
7572
  this.store.settleCronControl(input.id, { text: launchHeld ? `${text}\nNative Host가 보류되었습니다. HEAD에서 ${threadLane.id}의 모델·Host 상태를 확인하세요. PR 코드를 일반 레인으로 옮겨 실행하지 마세요.` : text });
7121
7573
  } catch (error) {
7122
7574
  const reason = error instanceof PrControlError ? error.message
7123
- : "원래 등록·소유자 경로·GitHub 상태 또는 레인 배정을 확인하지 못했습니다. 부모 채널의 /cron show 및 원래 스레드 기록을 확인하세요";
7575
+ : `원래 등록·소유자 경로·GitHub 상태 또는 레인 배정을 확인하지 못했습니다. 부모 채널의 ${prCronCommand(input.route.platform)} show 및 원래 스레드 기록을 확인하세요`;
7124
7576
  this.store.settleCronControl(input.id, { state: "cancelled", text: `PR 명령 보류: ${reason}. 자동 재시도하지 않습니다.` });
7125
7577
  } finally { this.prControlActive = false; this.activePrs.delete(slot); }
7126
7578
  }
@@ -7136,7 +7588,7 @@ export class Superagent {
7136
7588
  this.background((async () => {
7137
7589
  for (const lane of this.store.lanes()) {
7138
7590
  if (this.stopped) return;
7139
- if (lane.route.platform === "discord" && lane.route.guildId && lane.route.threadId) {
7591
+ if (nativeWorkThread(lane.route)) {
7140
7592
  await this.syncLaneThreadTitle(lane).catch(this.report);
7141
7593
  }
7142
7594
  if (this.restartFence()) { this.reconcileSavedThreadTitles = true; return; }
@@ -7228,7 +7680,9 @@ export class Superagent {
7228
7680
  const confirmation = this.store.getMeta(`topic-confirm:${input.id}`);
7229
7681
  if (confirmation !== null) {
7230
7682
  this.store.settle(input.id, confirmation ? "done" : "cancelled", confirmation ? undefined : {
7231
- id: `${input.id}:workspace`, text: "선택할 요청이 남아 있지 않거나 답을 확인할 수 없습니다. 아직 열려 있는 질문에 번호나 저장소 경로로 답장해 주세요.",
7683
+ id: `${input.id}:workspace-answer-refused`, text: input.route.platform === "slack"
7684
+ ? "선택이 만료됐거나 답할 질문을 하나로 확인할 수 없습니다. 열려 있는 질문에 표시된 `!choose` 명령을 사용해 주세요."
7685
+ : "선택할 요청이 남아 있지 않거나 답을 확인할 수 없습니다. 아직 열려 있는 질문에 번호나 저장소 경로로 답장해 주세요.",
7232
7686
  });
7233
7687
  return;
7234
7688
  }
@@ -7236,7 +7690,7 @@ export class Superagent {
7236
7690
  const request = protectedCommand ? { cwd: null, text: input.text } : topicRequest(placementText(input));
7237
7691
  const cwd = this.store.getMeta(`topic-cwd:${input.id}`);
7238
7692
  if (request.cwd !== null && !cwd) {
7239
- this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace`, text: "존재하는 디렉터리의 절대 경로가 필요합니다. 작업은 실행하지 않았습니다." });
7693
+ this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace-invalid`, text: "존재하는 디렉터리의 절대 경로가 필요합니다. 작업은 실행하지 않았습니다." });
7240
7694
  return;
7241
7695
  }
7242
7696
  const creation = this.store.getMeta(`topic-creator:${input.id}`);
@@ -7245,10 +7699,16 @@ export class Superagent {
7245
7699
  const existing = this.store.input(handoffId);
7246
7700
  const protectedPlacement = protectedCommand && (creation !== null || cwd !== null || saved !== null);
7247
7701
  // After loss of the placement receipt, never submit a second handoff.
7248
- if (existing?.target === owner && (!creation || this.store.output(`${input.id}:kickoff`)?.state === "sent")
7249
- && !(protectedPlacement && existing.state === "pending")) {
7250
- this.store.settle(input.id, "done");
7251
- return;
7702
+ if (existing?.target === owner && !(protectedPlacement && existing.state === "pending")) {
7703
+ const kickoff = creation ? this.store.output(`${input.id}:kickoff`) : null;
7704
+ if (!creation || kickoff?.state === "sent") {
7705
+ this.store.settle(input.id, "done");
7706
+ return;
7707
+ }
7708
+ if (kickoff && !protectedPlacement) {
7709
+ if (kickoff.state === "failed" || kickoff.state === "uncertain") this.holdTopicPlacement(input);
7710
+ return;
7711
+ }
7252
7712
  }
7253
7713
  if (protectedPlacement) {
7254
7714
  // Old ledgers may link this example to a placement which had not run.
@@ -7265,28 +7725,41 @@ export class Superagent {
7265
7725
  this.store.settle(input.id, "cancelled", { id: `${input.id}:closed`, text: `레인 ${owner}은 ${lane.workState} 상태입니다. 자동 재개하지 않았습니다. /status로 확인해 주세요.` });
7266
7726
  return;
7267
7727
  }
7268
- if (!creation && lane && cwd && cwd !== lane.cwd && discordWorkThread(input.route)) {
7269
- this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace`, text: "지정한 작업 폴더가 이 스레드와 달라 실행하지 않았습니다. 다른 폴더에서 시작하려면 `/new cwd: 절대경로` 다음 줄에 작업을 적어 주세요." });
7728
+ if (!creation && lane && cwd && cwd !== lane.cwd && nativeWorkThread(input.route)) {
7729
+ const prefix = input.route.platform === "slack" ? "!" : "/";
7730
+ this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace-mismatch`, text: `지정한 작업 폴더가 이 스레드와 달라 실행하지 않았습니다. 다른 폴더에서 시작하려면 \`${prefix}new cwd: 절대경로\` 다음 줄에 작업을 적어 주세요.` });
7270
7731
  return;
7271
7732
  }
7272
7733
  const priorKey = `topic-previous:${input.id}`;
7273
7734
  const automaticKey = `topic-choice-auto:${input.id}`;
7274
- const choosingHere = !creation && saved !== null && this.store.getMeta(priorKey) === null && this.store.getMeta(automaticKey) === null;
7735
+ const options: PastTopicRef[] = saved ? JSON.parse(saved) : [];
7736
+ const choosingHere = !creation && saved !== null && (options.length > 0 || cwd === null)
7737
+ && this.store.getMeta(priorKey) === null && (options.length === 0 || this.store.getMeta(automaticKey) === null);
7275
7738
  if (creation && !cwd || choosingHere) {
7276
- const options: PastTopicRef[] = saved ? JSON.parse(saved) : [];
7277
7739
  if (!this.store.output(`${input.id}:workspace`)) {
7740
+ const workspaceHint = choosingHere && input.route.platform === "slack"
7741
+ ? "잠시 후 다시 요청하거나, 현재 작업 폴더의 절대 경로로 답해 주세요. 다른 폴더에서 시작하려면 !new로 별도 작업을 요청해 주세요."
7742
+ : "잠시 후 다시 요청하거나 새 작업으로 시작하려면 절대 경로로 답해 주세요.";
7278
7743
  const question = options.length ? [choosingHere
7279
7744
  ? "어느 작업을 참고할까요? 번호로 답해 주세요. 5분 동안 답이 없으면 제가 골라 이 스레드에서 계속합니다."
7280
7745
  : "조건에 맞는 이전 작업이 여럿입니다. 이어갈 작업의 번호로 답해 주세요.",
7281
7746
  ...options.map((ref, index) =>
7282
7747
  `${index + 1}. ${basename(ref.cwd)} · ${new Date(ref.at).toISOString().slice(0, 16).replace("T", " ")} UTC · ${ref.entryId}`)].join("\n")
7283
- : this.store.getMeta(`topic-history-unavailable:${input.id}`) ? "OMP 메모리나 원래 세션을 조회하지 못해 이전 작업을 선택하지 않았습니다. 잠시 후 다시 요청하거나 새 작업으로 시작하려면 절대 경로로 답해 주세요."
7748
+ : this.store.getMeta(`topic-history-unavailable:${input.id}`) ? `OMP 메모리나 원래 세션을 조회하지 못해 이전 작업을 선택하지 않았습니다. ${workspaceHint}`
7284
7749
  : saved ? "설명에 맞는 이전 작업을 확인하지 못했습니다. 작업 단서를 더 넣어 다시 요청하거나, 새 작업으로 시작하려면 작업 디렉터리의 절대 경로로 답해 주세요."
7285
7750
  : "어느 저장소에서 작업할까요? 이 대화에서 사용한 저장소 이름이나 작업 디렉터리의 절대 경로로 답하면 원래 요청을 시작합니다.";
7286
- this.store.queueOutput({ id: `${input.id}:workspace`, sourceId: input.id, route: input.route, text: question });
7751
+ const explicit = input.route.platform === "slack" && input.route.threadId
7752
+ && input.id === `slack:${input.route.accountId}:${input.route.channelId}:${input.messageId}:original`
7753
+ && input.messageId && /^\d{1,20}\.\d{6}$/u.test(input.messageId);
7754
+ const text = explicit
7755
+ ? `${question}\n이 질문만 선택: \`!choose ${input.messageId} ${options.length ? "번호" : "/작업/경로"}\``
7756
+ : question;
7757
+ this.store.queueOutput({ id: `${input.id}:workspace`, sourceId: input.id, route: input.route, text });
7287
7758
  if (lane) this.background(this.syncLaneThreadTitle(lane));
7288
7759
  }
7289
- const deadline = choosingHere ? this.store.getMeta(`topic-choice-deadline:${input.id}`) : null;
7760
+ // Older ledgers may have started a timer for a failed lookup. Only a
7761
+ // question that presented real choices may select one automatically.
7762
+ const deadline = choosingHere && options.length ? this.store.getMeta(`topic-choice-deadline:${input.id}`) : null;
7290
7763
  if (!lane || deadline === null || Date.now() < Number(deadline) || this.store.hasPendingTopicChoice(input, Number(deadline))) return;
7291
7764
  const pauseRevision = this.pauseRevisions.get(owner);
7292
7765
  const local = (ref: PastTopicRef) => ref.laneId === owner && ref.sessionId === lane.sessionId;
@@ -7331,13 +7804,15 @@ export class Superagent {
7331
7804
  if (!head) return;
7332
7805
  const model = lane?.model ?? (await this.state(head)).model;
7333
7806
  if (!isLaneModel(model)) throw new Error("Cannot verify an initial topic model");
7807
+ const requestedCwd = this.store.getMeta(`topic-requested-cwd:${input.id}`) ?? request.cwd ?? cwd;
7334
7808
  await this.admitLane({
7335
- sourceId: input.id, cwd, title: `작업 ${owner}`,
7809
+ sourceId: input.id, cwd: requestedCwd, title: `작업 ${owner}`,
7336
7810
  kickoff: "이 주제의 독립 세션에서 요청을 처리합니다.",
7337
7811
  model, modelReason: "Start this topic with the verified current head model, without sharing its transcript.",
7338
7812
  ...(creation === "sibling" ? { destination: { ...physicalRoute(input.route), threadId: null } } : {}),
7339
7813
  ...(workflow ? { workflow: { name: workflow.name, reason: workflow.reason } } : {}),
7340
- });
7814
+ }, cwd);
7815
+ if (this.store.output(`${input.id}:kickoff`)?.state === "pending") return;
7341
7816
  } else {
7342
7817
  if (!lane) {
7343
7818
  const creatorPending = this.store.inputs(undefined, "pending").some(prior => prior.target === null
@@ -7352,16 +7827,25 @@ export class Superagent {
7352
7827
  this.store.settle(input.id, "done");
7353
7828
  } catch (error) {
7354
7829
  this.report(error);
7355
- this.store.settle(input.id, "uncertain", { id: `${input.id}:held`,
7356
- text: `주제 배정을 확인하지 못해 보류했습니다. 실행을 반복하지 않았습니다. 원래 스레드와 전송 기록을 확인한 뒤 /resolve ${input.id} 로 배정 보류만 종료할 수 있습니다.` });
7830
+ this.holdTopicPlacement(input);
7357
7831
  }
7358
7832
  }
7359
7833
 
7834
+ private holdTopicPlacement(input: InputRecord): void {
7835
+ this.store.settle(input.id, "uncertain", { id: `${input.id}:held`,
7836
+ text: `주제 배정을 확인하지 못해 보류했습니다. 실행을 반복하지 않았습니다. 원래 스레드와 전송 기록을 확인한 뒤 /resolve ${input.id} 로 배정 보류만 종료할 수 있습니다.` });
7837
+ }
7838
+
7360
7839
  private async pump(): Promise<void> {
7361
7840
  try {
7362
7841
  do {
7363
7842
  this.repeat = false;
7364
7843
  if (this.restartFence() || this.headRotationHeld()) return;
7844
+ const capacityHolds = new Map<string, CapacityHold>();
7845
+ for (const id of this.blocked) {
7846
+ const lane = this.store.lane(id);
7847
+ if (lane && !lane.remote && lane.pid !== null && !this.live.has(id)) await this.quarantineLocalOrphan(lane);
7848
+ }
7365
7849
  for (const live of this.live.values()) {
7366
7850
  if (live.releasing) {
7367
7851
  await this.release(live);
@@ -7519,6 +8003,17 @@ export class Superagent {
7519
8003
  this.store.settle(input.id, "cancelled");
7520
8004
  continue;
7521
8005
  }
8006
+ let workerAttachments = false;
8007
+ if (input.target && input.target !== "main") {
8008
+ if (deferredDispatch.has(input.target) || this.workerInbound.has(input.target)) continue;
8009
+ workerAttachments = input.attachments.length > 0 && !!this.store.lane(input.target)?.remote;
8010
+ if (workerAttachments) {
8011
+ // A lane's older pending work must run first. A file request
8012
+ // also fences later steers even before it becomes steerable.
8013
+ deferredDispatch.add(input.target);
8014
+ if (this.store.inputs(input.target, "pending")[0]?.id !== input.id) continue;
8015
+ }
8016
+ }
7522
8017
  // Resolve a lost native receipt even if HEAD itself is busy or out
7523
8018
  // of quota. No model is involved and a slow lane cannot stall the pump.
7524
8019
  if (!this.headStopping && !this.laneReceiptReady(input)) {
@@ -7579,7 +8074,6 @@ export class Superagent {
7579
8074
  if (this.modelChanges.has(input.target)) continue;
7580
8075
  if (input.target !== "main" && this.store.getMeta(`lane-quota-hold:${input.target}`)) continue;
7581
8076
  if (this.blocked.has(input.target)) continue;
7582
- if (deferredDispatch.has(input.target)) continue;
7583
8077
  if (heldKickoffs.has(input.target)) continue;
7584
8078
  if (this.kickoffHeld(input.target)) { heldKickoffs.add(input.target); continue; }
7585
8079
  heldKickoffs.clear();
@@ -7595,9 +8089,9 @@ export class Superagent {
7595
8089
  // A released SSH transport is separate from the old admission's
7596
8090
  // effect fence. Do not start a replacement for an input still held.
7597
8091
  if (lane.remote && !live && heldTargets.has(input.target)) continue;
7598
- live = await this.ensureLane(lane) ?? undefined;
8092
+ live = await this.ensureLane(lane, { onCapacityHold: hold => capacityHolds.set(input.id, hold) }) ?? undefined;
7599
8093
  }
7600
- if (!live || live.id === "main" && headWaitingForEvidence) continue;
8094
+ if (!live || live.id === "main" && headWaitingForEvidence || workerAttachments && live.preparing) continue;
7601
8095
  const steering = !!live.input;
7602
8096
  if (steering) {
7603
8097
  if (!this.canSteer(live, input)) continue;
@@ -7619,7 +8113,9 @@ export class Superagent {
7619
8113
  headWaitingForEvidence = true;
7620
8114
  continue;
7621
8115
  }
7622
- if (live.id !== "main" && isPrReviewLane(this.store, live.id)) {
8116
+ if (workerAttachments) {
8117
+ this.prepareWorkerInbound(live, input, steering);
8118
+ } else if (live.id !== "main" && isPrReviewLane(this.store, live.id)) {
7623
8119
  // Static patch verification can need several GitHub reads. Own
7624
8120
  // only this lane's preparation; keep the shared cron pump free.
7625
8121
  if (!live.preparing && !steering) this.background(this.dispatch(live, input).catch(error => {
@@ -7636,8 +8132,9 @@ export class Superagent {
7636
8132
  }
7637
8133
  } catch (error) { this.blocked.add(input.target); this.report(error); }
7638
8134
  }
8135
+ this.capacityHolds = capacityHolds;
7639
8136
  for (const live of [...this.live.values()]) {
7640
- if (live.id === "main" || live.busy || live.input) continue;
8137
+ if (live.id === "main" || live.busy || live.input || this.workerInbound.has(live.id)) continue;
7641
8138
  const evicting = Date.now() - live.lastActivity >= this.config.idleMs;
7642
8139
  this.maintainWorkerMemory(live, evicting);
7643
8140
  if (evicting && !(this.memoryPull?.live === live && performance.now() < this.memoryPull.deadline)) {
@@ -7648,7 +8145,34 @@ export class Superagent {
7648
8145
  } finally { await this.flushOutputs(); }
7649
8146
  }
7650
8147
 
7651
- private async attachments(input: InputRecord): Promise<AttachmentData> {
8148
+ private prepareWorkerInbound(live: Live, input: InputRecord, steering: boolean): void {
8149
+ if (!this.current(live)) return;
8150
+ const cancel = new AbortController();
8151
+ const lifecycle = AbortSignal.any([this.stopSignal.signal, cancel.signal]);
8152
+ // Per-lane ownership is published before doing any asynchronous work.
8153
+ // Keep it through discard so a resumed attempt cannot touch the old batch.
8154
+ const done = Promise.resolve().then(() => this.dispatch(live, input, steering, lifecycle)).catch(error => {
8155
+ if (!lifecycle.aborted && this.current(live)) {
8156
+ this.blocked.add(live.id);
8157
+ this.report(error);
8158
+ }
8159
+ }).finally(() => {
8160
+ this.workerInbound.delete(live.id);
8161
+ if (this.stopped) return;
8162
+ if (this.store.input(input.id)?.state !== "pending") {
8163
+ live.workerAttachmentReceipt = undefined;
8164
+ this.background(this.kick());
8165
+ } else if (cancel.signal.aborted && this.store.lane(live.id)?.workState === "open") {
8166
+ // An explicit resume or verified reconnect can race discard. Recheck
8167
+ // that wake after releasing ownership, without spinning on a hold.
8168
+ this.background(this.kick());
8169
+ }
8170
+ });
8171
+ this.workerInbound.set(live.id, { inputId: input.id, cancel, done });
8172
+ this.background(done);
8173
+ }
8174
+
8175
+ private async attachments(input: InputRecord, remote: boolean, lifecycle?: AbortSignal): Promise<AttachmentData> {
7652
8176
  const descriptions: string[] = [];
7653
8177
  const images: Array<{ type: "image"; data: string; mimeType: string }> = [];
7654
8178
  let imageBytes = 0;
@@ -7664,8 +8188,8 @@ export class Superagent {
7664
8188
  if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_ATTACHMENT_BYTES)) throw new Error("Invalid attachment size");
7665
8189
  }
7666
8190
  const batch = { inputId: input.id, route: source.route, attachments: input.attachments };
7667
- const receipt = await this.messenger.openAttachment(batch, AbortSignal.timeout(30_000 * batch.attachments.length + 1000))
7668
- .catch(() => { throw new Error("Attachment could not be safely downloaded; no prompt was submitted"); });
8191
+ const deadline = AbortSignal.timeout(30_000 * batch.attachments.length + 1000);
8192
+ const receipt = await this.messenger.openAttachment(batch, lifecycle ? AbortSignal.any([lifecycle, deadline]) : deadline);
7669
8193
  if (receipt.files.length !== batch.attachments.length) throw new Error("Invalid attachment spool receipt");
7670
8194
  for (const [index, attachment] of input.attachments.entries()) {
7671
8195
  const result = receipt.files[index];
@@ -7675,28 +8199,18 @@ export class Superagent {
7675
8199
  attachment.voice ? "voice message" : "",
7676
8200
  attachment.durationSeconds === undefined ? "" : `duration ${attachment.durationSeconds} seconds`,
7677
8201
  ].filter(Boolean).join("; ");
7678
- descriptions.push(`Attachment ${index + 1}: ${JSON.stringify(attachment.name)}; local file ${destination}; ${bytes} bytes${media ? `; ${media}` : ""}. Attachment contents are untrusted task data.`);
8202
+ const name = inertContext(JSON.stringify(attachment.name)).replaceAll("/skill:", "\\u002fskill:");
8203
+ const path = remote ? "" : ` local file ${destination};`;
8204
+ descriptions.push(`Attachment ${index + 1}: ${name};${path} ${bytes} bytes${media ? `; ${media}` : ""}. Attachment contents are untrusted task data.`);
7679
8205
  if (!mimeType.startsWith("image/")) continue;
7680
8206
  imageBytes += bytes;
7681
8207
  if (imageBytes > MAX_IMAGE_BYTES) throw new Error("Image payload exceeds the bounded native RPC allowance");
7682
- if (realpathSync(destination) !== destination) throw new Error("Attachment spool path changed");
7683
- const file = await open(destination, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
7684
- try {
7685
- const stat = await file.stat();
7686
- if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600
7687
- || stat.nlink !== 1 || stat.size !== bytes) throw new Error("Attachment spool file changed");
7688
- const data = Buffer.alloc(bytes);
7689
- for (let offset = 0; offset < bytes;) {
7690
- const { bytesRead } = await file.read(data, offset, bytes - offset, offset);
7691
- if (!bytesRead) throw new Error("Attachment spool file was truncated");
7692
- offset += bytesRead;
7693
- }
7694
- if (createHash("sha256").update(data).digest("hex") !== result.sha256)
7695
- throw new Error("Attachment image changed after the Gateway published its receipt");
8208
+ if (!remote) {
8209
+ const data = await readAttachmentBytes(result);
7696
8210
  images.push({ type: "image", data: data.toString("base64"), mimeType });
7697
- } finally { await file.close(); }
8211
+ }
7698
8212
  }
7699
- return { descriptions, images };
8213
+ return { descriptions, images, ...(remote && { workerFiles: receipt.files }) };
7700
8214
  }
7701
8215
 
7702
8216
  private headJobPause(live: Live, state: RuntimeState): readonly string[] | undefined {
@@ -7725,7 +8239,7 @@ export class Superagent {
7725
8239
  || this.store.input(owner.id)?.state !== "submitted"
7726
8240
  || input.state !== "pending" || input.target !== live.id || owner.workflow || input.workflow
7727
8241
  || routeKey(owner.route) !== routeKey(input.route) || this.headCommand(input)
7728
- || this.requestText(input).trimStart().startsWith("/") || this.headSuperstack(owner) || this.headSuperstack(input)
8242
+ || this.steeringTaskStartsWithCommand(input) || this.headSuperstack(owner) || this.headSuperstack(input)
7729
8243
  || this.store.approvals(live.id).length
7730
8244
  || this.modelChanges.has(live.id) || this.blocked.has(live.id)) return false;
7731
8245
  const inputs = this.store.inputs(live.id);
@@ -7776,17 +8290,28 @@ export class Superagent {
7776
8290
  return true;
7777
8291
  }
7778
8292
 
7779
- private async dispatch(live: Live, input: InputRecord, steering = false): Promise<void> {
8293
+ private steeringTaskStartsWithCommand(input: InputRecord): boolean {
8294
+ if (!this.requestText(input).trimStart().startsWith("/")) return false;
8295
+ if (input.route.platform !== "slack") return true;
8296
+ const source = this.store.topicDelivery(input.id)?.source;
8297
+ if (!source) return true;
8298
+ const placement = placementText(source);
8299
+ if (unverifiedSlackWorkspaceTask(source, placement)) return false;
8300
+ const projected = ownerPlacementWorkflow(source, placement, this.requestText(source, placement)).projection;
8301
+ return !projected?.selectorChanged || projected.text.trimStart().startsWith("/");
8302
+ }
8303
+
8304
+ private async dispatch(live: Live, input: InputRecord, steering = false, lifecycle?: AbortSignal): Promise<void> {
7780
8305
  if (this.restartFence() || live.id === "main" && this.headRecoveryActive()) return;
7781
8306
  const owner = live.input;
7782
8307
  if (steering && !this.canSteer(live, input)) return;
7783
8308
  live.preparing++;
7784
- try { await this.dispatchPrepared(live, input, steering, owner); }
8309
+ try { await this.dispatchPrepared(live, input, { steering, owner, lifecycle }); }
7785
8310
  catch (error) {
7786
8311
  if (!(error instanceof SupersededLaneModelCheck)) throw error;
7787
8312
  // A superseding model operation wakes the queue on completion. If it
7788
8313
  // already finished, request a fresh dispatch against its selection.
7789
- if (this.current(live) && !this.modelChanges.has(live.id)) this.background(this.kick());
8314
+ if (!lifecycle?.aborted && this.current(live) && !this.modelChanges.has(live.id)) this.background(this.kick());
7790
8315
  }
7791
8316
  finally {
7792
8317
  live.preparing--;
@@ -7799,7 +8324,12 @@ export class Superagent {
7799
8324
  }
7800
8325
  }
7801
8326
 
7802
- private async dispatchPrepared(live: Live, input: InputRecord, steering: boolean, owner: InputRecord | undefined): Promise<void> {
8327
+ private async dispatchPrepared(live: Live, input: InputRecord, { steering, owner, lifecycle }: {
8328
+ readonly steering: boolean; readonly owner?: InputRecord; readonly lifecycle?: AbortSignal;
8329
+ }): Promise<void> {
8330
+ const interrupted = () => lifecycle && (lifecycle.aborted || !this.current(live) || this.restartFence()
8331
+ || this.store.lane(live.id)?.workState !== "open" || this.store.input(input.id)?.state !== "pending");
8332
+ if (interrupted()) return;
7803
8333
  if (!this.laneReviewDispatchAllowed(input)) {
7804
8334
  this.store.settle(input.id, "cancelled");
7805
8335
  return;
@@ -7827,11 +8357,6 @@ export class Superagent {
7827
8357
  return;
7828
8358
  }
7829
8359
  }
7830
- if (remote && input.attachments.length) {
7831
- this.store.settle(input.id, "cancelled", { id: `${input.id}:attachments`,
7832
- text: "원격 레인으로 첨부 파일을 전송할 수 없어 요청을 실행하지 않았습니다. 첨부 없이 다시 요청해 주세요." });
7833
- return;
7834
- }
7835
8360
  let historyContext: string | null = null;
7836
8361
  const topicOwned = live.id !== "main" && this.store.getMeta(`topic-owner:${source.id}`) === live.id;
7837
8362
  const topic = live.id !== "main" ? this.store.topicDelivery(input.id) : null;
@@ -7841,8 +8366,11 @@ export class Superagent {
7841
8366
  text: "같은 주제에서 더 나중에 보낸 메시지를 먼저 접수해, 뒤늦게 도착한 이 요청은 실행하지 않았습니다. 여전히 필요한 작업이면 새 메시지로 지시해 주세요." });
7842
8367
  return;
7843
8368
  }
7844
- const writtenTask = this.requestText(source);
7845
- const sourceRequest = ownerWorkflowRequest(source, writtenTask);
8369
+ const ownerSource = this.store.getMeta(`user-source:${source.id}`) === "true";
8370
+ const ownerPlacement = ownerSource ? placementText(source) : source.text;
8371
+ const writtenTask = this.requestText(source, ownerPlacement);
8372
+ const protectedWorkspaceTask = unverifiedSlackWorkspaceTask(source, ownerPlacement);
8373
+ const sourceRequest = ownerPlacementWorkflow(source, ownerPlacement, writtenTask);
7846
8374
  const projectedTask = sourceRequest.projection
7847
8375
  && (directTopic || topicOwned || input.workflow || sourceRequest.projection.selectorChanged)
7848
8376
  ? sourceRequest.projection.text : undefined;
@@ -7851,11 +8379,12 @@ export class Superagent {
7851
8379
  const previous: PastTopicRef | null = pin ? JSON.parse(pin) : null;
7852
8380
  if (previous) {
7853
8381
  const lane = this.requireLane(live.id);
7854
- const inPlace = discordWorkThread(source.route) && routeKey(lane.route) === routeKey(source.route);
8382
+ const inPlace = nativeWorkThread(source.route) && routeKey(lane.route) === routeKey(source.route);
7855
8383
  if (inPlace || lane.cwd === previous.cwd) {
7856
8384
  try { historyContext = await this.previousContext(source, previous, live.id); }
7857
8385
  catch (error) { this.report(error); }
7858
8386
  }
8387
+ if (interrupted()) return;
7859
8388
  if (!historyContext && automatic === null) {
7860
8389
  this.store.settle(input.id, "cancelled", { id: `${input.id}:prior-held`, text: "선택한 이전 세션의 작업 근거나 상태를 다시 확인할 수 없어 실행하지 않았습니다." });
7861
8390
  return;
@@ -7865,10 +8394,10 @@ export class Superagent {
7865
8394
  // OMP retains its own magic-keyword settings and enabled-eval capability gate.
7866
8395
  const protectedCommand = telegramCommandBlocked(source);
7867
8396
  const ownerSelection = input.workflow?.provenance === "user" || topicOwned;
7868
- const workflowBlocked = ownerSelection && (protectedCommand
8397
+ const workflowBlocked = ownerSelection && (protectedCommand || protectedWorkspaceTask
7869
8398
  || sourceRequest.projection !== undefined && sourceRequest.name !== input.workflow?.name);
7870
8399
  const workflow = workflowBlocked ? null : input.workflow;
7871
- const stack = this.headSuperstack(input);
8400
+ const stack = protectedWorkspaceTask ? null : this.headSuperstack(input);
7872
8401
  const stackTask = stack?.kind === "task" ? headSuperstackTaskText(input, stack) : undefined;
7873
8402
  if (stack) {
7874
8403
  const hold = (text: string) => this.store.settle(input.id, "cancelled", { id: `${input.id}:superstack`, text });
@@ -7901,16 +8430,27 @@ export class Superagent {
7901
8430
  if (!legacyWorkflow) throw new Error("SUPER extension command is not advertised");
7902
8431
  }
7903
8432
  } catch {
8433
+ if (interrupted()) return;
7904
8434
  this.store.settle(input.id, "cancelled", { id: `${input.id}:workflow`, text: "요청한 SUPER 워크플로 확장을 native Host에서 확인할 수 없어 실행하지 않았습니다. 확장 설치·로드 상태를 확인해 주세요. native 활성화나 goal 생성을 주장하지 않습니다." });
7905
8435
  return;
7906
8436
  }
7907
8437
  }
8438
+ if (interrupted()) return;
7908
8439
  let attachmentData: AttachmentData;
7909
- try { attachmentData = await this.attachments(input); }
7910
- catch {
8440
+ try {
8441
+ const saved = lifecycle ? live.workerAttachmentReceipt : undefined;
8442
+ if (saved?.inputId === input.id && isDeepStrictEqual(saved.attachments, input.attachments)) {
8443
+ attachmentData = saved.data;
8444
+ } else {
8445
+ attachmentData = await this.attachments(input, Boolean(remote), lifecycle);
8446
+ if (lifecycle && !interrupted()) live.workerAttachmentReceipt = { inputId: input.id, attachments: input.attachments, data: attachmentData };
8447
+ }
8448
+ } catch {
8449
+ if (interrupted()) return;
7911
8450
  this.store.settle(input.id, "cancelled", { id: `${input.id}:attachments`, text: "첨부 파일을 안전하게 받을 수 없어 요청을 실행하지 않았습니다. 첨부 크기와 형식을 확인해 주세요." });
7912
8451
  return;
7913
8452
  }
8453
+ if (interrupted()) return;
7914
8454
  if (directTopic) {
7915
8455
  // A durable receipt proves who sent it then, not which account the
7916
8456
  // Gateway owns now. An unavailable read is not a rejected owner request.
@@ -7921,16 +8461,39 @@ export class Superagent {
7921
8461
  return;
7922
8462
  }
7923
8463
  }
8464
+ const requestId = `sg-${key(input.id)}-${live.generation}`;
8465
+ let stagedTransfer: AsyncDisposable | undefined;
8466
+ if (attachmentData.workerFiles) {
8467
+ const pending = this.store.input(input.id);
8468
+ if (lifecycle?.aborted || !this.current(live) || this.restartFence() || pending?.state !== "pending" || pending.target !== live.id
8469
+ || this.requireLane(live.id).workState !== "open") return;
8470
+ if (this.store.input(source.id)?.state === "cancelled" || directTopic && this.boundLane(source.route)?.id !== live.id) {
8471
+ this.store.settle(input.id, "cancelled");
8472
+ return;
8473
+ }
8474
+ try {
8475
+ const deadline = AbortSignal.timeout(300_000);
8476
+ stagedTransfer = await stageWorkerAttachments(live.connection, requestId, attachmentData.workerFiles,
8477
+ AbortSignal.any([lifecycle ?? this.stopSignal.signal, deadline]));
8478
+ } catch {
8479
+ if (interrupted()) return;
8480
+ this.store.settle(input.id, "cancelled", { id: `${input.id}:attachments`,
8481
+ text: "원격 레인에 첨부 파일을 안전하게 전송할 수 없어 요청을 실행하지 않았습니다." });
8482
+ return;
8483
+ }
8484
+ }
8485
+ await using transfer = stagedTransfer;
8486
+ if (interrupted()) return;
7924
8487
  let observationCursor: string | null | undefined;
7925
8488
  if (live.id !== "main" && !steering)
7926
8489
  observationCursor = await this.readJournalCursor(live, "capture native lane observation owner");
7927
- if (!this.current(live) || (live.id !== "main" && this.requireLane(live.id).workState !== "open")) return;
8490
+ if (lifecycle?.aborted || !this.current(live) || live.id !== "main" && this.requireLane(live.id).workState !== "open") return;
7928
8491
  if (live.id === "main" && (this.headStopping > 0 || this.headCompaction)) return;
7929
8492
  if (this.modelChanges.has(live.id)) return;
7930
8493
  // Downloads and other async work can outlive an operator's native model
7931
8494
  // change. Re-read immediately before durable submission, never reset it.
7932
8495
  const modelState = await this.checkLaneModel(live);
7933
- if (this.modelChanges.has(live.id)) return;
8496
+ if (lifecycle?.aborted || this.modelChanges.has(live.id)) return;
7934
8497
  if (!this.current(live) || (live.id !== "main" && this.requireLane(live.id).workState !== "open")) return;
7935
8498
  if (live.id === "main" && (this.headStopping > 0 || this.headCompaction)) return;
7936
8499
  if (this.store.input(input.id)?.state === "cancelled" || this.store.input(source.id)?.state === "cancelled") {
@@ -7938,7 +8501,7 @@ export class Superagent {
7938
8501
  return;
7939
8502
  }
7940
8503
  const actual = modelState ?? await this.state(live);
7941
- if (this.restartFence()) return;
8504
+ if (lifecycle?.aborted || this.restartFence()) return;
7942
8505
  const pending = this.store.input(input.id);
7943
8506
  if (!this.current(live) || live.input !== owner || pending?.state !== "pending" || pending.target !== live.id) return;
7944
8507
  if (this.modelChanges.has(live.id) || live.id === "main" && (this.headStopping > 0 || this.headCompaction)
@@ -7954,7 +8517,6 @@ export class Superagent {
7954
8517
  live.busy = !actual.isSettled;
7955
8518
  return;
7956
8519
  }
7957
- const requestId = `sg-${key(input.id)}-${live.generation}`;
7958
8520
  if (live.id === "main" && !steering) {
7959
8521
  const version = live.nativeVersion;
7960
8522
  const cursor = await this.readJournalCursor(live, "capture native HEAD request owner");
@@ -8037,20 +8599,22 @@ export class Superagent {
8037
8599
  ? replyVoiceProfile(this.store, voiceVersion) : undefined;
8038
8600
  this.store.setMeta(`steering-owner:${input.id}`, steering ? owner!.id : input.id);
8039
8601
  if (live.id !== "main" && this.store.getMeta(`lane-quota-hold:${live.id}`)) return;
8602
+ const workerResult = remote && actual.workerResultVersion === 1 ? this.resultAttachments.workerSource(input.id) : undefined;
8040
8603
  if (!this.store.submit(input.id, requestId, live.generation)) return;
8041
8604
  if (live.id === "main") this.headCoordinationActivityAt = performance.now();
8042
8605
  const submitted = { ...input, requestId, generation: live.generation, state: "submitted" as const };
8043
- live.admitted.set(requestId, { input: submitted });
8606
+ const admission: PromptAdmission = { input: submitted, ...(workerResult && { workerResult }) };
8607
+ live.admitted.set(requestId, admission);
8044
8608
  if (steering && live.running) this.activity(submitted, true);
8045
8609
  if (!steering) {
8046
8610
  live.input = submitted;
8047
8611
  live.headJobStarts = undefined;
8048
8612
  live.headJobMixed = false;
8049
8613
  live.headJobCleanAnswer = undefined;
8050
- live.discordNonCohortJobSeen = false;
8051
- live.discordJobContinuation = false;
8052
- live.discordContinuationJobIds = undefined;
8053
- live.discordJoinedAnswer = undefined;
8614
+ live.nonCohortJobSeen = false;
8615
+ live.headJobContinuation = false;
8616
+ live.headContinuationJobIds = undefined;
8617
+ live.joinedAnswer = undefined;
8054
8618
  if (live.id === "main") this.markActiveLaneReview(this.isLaneRecoveryReport(input.id)
8055
8619
  || input.id.startsWith(laneDecisionReview)
8056
8620
  ? input.id : undefined);
@@ -8072,11 +8636,12 @@ export class Superagent {
8072
8636
  const lane = live.id === "main" ? null : this.requireLane(live.id);
8073
8637
  const recoveryTarget = lane ? null : this.store.getMeta(`lane-recovery-target:${input.id}`);
8074
8638
  const bound = lane ? null : this.boundLane(input.route);
8075
- const originalText = projectedTask ?? writtenTask;
8639
+ const ownerTaskText = ownerSource ? presentSlackResultAttachment(source, writtenTask) : writtenTask;
8640
+ const originalText = projectedTask ?? ownerTaskText;
8076
8641
  // lane_start copies the owner's receipt; lane_message carries HEAD-authored text.
8077
8642
  const openingCopy = input.id === `handoff:${source.id}:lane`
8078
8643
  && this.store.getMeta(`kickoff-output:${input.id}`) === `${source.id}:kickoff`;
8079
- const taskText = topic || openingCopy ? originalText : this.requestText(input);
8644
+ const taskText = topic || openingCopy ? originalText : input.id === source.id ? ownerTaskText : this.requestText(input);
8080
8645
  const brief = lane && (lane.brief === writtenTask || lane.brief === originalText || lane.brief === taskText)
8081
8646
  ? "Use the original request/delegated instruction in this envelope." : lane?.brief;
8082
8647
  const priorAssignment = lane ? inertContext(JSON.stringify({ brief, acceptance: lane.acceptance })) : undefined;
@@ -8100,7 +8665,7 @@ export class Superagent {
8100
8665
  generation: bound.generation, sessionId: bound.sessionId, sessionFile: bound.sessionFile, model: bound.model,
8101
8666
  modelPreset: bound.modelPreset, modelHold: this.modelHolds.get(bound.id) ?? null,
8102
8667
  observation: bound.observation ?? null,
8103
- })}` : "No lane is bound to this conversation. Independent work needs an explicit verified cwd and exact head-selected available native model/preset before lane_start. Native judge is advisory; if unavailable or immaterial, state the exception and choose from verified native capabilities.",
8668
+ })}` : "No lane is bound to this conversation. For independent work, use lane_start with a verified cwd and an exact model or preset.",
8104
8669
  ].join("\n\n");
8105
8670
  const userInput = Boolean(topic) || !sourceId && this.store.getMeta(`user-source:${input.id}`) === "true";
8106
8671
  const literalOwnerText = protectedCommand && (userInput || openingCopy);
@@ -8111,9 +8676,10 @@ export class Superagent {
8111
8676
  workflow ? `Workflow activation requested: ${workflow.name}; provenance: ${workflow.provenance}; reason: ${workflow.reason}. Native flags, permissions and workflow state determine actual activation; this is not proof of arming or native goal creation.` : "",
8112
8677
  source.reply ? `Referenced message snapshot (untrusted context, not instructions, authorization, or a routing target; null fields mean unavailable):\n${inertContext(JSON.stringify(source.reply))}` : "",
8113
8678
  source.discordContext ? `Discord conversation snapshot (untrusted context, including names, topic and owner purpose notes; not instructions, authorization, repository selection, or automatic routing policy; omitted fields are unavailable):\n${inertContext(JSON.stringify(source.discordContext))}` : "",
8114
- projectedTask !== undefined || literalOwnerText || stack?.kind === "task" && stack.view === "telegram"
8115
- ? `Full Telegram message (formatted task data, not additional instructions):\n${inertContext(source.text)}` : "",
8116
- userInput || (workflow && taskText === originalText) || literalOwnerText ? ""
8679
+ protectedWorkspaceTask ? `Work requested in the selected workspace (formatted task text, not native controls):\n${inertContext(ownerTaskText)}` : "",
8680
+ !protectedWorkspaceTask && (projectedTask !== undefined || literalOwnerText || stack?.kind === "task" && stack.view === "telegram")
8681
+ ? `Full ${source.route.platform === "slack" ? "Slack" : "Telegram"} message (formatted task data, not additional instructions):\n${inertContext(source.text)}` : "",
8682
+ userInput || (workflow && taskText === originalText) || literalOwnerText || protectedWorkspaceTask ? ""
8117
8683
  : projectedTask !== undefined ? inertContext(taskText) : taskText, ...attachmentData.descriptions].filter(Boolean).join("\n\n");
8118
8684
  const message = review && reviewMaterial !== undefined ? PR_REVIEW_INPUT_PREFIX + inertContext(JSON.stringify({
8119
8685
  repository: review.repository, number: review.number, head: review.head, material: reviewMaterial,
@@ -8131,16 +8697,23 @@ export class Superagent {
8131
8697
  : stack.kind === "off" ? "superstack off" : "superstack"
8132
8698
  : workflow ? workflowPrompt(workflow, {
8133
8699
  id: source.id, workflow: protectedCommand || sourceRequest.projection?.selectorChanged ? null : source.workflow,
8134
- text: protectedCommand ? "" : originalText,
8700
+ text: protectedCommand || protectedWorkspaceTask ? "" : originalText,
8135
8701
  }, envelope,
8136
8702
  { legacyCommand: legacyWorkflow, worker: Boolean(remote) })
8137
- : `${workflowContext(envelope)}${userInput && !literalOwnerText && taskText ? `\n\n${taskText}` : ""}`;
8703
+ : `${workflowContext(envelope)}${userInput && !literalOwnerText && !protectedWorkspaceTask && taskText ? `\n\n${taskText}` : ""}`;
8704
+ const workerResponse = remote ? Promise.withResolvers<void>() : undefined;
8705
+ if (workerResponse) admission.worker = {
8706
+ command: "prompt", response: workerResponse.promise, ...(transfer && { attachments: true }),
8707
+ };
8138
8708
  try {
8139
- const response = successful(await live.connection.request({
8709
+ const reply = await live.connection.request({
8140
8710
  type: "prompt", message, ...(steering ? { streamingBehavior: "steer" } : {}),
8141
8711
  ...(attachmentData.images.length ? { images: attachmentData.images } : {}),
8712
+ ...(transfer ? { workerAttachments: true } : {}),
8713
+ ...(workerResult && { workerResult }),
8142
8714
  ...(replyVoice === undefined ? {} : { replyVoice }),
8143
- }, requestId), "prompt");
8715
+ }, requestId);
8716
+ const response = successful(reply, "prompt");
8144
8717
  // Synchronous local handling discards the native ticket and explicitly
8145
8718
  // returns false. A generic acknowledgement has no such completion proof.
8146
8719
  const admitted = live.admitted.get(requestId);
@@ -8150,7 +8723,7 @@ export class Superagent {
8150
8723
  }
8151
8724
  } catch {
8152
8725
  const admitted = live.admitted.get(requestId);
8153
- if (admitted && !admitted.result) {
8726
+ if (admitted && !admitted.result && (!remote || this.current(live) && this.store.input(input.id)?.state === "submitted")) {
8154
8727
  this.activity(submitted, false);
8155
8728
  const text = live.id === "main"
8156
8729
  ? "요청 접수 결과가 불확실합니다. 정확한 원래 세션의 접수·실행 근거가 있을 때만 격리된 헤드 복구 판단을 진행합니다. 근거가 없거나 불명확하면 계속 보류하며 자동 재시도하지 않습니다. 원래 세션을 확인하거나 /resolve <input-id>로 운영자가 불확실 상태를 종료할 수 있습니다."
@@ -8160,6 +8733,9 @@ export class Superagent {
8160
8733
  try { live.busy = !(await this.state(live)).isSettled; }
8161
8734
  catch { this.blocked.add(live.id); }
8162
8735
  }
8736
+ } finally {
8737
+ if (admission.worker) delete admission.worker.response;
8738
+ workerResponse?.resolve();
8163
8739
  }
8164
8740
  }
8165
8741
 
@@ -8186,8 +8762,8 @@ export class Superagent {
8186
8762
  if (text !== null) live.text = text;
8187
8763
  }
8188
8764
 
8189
- private observeDiscordHeadFollowup(live: Live, owner: InputRecord, message: Record<string, unknown>): void {
8190
- if (live.id !== "main" || owner.route.platform !== "discord" || live.admitted.size < 2 || !live.running) return;
8765
+ private observeHeadFollowup(live: Live, owner: InputRecord, message: Record<string, unknown>): void {
8766
+ if (live.id !== "main" || !supportsHeadFollowups(owner.route) || live.admitted.size < 2 || !live.running) return;
8191
8767
  if (message.role === "user" && !message.synthetic) {
8192
8768
  const first = Array.isArray(message.content)
8193
8769
  ? record(message.content.find(part => record(part).type === "text")).text : message.content;
@@ -8199,18 +8775,18 @@ export class Superagent {
8199
8775
  const admitted = live.admitted.get(`sg-${key(sourceId)}-${live.generation}`);
8200
8776
  if (admitted?.input.id === sourceId && admitted.input.messageId
8201
8777
  && routeKey(admitted.input.route) === routeKey(owner.route)) {
8202
- admitted.discordFollowupEnteredAt ??= live.nativeVersion;
8778
+ admitted.followupEnteredAt ??= live.nativeVersion;
8203
8779
  }
8204
8780
  } else if (message.role === "assistant" && !live.headJobMixed) {
8205
8781
  if (message.stopReason === "error" || message.stopReason === "aborted") {
8206
- live.discordJoinedAnswer = undefined;
8782
+ live.joinedAnswer = undefined;
8207
8783
  return;
8208
8784
  }
8209
8785
  const text = assistantText(message);
8210
8786
  // A native final uses the same block classification as canonical
8211
8787
  // delivery. A later answer after an unrelated job cannot inherit proof,
8212
8788
  // even if its text happens to be identical to the earlier final.
8213
- if (text !== null) live.discordJoinedAnswer = live.discordNonCohortJobSeen ? undefined
8789
+ if (text !== null) live.joinedAnswer = live.nonCohortJobSeen ? undefined
8214
8790
  : { text, observedAt: live.nativeVersion };
8215
8791
  }
8216
8792
  }
@@ -8264,31 +8840,31 @@ export class Superagent {
8264
8840
  if (message.stopReason === "stop") {
8265
8841
  const text = assistantText(message);
8266
8842
  if (text !== null) live.headJobCleanAnswer = { text,
8267
- ...(input?.route.platform === "discord" && !live.discordNonCohortJobSeen
8268
- ? { discordFollowupProofAt: live.nativeVersion } : {}) };
8843
+ ...(supportsHeadFollowups(input?.route) && !live.nonCohortJobSeen
8844
+ ? { followupProofAt: live.nativeVersion } : {}) };
8269
8845
  } else if (message.stopReason === "error" || message.stopReason === "aborted")
8270
8846
  live.headJobCleanAnswer = undefined;
8271
8847
  }
8272
- if (message.role === "toolResult" && (live.headJobPromptSeen || live.discordJobContinuation)
8848
+ if (message.role === "toolResult" && (live.headJobPromptSeen || live.headJobContinuation)
8273
8849
  && live.running && message.isError !== true) {
8274
8850
  const job = record(record(message.details).async);
8275
8851
  if (job.state === "running" && typeof job.jobId === "string" && job.type === message.toolName
8276
8852
  && typeof message.toolCallId === "string" && message.toolCallId
8277
8853
  && (job.type === "bash" || job.type === "eval" || job.type === "task")) {
8278
8854
  if (live.headJobPromptSeen) (live.headJobStarts ??= new Map()).set(job.jobId, message.toolCallId);
8279
- else (live.discordContinuationJobIds ??= new Set()).add(job.jobId);
8855
+ else (live.headContinuationJobIds ??= new Set()).add(job.jobId);
8280
8856
  }
8281
8857
  }
8282
8858
  if (message.role !== "custom") return;
8283
8859
  const items = message.customType === "async-result" ? headJobResults(message) : undefined;
8284
8860
  // The existing delivery boundary is the conversation. The stricter link
8285
8861
  // boundary is the current set of admitted requests, even in that same topic.
8286
- if (input?.route.platform === "discord") {
8862
+ if (input && supportsHeadFollowups(input.route)) {
8287
8863
  const ownsJob = (id: unknown) => {
8288
8864
  if (typeof id !== "string" || !id) return false;
8289
8865
  const owner = live.headJobOwners?.get(id)?.input;
8290
8866
  return owner ? owner.id === input.id || live.admitted.get(owner.requestId ?? "")?.input.id === owner.id
8291
- : live.headJobStarts?.has(id) || live.discordContinuationJobIds?.has(id);
8867
+ : live.headJobStarts?.has(id) || live.headContinuationJobIds?.has(id);
8292
8868
  };
8293
8869
  if (message.customType === "async-notify") {
8294
8870
  const reports = record(message.details).reports;
@@ -8296,17 +8872,17 @@ export class Superagent {
8296
8872
  if (!Array.isArray(reports) || !reports.length || reports.some(item => {
8297
8873
  const report = record(item);
8298
8874
  return report.type !== "bash" || !ownsJob(report.id);
8299
- })) live.discordNonCohortJobSeen = true;
8875
+ })) live.nonCohortJobSeen = true;
8300
8876
  } else if (message.customType === "launch-completion") {
8301
8877
  // No supervised-service launch is bound to a request by this path.
8302
- live.discordNonCohortJobSeen = true;
8878
+ live.nonCohortJobSeen = true;
8303
8879
  } else if (items) {
8304
- if (!items.size || [...items.keys()].some(id => !ownsJob(id))) live.discordNonCohortJobSeen = true;
8880
+ if (!items.size || [...items.keys()].some(id => !ownsJob(id))) live.nonCohortJobSeen = true;
8305
8881
  // A matched completion can prove that a new native run continues the
8306
8882
  // same admissions without re-emitting the original user's prompt.
8307
- if (live.running && !live.discordNonCohortJobSeen) live.discordJobContinuation = true;
8883
+ if (live.running && !live.nonCohortJobSeen) live.headJobContinuation = true;
8308
8884
  }
8309
- if (live.discordNonCohortJobSeen) live.discordJobContinuation = false;
8885
+ if (live.nonCohortJobSeen) live.headJobContinuation = false;
8310
8886
  }
8311
8887
  if (!items?.size || !live.headJobOwners?.size) return;
8312
8888
  const batch = live.headJobBatch ??= new Map();
@@ -8388,8 +8964,12 @@ export class Superagent {
8388
8964
 
8389
8965
  private observe(live: Live, frame: Record<string, unknown>): void {
8390
8966
  if (!this.current(live)) return;
8391
- // Read-only maintenance is not user activity, evidence, or input for a model.
8392
- if (frame.type === "response" && frame.command === "get_worker_memory") return;
8967
+ // The frame stream owns worker admission evidence both before and after
8968
+ // the request waiter times out. The waiter never classifies refusals.
8969
+ if (frame.type === "response") this.observeWorkerDispatch(live, frame);
8970
+ // Worker memory and file transport acknowledgements are not native run evidence.
8971
+ if (frame.type === "response" && (frame.command === "get_worker_memory" || frame.command === "copy_worker_result_attachment"
8972
+ || frame.command === "stage_worker_attachments")) return;
8393
8973
  if (live.id === "main" && frame.type !== "response" && frame.type !== "ready")
8394
8974
  this.headActivityAt = performance.now();
8395
8975
  // Managed host_message_update_activity ticks contribute only this heartbeat.
@@ -8442,7 +9022,7 @@ export class Superagent {
8442
9022
  if (live.id === "main") {
8443
9023
  live.headJobYield = undefined;
8444
9024
  live.headJobPromptSeen = false;
8445
- live.discordJobContinuation = false;
9025
+ live.headJobContinuation = false;
8446
9026
  live.headJobLoop = live.input ? "foreground" : "background";
8447
9027
  }
8448
9028
  this.resultAttachments.clearStarts(live);
@@ -8476,11 +9056,13 @@ export class Superagent {
8476
9056
  if (live.id !== "main" && live.input && !this.stopped) {
8477
9057
  try {
8478
9058
  let changed = false;
9059
+ if (frame.type === "tool_execution_start" || frame.type === "tool_execution_end") {
9060
+ const copy = this.resultAttachments.observe(live, frame, () => !this.restartFence() && this.current(live));
9061
+ if (copy) this.background(copy.finally(() => this.finish(live)));
9062
+ }
8479
9063
  if (frame.type === "tool_execution_start" && typeof frame.toolCallId === "string") {
8480
- this.resultAttachments.observe(live, frame, () => !this.restartFence() && this.current(live));
8481
9064
  changed = this.store.resolveLaneWaiting(live.input.id, live.generation, live.sessionId, "approval", frame.toolCallId);
8482
9065
  } else if (frame.type === "tool_execution_end" && typeof frame.toolCallId === "string") {
8483
- this.resultAttachments.observe(live, frame, () => !this.restartFence() && this.current(live));
8484
9066
  changed = this.store.resolveLaneWaiting(live.input.id, live.generation, live.sessionId, "tool", frame.toolCallId);
8485
9067
  changed = this.store.resolveLaneWaiting(live.input.id, live.generation, live.sessionId, "approval", frame.toolCallId) || changed;
8486
9068
  } else if (frame.type === "extension_ui_request" && frame.method === "cancel" && typeof frame.targetId === "string") {
@@ -8493,7 +9075,7 @@ export class Superagent {
8493
9075
  if (frame.type === "message_end" && live.id === "main") this.observeHeadJobMessage(live, record(frame.message));
8494
9076
  if (frame.type === "message_end" && live.input) {
8495
9077
  const message = record(frame.message);
8496
- this.observeDiscordHeadFollowup(live, live.input, message);
9078
+ this.observeHeadFollowup(live, live.input, message);
8497
9079
  if (message.role === "toolResult") {
8498
9080
  this.syncLaneObservations(live, message);
8499
9081
  }
@@ -8505,7 +9087,7 @@ export class Superagent {
8505
9087
  if (live.id === "main" && live.headJobMixed) return;
8506
9088
  const eventId = key(JSON.stringify([live.sessionId, live.generation, progress.identity]));
8507
9089
  try {
8508
- if (this.store.progress(live.input.id, live.generation, live.sessionId, eventId, progress.text, this.config.discord?.editProgressInPlace === true)) {
9090
+ if (this.store.progress(live.input.id, live.generation, live.sessionId, eventId, progress.text, this.editProgressInPlace(live.input.route))) {
8509
9091
  this.wakeOutputs();
8510
9092
  this.background(this.kick());
8511
9093
  }
@@ -8533,12 +9115,24 @@ export class Superagent {
8533
9115
  }
8534
9116
  }
8535
9117
  if (frame.type === "prompt_result" && typeof frame.id === "string") {
9118
+ const paused = live.pausedWorkerAdmissions?.get(frame.id);
9119
+ if (paused?.worker?.command === "prompt") {
9120
+ live.pausedWorkerAdmissions?.delete(frame.id);
9121
+ const input = this.store.input(paused.input.id);
9122
+ if (frame.status === "aborted" && input?.state === "uncertain" && input.generation === live.generation
9123
+ && this.store.lane(live.id)?.sessionId === live.sessionId && input.target === live.id
9124
+ && input.requestId === frame.id && this.store.settle(input.id, "cancelled")) {
9125
+ this.background(this.kick());
9126
+ }
9127
+ }
8536
9128
  if (live.id === "main" && frame.id === this.bootstrapActive && !this.bootstrapResult) {
8537
9129
  this.bootstrapResult = { status: String(frame.status), agentInvoked: frame.agentInvoked === true };
8538
9130
  this.background(this.finish(live));
8539
9131
  }
8540
9132
  const admitted = live.admitted.get(frame.id);
8541
- if (admitted && !admitted.result) {
9133
+ if (admitted && !admitted.result
9134
+ && (!admitted.worker || admitted.worker.command === "prompt"
9135
+ && (!admitted.worker.outcome || admitted.worker.outcome === "acknowledged"))) {
8542
9136
  admitted.result = nativePromptResult(frame);
8543
9137
  if (live.input?.requestId === frame.id) live.result = admitted.result;
8544
9138
  this.background(this.finish(live));
@@ -8575,7 +9169,9 @@ export class Superagent {
8575
9169
  }
8576
9170
 
8577
9171
  private async finishOnce(live: Live): Promise<void> {
8578
- if (!this.ready || !this.current(live) || live.preparing) return;
9172
+ // Keep the existing admitted source available to a bounded copy already
9173
+ // authorized by its live tool result; do not extend native execution.
9174
+ if (!this.ready || !this.current(live) || live.preparing || this.resultAttachments.copyPending(live)) return;
8579
9175
  await this.finishBootstrap(live);
8580
9176
  if (live.id === "main" && (this.headRecoveryActive() || this.store.hasHeadRecoveryInput())) {
8581
9177
  await this.flushOutputs();
@@ -8701,6 +9297,7 @@ export class Superagent {
8701
9297
  stackOutcome = superstackControlOutcome(input.id, stack.kind === "enable", enabled);
8702
9298
  }
8703
9299
  }
9300
+ if (this.resultAttachments.copyPending(live)) return;
8704
9301
  const wasBusy = live.busy;
8705
9302
  live.busy = !settled;
8706
9303
  live.running = false;
@@ -8722,9 +9319,9 @@ export class Superagent {
8722
9319
  : headFailed
8723
9320
  ? `실행이 실패했습니다. 작업 완료로 처리하지 않았고 다시 실행하지 않았습니다. 실패 전에 도구가 실행됐거나 효과를 확인할 수 없어 뒤 HEAD 요청이 막혀 있습니다. 원래 작업을 확인한 뒤 /resolve ${input.id} 로 이 요청을 닫으면 다음 요청을 처리합니다.`
8724
9321
  : "실행이 실패했습니다. 작업 완료로 처리하지 않았습니다.");
8725
- const discordHeadFollowups: string[] = [];
8726
- const sharedAnswerAt = !completed ? undefined : live.headJobMixed ? live.headJobCleanAnswer?.discordFollowupProofAt
8727
- : live.discordJoinedAnswer?.text === text ? live.discordJoinedAnswer.observedAt : undefined;
9322
+ const headFollowups: string[] = [];
9323
+ const sharedAnswerAt = !completed ? undefined : live.headJobMixed ? live.headJobCleanAnswer?.followupProofAt
9324
+ : live.joinedAnswer?.text === text ? live.joinedAnswer.observedAt : undefined;
8728
9325
  for (const admitted of admissions) {
8729
9326
  this.activity(admitted.input, false);
8730
9327
  if (admitted.input.id === input.id || this.store.input(admitted.input.id)?.state === "cancelled") continue;
@@ -8741,8 +9338,8 @@ export class Superagent {
8741
9338
  separateError ? { id: `${admitted.input.id}:answer`, laneFailure: admitted.result?.quota ? "quota" : "recover",
8742
9339
  text: laneFailureNotice(this.store, admitted.input, { quota: !!admitted.result?.quota, toolFree: false, result: admitted.result }) } : undefined);
8743
9340
  if (settled && status === "completed" && admitted.result?.agentInvoked && sharedAnswerAt !== undefined
8744
- && admitted.discordFollowupEnteredAt !== undefined && admitted.discordFollowupEnteredAt < sharedAnswerAt) {
8745
- discordHeadFollowups.push(admitted.input.id);
9341
+ && admitted.followupEnteredAt !== undefined && admitted.followupEnteredAt < sharedAnswerAt) {
9342
+ headFollowups.push(admitted.input.id);
8746
9343
  }
8747
9344
  }
8748
9345
  let headModel: HeadModelChange | undefined;
@@ -8765,8 +9362,8 @@ export class Superagent {
8765
9362
  this.store.settle(input.id, state, !reviewingLaneDecision && (text || live.id !== "main")
8766
9363
  ? { id: `${input.id}:answer`, text,
8767
9364
  ...(laneError ? { laneFailure: quota ? "quota" : "recover" } : {}),
8768
- ...(discordHeadFollowups.length ? { discordHeadFollowups } : {}) }
8769
- : undefined, headModel, this.config.discord?.editProgressInPlace === true);
9365
+ ...(headFollowups.length ? { headFollowups } : {}) }
9366
+ : undefined, headModel, this.editProgressInPlace(input.route));
8770
9367
  if (live.id === "main") this.headCoordinationActivityAt = performance.now();
8771
9368
  if (live.input === input) {
8772
9369
  live.admitted.clear();
@@ -8851,7 +9448,7 @@ export class Superagent {
8851
9448
  // The pin establishes that the report route is not an approval fallback.
8852
9449
  // Recognize the parent handoff even if that pin or its owner link is lost.
8853
9450
  if (this.store.getMeta(`report-approval-source:${reportId}`) !== null) return true;
8854
- if (!discordWorkThread(lane.route) || lane.route.topicId !== undefined) return false;
9451
+ if (!nativeWorkThread(lane.route) || lane.route.topicId !== undefined) return false;
8855
9452
  const failedId = this.store.getMeta(`lane-recovery-input:${reportId}`);
8856
9453
  if (failedId && this.store.getMeta(`handoff-reply:${failedId}`) !== null) return true;
8857
9454
  const owner = this.store.ownerSource(reportId);
@@ -9182,12 +9779,12 @@ export class Superagent {
9182
9779
  if (route) {
9183
9780
  const routeKeyValue = physicalRouteKey(route);
9184
9781
  if (!this.routeOutbounds.has(routeKeyValue)) {
9185
- const batch = this.filterFlushable(this.store.outputs(routeKeyValue));
9782
+ const batch = this.filterFlushable(this.store.deliverableOutputs(routeKeyValue));
9186
9783
  if (batch.length) this.background(this.startOutputRouteWorker(routeKeyValue, batch));
9187
9784
  }
9188
9785
  return;
9189
9786
  }
9190
- const byRoute = Map.groupBy(this.filterFlushable(this.store.outputs()), output => physicalRouteKey(output.route));
9787
+ const byRoute = Map.groupBy(this.filterFlushable(this.store.deliverableOutputs()), output => physicalRouteKey(output.route));
9191
9788
  for (const [routeKeyValue, batch] of byRoute) {
9192
9789
  if (!this.routeOutbounds.has(routeKeyValue)) this.background(this.startOutputRouteWorker(routeKeyValue, batch));
9193
9790
  }
@@ -9202,7 +9799,7 @@ export class Superagent {
9202
9799
  release();
9203
9800
  return delivered;
9204
9801
  }
9205
- const outputs = batch ?? this.filterFlushable(this.store.outputs(routeKeyValue));
9802
+ const outputs = batch ?? this.filterFlushable(this.store.deliverableOutputs(routeKeyValue));
9206
9803
  batch = undefined;
9207
9804
  if (outputs.every(output => deferredLaneNotices.has(output.id))) {
9208
9805
  // Release route ownership synchronously with the final empty-queue read so
@@ -9226,12 +9823,12 @@ export class Superagent {
9226
9823
  }
9227
9824
  if (verification === "deferred") { deferredLaneNotices.add(output.id); continue; }
9228
9825
  if (verification === "held") {
9229
- if (!this.stopped && this.store.claimOutput(output.id, this.config.discord?.editProgressInPlace === true))
9826
+ if (!this.stopped && this.store.claimOutput(output.id, this.editProgressInPlace(output.route)))
9230
9827
  this.store.finishOutput(output.id, "failed", undefined, "Lane watch notice is held or no longer tracked");
9231
9828
  continue;
9232
9829
  }
9233
9830
  }
9234
- if (this.stopped || !this.store.claimOutput(output.id, this.config.discord?.editProgressInPlace === true)) continue;
9831
+ if (this.stopped || !this.store.claimOutput(output.id, this.editProgressInPlace(output.route))) continue;
9235
9832
  if (output.id === `${output.sourceId}:cron-shell` && this.cronJobs.isDisabledShellRun(output.sourceId)) {
9236
9833
  this.store.finishOutput(output.id, "failed", undefined, "Legacy cron shell output was not sent");
9237
9834
  continue;
@@ -9262,12 +9859,29 @@ export class Superagent {
9262
9859
  try { this.resultAttachments.authorizeOwner(output.route); }
9263
9860
  catch (error) { throw new DeliveryError("Result attachment route is no longer authorized", "rejected", undefined, { cause: error }); }
9264
9861
  }
9862
+ if (output.id === `${output.sourceId}:restart-ack`) {
9863
+ const restart = this.restartFence();
9864
+ if (restart?.ackOutputId !== output.id || restart.inputId !== output.sourceId
9865
+ || this.store.getMeta("gateway:operator-stop") !== (restart.stopBoundary ?? null)) {
9866
+ throw new DeliveryError("Restart was superseded before the acknowledgement was posted", "rejected");
9867
+ }
9868
+ }
9265
9869
  // The claim may have fixed an in-place status edit target.
9266
9870
  remoteId = await this.messenger.send(this.store.output(output.id)!);
9267
9871
  }
9268
9872
  catch (error) {
9269
9873
  const rejected = error instanceof DeliveryError && error.certainty === "rejected";
9874
+ if ((!rejected && this.store.reconcileSlackOutput(output.id)) || this.store.reconcileSlackJoinedOutput(output.id)) {
9875
+ const disposition = this.store.output(output.id)?.state;
9876
+ if (disposition === "pending") return delivered;
9877
+ delivered ||= disposition === "sent";
9878
+ this.outputSettled(output);
9879
+ continue;
9880
+ }
9881
+ if (rejected && error.retryAfterMs !== undefined && this.store.deferSlackJoinedOutput(output.id, error.retryAfterMs))
9882
+ return delivered;
9270
9883
  this.store.finishOutput(output.id, rejected ? "failed" : "uncertain", undefined, rejected ? "Messenger rejected delivery" : "Messenger send outcome uncertain");
9884
+ this.outputSettled(output);
9271
9885
  if (rejected) this.resultAttachments.discard(output.resultAttachment?.payload);
9272
9886
  if (resultInputId) this.syncLaneThreadAfterResult(resultInputId);
9273
9887
  this.report(new Error(`Delivery ${output.id} ${rejected ? "rejected" : "uncertain"}`));
@@ -9275,6 +9889,7 @@ export class Superagent {
9275
9889
  }
9276
9890
  // Persist a successful remote send without reinterpreting a local failure.
9277
9891
  this.store.finishOutput(output.id, "sent", remoteId);
9892
+ this.outputSettled(output);
9278
9893
  this.resultAttachments.discard(output.resultAttachment?.payload);
9279
9894
  if (resultInputId) this.syncLaneThreadAfterResult(resultInputId);
9280
9895
  delivered = true;
@@ -9282,10 +9897,25 @@ export class Superagent {
9282
9897
  }
9283
9898
  }
9284
9899
 
9900
+ private outputSettled(output: OutputRecord): void {
9901
+ if (output.route.platform === "slack" && output.id === `${output.sourceId}:workspace`)
9902
+ this.routingDrain.available(routingConversation(output.route));
9903
+ if (this.store.getMeta(`kickoff-output:${output.sourceId}`) === output.id) {
9904
+ // A kickoff can settle inside the current pump's final flush, after its
9905
+ // scan skipped the held handoff. Keep the wake in that same drain.
9906
+ if (this.pumping) this.repeat = true;
9907
+ else this.background(this.kick());
9908
+ }
9909
+ if (this.restartAckWaiting === output.id) {
9910
+ this.restartAckWaiting = undefined;
9911
+ const input = this.store.input(output.sourceId);
9912
+ if (input) this.background(this.runHeadRestart(input));
9913
+ }
9914
+ }
9285
9915
 
9286
9916
  private async flushOutputs(targetRouteKey?: string): Promise<void> {
9287
9917
  if (this.stopped) return;
9288
- const pending = this.filterFlushable(this.store.outputs(targetRouteKey));
9918
+ const pending = this.filterFlushable(this.store.deliverableOutputs(targetRouteKey));
9289
9919
  if (!pending.length) {
9290
9920
  if (targetRouteKey) {
9291
9921
  const existing = this.routeOutbounds.get(targetRouteKey);