omp-superagent 0.1.17 → 0.1.18

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 (36) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +78 -29
  4. package/docs/OPERATIONS.md +59 -20
  5. package/docs/design/execution.md +30 -15
  6. package/docs/design/messaging.md +126 -43
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  9. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  10. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  12. package/package.json +1 -1
  13. package/skills/head/SKILL.md +2 -2
  14. package/skills/head/references/routing.md +17 -6
  15. package/src/config/config.ts +15 -0
  16. package/src/contracts.ts +46 -3
  17. package/src/cron/cron-jobs.ts +135 -92
  18. package/src/cron/cron-pr-intake.ts +18 -11
  19. package/src/extension.ts +15 -5
  20. package/src/gateway/gateway-client.ts +3 -1
  21. package/src/lane/workflow.ts +12 -6
  22. package/src/managed-super-probe.ts +21 -15
  23. package/src/messaging/messenger-command-catalog.json +1 -1
  24. package/src/messaging/messenger-commands.ts +8 -3
  25. package/src/messaging/slack-context.ts +50 -0
  26. package/src/omp/superkit-skills.ts +15 -2
  27. package/src/pr/pr-intake-order.ts +62 -0
  28. package/src/pr/pr-intake-review.ts +49 -31
  29. package/src/pr/pr-intake-work.ts +3 -2
  30. package/src/routing/message-order.ts +22 -1
  31. package/src/routing/topic-request.ts +41 -0
  32. package/src/runtime/controller.ts +461 -178
  33. package/src/runtime/deferred-routing.ts +12 -4
  34. package/src/runtime/dm-timeline.ts +3 -3
  35. package/src/storage/deferred-routing.ts +25 -4
  36. package/src/storage/store.ts +367 -50
@@ -6,7 +6,7 @@ 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, InputRecord, Lane, LaneModel, LaneModelChoice, LanePresetSnapshot, 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";
@@ -24,8 +24,8 @@ import { HostConnection, type HostOptions, PR_REVIEW_INPUT_PREFIX, startHost } f
24
24
  import type { FastModeState } from "../omp/host-protocol";
25
25
  import { nativeDefaultModelEvidence, recordedFallbackEvidence } from "./model-journal";
26
26
  import { DmTimeline, eventOrderId, newLogicalTopicId } from "./dm-timeline";
27
- import { compareMessageIds } from "../routing/message-order";
28
- import { matchesWrittenCommand, messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
27
+ import { compareMessageIds, slackWorkspaceQuestionTimestamp } from "../routing/message-order";
28
+ import { decodeSlackMrkdwn, matchesWrittenCommand, messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
29
29
  import { acceptsRestrictedModelSelector, codingModels, isLaneModel, laneModelArgument, resolveLaneModelChoice, sameLaneModel, type LaneModelCandidate } from "../lane/lane-models";
30
30
  import { advertisedLegacyWorkflow, advertisedWorkflow, headWorkflow, ownerWorkflowRequest, workflowChoice, workflowContext, workflowPrompt } from "../lane/workflow";
31
31
  import { admitHeadSuperstack, advertisesSuperstack, headSuperstackTaskPrefix, headSuperstackTaskText, recordedHeadSuperstack,
@@ -34,7 +34,7 @@ import type { NativePresetInspection } from "../omp/native-presets";
34
34
  import { PresetRoleSync, type PresetRoleSyncAdapters } from "./preset-sync";
35
35
  import type { HeadInitialization } from "../gateway/gateway-wire";
36
36
  import { repositoryRoot } from "../operator/repository";
37
- import { discordThreadSplit, editsTopicPlacement, existingWorkspace, inferredWorkspace, namedWorkspaces, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
37
+ import { discordThreadSplit, editsTopicPlacement, existingWorkspace, inferredWorkspace, matchingSlackHistoryChoice, namedWorkspaces, slackWorkspaceAnswer, slackWorkspacePlacement, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
38
38
  import { findPastTopic, findRoutingTopics, joinedTopicProvenance, pastTopicQuery, readPastTopic, routingExcerpt, routingSubject, transportRoutingProse } from "../routing/topic-history";
39
39
  import { parseLaneReportResult } from "../lane/lane-report";
40
40
  import { isLaneWatchNotice, LaneWatcher, type LaneWatchCommand } from "../lane/lane-watch";
@@ -45,7 +45,8 @@ import { isPrObservation, PrWatcher, type PrWatchCommand } from "../pr/pr-watch"
45
45
  import { CRON_RUN_PREFIX, CronJobs, type CronCreate } from "../cron/cron-jobs";
46
46
  import { CronPrIntake, isPrIntakeOffer, type IntakeScan } from "../cron/cron-pr-intake";
47
47
  import { prModeArgument } from "../pr/pr-intake-mode";
48
- import { intakeStatusKey, intakeThreadKey, intakeWorkId, intakeWorkPrefix, prThreadTitle, unattendedSource } from "../pr/pr-intake-work";
48
+ import { isPrMessageId } from "../pr/pr-intake-order";
49
+ import { intakeStatusKey, intakeThreadKey, intakeWorkId, intakeWorkPrefix, prCronCommand, prThreadTitle, unattendedSource } from "../pr/pr-intake-work";
49
50
  import { readIntakePulls } from "../pr/pr-intake-github";
50
51
  import { isPrReviewLane, prAction, PrControlError, PrReviews, prReviewApis, type ReviewRound } from "../pr/pr-intake-review";
51
52
  import { prReviewModelChoices } from "../pr/pr-review-models";
@@ -109,6 +110,22 @@ function discordWorkThread(route: Route): boolean {
109
110
  return route.platform === "discord" && route.guildId !== null && route.threadId !== null;
110
111
  }
111
112
 
113
+ function nativeWorkThread(route: Route): boolean {
114
+ return discordWorkThread(route) || route.platform === "slack" && route.threadId !== null;
115
+ }
116
+
117
+ function supportsHeadFollowups(route?: Route): boolean {
118
+ return route?.platform === "discord" || route?.platform === "slack";
119
+ }
120
+
121
+ function routingReply(input: Inbound) {
122
+ const slackRoot = !input.reply && input.route.platform === "slack" ? input.route.threadId : null;
123
+ return {
124
+ replyId: input.reply?.messageId ?? slackRoot,
125
+ replyRoute: slackRoot ? { ...physicalRoute(input.route), threadId: null } : input.route,
126
+ };
127
+ }
128
+
112
129
  function catchupBoundaryKey(route: Route): string | null {
113
130
  return route.platform === "discord" || route.platform === "slack"
114
131
  ? `${route.platform}:catchup-boundary:${physicalRouteKey(route)}` : null;
@@ -120,16 +137,45 @@ function inertContext(text: string): string {
120
137
  }
121
138
 
122
139
  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;
140
+ // Only a proven Slack address can expose a workspace header or a natural
141
+ // split. The projected prose cannot supply a command or workflow selector.
142
+ let text = input.text;
143
+ let addressedProse: string | undefined;
144
+ let addressedWorkspace = false;
145
+ if (input.route.platform === "slack" && input.messageId !== null && !input.reply && !input.unresolvedReply && !input.attachments.length) {
146
+ text = slackWorkspacePlacement(input.text, input.routingText);
147
+ addressedWorkspace = input.routingText !== undefined && /^cwd:/iu.test(input.routingText);
148
+ addressedProse = input.routingText;
149
+ }
150
+ if (!nativeWorkThread(input.route) || input.text.trimStart().startsWith("/")
151
+ || input.route.platform === "slack" && (input.reply || input.unresolvedReply || input.attachments.length))
152
+ return messengerCommandText(text === input.text ? input : { ...input, text });
153
+ // A legacy routing view is useful data, but it never grants a new split.
154
+ if (input.route.platform === "slack" && input.slackVerifiedRoutingBody !== true) return text;
155
+ const request = topicRequest(text);
156
+ const split = discordThreadSplit(addressedWorkspace ? request.text : addressedProse ?? request.text);
157
+ if (split === null) return text;
127
158
  if (!split) return "/new";
128
159
  // 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}`;
160
+ const header = text.slice(0, text.length - request.text.length);
161
+ // The workspace path has already been decoded; normalize just the task.
162
+ const body = input.route.platform === "slack" && (addressedWorkspace || addressedProse === undefined)
163
+ ? decodeSlackMrkdwn(split) : split;
164
+ return `/new ${header}${body}`;
131
165
  }
132
166
 
167
+ /** A Slack routing wrapper can select placement without attesting a workflow selector. */
168
+ function unverifiedSlackWorkspaceTask(input: Inbound, placement: string): boolean {
169
+ return input.route.platform === "slack" && input.messageId !== null && input.slackVerifiedRoutingBody !== true
170
+ && topicRequest(placement).cwd !== null;
171
+ }
172
+
173
+ function ownerPlacementWorkflow(input: Inbound, placement: string, task: string) {
174
+ const unverifiedTask = input.route.platform === "slack" && input.messageId !== null && (
175
+ /^\/new(?:\s|$)/u.test(placement.trimStart()) && !/^\/new(?:\s|$)/u.test(input.text.trimStart())
176
+ || unverifiedSlackWorkspaceTask(input, placement));
177
+ return ownerWorkflowRequest(input, task, unverifiedTask);
178
+ }
133
179
  function messengerEdit(input: Inbound): boolean {
134
180
  if (input.messageId === null) return false;
135
181
  const { platform, accountId, channelId } = input.route;
@@ -139,7 +185,7 @@ function messengerEdit(input: Inbound): boolean {
139
185
 
140
186
  function matchHeadControl(text: string, platform: Route["platform"]): HeadCommand | null {
141
187
  const match = headControlPattern.exec(text.trim());
142
- if (!match || match[1] === "usage-reset" && platform !== "discord") return null;
188
+ if (!match || match[1] === "usage-reset" && platform !== "discord" && platform !== "slack") return null;
143
189
  const name = match[1] as HeadCommand["name"];
144
190
  const argument = (match[2] ?? "").trim();
145
191
  // PR actions contain only identifiers. Use the same tokens for admission receipts,
@@ -190,7 +236,7 @@ interface Live {
190
236
  connection: RuntimeHost;
191
237
  input?: InputRecord;
192
238
  result?: NativePromptResult;
193
- admitted: Map<string, { input: InputRecord; result?: NativePromptResult; discordFollowupEnteredAt?: number }>;
239
+ admitted: Map<string, { input: InputRecord; result?: NativePromptResult; followupEnteredAt?: number }>;
194
240
  running: boolean;
195
241
  preparing: number;
196
242
  ownedRuns: number;
@@ -212,11 +258,11 @@ interface Live {
212
258
  headJobPromptSeen?: boolean;
213
259
  headJobBatch?: Map<string, string>;
214
260
  headJobMixed?: boolean;
215
- headJobCleanAnswer?: { text: string; discordFollowupProofAt?: number };
216
- discordNonCohortJobSeen?: boolean;
217
- discordJobContinuation?: boolean;
218
- discordContinuationJobIds?: Set<string>;
219
- discordJoinedAnswer?: { text: string; observedAt: number };
261
+ headJobCleanAnswer?: { text: string; followupProofAt?: number };
262
+ nonCohortJobSeen?: boolean;
263
+ headJobContinuation?: boolean;
264
+ headContinuationJobIds?: Set<string>;
265
+ joinedAnswer?: { text: string; observedAt: number };
220
266
  releasing?: boolean;
221
267
  lostDuringRelease?: boolean;
222
268
  nextReleaseProbe?: number;
@@ -258,8 +304,9 @@ interface HeadCommand {
258
304
  }
259
305
 
260
306
  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";
307
+ return command.name === "usage-reset"
308
+ ? (platform === "discord" || platform === "slack") && !command.argument
309
+ : platform !== "discord" && command.name === "usage" && command.argument === "reset";
263
310
  }
264
311
 
265
312
  function usageResetHint(platform: Route["platform"]): string {
@@ -423,6 +470,7 @@ export class Superagent {
423
470
  private laneMutations = 0;
424
471
  private headStopTail: Promise<void> = Promise.resolve();
425
472
  private restartActive?: string;
473
+ private restartAckWaiting?: string;
426
474
  private headActivityAt = performance.now();
427
475
  private headCoordinationActivityAt = this.headActivityAt;
428
476
  private sleepProof?: { readonly activityAt: number; readonly attestation: RotationAttestation };
@@ -482,6 +530,7 @@ export class Superagent {
482
530
  stopped: () => this.stopped,
483
531
  fenced: () => this.restartFence() !== null || this.headRotationHeld("hibernate"),
484
532
  recovery: input => this.deferredRecoveryControl(input),
533
+ awaitingReceipt: input => this.awaitingSlackChoiceReceipt(input),
485
534
  admit: id => this.intake(() => {
486
535
  const input = store.deferredRouting.input(id);
487
536
  if (!input) throw new Error(`Deferred receipt ${id} disappeared before admission`);
@@ -2557,7 +2606,7 @@ export class Superagent {
2557
2606
  const questionId = `${prior.id}:workspace`;
2558
2607
  if (this.store.output(questionId)?.state !== "sent") return false;
2559
2608
  if (routeKey(prior.route) === routeKey(followup.route)) {
2560
- if (!followup.reply) return discordWorkThread(followup.route) || this.isDm(followup.route);
2609
+ if (!followup.reply) return nativeWorkThread(followup.route) || this.isDm(followup.route);
2561
2610
  return this.store.sentOutputForMessage(followup.route, followup.reply.messageId)?.id === questionId
2562
2611
  || prior.messageId === followup.reply.messageId;
2563
2612
  }
@@ -2631,7 +2680,7 @@ export class Superagent {
2631
2680
  if (!lane || lane.sessionId !== ref.sessionId || lane.cwd !== ref.cwd || existingWorkspace(ref.cwd) !== ref.cwd
2632
2681
  || !authorizeRoute(this.config, lane.route) || lane.route.platform === source.platform && lane.route.accountId !== source.accountId
2633
2682
  || 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)) {
2683
+ if (lane.id === owner && nativeWorkThread(source) && routeKey(source) === routeKey(lane.route)) {
2635
2684
  return lane.workState === "open" ? lane : null;
2636
2685
  }
2637
2686
  if (lane.runtimeState === "running" || lane.runtimeState === "starting"
@@ -2644,7 +2693,7 @@ export class Superagent {
2644
2693
  if (!lane) return null;
2645
2694
  // The destination can consult a pinned entry in its own active journal.
2646
2695
  // 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)) {
2696
+ if (lane.id !== owner || !nativeWorkThread(source.route) || routeKey(source.route) !== routeKey(lane.route)) {
2648
2697
  const previous = this.live.get(lane.id);
2649
2698
  if (previous) {
2650
2699
  const state = await this.state(previous);
@@ -2673,8 +2722,9 @@ export class Superagent {
2673
2722
  const conversation = routingConversation(input.route);
2674
2723
  const waiting = queue.head(conversation) !== null;
2675
2724
  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) {
2725
+ const bypass = recovery?.priority === "immediate" || recovery?.priority === "retry" && this.routingDrain.blocked(conversation);
2726
+ if (waiting ? bypass || this.store.input(input.id) !== null
2727
+ : this.routingIntent(intake).query === null && !this.awaitingSlackChoiceReceipt(intake)) {
2678
2728
  await this.admit(input);
2679
2729
  return;
2680
2730
  }
@@ -2683,6 +2733,59 @@ export class Superagent {
2683
2733
  this.remember(input);
2684
2734
  }
2685
2735
 
2736
+ private awaitingSlackChoiceReceipt(input: Inbound): boolean {
2737
+ const { messageId, route } = input;
2738
+ const { threadId } = route;
2739
+ if (route.platform !== "slack" || threadId === null || messageId === null
2740
+ || input.pickerSelection || input.reply || input.unresolvedReply || input.attachments.length || messengerEdit(input)) return false;
2741
+ const bareStop = input.text.trim() === "/stop";
2742
+ const answer = bareStop ? null : slackWorkspaceAnswer(input.text, input.routingText, input.slackVerifiedRoutingBody);
2743
+ if (!bareStop && (!answer || codeHandledControl(input.text, route.platform))) return false;
2744
+ const explicit = answer?.source ?? null;
2745
+ const parent = { ...physicalRoute(route), threadId: null };
2746
+ if (bareStop) {
2747
+ const root = this.store.repliedStop(parent, threadId);
2748
+ // A bound lane is a definite target unless the root carries conflicting
2749
+ // evidence. An unrelated in-flight channel post cannot override it.
2750
+ if (root.kind === "lane" || root.kind === "sources" || root.kind === "workspace"
2751
+ || root.kind === "unknown" && this.boundLane(route)) return false;
2752
+ }
2753
+ const rootPost = !bareStop && !explicit && this.store.sentOutputForMessage(parent, threadId);
2754
+ if (rootPost && rootPost.id === `${rootPost.sourceId}:workspace`) return false;
2755
+ const threadKey = routeKey(route);
2756
+ const parentKey = routeKey(parent);
2757
+ const explicitSource = explicit && this.store.firstAdmittedMessage(route, explicit);
2758
+ const pending = explicit ? explicitSource ? [explicitSource] : [] : this.store.inputs(undefined, "pending");
2759
+ const possibleRoot = !explicit && compareMessageIds("slack", messageId, threadId) === 1;
2760
+ const candidates = pending.filter(prior => prior.state === "pending"
2761
+ && this.store.getMeta(`user-source:${prior.id}`) === "true" && this.workspaceChoiceOpen(prior.id));
2762
+ const couldAnswer = (source: InputRecord) => {
2763
+ if (this.store.output(`${source.id}:workspace`)?.state !== "sending") return false;
2764
+ if (bareStop || explicit) return true;
2765
+ if (!answer) return false;
2766
+ const choices: PastTopicRef[] = JSON.parse(this.store.getMeta(`topic-history:${source.id}`) ?? "[]");
2767
+ if (choices.length) return matchingSlackHistoryChoice(answer.text, answer.cwd, choices) !== undefined;
2768
+ return existingWorkspace(answer.cwd ?? answer.text) !== null || answer.cwd === null
2769
+ && namedWorkspaces(answer.text, this.store.lanes().filter(lane => this.sameConversation(lane.route, route)), true).size === 1;
2770
+ };
2771
+ const sameThread = candidates.filter(source => routeKey(source.route) === threadKey && source.messageId !== null
2772
+ && compareMessageIds("slack", messageId, source.messageId) === 1);
2773
+ if (!bareStop && sameThread.length === 1 && couldAnswer(sameThread[0])) return true;
2774
+ // A channel-root question publishes before its send receipt reaches HEAD.
2775
+ // A plausible reply to that new root can wait, but only the exact posted
2776
+ // thread timestamp authorizes selecting the original question at admission.
2777
+ return possibleRoot && candidates.some(source => physicalRouteKey(source.route) === parentKey
2778
+ && (source.messageId === null ? !!source.invocationId : compareMessageIds("slack", threadId, source.messageId) === 1)
2779
+ && couldAnswer(source));
2780
+ }
2781
+
2782
+ private workspaceChoiceOpen(id: string): boolean {
2783
+ if (this.store.getMeta(`topic-confirm:${id}`) !== null || this.store.getMeta(`topic-previous:${id}`) !== null) return false;
2784
+ const history = this.store.getMeta(`topic-history:${id}`);
2785
+ if (this.store.getMeta(`topic-choice-auto:${id}`) !== null && history !== "[]") return false;
2786
+ return this.store.getMeta(`topic-creator:${id}`) ? !this.store.getMeta(`topic-cwd:${id}`) : Boolean(history);
2787
+ }
2788
+
2686
2789
  private deferredRecoveryControl(input: Inbound): RecoveryControl | null {
2687
2790
  const candidate = deferredRecoveryCandidate(input.text);
2688
2791
  if (!candidate || telegramCommandBlocked(input) || input.pickerSelection
@@ -2694,10 +2797,17 @@ export class Superagent {
2694
2797
  const lane = this.explicitLaneStop(candidate.laneId);
2695
2798
  return lane && this.workRoute(lane.route) ? { priority: "immediate", laneId: lane.id } : null;
2696
2799
  }
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;
2800
+ // A Slack root can point to an outstanding placement rather than the
2801
+ // bound lane. Reply-relative stops keep ordinary admission order.
2802
+ if (input.reply || input.route.topicId !== undefined || !nativeWorkThread(input.route)
2803
+ || this.awaitingSlackChoiceReceipt(input)) return null;
2804
+ const lane = this.store.laneForRoute(input.route);
2805
+ if (!lane || !authorizeRoute(this.config, lane.route)) return null;
2806
+ const { replyId, replyRoute } = routingReply(input);
2807
+ const receipt = replyId ? this.store.repliedStop(replyRoute, replyId) : null;
2808
+ if (receipt?.kind === "workspace" || receipt?.kind === "unverified"
2809
+ || receipt?.kind === "lane" && (receipt.lane.id !== lane.id || receipt.unplaced.length > 0)) return null;
2810
+ return { priority: "retry", laneId: lane.id };
2701
2811
  }
2702
2812
 
2703
2813
  /** Admit queued inputs of each conversation in order; resumes after restart and after a failed admission's backoff. */
@@ -2731,7 +2841,7 @@ export class Superagent {
2731
2841
  || typeof selection.cardId !== "string" || !selection.cardId
2732
2842
  || input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined || input.attachments.length) return null;
2733
2843
  if (picker.kind === "model" && picker.modelTargets !== undefined) {
2734
- if (input.route.platform !== "discord" || input.reply || input.discordOriginalText !== undefined
2844
+ if ((input.route.platform !== "discord" && input.route.platform !== "slack") || input.reply || input.discordOriginalText !== undefined
2735
2845
  || !picker.modelTargets || !source || source.state !== "done"
2736
2846
  || routeKey(source.route) !== routeKey(output.route) || output.id !== `${source.id}:head-control`
2737
2847
  || !this.originalOwnerControl(source) || (selection.target !== "head" && (selection.target !== "lane" || !picker.modelTargets.lane))) return null;
@@ -2772,24 +2882,24 @@ export class Superagent {
2772
2882
  && (prModeArgument(input.text) !== null || /^\/head(?:\s|$)/.test(input.text.trimStart()));
2773
2883
  const request = topicRequest(placement);
2774
2884
  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;
2885
+ const slackChoice = input.route.platform === "slack" && /^!choose(?:\s|$)/u.test(input.text.trim());
2886
+ const candidate = !slackChoice && request.cwd === null ? pastTopicQuery(historyText) : null;
2887
+ const { replyId, replyRoute } = routingReply(input);
2779
2888
  const discordEdit = input.route.platform === "discord" && editEvent;
2780
- const query = !selection && !discordEdit && !headAddressed && !codeHandledControl(input.text, input.route.platform)
2889
+ const slackEdit = input.route.platform === "slack" && editEvent;
2890
+ const query = !selection && !discordEdit && !slackEdit && !headAddressed && !codeHandledControl(input.text, input.route.platform)
2781
2891
  && candidate && !this.store.input(input.id)
2782
2892
  && !(input.messageId && this.store.firstAdmittedMessage(input.route, input.messageId))
2783
2893
  && !(input.reply && this.store.repliedTopicWorkspace(input.route, input.reply.messageId))
2784
2894
  && !(replyId && this.store.sentOutputForMessage(replyRoute, replyId)?.id.endsWith(":workspace")) ? candidate : null;
2785
- return { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, query };
2895
+ return { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, slackEdit, slackChoice, query };
2786
2896
  }
2787
2897
 
2788
2898
  private async admit(original: Inbound, deferred = false): Promise<void> {
2789
2899
  let input = this.intakeInput(original);
2790
2900
  const selection = input.pickerSelection;
2791
2901
  const eventId = selection ? null : eventOrderId(input);
2792
- const { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, query } = this.routingIntent(input);
2902
+ const { placement, commandBlocked, editEvent, headAddressed, request, historyText, replyRoute, replyId, discordEdit, slackEdit, slackChoice, query } = this.routingIntent(input);
2793
2903
  let history: PastTopicRef[] | null = null;
2794
2904
  let historyUnavailable = false;
2795
2905
  if (query !== null) {
@@ -2857,10 +2967,15 @@ export class Superagent {
2857
2967
  } else if (discordEdit && discordWorkThread(input.route) && (/^\/new(?:\s|$)/.test(placement.trimStart()) || /^\d+$/.test(placement.trim())
2858
2968
  || (replyId && this.store.sentOutputForMessage(replyRoute, replyId)?.id.endsWith(":workspace")))) {
2859
2969
  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;
2970
+ } else {
2971
+ const editedPlacement = slackEdit && (editsTopicPlacement("", placement)
2972
+ || (replyId && this.store.sentOutputForMessage(replyRoute, replyId)?.id.endsWith(":workspace")));
2973
+ if (!selection && this.isDm(input.route)) {
2974
+ const admission = this.dmTimeline.admit(input, eventId, commandBlocked || Boolean(editedPlacement));
2975
+ input = admission.input;
2976
+ metadata = admission.metadata;
2977
+ }
2978
+ if (editedPlacement) metadata = { ...metadata, [`dm:control-edit:${input.id}`]: "true" };
2864
2979
  }
2865
2980
  if (!commandBlocked && !priorRevision && editEvent && codeHandledControl(input.text, input.route.platform)) {
2866
2981
  metadata = { ...metadata, [`dm:control-edit:${input.id}`]: "command" };
@@ -2892,19 +3007,20 @@ export class Superagent {
2892
3007
  const ordinary = !headAddressed && !selection && !metadata[`dm:control-edit:${input.id}`]
2893
3008
  && !codeHandledControl(commandText, input.route.platform) && !["/main", "/new"].includes(commandText);
2894
3009
  if (ordinary && (priorRevision?.target !== "main" || priorOwner)) {
2895
- const keepThread = discordWorkThread(input.route) && !newTopic && Boolean(bound || opening);
3010
+ const keepThread = nativeWorkThread(input.route) && !newTopic && Boolean(bound || opening);
2896
3011
  const sibling = !keepThread && !this.isDm(input.route) && !!input.route.threadId
2897
3012
  && (newTopic || changesWorkspace || separateHistory && Boolean(bound || opening));
2898
3013
  const newPlacement = sibling || !keepThread && (changesWorkspace || separateHistory);
2899
3014
  const owner = priorOwner ?? (newPlacement ? null : bound?.id ?? (!commandBlocked && opening ? this.store.getMeta(`topic-owner:${opening.id}`) : null));
2900
3015
  const selectedTopic = !commandBlocked && !owner && this.dmTimeline.isExplicitTopic(input.route);
2901
- // On a bound Discord thread the prior session supplies evidence, not a
3016
+ // In a bound thread the prior session supplies evidence, not a
2902
3017
  // destination or cwd. A lookup with no match leaves local context alone.
2903
- const consultHistory = history !== null && (!owner || keepThread && history.length > 1);
3018
+ const unavailableInSlackThread = keepThread && input.route.platform === "slack" && historyUnavailable;
3019
+ const consultHistory = history !== null && (!owner || keepThread && history.length > 1 || unavailableInSlackThread);
2904
3020
  metadata = { ...metadata,
2905
3021
  ...(workspace ? { [`topic-cwd:${input.id}`]: workspace } : {}),
2906
3022
  ...(consultHistory ? { [`topic-history:${input.id}`]: JSON.stringify(history) } : {}),
2907
- ...(historyUnavailable && !owner ? { [`topic-history-unavailable:${input.id}`]: "true" } : {}),
3023
+ ...(historyUnavailable && (!owner || unavailableInSlackThread) ? { [`topic-history-unavailable:${input.id}`]: "true" } : {}),
2908
3024
  ...(past && (!owner || keepThread) ? { [`topic-previous:${input.id}`]: JSON.stringify(past),
2909
3025
  ...(!owner ? { [`topic-cwd:${input.id}`]: past.cwd } : {}) } : {}),
2910
3026
  };
@@ -2916,7 +3032,11 @@ export class Superagent {
2916
3032
  const referenceRoute = slackRoot ? { ...physicalRoute(input.route), threadId: null } : input.route;
2917
3033
  const output = reference ? this.store.sentOutputForMessage(referenceRoute, reference) : null;
2918
3034
  const question = output && output.id === `${output.sourceId}:workspace` ? output : null;
2919
- const text = request.text.trim();
3035
+ const slack = input.route.platform === "slack";
3036
+ const slackAnswer = slack && input.messageId !== null && !input.reply && !input.unresolvedReply && !input.attachments.length
3037
+ ? slackWorkspaceAnswer(input.text, input.routingText, input.slackVerifiedRoutingBody) : null;
3038
+ const explicitSource = slackAnswer?.source && this.store.firstAdmittedMessage(input.route, slackAnswer.source);
3039
+ const text = slackAnswer?.text ?? request.text.trim();
2920
3040
  const numberReply = /^\d+$/.test(text);
2921
3041
  const repliedOriginal = discordWorkThread(input.route) && input.reply && !question
2922
3042
  ? this.store.firstAdmittedMessage(input.route, input.reply.messageId) : null;
@@ -2925,15 +3045,14 @@ export class Superagent {
2925
3045
  const referencedOptions: PastTopicRef[] = offered ? JSON.parse(offered) : [];
2926
3046
  const replyingToHistory = referencedOptions.length > 0 && (numberReply || headerOnly || referencedOptions.some(ref =>
2927
3047
  ref.cwd === text || basename(ref.cwd).toLowerCase() === text.toLowerCase()));
2928
- const waiting = headerOnly || request.cwd === null && (opening || reference || !owner || keepThread && numberReply) ?
3048
+ const waiting = slackChoice || headerOnly || request.cwd === null && (opening || reference || !owner || keepThread && numberReply) ?
2929
3049
  this.store.inputs(undefined, "pending").filter(prior =>
2930
- (question ? prior.id === question.sourceId && (slackRoot || routeKey(prior.route) === routeKey(input.route))
3050
+ (slackChoice ? explicitSource && explicitSource.id === prior.id && routeKey(prior.route) === routeKey(input.route)
3051
+ : question ? prior.id === question.sourceId && (slackRoot || routeKey(prior.route) === routeKey(input.route))
2931
3052
  : 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}`))
3053
+ && (!slackChoice || this.store.getMeta(`user-source:${prior.id}`) === "true"
3054
+ && this.store.output(`${prior.id}:workspace`)?.state === "sent")
3055
+ && this.workspaceChoiceOpen(prior.id)
2937
3056
  ) : [];
2938
3057
  const lanes = request.cwd === null && (newTopic || selectedTopic || waiting.length > 0 || reference && !owner)
2939
3058
  ? this.store.lanes().filter(lane => this.sameConversation(lane.route, input.route)) : [];
@@ -2946,27 +3065,44 @@ export class Superagent {
2946
3065
  const heldContext = original && !owner && !newTopic && request.cwd === null && history === null
2947
3066
  && this.heldPlacementMatches(original, input) ? original : null;
2948
3067
  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) : [];
3068
+ const slackHistoryMatch = slackAnswer ? matchingSlackHistoryChoice(slackAnswer.text, slackAnswer.cwd, choices) : undefined;
3069
+ const ambiguousSlackNumber = !!slackAnswer && !slackChoice && /^[1-9]\d*$/u.test(text)
3070
+ && this.store.hasSlackHistoryChoice(input.route, Number(text), input.receivedAt, original?.id);
3071
+ const questionId = slack && original && slackWorkspaceQuestionTimestamp(this.store, original);
3072
+ const afterSlackPost = Boolean(questionId && input.messageId
3073
+ && compareMessageIds("slack", input.messageId, questionId) === 1);
3074
+ const authorizedChoice = !slackEdit && !ambiguousSlackNumber
3075
+ && (!slack || !!slackAnswer && input.route.threadId !== null && afterSlackPost);
3076
+ if (original && choices.length && !newTopic && (slackChoice || headerOnly || answeringQuestion || replyingToHistory || bareNames.size || barePath || numberReply || slackHistoryMatch)) {
3077
+ let selected = slackHistoryMatch;
3078
+ if (!slack) {
3079
+ const number = request.cwd === null && numberReply ? Number(text) : null;
3080
+ const matches = number === null ? choices.filter(ref => headerOnly || barePath
3081
+ ? ref.cwd === (workspace ?? barePath) : basename(ref.cwd).toLowerCase() === text.toLowerCase())
3082
+ : /^[1-9]\d*$/.test(text) ? choices.slice(number - 1, number) : [];
3083
+ selected = matches.length === 1 ? matches[0] : undefined;
3084
+ }
2954
3085
  const placedChoice = !this.store.getMeta(`topic-creator:${original.id}`);
2955
3086
  const deadline = this.store.getMeta(`topic-choice-deadline:${original.id}`);
2956
3087
  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;
3088
+ && (afterSlackPost || question !== null || input.receivedAt >= Number(deadline) - TOPIC_CHOICE_WAIT_MS);
3089
+ if (discordEdit || !authorizedChoice || !inTime) selected = undefined;
2959
3090
  metadata = { ...metadata, [`topic-confirm:${input.id}`]: selected ? original.id : "",
2960
3091
  ...(selected ? { [`topic-previous:${original.id}`]: JSON.stringify(selected),
2961
3092
  ...(placedChoice ? {} : { [`topic-cwd:${original.id}`]: selected.cwd }) } : {}) };
2962
3093
  } else if (replyingToHistory || keepThread && numberReply && waiting.length > 1
3094
+ || ambiguousSlackNumber
2963
3095
  || numberReply && input.reply && !output && this.store.isDiscordWorkspaceQuestion(input.route, input.reply.messageId)) {
2964
3096
  metadata = { ...metadata, [`topic-confirm:${input.id}`]: "" };
2965
- } else if (headerOnly || barePath || bareNames.size || answeringQuestion && !heldContext) {
3097
+ } else if (slackChoice || headerOnly || barePath || bareNames.size || answeringQuestion && !heldContext) {
2966
3098
  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 } : {}) };
3099
+ const originalLane = original && this.store.getMeta(`topic-owner:${original.id}`);
3100
+ const fixedWorkspace = originalLane && original && !this.store.getMeta(`topic-creator:${original.id}`)
3101
+ ? this.store.lane(originalLane)?.cwd : undefined;
3102
+ const confirmed = original && authorizedChoice && selected && existingWorkspace(selected) === selected
3103
+ && (!slack || fixedWorkspace === undefined || selected === fixedWorkspace) ? original : null;
3104
+ metadata = { ...metadata, [`topic-confirm:${input.id}`]: confirmed?.id ?? "",
3105
+ ...(confirmed && selected ? { [`topic-cwd:${confirmed.id}`]: selected } : {}) };
2970
3106
  } else if (!owner && request.cwd === null && history === null) {
2971
3107
  const replied = reference ? this.store.repliedTopicWorkspace(referenceRoute, reference) : null;
2972
3108
  const selected = newTopic || selectedTopic || replied
@@ -3045,9 +3181,10 @@ export class Superagent {
3045
3181
  }
3046
3182
  }
3047
3183
  const task = this.requestText(input, placement);
3048
- const workflow = commandBlocked || metadata[`dm:control-edit:${input.id}`] ? null : ownerWorkflowRequest(input, task).name;
3184
+ const workflow = commandBlocked || metadata[`dm:control-edit:${input.id}`] ? null : ownerPlacementWorkflow(input, placement, task).name;
3049
3185
  const target = ordinary && metadata[`topic-owner:${input.id}`] ? null : "main";
3050
3186
  const stack = target === "main" && !commandBlocked && !metadata[`dm:control-edit:${input.id}`] && !editEvent && !selection
3187
+ && !unverifiedSlackWorkspaceTask(input, placement)
3051
3188
  ? admitHeadSuperstack(input, task) : undefined;
3052
3189
  if (stack) metadata = { ...metadata, [`head-superstack:${input.id}`]: JSON.stringify(stack) };
3053
3190
  if (ordinary && target === "main") metadata = { ...metadata, [`head-routing:${input.id}`]: "true" };
@@ -3095,6 +3232,10 @@ export class Superagent {
3095
3232
  const restart = this.restartFence();
3096
3233
  if (restart && target === "main"
3097
3234
  && !["handoff", "accepted", "uncertain"].includes(restart.state)) {
3235
+ if (this.restartAckWaiting === restart.ackOutputId) {
3236
+ this.restartAckWaiting = undefined;
3237
+ this.restartActive = undefined;
3238
+ }
3098
3239
  this.store.settle(restart.inputId, "cancelled");
3099
3240
  this.saveRestart({ ...restart, state: "refused" }, false);
3100
3241
  this.restartResult(restart, "Explicit HEAD stop superseded restart before lifecycle handoff. No successor was authorized.");
@@ -3129,6 +3270,11 @@ export class Superagent {
3129
3270
  return route.guildId === null && route.threadId === null;
3130
3271
  }
3131
3272
 
3273
+ private editProgressInPlace(route: Route): boolean {
3274
+ return route.platform === "discord" ? this.config.discord?.editProgressInPlace === true
3275
+ : route.platform === "slack" && this.config.slack?.editProgressInPlace === true;
3276
+ }
3277
+
3132
3278
  private hasPlacementIntent(input: InputRecord): boolean {
3133
3279
  if (telegramCommandBlocked(input)) return false;
3134
3280
  const placement = placementText(input);
@@ -3166,18 +3312,23 @@ export class Superagent {
3166
3312
 
3167
3313
  /**
3168
3314
  * 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,
3315
+ * Discord guild or Slack workspace parent in the same bot account and owner,
3170
3316
  * but a different channel. The policy opt-in is checked separately so a later
3171
3317
  * config change can never make an interrupted creation replayable.
3172
3318
  */
3173
3319
  private crossChannelParent(source: Route, parent: Route): boolean {
3174
- return source.platform === "discord" && parent.platform === "discord"
3320
+ return (source.platform === "discord" || source.platform === "slack") && parent.platform === source.platform
3175
3321
  && source.guildId !== null && parent.guildId === source.guildId
3176
3322
  && parent.accountId === source.accountId && parent.authorityId === source.authorityId
3177
3323
  && parent.threadId === null && parent.topicId === undefined
3178
3324
  && !this.sameConversation(source, parent);
3179
3325
  }
3180
3326
 
3327
+ private allowsCrossChannelThreads(platform: Route["platform"]): boolean {
3328
+ return platform === "slack" ? this.config.slack?.allowCrossChannelThreads === true
3329
+ : platform === "discord" && this.config.discord?.allowCrossChannelThreads === true;
3330
+ }
3331
+
3181
3332
  /**
3182
3333
  * Repair only the exact thread the adapter journaled as its native result for
3183
3334
  * the journaled cross-channel parent. A thread in the source parent, or any
@@ -3210,6 +3361,10 @@ export class Superagent {
3210
3361
  }
3211
3362
 
3212
3363
  private routingRequestText(input: Inbound): string {
3364
+ if (input.route.platform === "slack" && input.routingText !== undefined) {
3365
+ const placement = placementText(input);
3366
+ return placement === input.text && !/^cwd:/iu.test(input.routingText) ? input.routingText : this.requestText(input, placement);
3367
+ }
3213
3368
  const routingInput = { ...input, text: transportRoutingProse(input) };
3214
3369
  return this.requestText(routingInput, placementText(routingInput));
3215
3370
  }
@@ -3295,8 +3450,8 @@ export class Superagent {
3295
3450
  const isNew = /^\/new(?:\s|$)/.test(command);
3296
3451
  if (!isNew && command !== "/main") return false;
3297
3452
  if (isNew && this.requestText(input)) return false;
3298
- const text = isNew && discordWorkThread(input.route)
3299
- ? "어떤 작업을 새 스레드에서 시작할까요? `/new 작업 내용`으로 알려 주세요. 지금 스레드의 작업은 그대로 둡니다."
3453
+ const text = isNew && nativeWorkThread(input.route)
3454
+ ? `어떤 작업을 새 스레드에서 시작할까요? \`${input.route.platform === "slack" ? "!" : "/"}new 작업 내용\`으로 알려 주세요. 지금 스레드의 작업은 그대로 둡니다.`
3300
3455
  : !this.isDm(input.route)
3301
3456
  ? "독립 주제는 새 스레드·포럼 주제에서 시작해 주세요. DM에서는 /new 요청으로 새 주제를 만들고 /main으로 메인 대화에 돌아갈 수 있습니다."
3302
3457
  : isNew ? "새 DM 주제를 열었습니다. 이 주제에서 처리할 요청이나 질문을 보내 주세요. 저장소는 요청을 확인한 뒤 선택합니다."
@@ -3668,9 +3823,9 @@ export class Superagent {
3668
3823
  const original = this.store.ownerSource(sourceId);
3669
3824
  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
3825
  if (original) this.assertFirstDmHandoffSource(original, sourceId);
3671
- if (destination && original && discordWorkThread(original.route) && this.store.getMeta(`head-routing:${original.id}`) === "true"
3826
+ if (destination && original && nativeWorkThread(original.route) && this.store.getMeta(`head-routing:${original.id}`) === "true"
3672
3827
  && 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");
3828
+ throw new Error("Work from this thread stays in the original thread unless the owner explicitly requests a split");
3674
3829
  }
3675
3830
  this.assertCronDelegationOpen(sourceId);
3676
3831
  return null;
@@ -3850,7 +4005,7 @@ export class Superagent {
3850
4005
  if (requestedParent && !this.sameConversation(original.route, requestedParent)) {
3851
4006
  // The destination was authorized above (same owner, allowed guild and
3852
4007
  // channel). Only the opt-in owner policy widens the source parent.
3853
- if (this.config.discord?.allowCrossChannelThreads !== true || !this.crossChannelParent(original.route, requestedParent))
4008
+ if (!this.allowsCrossChannelThreads(original.route.platform) || !this.crossChannelParent(original.route, requestedParent))
3854
4009
  throw new Error("A new sibling topic must use the source conversation's authorized parent");
3855
4010
  }
3856
4011
  // A read-only capability rejection has created nothing. Let the head select
@@ -3951,7 +4106,7 @@ export class Superagent {
3951
4106
  this.authorized(destination, "work");
3952
4107
  if (!destination.threadId && !destination.topicId) throw new Error("Delegation needs an independent destination topic");
3953
4108
  if (destination.threadId && routeKey(destination) !== routeKey(original.route)
3954
- && this.sameConversation(original.route, destination) && (!input.destination || requestedParent)) {
4109
+ && (requestedParent !== null || !input.destination && this.sameConversation(original.route, destination))) {
3955
4110
  this.store.setMeta(nativeKey, "true");
3956
4111
  }
3957
4112
  this.store.setMeta(destinationKey, JSON.stringify(destination));
@@ -4042,7 +4197,11 @@ export class Superagent {
4042
4197
  this.store.queueOutput({ id: kickoffId, sourceId: source.id, route: lane.route, text: input.kickoff });
4043
4198
  this.wakeOutputs(original.route);
4044
4199
  await this.flushOutputs(physicalRouteKey(lane.route));
4045
- if (this.store.output(kickoffId)?.state !== "sent") {
4200
+ const kickoff = this.store.output(kickoffId);
4201
+ // Binding is durable, but a route-ordered retry can still hold its
4202
+ // kickoff. The existing kickoff fence prevents native dispatch.
4203
+ if (kickoff?.state === "pending") return lane;
4204
+ if (kickoff?.state !== "sent") {
4046
4205
  throw new Error("Kickoff delivery is not confirmed; lane execution is held without retrying the message");
4047
4206
  }
4048
4207
  void this.kick().catch(this.report);
@@ -4097,7 +4256,7 @@ export class Superagent {
4097
4256
  // Do not rebind the inbound message, topic, or source of native callbacks.
4098
4257
  const reportInThread = original.target === "main" && !original.pickerSelection
4099
4258
  && this.store.getMeta(`user-source:${original.id}`) === "true"
4100
- && discordWorkThread(lane.route) && lane.route.topicId === undefined
4259
+ && nativeWorkThread(lane.route) && lane.route.topicId === undefined
4101
4260
  && routeKey(original.route) === routeKey({ ...lane.route, threadId: null });
4102
4261
  const queued = this.store.receive({
4103
4262
  id: handoffId, route: lane.route, messageId: original.messageId,
@@ -4300,8 +4459,8 @@ export class Superagent {
4300
4459
  }
4301
4460
  const route = physicalRoute(laneId ? this.requireLane(laneId).route : source.route);
4302
4461
  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");
4462
+ if (!this.messenger.inspectThread || !nativeWorkThread(route) && !(route.platform === "discord" && route.guildId))
4463
+ throw new Error("Thread inspection requires a Slack thread or Discord guild conversation");
4305
4464
  return this.messenger.inspectThread(route);
4306
4465
  }
4307
4466
 
@@ -4315,6 +4474,31 @@ export class Superagent {
4315
4474
  return this.messenger.inspectDiscordContext(physicalRoute(source.route));
4316
4475
  }
4317
4476
 
4477
+ async inspectSlackContext(sourceId: string): Promise<SlackContext> {
4478
+ const source = this.observationSource(sourceId, "Slack context");
4479
+ if (source.route.platform !== "slack" || !this.messenger.inspectSlackContext)
4480
+ throw new Error("Slack context inspection requires a supported Slack source");
4481
+ return this.messenger.inspectSlackContext({ sourceId, route: physicalRoute(source.route) });
4482
+ }
4483
+
4484
+ async slackPurpose(input: { sourceId: string; scope?: "channel" | "thread" } & (
4485
+ { action: "list" | "clear" } | { action: "set"; purpose: string }
4486
+ )): Promise<readonly SlackPurposeNote[]> {
4487
+ if (input.action !== "list") this.assertLaneRecoveryMutation(input.sourceId);
4488
+ this.assertRestartOpen();
4489
+ if (this.stopped) throw new Error("Controller is stopped");
4490
+ const source = this.observationSource(input.sourceId, "Slack purpose");
4491
+ if (source.route.platform !== "slack" || !this.messenger.slackPurpose)
4492
+ throw new Error("Slack purpose requires a supported Slack source");
4493
+ if (input.scope !== undefined && input.scope !== "channel" && input.scope !== "thread")
4494
+ throw new Error("Invalid Slack purpose scope");
4495
+ if (input.scope === "thread" && !source.route.threadId) throw new Error("The original source has no Slack thread");
4496
+ const route = { ...physicalRoute(source.route), ...(input.scope === "channel" ? { threadId: null } : {}) };
4497
+ return this.messenger.slackPurpose(input.action === "set"
4498
+ ? { sourceId: input.sourceId, route, action: input.action, purpose: input.purpose }
4499
+ : { sourceId: input.sourceId, route, action: input.action });
4500
+ }
4501
+
4318
4502
  async messengerPresence(sourceId: string, action: PresenceAction, platform?: Route["platform"]) {
4319
4503
  const source = this.observationSource(sourceId, "Messenger presence");
4320
4504
  if (platform !== undefined && platform !== source.route.platform)
@@ -4368,8 +4552,8 @@ export class Superagent {
4368
4552
  const lane = this.requireLane(input.id);
4369
4553
  this.authorized(lane.route, "work");
4370
4554
  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");
4555
+ if (!nativeWorkThread(lane.route) || !messenger.updateThread)
4556
+ throw new Error("Thread changes require a managed Discord or Slack thread");
4373
4557
  const changes = structuredClone(input.changes);
4374
4558
  const request = { route: physicalRoute(lane.route), changes };
4375
4559
  const receiptKey = `lane-thread:${lane.id}:${input.sourceId}`;
@@ -4378,7 +4562,7 @@ export class Superagent {
4378
4562
  const receipt: { request: typeof request; result?: ThreadInfo; error?: string; certainty?: "rejected" | "uncertain" } = JSON.parse(saved);
4379
4563
  if (!isDeepStrictEqual(receipt.request, request)) throw new Error("Thread-change source identity conflict");
4380
4564
  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",
4565
+ throw new DeliveryError(receipt.error ?? "Thread change is pending or uncertain; inspect the messenger before a new explicit request",
4382
4566
  receipt.certainty ?? "uncertain");
4383
4567
  }
4384
4568
  // Persist intent before IPC. A lost receipt must not repeat a remote edit.
@@ -4415,7 +4599,7 @@ export class Superagent {
4415
4599
  private async syncLaneThreadTitle(lane: Lane): Promise<void> {
4416
4600
  const { messenger } = this;
4417
4601
  const route = physicalRoute(lane.route);
4418
- if (route.platform !== "discord" || !route.guildId || !route.threadId || !messenger.inspectThread || !messenger.updateThread) return;
4602
+ if (!nativeWorkThread(route) || !messenger.inspectThread || !messenger.updateThread) return;
4419
4603
  const inspect = messenger.inspectThread.bind(messenger);
4420
4604
  const update = messenger.updateThread.bind(messenger);
4421
4605
  const active = () => {
@@ -4432,8 +4616,8 @@ export class Superagent {
4432
4616
  const thread = await inspect(route);
4433
4617
  if (physicalRouteKey(thread.route) !== physicalRouteKey(route))
4434
4618
  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
4619
+ if ((route.platform === "slack" ? !thread.editableTitle : thread.archived !== false) || !active()) return;
4620
+ // Re-read after the lookup so an older settle cannot clear a
4437
4621
  // newer run or a surviving input/approval hold. Open is not active.
4438
4622
  let current = this.store.lane(lane.id);
4439
4623
  if (!current) return;
@@ -4452,7 +4636,7 @@ export class Superagent {
4452
4636
  }
4453
4637
  const base = thread.title.replace(/^(?:⏳|✅) /u, "");
4454
4638
  if (prefix === null || !base.trim()) return;
4455
- // Keep the title within Discord's name limit without splitting a surrogate pair.
4639
+ // Keep the work title within its limit without splitting a surrogate pair.
4456
4640
  const title = (prefix + base).slice(0, 100).replace(/[\uD800-\uDBFF]$/, "").trimEnd();
4457
4641
  if (title === thread.title) return;
4458
4642
  this.laneMutations++;
@@ -4465,7 +4649,7 @@ export class Superagent {
4465
4649
  if (!(error instanceof DeliveryError && error.certainty === "rejected" && error.retryAfterMs !== undefined)) throw error;
4466
4650
  if (!active()) return;
4467
4651
  // Retry only a confirmed rate-limit rejection; recompute the desired
4468
- // prefix when Discord permits a new change, never replay a stale write.
4652
+ // prefix when the messenger permits a new change, never replay a stale write.
4469
4653
  const retry = setTimeout(() => {
4470
4654
  this.threadTitleRetries.delete(lane.id);
4471
4655
  this.background(this.syncLaneThreadTitle(lane));
@@ -5446,16 +5630,21 @@ export class Superagent {
5446
5630
  let handedOff = false;
5447
5631
  try {
5448
5632
  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");
5633
+ if (!this.store.output(restart.ackOutputId)) {
5634
+ restart = { ...restart, state: "acknowledging" };
5635
+ this.saveRestart(restart);
5636
+ this.store.settle(input.id, "done", { id: restart.ackOutputId,
5637
+ 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." });
5638
+ }
5639
+ await this.flushOutputs(physicalRouteKey(input.route));
5457
5640
  const ack = this.store.output(restart.ackOutputId);
5458
5641
  this.assertRestartCurrent(restart);
5642
+ if (ack?.state === "pending") {
5643
+ // In particular, a same-route Retry-After can keep the ACK ineligible.
5644
+ // Release the control drain; its own terminal receipt wakes this request.
5645
+ this.restartAckWaiting = ack.id;
5646
+ return;
5647
+ }
5459
5648
  if (ack?.state !== "sent") {
5460
5649
  if (ack?.state === "failed") this.refuseRestart(restart, "The required ACK was rejected; no restart handoff was attempted.");
5461
5650
  else {
@@ -5523,7 +5712,7 @@ export class Superagent {
5523
5712
  JSON.stringify({ ...current, state: "failed" }), output)) this.report(error);
5524
5713
  }
5525
5714
  } finally {
5526
- if (this.restartActive === input.id) this.restartActive = undefined;
5715
+ if (this.restartActive === input.id && this.restartAckWaiting !== restart.ackOutputId) this.restartActive = undefined;
5527
5716
  }
5528
5717
  }
5529
5718
 
@@ -5890,15 +6079,16 @@ export class Superagent {
5890
6079
  "Supported owner commands (Slack uses ! instead of /, e.g. !status):",
5891
6080
  "/help; /status; /context — read current shared HEAD, even while busy; no model turn.",
5892
6081
  "/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."] : []),
6082
+ `${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.`,
6083
+ ...(input.route.platform === "slack" ? ["!model — choose HEAD or the current lane, then choose a provider and model."]
6084
+ : input.route.platform === "discord" ? ["/model — choose HEAD or the current lane, then choose a provider and model."] : []),
5895
6085
  "/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
6086
  `${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
6087
  "/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
6088
  "/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
6089
  "/compact [instructions] — native shared HEAD compaction; multiline instructions allowed; requires idle, unambiguous state.",
5900
6090
  "/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 로 단계를 선택하세요.',
6091
+ `${input.route.platform === "slack" ? '!cron' : '/cron'} pr-add "every 5m" OWNER/REPO — 외부 PR 자동 리뷰와 GitHub 코멘트를 시작합니다. 등록한 부모 채널에서 단계(review, fix, merge)를 선택하세요.`,
5902
6092
  "/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
6093
  "/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
6094
  "/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 +6287,7 @@ export class Superagent {
6097
6287
  };
6098
6288
  this.store.setMeta("head:stop-boundary", JSON.stringify({
6099
6289
  inputId: input.id,
6100
- prDiscordOrder: this.cronJobs.prStopOrder(boundary, input),
6290
+ prOrder: this.cronJobs.prStopOrder(boundary, input),
6101
6291
  cancelledInputIds: [...new Set([...previousBoundary.cancelledInputIds, ...cancelledInputIds])],
6102
6292
  deferredStoppedIds: [...new Set([...(previousBoundary.deferredStoppedIds ?? []), ...deferredStoppedIds])],
6103
6293
  }));
@@ -6324,6 +6514,10 @@ export class Superagent {
6324
6514
  this.controlReply(input, `Invalid syntax. Use /usage or ${resetInput}. A ticket can only be spent from the confirmation card.`, "cancelled");
6325
6515
  return;
6326
6516
  }
6517
+ if (input.route.platform === "slack" && !input.pickerSelection && !this.originalOwnerControl(input)) {
6518
+ this.controlReply(input, `Open ${resetCommand} as a new owner command without attachments.`, "cancelled");
6519
+ return;
6520
+ }
6327
6521
  const savedKey = this.store.getMeta("usage-reset:identity-key");
6328
6522
  const identityKey = savedKey ?? crypto.randomUUID();
6329
6523
  if (savedKey === null) this.store.setMeta("usage-reset:identity-key", identityKey);
@@ -6460,7 +6654,8 @@ export class Superagent {
6460
6654
  return;
6461
6655
  }
6462
6656
  const presetCommand = this.headPresetCommand(command);
6463
- const scopedOpening = input.route.platform === "discord" && command.name === "model" && !command.argument && !command.picker;
6657
+ const scopedOpening = (input.route.platform === "discord" || input.route.platform === "slack")
6658
+ && command.name === "model" && !command.argument && !command.picker;
6464
6659
  const reply = (text: string, outcome: "done" | "cancelled" | "uncertain" = "done", picker?: HeadPicker) => {
6465
6660
  const scope = presetCommand?.global ? "HEAD preset command (existing lanes unchanged)." : "HEAD session only (not lanes or global defaults).";
6466
6661
  this.store.settle(input.id, outcome, { id: `${input.id}:head-control`, text: scopedOpening ? text : `${scope} ${text}`, ...(picker ? { picker } : {}) });
@@ -6529,7 +6724,7 @@ export class Superagent {
6529
6724
  } : undefined);
6530
6725
  } else if (command.name === "model") {
6531
6726
  if (scopedOpening && !this.originalOwnerControl(input)) {
6532
- reply("Open /model from an original owner command in this conversation.", "cancelled");
6727
+ reply(`Open ${prefix}model from an original owner command in this conversation.`, "cancelled");
6533
6728
  return;
6534
6729
  }
6535
6730
  const catalog = await this.nativeModelCatalog().catch(() => null);
@@ -6788,7 +6983,8 @@ export class Superagent {
6788
6983
  }
6789
6984
 
6790
6985
  private originalOwnerControl(input: InputRecord): boolean {
6791
- if (input.pickerSelection || input.attachments.length || messengerEdit(input) || !authorizeRoute(this.config, input.route)) return false;
6986
+ if (input.pickerSelection || input.attachments.length || input.route.platform === "slack" && input.unresolvedReply
6987
+ || messengerEdit(input) || !authorizeRoute(this.config, input.route)) return false;
6792
6988
  return matchesWrittenCommand(input);
6793
6989
  }
6794
6990
 
@@ -6981,8 +7177,11 @@ export class Superagent {
6981
7177
  if (!isLaneModel(model)) throw new PrControlError("현재 HEAD 모델을 확인할 수 없습니다.");
6982
7178
  if (source.route.threadId) {
6983
7179
  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에서 확인할 수 없습니다.");
7180
+ const slack = source.route.platform === "slack";
7181
+ const offerAnchor = this.store.getMeta(intakeThreadKey(round.job, round.number));
7182
+ if (!actual || routeKey(actual.route) !== routeKey(source.route)
7183
+ || (slack ? actual.botStarter !== (source.route.threadId === offerAnchor) : actual.archived !== false))
7184
+ throw new PrControlError("원래 메시지에서 열린 검토 스레드임을 확인할 수 없습니다.");
6986
7185
  }
6987
7186
  const cwd = join(this.config.stateDir, "pr-reviews", round.laneId);
6988
7187
  privateDirectory(cwd);
@@ -6991,7 +7190,7 @@ export class Superagent {
6991
7190
  await this.admitLane({ sourceId: source.id, cwd, destination: physicalRoute(source.route), placement: { target: "local" },
6992
7191
  title: prThreadTitle(round.repository, round.number), model, modelReason: "Inherit the verified HEAD model for this static PR review.",
6993
7192
  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}` });
7193
+ kickoff: `PR #${round.number} 정적 검토 전용 스레드입니다. 검토 상태와 다음 명령: ${source.route.platform === "slack" ? "!" : "/"}cron pr-status ${round.job} ${round.number}` });
6995
7194
  }
6996
7195
 
6997
7196
  private async drivePrScan({ job, entries }: IntakeScan): Promise<void> {
@@ -7017,11 +7216,13 @@ export class Superagent {
7017
7216
  verify();
7018
7217
  const previous = this.prReviews.saved(job.id, number);
7019
7218
  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가 없어 자동 검토를 시작하지 않았습니다.");
7219
+ const slack = route.platform === "slack";
7220
+ if (!isPrMessageId(route.platform, anchor))
7221
+ throw new PrControlError("PR 알림의 실제 메시지 ID가 없어 자동 검토를 시작하지 않았습니다.");
7021
7222
  if (!head && !previous) continue;
7022
7223
  const threadKey = intakeThreadKey(job.id, number);
7023
7224
  const claimed = this.store.getMeta(threadKey);
7024
- if (claimed === null) {
7225
+ if (claimed === null && !slack) {
7025
7226
  if (!this.messenger.inspectThread || !await this.messenger.canCreateThread?.(offer.route))
7026
7227
  throw new PrControlError("원래 Discord 알림에 스레드를 만들고 확인할 권한이 없습니다.");
7027
7228
  verify();
@@ -7036,12 +7237,15 @@ export class Superagent {
7036
7237
  if (routeKey(created) !== routeKey(route))
7037
7238
  throw new PrControlError("Discord 스레드와 원래 알림 메시지 ID가 다릅니다. 생성 요청을 반복하지 않습니다.");
7038
7239
  } else if (claimed === `rejected:${anchor}`) continue;
7039
- else if (claimed !== anchor) throw new PrControlError("원래 알림과 스레드 영수증이 일치하지 않습니다.");
7240
+ else if (claimed !== null && claimed !== anchor) throw new PrControlError("원래 알림과 스레드 영수증이 일치하지 않습니다.");
7040
7241
  verify();
7041
7242
  const thread = await this.messenger.inspectThread?.(route);
7042
- if (!thread || thread.archived !== false || routeKey(thread.route) !== routeKey(route))
7243
+ if (!thread || routeKey(thread.route) !== routeKey(route) || (slack ? thread.botStarter !== true : thread.archived !== false))
7043
7244
  throw new PrControlError("원래 알림에 연결된 활성 스레드가 확인되지 않습니다. 두 번째 스레드를 만들지 않습니다.");
7044
7245
  verify();
7246
+ // Slack replies use the verified alert itself as their root. There is
7247
+ // no remote create operation to claim or repeat before binding it.
7248
+ if (slack && claimed === null) this.store.setMeta(threadKey, anchor);
7045
7249
  let next = head;
7046
7250
  if (previous) {
7047
7251
  const lane = this.store.lane(previous.laneId);
@@ -7068,14 +7272,14 @@ export class Superagent {
7068
7272
  const sourceId = intakeWorkId(job.id, number, policy.revision, next);
7069
7273
  const laneId = previous?.laneId ?? `lane-${key(`handoff:${sourceId}:lane`)}`;
7070
7274
  const bound = this.store.laneForRoute(route);
7071
- if (bound && (!previous || bound.id !== laneId)) throw new PrControlError("원래 Discord 스레드가 다른 작업에 배정됐습니다.");
7275
+ if (bound && (!previous || bound.id !== laneId)) throw new PrControlError("원래 스레드가 다른 작업에 배정됐습니다.");
7072
7276
  const round = this.prReviews.startAutomated(job, candidate, next, route, laneId, policy.revision);
7073
7277
  const source = this.store.input(round.source);
7074
7278
  if (!source) throw new PrControlError("자동 검토 작업 영수증을 확인하지 못했습니다.");
7075
7279
  try {
7076
7280
  await this.placePrReview(round, source, !previous, verify);
7077
7281
  this.store.settle(source.id, "done");
7078
- this.store.setMeta(slot, `PR #${number} 검토 접수: ${next}. <#${anchor}>`);
7282
+ this.store.setMeta(slot, `PR #${number} 검토 접수: ${next}. ${slack ? `스레드 ${anchor}` : `<#${anchor}>`}`);
7079
7283
  this.background(this.kick());
7080
7284
  } catch (error) {
7081
7285
  // Only the native lane input may have reached OMP. Placement/outbox
@@ -7085,7 +7289,7 @@ export class Superagent {
7085
7289
  }
7086
7290
  } catch (error) {
7087
7291
  this.store.setMeta(slot, error instanceof PrControlError ? error.message
7088
- : `PR #${number} 자동 처리 보류. /cron pr-status ${job.id} ${number} 및 원래 알림·스레드의 실제 상태를 확인하세요.`);
7292
+ : `PR #${number} 자동 처리 보류. ${prCronCommand(offer.route.platform)} pr-status ${job.id} ${number} 및 원래 알림·스레드의 실제 상태를 확인하세요.`);
7089
7293
  } finally { this.activePrs.delete(slot); }
7090
7294
  }
7091
7295
  }
@@ -7110,9 +7314,15 @@ export class Superagent {
7110
7314
  this.prControlActive = true;
7111
7315
  try {
7112
7316
  verify();
7113
- if (!this.messenger.assertRoute) throw new PrControlError("인증된 Discord 경로를 확인할 수 없습니다.");
7317
+ if (!this.messenger.assertRoute) throw new PrControlError("인증된 메신저 경로를 확인할 수 없습니다.");
7114
7318
  try { await this.messenger.assertRoute(input.route); }
7115
- catch { throw new PrControlError("원래 Discord 봇 계정·채널·스레드의 접근을 확인할 수 없습니다."); }
7319
+ catch { throw new PrControlError("원래 봇 계정·채널·스레드의 접근을 확인할 수 없습니다."); }
7320
+ if (input.route.platform === "slack" && input.route.threadId) {
7321
+ const root = await this.messenger.inspectThread?.(input.route);
7322
+ if (!root || routeKey(root.route) !== routeKey(input.route) || typeof root.botStarter !== "boolean")
7323
+ throw new PrControlError("원래 Slack PR 스레드의 시작 메시지를 확인할 수 없습니다.");
7324
+ }
7325
+ verify();
7116
7326
  const id = `lane-${key(`handoff:${input.id}:lane`)}`;
7117
7327
  const text = await this.prReviews.control(input, argument, { verify, newLaneId: id, signal: this.stopSignal.signal,
7118
7328
  place: (round, first) => this.placePrReview(round, input, first, verify) });
@@ -7120,7 +7330,7 @@ export class Superagent {
7120
7330
  this.store.settleCronControl(input.id, { text: launchHeld ? `${text}\nNative Host가 보류되었습니다. HEAD에서 ${threadLane.id}의 모델·Host 상태를 확인하세요. PR 코드를 일반 레인으로 옮겨 실행하지 마세요.` : text });
7121
7331
  } catch (error) {
7122
7332
  const reason = error instanceof PrControlError ? error.message
7123
- : "원래 등록·소유자 경로·GitHub 상태 또는 레인 배정을 확인하지 못했습니다. 부모 채널의 /cron show 및 원래 스레드 기록을 확인하세요";
7333
+ : `원래 등록·소유자 경로·GitHub 상태 또는 레인 배정을 확인하지 못했습니다. 부모 채널의 ${prCronCommand(input.route.platform)} show 및 원래 스레드 기록을 확인하세요`;
7124
7334
  this.store.settleCronControl(input.id, { state: "cancelled", text: `PR 명령 보류: ${reason}. 자동 재시도하지 않습니다.` });
7125
7335
  } finally { this.prControlActive = false; this.activePrs.delete(slot); }
7126
7336
  }
@@ -7136,7 +7346,7 @@ export class Superagent {
7136
7346
  this.background((async () => {
7137
7347
  for (const lane of this.store.lanes()) {
7138
7348
  if (this.stopped) return;
7139
- if (lane.route.platform === "discord" && lane.route.guildId && lane.route.threadId) {
7349
+ if (nativeWorkThread(lane.route)) {
7140
7350
  await this.syncLaneThreadTitle(lane).catch(this.report);
7141
7351
  }
7142
7352
  if (this.restartFence()) { this.reconcileSavedThreadTitles = true; return; }
@@ -7228,7 +7438,9 @@ export class Superagent {
7228
7438
  const confirmation = this.store.getMeta(`topic-confirm:${input.id}`);
7229
7439
  if (confirmation !== null) {
7230
7440
  this.store.settle(input.id, confirmation ? "done" : "cancelled", confirmation ? undefined : {
7231
- id: `${input.id}:workspace`, text: "선택할 요청이 남아 있지 않거나 답을 확인할 수 없습니다. 아직 열려 있는 질문에 번호나 저장소 경로로 답장해 주세요.",
7441
+ id: `${input.id}:workspace-answer-refused`, text: input.route.platform === "slack"
7442
+ ? "선택이 만료됐거나 답할 질문을 하나로 확인할 수 없습니다. 열려 있는 질문에 표시된 `!choose` 명령을 사용해 주세요."
7443
+ : "선택할 요청이 남아 있지 않거나 답을 확인할 수 없습니다. 아직 열려 있는 질문에 번호나 저장소 경로로 답장해 주세요.",
7232
7444
  });
7233
7445
  return;
7234
7446
  }
@@ -7236,7 +7448,7 @@ export class Superagent {
7236
7448
  const request = protectedCommand ? { cwd: null, text: input.text } : topicRequest(placementText(input));
7237
7449
  const cwd = this.store.getMeta(`topic-cwd:${input.id}`);
7238
7450
  if (request.cwd !== null && !cwd) {
7239
- this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace`, text: "존재하는 디렉터리의 절대 경로가 필요합니다. 작업은 실행하지 않았습니다." });
7451
+ this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace-invalid`, text: "존재하는 디렉터리의 절대 경로가 필요합니다. 작업은 실행하지 않았습니다." });
7240
7452
  return;
7241
7453
  }
7242
7454
  const creation = this.store.getMeta(`topic-creator:${input.id}`);
@@ -7245,10 +7457,16 @@ export class Superagent {
7245
7457
  const existing = this.store.input(handoffId);
7246
7458
  const protectedPlacement = protectedCommand && (creation !== null || cwd !== null || saved !== null);
7247
7459
  // 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;
7460
+ if (existing?.target === owner && !(protectedPlacement && existing.state === "pending")) {
7461
+ const kickoff = creation ? this.store.output(`${input.id}:kickoff`) : null;
7462
+ if (!creation || kickoff?.state === "sent") {
7463
+ this.store.settle(input.id, "done");
7464
+ return;
7465
+ }
7466
+ if (kickoff && !protectedPlacement) {
7467
+ if (kickoff.state === "failed" || kickoff.state === "uncertain") this.holdTopicPlacement(input);
7468
+ return;
7469
+ }
7252
7470
  }
7253
7471
  if (protectedPlacement) {
7254
7472
  // Old ledgers may link this example to a placement which had not run.
@@ -7265,28 +7483,41 @@ export class Superagent {
7265
7483
  this.store.settle(input.id, "cancelled", { id: `${input.id}:closed`, text: `레인 ${owner}은 ${lane.workState} 상태입니다. 자동 재개하지 않았습니다. /status로 확인해 주세요.` });
7266
7484
  return;
7267
7485
  }
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: 절대경로` 다음 줄에 작업을 적어 주세요." });
7486
+ if (!creation && lane && cwd && cwd !== lane.cwd && nativeWorkThread(input.route)) {
7487
+ const prefix = input.route.platform === "slack" ? "!" : "/";
7488
+ this.store.settle(input.id, "cancelled", { id: `${input.id}:workspace-mismatch`, text: `지정한 작업 폴더가 이 스레드와 달라 실행하지 않았습니다. 다른 폴더에서 시작하려면 \`${prefix}new cwd: 절대경로\` 다음 줄에 작업을 적어 주세요.` });
7270
7489
  return;
7271
7490
  }
7272
7491
  const priorKey = `topic-previous:${input.id}`;
7273
7492
  const automaticKey = `topic-choice-auto:${input.id}`;
7274
- const choosingHere = !creation && saved !== null && this.store.getMeta(priorKey) === null && this.store.getMeta(automaticKey) === null;
7493
+ const options: PastTopicRef[] = saved ? JSON.parse(saved) : [];
7494
+ const choosingHere = !creation && saved !== null && (options.length > 0 || cwd === null)
7495
+ && this.store.getMeta(priorKey) === null && (options.length === 0 || this.store.getMeta(automaticKey) === null);
7275
7496
  if (creation && !cwd || choosingHere) {
7276
- const options: PastTopicRef[] = saved ? JSON.parse(saved) : [];
7277
7497
  if (!this.store.output(`${input.id}:workspace`)) {
7498
+ const workspaceHint = choosingHere && input.route.platform === "slack"
7499
+ ? "잠시 후 다시 요청하거나, 현재 작업 폴더의 절대 경로로 답해 주세요. 다른 폴더에서 시작하려면 !new로 별도 작업을 요청해 주세요."
7500
+ : "잠시 후 다시 요청하거나 새 작업으로 시작하려면 절대 경로로 답해 주세요.";
7278
7501
  const question = options.length ? [choosingHere
7279
7502
  ? "어느 작업을 참고할까요? 번호로 답해 주세요. 5분 동안 답이 없으면 제가 골라 이 스레드에서 계속합니다."
7280
7503
  : "조건에 맞는 이전 작업이 여럿입니다. 이어갈 작업의 번호로 답해 주세요.",
7281
7504
  ...options.map((ref, index) =>
7282
7505
  `${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 메모리나 원래 세션을 조회하지 못해 이전 작업을 선택하지 않았습니다. 잠시 후 다시 요청하거나 새 작업으로 시작하려면 절대 경로로 답해 주세요."
7506
+ : this.store.getMeta(`topic-history-unavailable:${input.id}`) ? `OMP 메모리나 원래 세션을 조회하지 못해 이전 작업을 선택하지 않았습니다. ${workspaceHint}`
7284
7507
  : saved ? "설명에 맞는 이전 작업을 확인하지 못했습니다. 작업 단서를 더 넣어 다시 요청하거나, 새 작업으로 시작하려면 작업 디렉터리의 절대 경로로 답해 주세요."
7285
7508
  : "어느 저장소에서 작업할까요? 이 대화에서 사용한 저장소 이름이나 작업 디렉터리의 절대 경로로 답하면 원래 요청을 시작합니다.";
7286
- this.store.queueOutput({ id: `${input.id}:workspace`, sourceId: input.id, route: input.route, text: question });
7509
+ const explicit = input.route.platform === "slack" && input.route.threadId
7510
+ && input.id === `slack:${input.route.accountId}:${input.route.channelId}:${input.messageId}:original`
7511
+ && input.messageId && /^\d{1,20}\.\d{6}$/u.test(input.messageId);
7512
+ const text = explicit
7513
+ ? `${question}\n이 질문만 선택: \`!choose ${input.messageId} ${options.length ? "번호" : "/작업/경로"}\``
7514
+ : question;
7515
+ this.store.queueOutput({ id: `${input.id}:workspace`, sourceId: input.id, route: input.route, text });
7287
7516
  if (lane) this.background(this.syncLaneThreadTitle(lane));
7288
7517
  }
7289
- const deadline = choosingHere ? this.store.getMeta(`topic-choice-deadline:${input.id}`) : null;
7518
+ // Older ledgers may have started a timer for a failed lookup. Only a
7519
+ // question that presented real choices may select one automatically.
7520
+ const deadline = choosingHere && options.length ? this.store.getMeta(`topic-choice-deadline:${input.id}`) : null;
7290
7521
  if (!lane || deadline === null || Date.now() < Number(deadline) || this.store.hasPendingTopicChoice(input, Number(deadline))) return;
7291
7522
  const pauseRevision = this.pauseRevisions.get(owner);
7292
7523
  const local = (ref: PastTopicRef) => ref.laneId === owner && ref.sessionId === lane.sessionId;
@@ -7338,6 +7569,7 @@ export class Superagent {
7338
7569
  ...(creation === "sibling" ? { destination: { ...physicalRoute(input.route), threadId: null } } : {}),
7339
7570
  ...(workflow ? { workflow: { name: workflow.name, reason: workflow.reason } } : {}),
7340
7571
  });
7572
+ if (this.store.output(`${input.id}:kickoff`)?.state === "pending") return;
7341
7573
  } else {
7342
7574
  if (!lane) {
7343
7575
  const creatorPending = this.store.inputs(undefined, "pending").some(prior => prior.target === null
@@ -7352,11 +7584,15 @@ export class Superagent {
7352
7584
  this.store.settle(input.id, "done");
7353
7585
  } catch (error) {
7354
7586
  this.report(error);
7355
- this.store.settle(input.id, "uncertain", { id: `${input.id}:held`,
7356
- text: `주제 배정을 확인하지 못해 보류했습니다. 실행을 반복하지 않았습니다. 원래 스레드와 전송 기록을 확인한 뒤 /resolve ${input.id} 로 배정 보류만 종료할 수 있습니다.` });
7587
+ this.holdTopicPlacement(input);
7357
7588
  }
7358
7589
  }
7359
7590
 
7591
+ private holdTopicPlacement(input: InputRecord): void {
7592
+ this.store.settle(input.id, "uncertain", { id: `${input.id}:held`,
7593
+ text: `주제 배정을 확인하지 못해 보류했습니다. 실행을 반복하지 않았습니다. 원래 스레드와 전송 기록을 확인한 뒤 /resolve ${input.id} 로 배정 보류만 종료할 수 있습니다.` });
7594
+ }
7595
+
7360
7596
  private async pump(): Promise<void> {
7361
7597
  try {
7362
7598
  do {
@@ -7725,7 +7961,7 @@ export class Superagent {
7725
7961
  || this.store.input(owner.id)?.state !== "submitted"
7726
7962
  || input.state !== "pending" || input.target !== live.id || owner.workflow || input.workflow
7727
7963
  || routeKey(owner.route) !== routeKey(input.route) || this.headCommand(input)
7728
- || this.requestText(input).trimStart().startsWith("/") || this.headSuperstack(owner) || this.headSuperstack(input)
7964
+ || this.steeringTaskStartsWithCommand(input) || this.headSuperstack(owner) || this.headSuperstack(input)
7729
7965
  || this.store.approvals(live.id).length
7730
7966
  || this.modelChanges.has(live.id) || this.blocked.has(live.id)) return false;
7731
7967
  const inputs = this.store.inputs(live.id);
@@ -7776,6 +8012,17 @@ export class Superagent {
7776
8012
  return true;
7777
8013
  }
7778
8014
 
8015
+ private steeringTaskStartsWithCommand(input: InputRecord): boolean {
8016
+ if (!this.requestText(input).trimStart().startsWith("/")) return false;
8017
+ if (input.route.platform !== "slack") return true;
8018
+ const source = this.store.topicDelivery(input.id)?.source;
8019
+ if (!source) return true;
8020
+ const placement = placementText(source);
8021
+ if (unverifiedSlackWorkspaceTask(source, placement)) return false;
8022
+ const projected = ownerPlacementWorkflow(source, placement, this.requestText(source, placement)).projection;
8023
+ return !projected?.selectorChanged || projected.text.trimStart().startsWith("/");
8024
+ }
8025
+
7779
8026
  private async dispatch(live: Live, input: InputRecord, steering = false): Promise<void> {
7780
8027
  if (this.restartFence() || live.id === "main" && this.headRecoveryActive()) return;
7781
8028
  const owner = live.input;
@@ -7841,8 +8088,10 @@ export class Superagent {
7841
8088
  text: "같은 주제에서 더 나중에 보낸 메시지를 먼저 접수해, 뒤늦게 도착한 이 요청은 실행하지 않았습니다. 여전히 필요한 작업이면 새 메시지로 지시해 주세요." });
7842
8089
  return;
7843
8090
  }
7844
- const writtenTask = this.requestText(source);
7845
- const sourceRequest = ownerWorkflowRequest(source, writtenTask);
8091
+ const ownerPlacement = this.store.getMeta(`user-source:${source.id}`) === "true" ? placementText(source) : source.text;
8092
+ const writtenTask = this.requestText(source, ownerPlacement);
8093
+ const protectedWorkspaceTask = unverifiedSlackWorkspaceTask(source, ownerPlacement);
8094
+ const sourceRequest = ownerPlacementWorkflow(source, ownerPlacement, writtenTask);
7846
8095
  const projectedTask = sourceRequest.projection
7847
8096
  && (directTopic || topicOwned || input.workflow || sourceRequest.projection.selectorChanged)
7848
8097
  ? sourceRequest.projection.text : undefined;
@@ -7851,7 +8100,7 @@ export class Superagent {
7851
8100
  const previous: PastTopicRef | null = pin ? JSON.parse(pin) : null;
7852
8101
  if (previous) {
7853
8102
  const lane = this.requireLane(live.id);
7854
- const inPlace = discordWorkThread(source.route) && routeKey(lane.route) === routeKey(source.route);
8103
+ const inPlace = nativeWorkThread(source.route) && routeKey(lane.route) === routeKey(source.route);
7855
8104
  if (inPlace || lane.cwd === previous.cwd) {
7856
8105
  try { historyContext = await this.previousContext(source, previous, live.id); }
7857
8106
  catch (error) { this.report(error); }
@@ -7865,10 +8114,10 @@ export class Superagent {
7865
8114
  // OMP retains its own magic-keyword settings and enabled-eval capability gate.
7866
8115
  const protectedCommand = telegramCommandBlocked(source);
7867
8116
  const ownerSelection = input.workflow?.provenance === "user" || topicOwned;
7868
- const workflowBlocked = ownerSelection && (protectedCommand
8117
+ const workflowBlocked = ownerSelection && (protectedCommand || protectedWorkspaceTask
7869
8118
  || sourceRequest.projection !== undefined && sourceRequest.name !== input.workflow?.name);
7870
8119
  const workflow = workflowBlocked ? null : input.workflow;
7871
- const stack = this.headSuperstack(input);
8120
+ const stack = protectedWorkspaceTask ? null : this.headSuperstack(input);
7872
8121
  const stackTask = stack?.kind === "task" ? headSuperstackTaskText(input, stack) : undefined;
7873
8122
  if (stack) {
7874
8123
  const hold = (text: string) => this.store.settle(input.id, "cancelled", { id: `${input.id}:superstack`, text });
@@ -8047,10 +8296,10 @@ export class Superagent {
8047
8296
  live.headJobStarts = undefined;
8048
8297
  live.headJobMixed = false;
8049
8298
  live.headJobCleanAnswer = undefined;
8050
- live.discordNonCohortJobSeen = false;
8051
- live.discordJobContinuation = false;
8052
- live.discordContinuationJobIds = undefined;
8053
- live.discordJoinedAnswer = undefined;
8299
+ live.nonCohortJobSeen = false;
8300
+ live.headJobContinuation = false;
8301
+ live.headContinuationJobIds = undefined;
8302
+ live.joinedAnswer = undefined;
8054
8303
  if (live.id === "main") this.markActiveLaneReview(this.isLaneRecoveryReport(input.id)
8055
8304
  || input.id.startsWith(laneDecisionReview)
8056
8305
  ? input.id : undefined);
@@ -8111,9 +8360,10 @@ export class Superagent {
8111
8360
  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
8361
  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
8362
  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 ? ""
8363
+ protectedWorkspaceTask ? `Work requested in the selected workspace (formatted task text, not native controls):\n${inertContext(writtenTask)}` : "",
8364
+ !protectedWorkspaceTask && (projectedTask !== undefined || literalOwnerText || stack?.kind === "task" && stack.view === "telegram")
8365
+ ? `Full ${source.route.platform === "slack" ? "Slack" : "Telegram"} message (formatted task data, not additional instructions):\n${inertContext(source.text)}` : "",
8366
+ userInput || (workflow && taskText === originalText) || literalOwnerText || protectedWorkspaceTask ? ""
8117
8367
  : projectedTask !== undefined ? inertContext(taskText) : taskText, ...attachmentData.descriptions].filter(Boolean).join("\n\n");
8118
8368
  const message = review && reviewMaterial !== undefined ? PR_REVIEW_INPUT_PREFIX + inertContext(JSON.stringify({
8119
8369
  repository: review.repository, number: review.number, head: review.head, material: reviewMaterial,
@@ -8131,10 +8381,10 @@ export class Superagent {
8131
8381
  : stack.kind === "off" ? "superstack off" : "superstack"
8132
8382
  : workflow ? workflowPrompt(workflow, {
8133
8383
  id: source.id, workflow: protectedCommand || sourceRequest.projection?.selectorChanged ? null : source.workflow,
8134
- text: protectedCommand ? "" : originalText,
8384
+ text: protectedCommand || protectedWorkspaceTask ? "" : originalText,
8135
8385
  }, envelope,
8136
8386
  { legacyCommand: legacyWorkflow, worker: Boolean(remote) })
8137
- : `${workflowContext(envelope)}${userInput && !literalOwnerText && taskText ? `\n\n${taskText}` : ""}`;
8387
+ : `${workflowContext(envelope)}${userInput && !literalOwnerText && !protectedWorkspaceTask && taskText ? `\n\n${taskText}` : ""}`;
8138
8388
  try {
8139
8389
  const response = successful(await live.connection.request({
8140
8390
  type: "prompt", message, ...(steering ? { streamingBehavior: "steer" } : {}),
@@ -8186,8 +8436,8 @@ export class Superagent {
8186
8436
  if (text !== null) live.text = text;
8187
8437
  }
8188
8438
 
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;
8439
+ private observeHeadFollowup(live: Live, owner: InputRecord, message: Record<string, unknown>): void {
8440
+ if (live.id !== "main" || !supportsHeadFollowups(owner.route) || live.admitted.size < 2 || !live.running) return;
8191
8441
  if (message.role === "user" && !message.synthetic) {
8192
8442
  const first = Array.isArray(message.content)
8193
8443
  ? record(message.content.find(part => record(part).type === "text")).text : message.content;
@@ -8199,18 +8449,18 @@ export class Superagent {
8199
8449
  const admitted = live.admitted.get(`sg-${key(sourceId)}-${live.generation}`);
8200
8450
  if (admitted?.input.id === sourceId && admitted.input.messageId
8201
8451
  && routeKey(admitted.input.route) === routeKey(owner.route)) {
8202
- admitted.discordFollowupEnteredAt ??= live.nativeVersion;
8452
+ admitted.followupEnteredAt ??= live.nativeVersion;
8203
8453
  }
8204
8454
  } else if (message.role === "assistant" && !live.headJobMixed) {
8205
8455
  if (message.stopReason === "error" || message.stopReason === "aborted") {
8206
- live.discordJoinedAnswer = undefined;
8456
+ live.joinedAnswer = undefined;
8207
8457
  return;
8208
8458
  }
8209
8459
  const text = assistantText(message);
8210
8460
  // A native final uses the same block classification as canonical
8211
8461
  // delivery. A later answer after an unrelated job cannot inherit proof,
8212
8462
  // even if its text happens to be identical to the earlier final.
8213
- if (text !== null) live.discordJoinedAnswer = live.discordNonCohortJobSeen ? undefined
8463
+ if (text !== null) live.joinedAnswer = live.nonCohortJobSeen ? undefined
8214
8464
  : { text, observedAt: live.nativeVersion };
8215
8465
  }
8216
8466
  }
@@ -8264,31 +8514,31 @@ export class Superagent {
8264
8514
  if (message.stopReason === "stop") {
8265
8515
  const text = assistantText(message);
8266
8516
  if (text !== null) live.headJobCleanAnswer = { text,
8267
- ...(input?.route.platform === "discord" && !live.discordNonCohortJobSeen
8268
- ? { discordFollowupProofAt: live.nativeVersion } : {}) };
8517
+ ...(supportsHeadFollowups(input?.route) && !live.nonCohortJobSeen
8518
+ ? { followupProofAt: live.nativeVersion } : {}) };
8269
8519
  } else if (message.stopReason === "error" || message.stopReason === "aborted")
8270
8520
  live.headJobCleanAnswer = undefined;
8271
8521
  }
8272
- if (message.role === "toolResult" && (live.headJobPromptSeen || live.discordJobContinuation)
8522
+ if (message.role === "toolResult" && (live.headJobPromptSeen || live.headJobContinuation)
8273
8523
  && live.running && message.isError !== true) {
8274
8524
  const job = record(record(message.details).async);
8275
8525
  if (job.state === "running" && typeof job.jobId === "string" && job.type === message.toolName
8276
8526
  && typeof message.toolCallId === "string" && message.toolCallId
8277
8527
  && (job.type === "bash" || job.type === "eval" || job.type === "task")) {
8278
8528
  if (live.headJobPromptSeen) (live.headJobStarts ??= new Map()).set(job.jobId, message.toolCallId);
8279
- else (live.discordContinuationJobIds ??= new Set()).add(job.jobId);
8529
+ else (live.headContinuationJobIds ??= new Set()).add(job.jobId);
8280
8530
  }
8281
8531
  }
8282
8532
  if (message.role !== "custom") return;
8283
8533
  const items = message.customType === "async-result" ? headJobResults(message) : undefined;
8284
8534
  // The existing delivery boundary is the conversation. The stricter link
8285
8535
  // boundary is the current set of admitted requests, even in that same topic.
8286
- if (input?.route.platform === "discord") {
8536
+ if (input && supportsHeadFollowups(input.route)) {
8287
8537
  const ownsJob = (id: unknown) => {
8288
8538
  if (typeof id !== "string" || !id) return false;
8289
8539
  const owner = live.headJobOwners?.get(id)?.input;
8290
8540
  return owner ? owner.id === input.id || live.admitted.get(owner.requestId ?? "")?.input.id === owner.id
8291
- : live.headJobStarts?.has(id) || live.discordContinuationJobIds?.has(id);
8541
+ : live.headJobStarts?.has(id) || live.headContinuationJobIds?.has(id);
8292
8542
  };
8293
8543
  if (message.customType === "async-notify") {
8294
8544
  const reports = record(message.details).reports;
@@ -8296,17 +8546,17 @@ export class Superagent {
8296
8546
  if (!Array.isArray(reports) || !reports.length || reports.some(item => {
8297
8547
  const report = record(item);
8298
8548
  return report.type !== "bash" || !ownsJob(report.id);
8299
- })) live.discordNonCohortJobSeen = true;
8549
+ })) live.nonCohortJobSeen = true;
8300
8550
  } else if (message.customType === "launch-completion") {
8301
8551
  // No supervised-service launch is bound to a request by this path.
8302
- live.discordNonCohortJobSeen = true;
8552
+ live.nonCohortJobSeen = true;
8303
8553
  } else if (items) {
8304
- if (!items.size || [...items.keys()].some(id => !ownsJob(id))) live.discordNonCohortJobSeen = true;
8554
+ if (!items.size || [...items.keys()].some(id => !ownsJob(id))) live.nonCohortJobSeen = true;
8305
8555
  // A matched completion can prove that a new native run continues the
8306
8556
  // same admissions without re-emitting the original user's prompt.
8307
- if (live.running && !live.discordNonCohortJobSeen) live.discordJobContinuation = true;
8557
+ if (live.running && !live.nonCohortJobSeen) live.headJobContinuation = true;
8308
8558
  }
8309
- if (live.discordNonCohortJobSeen) live.discordJobContinuation = false;
8559
+ if (live.nonCohortJobSeen) live.headJobContinuation = false;
8310
8560
  }
8311
8561
  if (!items?.size || !live.headJobOwners?.size) return;
8312
8562
  const batch = live.headJobBatch ??= new Map();
@@ -8442,7 +8692,7 @@ export class Superagent {
8442
8692
  if (live.id === "main") {
8443
8693
  live.headJobYield = undefined;
8444
8694
  live.headJobPromptSeen = false;
8445
- live.discordJobContinuation = false;
8695
+ live.headJobContinuation = false;
8446
8696
  live.headJobLoop = live.input ? "foreground" : "background";
8447
8697
  }
8448
8698
  this.resultAttachments.clearStarts(live);
@@ -8493,7 +8743,7 @@ export class Superagent {
8493
8743
  if (frame.type === "message_end" && live.id === "main") this.observeHeadJobMessage(live, record(frame.message));
8494
8744
  if (frame.type === "message_end" && live.input) {
8495
8745
  const message = record(frame.message);
8496
- this.observeDiscordHeadFollowup(live, live.input, message);
8746
+ this.observeHeadFollowup(live, live.input, message);
8497
8747
  if (message.role === "toolResult") {
8498
8748
  this.syncLaneObservations(live, message);
8499
8749
  }
@@ -8505,7 +8755,7 @@ export class Superagent {
8505
8755
  if (live.id === "main" && live.headJobMixed) return;
8506
8756
  const eventId = key(JSON.stringify([live.sessionId, live.generation, progress.identity]));
8507
8757
  try {
8508
- if (this.store.progress(live.input.id, live.generation, live.sessionId, eventId, progress.text, this.config.discord?.editProgressInPlace === true)) {
8758
+ if (this.store.progress(live.input.id, live.generation, live.sessionId, eventId, progress.text, this.editProgressInPlace(live.input.route))) {
8509
8759
  this.wakeOutputs();
8510
8760
  this.background(this.kick());
8511
8761
  }
@@ -8722,9 +8972,9 @@ export class Superagent {
8722
8972
  : headFailed
8723
8973
  ? `실행이 실패했습니다. 작업 완료로 처리하지 않았고 다시 실행하지 않았습니다. 실패 전에 도구가 실행됐거나 효과를 확인할 수 없어 뒤 HEAD 요청이 막혀 있습니다. 원래 작업을 확인한 뒤 /resolve ${input.id} 로 이 요청을 닫으면 다음 요청을 처리합니다.`
8724
8974
  : "실행이 실패했습니다. 작업 완료로 처리하지 않았습니다.");
8725
- const discordHeadFollowups: string[] = [];
8726
- const sharedAnswerAt = !completed ? undefined : live.headJobMixed ? live.headJobCleanAnswer?.discordFollowupProofAt
8727
- : live.discordJoinedAnswer?.text === text ? live.discordJoinedAnswer.observedAt : undefined;
8975
+ const headFollowups: string[] = [];
8976
+ const sharedAnswerAt = !completed ? undefined : live.headJobMixed ? live.headJobCleanAnswer?.followupProofAt
8977
+ : live.joinedAnswer?.text === text ? live.joinedAnswer.observedAt : undefined;
8728
8978
  for (const admitted of admissions) {
8729
8979
  this.activity(admitted.input, false);
8730
8980
  if (admitted.input.id === input.id || this.store.input(admitted.input.id)?.state === "cancelled") continue;
@@ -8741,8 +8991,8 @@ export class Superagent {
8741
8991
  separateError ? { id: `${admitted.input.id}:answer`, laneFailure: admitted.result?.quota ? "quota" : "recover",
8742
8992
  text: laneFailureNotice(this.store, admitted.input, { quota: !!admitted.result?.quota, toolFree: false, result: admitted.result }) } : undefined);
8743
8993
  if (settled && status === "completed" && admitted.result?.agentInvoked && sharedAnswerAt !== undefined
8744
- && admitted.discordFollowupEnteredAt !== undefined && admitted.discordFollowupEnteredAt < sharedAnswerAt) {
8745
- discordHeadFollowups.push(admitted.input.id);
8994
+ && admitted.followupEnteredAt !== undefined && admitted.followupEnteredAt < sharedAnswerAt) {
8995
+ headFollowups.push(admitted.input.id);
8746
8996
  }
8747
8997
  }
8748
8998
  let headModel: HeadModelChange | undefined;
@@ -8765,8 +9015,8 @@ export class Superagent {
8765
9015
  this.store.settle(input.id, state, !reviewingLaneDecision && (text || live.id !== "main")
8766
9016
  ? { id: `${input.id}:answer`, text,
8767
9017
  ...(laneError ? { laneFailure: quota ? "quota" : "recover" } : {}),
8768
- ...(discordHeadFollowups.length ? { discordHeadFollowups } : {}) }
8769
- : undefined, headModel, this.config.discord?.editProgressInPlace === true);
9018
+ ...(headFollowups.length ? { headFollowups } : {}) }
9019
+ : undefined, headModel, this.editProgressInPlace(input.route));
8770
9020
  if (live.id === "main") this.headCoordinationActivityAt = performance.now();
8771
9021
  if (live.input === input) {
8772
9022
  live.admitted.clear();
@@ -8851,7 +9101,7 @@ export class Superagent {
8851
9101
  // The pin establishes that the report route is not an approval fallback.
8852
9102
  // Recognize the parent handoff even if that pin or its owner link is lost.
8853
9103
  if (this.store.getMeta(`report-approval-source:${reportId}`) !== null) return true;
8854
- if (!discordWorkThread(lane.route) || lane.route.topicId !== undefined) return false;
9104
+ if (!nativeWorkThread(lane.route) || lane.route.topicId !== undefined) return false;
8855
9105
  const failedId = this.store.getMeta(`lane-recovery-input:${reportId}`);
8856
9106
  if (failedId && this.store.getMeta(`handoff-reply:${failedId}`) !== null) return true;
8857
9107
  const owner = this.store.ownerSource(reportId);
@@ -9182,12 +9432,12 @@ export class Superagent {
9182
9432
  if (route) {
9183
9433
  const routeKeyValue = physicalRouteKey(route);
9184
9434
  if (!this.routeOutbounds.has(routeKeyValue)) {
9185
- const batch = this.filterFlushable(this.store.outputs(routeKeyValue));
9435
+ const batch = this.filterFlushable(this.store.deliverableOutputs(routeKeyValue));
9186
9436
  if (batch.length) this.background(this.startOutputRouteWorker(routeKeyValue, batch));
9187
9437
  }
9188
9438
  return;
9189
9439
  }
9190
- const byRoute = Map.groupBy(this.filterFlushable(this.store.outputs()), output => physicalRouteKey(output.route));
9440
+ const byRoute = Map.groupBy(this.filterFlushable(this.store.deliverableOutputs()), output => physicalRouteKey(output.route));
9191
9441
  for (const [routeKeyValue, batch] of byRoute) {
9192
9442
  if (!this.routeOutbounds.has(routeKeyValue)) this.background(this.startOutputRouteWorker(routeKeyValue, batch));
9193
9443
  }
@@ -9202,7 +9452,7 @@ export class Superagent {
9202
9452
  release();
9203
9453
  return delivered;
9204
9454
  }
9205
- const outputs = batch ?? this.filterFlushable(this.store.outputs(routeKeyValue));
9455
+ const outputs = batch ?? this.filterFlushable(this.store.deliverableOutputs(routeKeyValue));
9206
9456
  batch = undefined;
9207
9457
  if (outputs.every(output => deferredLaneNotices.has(output.id))) {
9208
9458
  // Release route ownership synchronously with the final empty-queue read so
@@ -9226,12 +9476,12 @@ export class Superagent {
9226
9476
  }
9227
9477
  if (verification === "deferred") { deferredLaneNotices.add(output.id); continue; }
9228
9478
  if (verification === "held") {
9229
- if (!this.stopped && this.store.claimOutput(output.id, this.config.discord?.editProgressInPlace === true))
9479
+ if (!this.stopped && this.store.claimOutput(output.id, this.editProgressInPlace(output.route)))
9230
9480
  this.store.finishOutput(output.id, "failed", undefined, "Lane watch notice is held or no longer tracked");
9231
9481
  continue;
9232
9482
  }
9233
9483
  }
9234
- if (this.stopped || !this.store.claimOutput(output.id, this.config.discord?.editProgressInPlace === true)) continue;
9484
+ if (this.stopped || !this.store.claimOutput(output.id, this.editProgressInPlace(output.route))) continue;
9235
9485
  if (output.id === `${output.sourceId}:cron-shell` && this.cronJobs.isDisabledShellRun(output.sourceId)) {
9236
9486
  this.store.finishOutput(output.id, "failed", undefined, "Legacy cron shell output was not sent");
9237
9487
  continue;
@@ -9262,12 +9512,29 @@ export class Superagent {
9262
9512
  try { this.resultAttachments.authorizeOwner(output.route); }
9263
9513
  catch (error) { throw new DeliveryError("Result attachment route is no longer authorized", "rejected", undefined, { cause: error }); }
9264
9514
  }
9515
+ if (output.id === `${output.sourceId}:restart-ack`) {
9516
+ const restart = this.restartFence();
9517
+ if (restart?.ackOutputId !== output.id || restart.inputId !== output.sourceId
9518
+ || this.store.getMeta("gateway:operator-stop") !== (restart.stopBoundary ?? null)) {
9519
+ throw new DeliveryError("Restart was superseded before the acknowledgement was posted", "rejected");
9520
+ }
9521
+ }
9265
9522
  // The claim may have fixed an in-place status edit target.
9266
9523
  remoteId = await this.messenger.send(this.store.output(output.id)!);
9267
9524
  }
9268
9525
  catch (error) {
9269
9526
  const rejected = error instanceof DeliveryError && error.certainty === "rejected";
9527
+ if ((!rejected && this.store.reconcileSlackOutput(output.id)) || this.store.reconcileSlackJoinedOutput(output.id)) {
9528
+ const disposition = this.store.output(output.id)?.state;
9529
+ if (disposition === "pending") return delivered;
9530
+ delivered ||= disposition === "sent";
9531
+ this.outputSettled(output);
9532
+ continue;
9533
+ }
9534
+ if (rejected && error.retryAfterMs !== undefined && this.store.deferSlackJoinedOutput(output.id, error.retryAfterMs))
9535
+ return delivered;
9270
9536
  this.store.finishOutput(output.id, rejected ? "failed" : "uncertain", undefined, rejected ? "Messenger rejected delivery" : "Messenger send outcome uncertain");
9537
+ this.outputSettled(output);
9271
9538
  if (rejected) this.resultAttachments.discard(output.resultAttachment?.payload);
9272
9539
  if (resultInputId) this.syncLaneThreadAfterResult(resultInputId);
9273
9540
  this.report(new Error(`Delivery ${output.id} ${rejected ? "rejected" : "uncertain"}`));
@@ -9275,6 +9542,7 @@ export class Superagent {
9275
9542
  }
9276
9543
  // Persist a successful remote send without reinterpreting a local failure.
9277
9544
  this.store.finishOutput(output.id, "sent", remoteId);
9545
+ this.outputSettled(output);
9278
9546
  this.resultAttachments.discard(output.resultAttachment?.payload);
9279
9547
  if (resultInputId) this.syncLaneThreadAfterResult(resultInputId);
9280
9548
  delivered = true;
@@ -9282,10 +9550,25 @@ export class Superagent {
9282
9550
  }
9283
9551
  }
9284
9552
 
9553
+ private outputSettled(output: OutputRecord): void {
9554
+ if (output.route.platform === "slack" && output.id === `${output.sourceId}:workspace`)
9555
+ this.routingDrain.available(routingConversation(output.route));
9556
+ if (this.store.getMeta(`kickoff-output:${output.sourceId}`) === output.id) {
9557
+ // A kickoff can settle inside the current pump's final flush, after its
9558
+ // scan skipped the held handoff. Keep the wake in that same drain.
9559
+ if (this.pumping) this.repeat = true;
9560
+ else this.background(this.kick());
9561
+ }
9562
+ if (this.restartAckWaiting === output.id) {
9563
+ this.restartAckWaiting = undefined;
9564
+ const input = this.store.input(output.sourceId);
9565
+ if (input) this.background(this.runHeadRestart(input));
9566
+ }
9567
+ }
9285
9568
 
9286
9569
  private async flushOutputs(targetRouteKey?: string): Promise<void> {
9287
9570
  if (this.stopped) return;
9288
- const pending = this.filterFlushable(this.store.outputs(targetRouteKey));
9571
+ const pending = this.filterFlushable(this.store.deliverableOutputs(targetRouteKey));
9289
9572
  if (!pending.length) {
9290
9573
  if (targetRouteKey) {
9291
9574
  const existing = this.routeOutbounds.get(targetRouteKey);