work-ally 0.2.0-alpha.1

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 (172) hide show
  1. package/AGENTS.md +110 -0
  2. package/DASHBOARD.md +160 -0
  3. package/PRODUCT.md +113 -0
  4. package/README.md +403 -0
  5. package/ally.sh +171 -0
  6. package/bridge/src/approval-rules.ts +360 -0
  7. package/bridge/src/channel-delivery.ts +207 -0
  8. package/bridge/src/channel-types.ts +22 -0
  9. package/bridge/src/channels/fake/adapter.ts +31 -0
  10. package/bridge/src/channels/feishu/adapter.ts +411 -0
  11. package/bridge/src/channels/feishu/approvals.ts +6 -0
  12. package/bridge/src/channels/feishu/formatter.ts +276 -0
  13. package/bridge/src/channels/feishu/normalize.ts +368 -0
  14. package/bridge/src/codex-config.ts +52 -0
  15. package/bridge/src/config.ts +240 -0
  16. package/bridge/src/fake-runtime-client.ts +505 -0
  17. package/bridge/src/handoff-service.ts +494 -0
  18. package/bridge/src/logger.ts +194 -0
  19. package/bridge/src/memory-digest.ts +186 -0
  20. package/bridge/src/receiver-approval-autonomy.ts +158 -0
  21. package/bridge/src/receiver-control-core.ts +140 -0
  22. package/bridge/src/receiver-control-work-session.ts +218 -0
  23. package/bridge/src/receiver-control.ts +83 -0
  24. package/bridge/src/receiver-delivery.ts +136 -0
  25. package/bridge/src/receiver-helpers.ts +96 -0
  26. package/bridge/src/receiver-human-gate.ts +333 -0
  27. package/bridge/src/receiver-inbound-preflight.ts +162 -0
  28. package/bridge/src/receiver-recovery.ts +236 -0
  29. package/bridge/src/receiver-runtime-callbacks.ts +367 -0
  30. package/bridge/src/receiver-runtime-policy.ts +132 -0
  31. package/bridge/src/receiver-runtime-state.ts +124 -0
  32. package/bridge/src/receiver-support-actions.ts +189 -0
  33. package/bridge/src/receiver-thread-start.ts +57 -0
  34. package/bridge/src/receiver-turn-coordination.ts +94 -0
  35. package/bridge/src/receiver-turn-execution.ts +257 -0
  36. package/bridge/src/receiver-turn-failure.ts +143 -0
  37. package/bridge/src/receiver-turn-result.ts +185 -0
  38. package/bridge/src/receiver-turn-steer.ts +70 -0
  39. package/bridge/src/receiver-work-session.ts +76 -0
  40. package/bridge/src/receiver.ts +329 -0
  41. package/bridge/src/router.ts +62 -0
  42. package/bridge/src/runtime-client-agent-messages.ts +150 -0
  43. package/bridge/src/runtime-client-message-dispatch.ts +176 -0
  44. package/bridge/src/runtime-client-protocol.ts +411 -0
  45. package/bridge/src/runtime-client-request-ops.ts +56 -0
  46. package/bridge/src/runtime-client-run-turn.ts +158 -0
  47. package/bridge/src/runtime-client-thread-ops.ts +270 -0
  48. package/bridge/src/runtime-client-transport.ts +309 -0
  49. package/bridge/src/runtime-client-turn-poll.ts +224 -0
  50. package/bridge/src/runtime-client-turn-read.ts +185 -0
  51. package/bridge/src/runtime-client-turn-state.ts +105 -0
  52. package/bridge/src/runtime-client.ts +344 -0
  53. package/bridge/src/runtime-user-input.ts +403 -0
  54. package/bridge/src/scheduler.ts +239 -0
  55. package/bridge/src/server-handoff-command.ts +364 -0
  56. package/bridge/src/server-main.ts +80 -0
  57. package/bridge/src/server-routine-command.ts +60 -0
  58. package/bridge/src/server-routine-execution.ts +222 -0
  59. package/bridge/src/server-runtime-app-support.ts +107 -0
  60. package/bridge/src/server-runtime-app.ts +238 -0
  61. package/bridge/src/server-thread-sync-command.ts +63 -0
  62. package/bridge/src/server.ts +17 -0
  63. package/bridge/src/session-store-delivery.ts +220 -0
  64. package/bridge/src/session-store-human-gate.ts +380 -0
  65. package/bridge/src/session-store-inbound-acceptance.ts +66 -0
  66. package/bridge/src/session-store-meta.ts +134 -0
  67. package/bridge/src/session-store-turn-ledger.ts +272 -0
  68. package/bridge/src/session-store.ts +380 -0
  69. package/bridge/src/system-notify.ts +220 -0
  70. package/bridge/src/thread-sync.ts +200 -0
  71. package/bridge/src/translator.ts +494 -0
  72. package/bridge/src/types.ts +289 -0
  73. package/bridge/src/utils.ts +104 -0
  74. package/bridge/src/work-session-store.ts +471 -0
  75. package/docs/.gitkeep +0 -0
  76. package/docs/architecture/codex-feishu-bridge-proposal.md +2742 -0
  77. package/docs/completed/FEATURE-feishu-markdown-and-reply-support.md +327 -0
  78. package/docs/completed/README.md +21 -0
  79. package/docs/completed/SPEC-approval-autonomy-and-safe-defaults.md +205 -0
  80. package/docs/completed/SPEC-approval-batch-and-strict-reply-shortcuts.md +153 -0
  81. package/docs/completed/SPEC-conversation-noise-reduction-and-busy-input-gate.md +538 -0
  82. package/docs/completed/SPEC-engineering-sop-skillization.md +190 -0
  83. package/docs/completed/SPEC-faithful-bridge-core-thinning-v2.md +376 -0
  84. package/docs/completed/SPEC-faithful-bridge-core-thinning.md +1071 -0
  85. package/docs/completed/SPEC-group-chat-sender-identity.md +301 -0
  86. package/docs/completed/SPEC-middleware-exception-visibility.md +227 -0
  87. package/docs/completed/SPEC-nightly-memory-digest-visibility.md +121 -0
  88. package/docs/completed/SPEC-project-group-chat-human-centered-conversation-mapping.md +326 -0
  89. package/docs/completed/SPEC-remove-cli-persona-bootstrap.md +201 -0
  90. package/docs/developer-workflow.md +49 -0
  91. package/docs/implementation/SPEC-codex-same-machine-session-handoff-implementation.md +239 -0
  92. package/docs/implementation/test-coverage-map.md +363 -0
  93. package/docs/implementation/work-ally-implementation-guide.md +790 -0
  94. package/docs/issues/README.md +10 -0
  95. package/docs/issues/pending/ANALYSIS-ally-premature-recovery-notice-and-task-state-semantics-2026-03-18.md +295 -0
  96. package/docs/issues/resolved/ANALYSIS-approval-waiting-visible-but-approval-artifact-missing-2026-03-16.md +466 -0
  97. package/docs/issues/resolved/ANALYSIS-blocking-state-visible-without-user-actionable-artifact-2026-03-16.md +261 -0
  98. package/docs/issues/resolved/ANALYSIS-codex-app-server-transport-disconnect-semantics-2026-03-14.md +606 -0
  99. package/docs/issues/resolved/ANALYSIS-premature-terminalization-on-fresh-thread-poll-and-object-error-leak-2026-03-16.md +348 -0
  100. package/docs/issues/resolved/ANALYSIS-runtime-turn-delivery-and-recovery-2026-03-14.md +603 -0
  101. package/docs/issues/resolved/ANALYSIS-self-test-gap-approval-waiting-visible-but-approval-artifact-missing-2026-03-16.md +166 -0
  102. package/docs/issues/resolved/ANALYSIS-self-test-gap-blocking-state-visible-without-user-actionable-artifact-2026-03-16.md +186 -0
  103. package/docs/issues/resolved/ANALYSIS-self-test-gap-premature-terminalization-on-fresh-thread-poll-and-object-error-leak-2026-03-16.md +166 -0
  104. package/docs/issues/resolved/REPORT-ally-runtime-turn-delivery-3b42fb8-2026-03-15.md +373 -0
  105. package/docs/manual-acceptance.md +127 -0
  106. package/docs/ops-runbook.md +44 -0
  107. package/docs/planning/FEATURE-memory-system.md +748 -0
  108. package/docs/planning/SPEC-active-turn-steer-and-context-compaction-visibility.md +269 -0
  109. package/docs/planning/SPEC-approval-rules-inheritance-and-local-validation-lane.md +450 -0
  110. package/docs/planning/SPEC-assistant-persona-bootstrap.md +199 -0
  111. package/docs/planning/SPEC-assistant-rename.md +610 -0
  112. package/docs/planning/SPEC-bridge-app-server-protocol-alignment.md +667 -0
  113. package/docs/planning/SPEC-claude-runtime-host-for-work-ally.md +434 -0
  114. package/docs/planning/SPEC-cli-feishu-codex-session-unification.md +236 -0
  115. package/docs/planning/SPEC-codex-same-machine-session-handoff.md +873 -0
  116. package/docs/planning/SPEC-feishu-reaction-shortcuts.md +282 -0
  117. package/docs/planning/SPEC-local-stable-release-boundary.md +166 -0
  118. package/docs/planning/SPEC-managed-thread-entry-and-surface-mobility.md +862 -0
  119. package/docs/planning/SPEC-minimal-bridge-semantics-and-user-visible-surface.md +362 -0
  120. package/docs/planning/SPEC-npm-alpha-distribution-and-install-first-release.md +222 -0
  121. package/docs/planning/SPEC-remove-websocket-runtime-transport.md +364 -0
  122. package/docs/planning/SPEC-runtime-abstraction-phase-1.md +424 -0
  123. package/docs/planning/SPEC-runtime-connection-and-turn-recovery-semantics.md +274 -0
  124. package/docs/planning/SPEC-session-presence-and-state-visibility.md +397 -0
  125. package/docs/planning/SPEC-skill-first-capability-packaging.md +338 -0
  126. package/docs/planning/SPEC-stable-archive-contract.md +456 -0
  127. package/docs/planning/SPEC-supervised-start-boundary.md +127 -0
  128. package/docs/planning/SPEC-user-barrier-reduction-and-activation.md +832 -0
  129. package/docs/planning/ally-next.md +1278 -0
  130. package/docs/planning/assistant-workbench-spec.md +725 -0
  131. package/docs/planning/product-workbench.md +283 -0
  132. package/docs/product-onboarding.md +227 -0
  133. package/docs/product-spec-standard.md +528 -0
  134. package/docs/troubleshooting.md +45 -0
  135. package/docs/user-quickstart.md +46 -0
  136. package/internal/dispatch.sh +95 -0
  137. package/internal/lib/common.sh +1450 -0
  138. package/internal/modules/assistant/manage.sh +1312 -0
  139. package/internal/modules/bootstrap/setup.sh +144 -0
  140. package/internal/modules/config/init-env.sh +10 -0
  141. package/internal/modules/global/manage.sh +154 -0
  142. package/internal/modules/handoff/manage.sh +54 -0
  143. package/internal/modules/mcp/manage.sh +83 -0
  144. package/internal/modules/ops/logs.sh +76 -0
  145. package/internal/modules/routines/manage.sh +55 -0
  146. package/internal/modules/runtime/assistant-autosave.sh +26 -0
  147. package/internal/modules/runtime/restart.sh +6 -0
  148. package/internal/modules/runtime/start.sh +283 -0
  149. package/internal/modules/runtime/status.sh +194 -0
  150. package/internal/modules/runtime/stop.sh +55 -0
  151. package/internal/modules/runtime/supervisor.sh +216 -0
  152. package/internal/modules/runtime/update.sh +26 -0
  153. package/package.json +41 -0
  154. package/runtime/config/.gitkeep +0 -0
  155. package/runtime/host/.gitkeep +0 -0
  156. package/runtime/host/healthcheck-codex-app-server.ts +22 -0
  157. package/runtime/host/ping-pong-codex-app-server.ts +66 -0
  158. package/runtime/host/probe-codex-app-server.ts +115 -0
  159. package/skills/archive-reader/SKILL.md +9 -0
  160. package/skills/feishu-production-debug/SKILL.md +37 -0
  161. package/skills/feishu-production-debug/references/feishu-debug-order.md +49 -0
  162. package/skills/feishu-production-debug/references/platform-permission-baseline.md +23 -0
  163. package/skills/issue-to-spec-triage/SKILL.md +44 -0
  164. package/skills/issue-to-spec-triage/references/triage-rules.md +66 -0
  165. package/skills/memory-digest/SKILL.md +9 -0
  166. package/skills/post-implementation-closure/SKILL.md +39 -0
  167. package/skills/post-implementation-closure/references/closure-checklist.md +45 -0
  168. package/skills/post-implementation-closure/references/doc-drift-map.md +49 -0
  169. package/skills/product-spec/SKILL.md +244 -0
  170. package/templates/env.example +5 -0
  171. package/templates/routines/nightly-memory-digest.yaml +10 -0
  172. package/templates/workspace/AGENTS.md +26 -0
@@ -0,0 +1,162 @@
1
+ import type { OutboundEnvelope } from './channel-types.ts';
2
+ import { logInfo, logWarn } from './logger.ts';
3
+ import type { SessionStore } from './session-store.ts';
4
+ import type { WaitingState } from './receiver-human-gate.ts';
5
+ import { pendingDeliveryIssueMessage, systemNoticeMessage, waitingUserInputFollowUpMessage } from './translator.ts';
6
+ import type { InboundMessage, RuntimeThreadStatus, SessionMeta } from './types.ts';
7
+
8
+ interface SendLike {
9
+ (
10
+ outbound: OutboundEnvelope,
11
+ extra?: Record<string, unknown>,
12
+ delivery?: { trackTurnId?: string | null },
13
+ ): Promise<boolean>;
14
+ }
15
+
16
+ interface InboundPreflightDeps {
17
+ sessionStore: SessionStore;
18
+ send: SendLike;
19
+ maybeResumePendingUserInput(message: InboundMessage): Promise<boolean>;
20
+ replayHiddenPendingApproval(conversationRef: InboundMessage['conversationRef'], threadId: string, turnId: string): Promise<boolean>;
21
+ replayHiddenPendingUserInput(conversationRef: InboundMessage['conversationRef'], threadId: string, turnId: string): Promise<boolean>;
22
+ redeliverPendingTurnResult(conversationRef: InboundMessage['conversationRef'], turnId: string): Promise<boolean>;
23
+ currentRuntimeThreadStatus(session: { threadId: string | null }): Promise<RuntimeThreadStatus | null>;
24
+ waitingStateFor(session: SessionMeta): WaitingState;
25
+ runtimeWaitingStateFor(status: RuntimeThreadStatus | null | undefined): WaitingState;
26
+ runtimeRecoveryKindFor(text: string): unknown;
27
+ maybeHandleWaitingApprovalShortcut(message: InboundMessage, session: SessionMeta): Promise<boolean>;
28
+ isActiveTurnStale(runtimeStatus: RuntimeThreadStatus | null): boolean;
29
+ clearRuntimeRecovery(ref: InboundMessage['conversationRef']): void;
30
+ steerActiveTurn(
31
+ message: InboundMessage,
32
+ session: SessionMeta,
33
+ runtimeWaitingState: WaitingState,
34
+ ): Promise<'handled' | 'retry_start' | null>;
35
+ }
36
+
37
+ export type InboundPreflightResult =
38
+ | { kind: 'handled' }
39
+ | { kind: 'continue'; session: SessionMeta };
40
+
41
+ export async function handleInboundPreflight(
42
+ deps: InboundPreflightDeps,
43
+ message: InboundMessage,
44
+ ): Promise<InboundPreflightResult> {
45
+ if (!message.text.trim()) {
46
+ logWarn('receiver', 'inbound_empty_text', {
47
+ messageId: message.messageId,
48
+ conversationId: message.conversationRef.conversationId,
49
+ });
50
+ await deps.send({
51
+ type: 'status_reply',
52
+ conversationRef: message.conversationRef,
53
+ text: '收到一条结构化消息,但当前无法稳定提取正文。请改发纯文本,或直接粘贴链接/文档地址。',
54
+ });
55
+ return { kind: 'handled' };
56
+ }
57
+
58
+ if (await deps.maybeResumePendingUserInput(message)) {
59
+ return { kind: 'handled' };
60
+ }
61
+
62
+ const latestSession = deps.sessionStore.getSession(message.conversationRef);
63
+ const latestDeliveryIssue = deps.sessionStore.findLatestDeliveryIssue(message.conversationRef);
64
+ if (
65
+ latestDeliveryIssue
66
+ && latestDeliveryIssue.messageId
67
+ && latestDeliveryIssue.messageId !== message.messageId
68
+ && latestSession?.lastMessageId === latestDeliveryIssue.messageId
69
+ ) {
70
+ const redelivered = await deps.redeliverPendingTurnResult(message.conversationRef, latestDeliveryIssue.turnId);
71
+ if (!redelivered) {
72
+ await deps.send({
73
+ type: 'status_reply',
74
+ conversationRef: message.conversationRef,
75
+ text: systemNoticeMessage(pendingDeliveryIssueMessage()),
76
+ }, {
77
+ source: 'pending_delivery_issue_notice',
78
+ thread_id: latestDeliveryIssue.threadId,
79
+ turn_id: latestDeliveryIssue.turnId,
80
+ failed_message_id: latestDeliveryIssue.messageId,
81
+ });
82
+ }
83
+ }
84
+
85
+ const session = deps.sessionStore.ensureSession(message.conversationRef);
86
+ const runtimeStatus = await deps.currentRuntimeThreadStatus(session);
87
+ const waitingState = deps.waitingStateFor(session);
88
+ const runtimeWaitingState = waitingState ? null : deps.runtimeWaitingStateFor(runtimeStatus);
89
+ if (!session.activeTurnId && session.lastTurnId) {
90
+ const previousTurn = deps.sessionStore.getTurnLedger(message.conversationRef, session.lastTurnId);
91
+ if (previousTurn && previousTurn.executionStatus === 'failed' && deps.runtimeRecoveryKindFor(previousTurn.error || '')) {
92
+ deps.sessionStore.markTurnSuppressed(message.conversationRef, session.lastTurnId, {
93
+ threadId: previousTurn.threadId || session.threadId,
94
+ suppressedByMessageId: message.messageId,
95
+ suppressedByTurnId: null,
96
+ reason: 'session advanced after unresolved recovery state',
97
+ });
98
+ }
99
+ }
100
+
101
+ if (waitingState && session.threadId && session.activeTurnId) {
102
+ logInfo('receiver', 'waiting_user_follow_up_intercepted', {
103
+ messageId: message.messageId,
104
+ conversationId: message.conversationRef.conversationId,
105
+ threadId: session.threadId,
106
+ activeTurnId: session.activeTurnId,
107
+ waitingState,
108
+ });
109
+ if (waitingState === 'approval' && await deps.maybeHandleWaitingApprovalShortcut(message, session)) {
110
+ return { kind: 'handled' };
111
+ }
112
+ await deps.send({
113
+ type: 'status_reply',
114
+ conversationRef: message.conversationRef,
115
+ text: systemNoticeMessage(waitingUserInputFollowUpMessage()),
116
+ }, {
117
+ source: 'waiting_user_follow_up',
118
+ thread_id: session.threadId,
119
+ turn_id: session.activeTurnId,
120
+ waiting_state: waitingState,
121
+ message_id: message.messageId,
122
+ });
123
+ return { kind: 'handled' };
124
+ }
125
+
126
+ if (!waitingState && runtimeWaitingState && session.threadId && session.activeTurnId) {
127
+ const replayed = runtimeWaitingState === 'approval'
128
+ ? await deps.replayHiddenPendingApproval(message.conversationRef, session.threadId, session.activeTurnId)
129
+ : await deps.replayHiddenPendingUserInput(message.conversationRef, session.threadId, session.activeTurnId);
130
+ if (replayed) {
131
+ return { kind: 'handled' };
132
+ }
133
+ }
134
+
135
+ if (session.threadId && session.activeTurnId && deps.isActiveTurnStale(runtimeStatus)) {
136
+ const staleTurnId = session.activeTurnId;
137
+ const staleThreadId = session.threadId;
138
+ deps.sessionStore.clearActiveTurn(message.conversationRef);
139
+ deps.sessionStore.markTurnSuppressed(message.conversationRef, staleTurnId, {
140
+ threadId: staleThreadId,
141
+ suppressedByMessageId: message.messageId,
142
+ suppressedByTurnId: null,
143
+ reason: 'stale active turn cleared before accepting newer inbound message',
144
+ });
145
+ deps.clearRuntimeRecovery(message.conversationRef);
146
+ }
147
+
148
+ const latestAfterCleanup = deps.sessionStore.ensureSession(message.conversationRef);
149
+ if (latestAfterCleanup.threadId && latestAfterCleanup.activeTurnId) {
150
+ const steerResult = await deps.steerActiveTurn(message, latestAfterCleanup, runtimeWaitingState);
151
+ if (steerResult === 'handled') {
152
+ return { kind: 'handled' };
153
+ }
154
+ if (steerResult === 'retry_start') {
155
+ }
156
+ }
157
+
158
+ return {
159
+ kind: 'continue',
160
+ session: latestAfterCleanup,
161
+ };
162
+ }
@@ -0,0 +1,236 @@
1
+ import type { OutboundEnvelope } from './channel-types.ts';
2
+ import { logInfo, logWarn } from './logger.ts';
3
+ import { runtimeFinalStateRecoveryRequiredMessage, runtimeRecoveryRequiredMessage, systemNoticeMessage } from './translator.ts';
4
+ import type { ConversationRef, RuntimeThreadStatus, RuntimeTurnResult } from './types.ts';
5
+
6
+ export type RecoveryKind = 'infrastructure' | 'final_state_unconfirmed';
7
+
8
+ export interface StaleTurnSuppressedDetails {
9
+ messageId: string;
10
+ threadId: string | null;
11
+ turnId: string | null;
12
+ stage: 'progress' | 'approval' | 'user_input' | 'failure' | 'result';
13
+ reason: string;
14
+ status?: string | null;
15
+ }
16
+
17
+ interface SendLike {
18
+ (
19
+ outbound: OutboundEnvelope,
20
+ extra?: Record<string, unknown>,
21
+ delivery?: { trackTurnId?: string | null },
22
+ ): Promise<boolean>;
23
+ }
24
+
25
+ interface RecoveryRuntimeLike {
26
+ recoverTurnResult?(threadId: string, turnId: string, options?: { timeoutMs?: number; pollMs?: number }): Promise<RuntimeTurnResult | null>;
27
+ }
28
+
29
+ interface StaleDeps {
30
+ markTurnSuppressed(conversationRef: ConversationRef, turnId: string | null, threadId: string | null, reason: string): void;
31
+ }
32
+
33
+ interface RecoveryNoticeDeps {
34
+ clearRuntimeRecovery(conversationRef: ConversationRef): void;
35
+ send: SendLike;
36
+ }
37
+
38
+ interface TryRecoverDeps extends StaleDeps {
39
+ runtime: RecoveryRuntimeLike;
40
+ clearRuntimeRecovery(conversationRef: ConversationRef): void;
41
+ markRuntimeRecovery(conversationRef: ConversationRef): void;
42
+ isTurnStillCurrent(conversationRef: ConversationRef, messageId: string, turnId: string | null): boolean;
43
+ visibilityDelayMs: number;
44
+ }
45
+
46
+ export function isActiveTurnStale(runtimeStatus: RuntimeThreadStatus | null): boolean {
47
+ return runtimeStatus?.type === 'idle' || runtimeStatus?.type === 'notLoaded';
48
+ }
49
+
50
+ export function isRuntimeInfrastructureError(text: string): boolean {
51
+ return /runtime (?:stdio|transport) is not connected|runtime child process exited|runtime connect timed out/i.test(text || '');
52
+ }
53
+
54
+ export function isRuntimeFinalStateUnconfirmedError(text: string): boolean {
55
+ return /runtime turn final state unavailable|runtime turn reconciliation failed/i.test(text || '');
56
+ }
57
+
58
+ export function runtimeRecoveryKindFor(text: string): RecoveryKind | null {
59
+ if (isRuntimeInfrastructureError(text)) {
60
+ return 'infrastructure';
61
+ }
62
+ if (isRuntimeFinalStateUnconfirmedError(text)) {
63
+ return 'final_state_unconfirmed';
64
+ }
65
+ return null;
66
+ }
67
+
68
+ export function recoveryAttemptSilentWindowMs(startedAt: string | null, visibilityDelayMs: number): number {
69
+ if (visibilityDelayMs <= 0) {
70
+ return 0;
71
+ }
72
+ const startedMs = startedAt ? Date.parse(startedAt) : Number.NaN;
73
+ if (!Number.isFinite(startedMs)) {
74
+ return visibilityDelayMs;
75
+ }
76
+ return Math.max(0, visibilityDelayMs - Math.max(0, Date.now() - startedMs));
77
+ }
78
+
79
+ export function noteStaleTurnSuppressed(
80
+ deps: StaleDeps,
81
+ conversationRef: ConversationRef,
82
+ details: StaleTurnSuppressedDetails,
83
+ ): void {
84
+ logWarn('receiver', 'stale_turn_output_suppressed', {
85
+ conversationId: conversationRef.conversationId,
86
+ messageId: details.messageId,
87
+ threadId: details.threadId,
88
+ turnId: details.turnId,
89
+ stage: details.stage,
90
+ reason: details.reason,
91
+ status: details.status || null,
92
+ });
93
+ deps.markTurnSuppressed(conversationRef, details.turnId, details.threadId, details.reason);
94
+ }
95
+
96
+ export async function sendRuntimeRecoveryNotice(
97
+ deps: RecoveryNoticeDeps,
98
+ conversationRef: ConversationRef,
99
+ threadId: string,
100
+ turnId: string | null,
101
+ errorText: string,
102
+ recoveryKind: RecoveryKind,
103
+ ): Promise<void> {
104
+ deps.clearRuntimeRecovery(conversationRef);
105
+ const text = systemNoticeMessage(
106
+ recoveryKind === 'final_state_unconfirmed'
107
+ ? runtimeFinalStateRecoveryRequiredMessage()
108
+ : runtimeRecoveryRequiredMessage(),
109
+ );
110
+ await deps.send({
111
+ type: 'error_reply',
112
+ conversationRef,
113
+ text,
114
+ }, {
115
+ source: 'runtime_recovery_notice_sent',
116
+ thread_id: threadId,
117
+ turn_id: turnId,
118
+ recovery_kind: recoveryKind,
119
+ }, { trackTurnId: turnId });
120
+ }
121
+
122
+ function finishRecoveredTurnResult(
123
+ deps: TryRecoverDeps,
124
+ conversationRef: ConversationRef,
125
+ threadId: string,
126
+ turnId: string,
127
+ messageId: string,
128
+ recoveryKind: RecoveryKind,
129
+ recovered: RuntimeTurnResult,
130
+ noticeVisible: boolean,
131
+ ): RuntimeTurnResult | null {
132
+ if (!deps.isTurnStillCurrent(conversationRef, messageId, turnId)) {
133
+ noteStaleTurnSuppressed(deps, conversationRef, {
134
+ messageId,
135
+ threadId: recovered.threadId,
136
+ turnId: recovered.turnId,
137
+ stage: 'result',
138
+ reason: 'session advanced before recovered turn result became user-visible',
139
+ status: recovered.status,
140
+ });
141
+ return null;
142
+ }
143
+ logInfo('receiver', 'turn_recovered', {
144
+ conversationId: conversationRef.conversationId,
145
+ threadId: recovered.threadId,
146
+ turnId: recovered.turnId,
147
+ status: recovered.status,
148
+ recoveryKind,
149
+ recoveryNoticeVisible: noticeVisible,
150
+ });
151
+ deps.clearRuntimeRecovery(conversationRef);
152
+ return recovered;
153
+ }
154
+
155
+ export async function tryRecoverTurnResult(
156
+ deps: TryRecoverDeps,
157
+ conversationRef: ConversationRef,
158
+ threadId: string,
159
+ turnId: string | null,
160
+ messageId: string,
161
+ errorText: string,
162
+ startedAt: string | null,
163
+ ): Promise<RuntimeTurnResult | null> {
164
+ const recoveryKind = runtimeRecoveryKindFor(errorText);
165
+ if (!turnId || !recoveryKind || typeof deps.runtime.recoverTurnResult !== 'function') {
166
+ return null;
167
+ }
168
+ if (!deps.isTurnStillCurrent(conversationRef, messageId, turnId)) {
169
+ noteStaleTurnSuppressed(deps, conversationRef, {
170
+ messageId,
171
+ threadId,
172
+ turnId,
173
+ stage: 'failure',
174
+ reason: 'session advanced before turn recovery attempt became user-visible',
175
+ });
176
+ return null;
177
+ }
178
+
179
+ deps.markRuntimeRecovery(conversationRef);
180
+
181
+ const silentWindowMs = recoveryAttemptSilentWindowMs(startedAt, deps.visibilityDelayMs);
182
+ if (silentWindowMs > 0) {
183
+ const recoveredDuringGrace = await deps.runtime.recoverTurnResult(threadId, turnId, {
184
+ timeoutMs: silentWindowMs,
185
+ pollMs: Math.min(250, silentWindowMs),
186
+ });
187
+ if (recoveredDuringGrace) {
188
+ return finishRecoveredTurnResult(
189
+ deps,
190
+ conversationRef,
191
+ threadId,
192
+ turnId,
193
+ messageId,
194
+ recoveryKind,
195
+ recoveredDuringGrace,
196
+ false,
197
+ );
198
+ }
199
+ }
200
+
201
+ if (!deps.isTurnStillCurrent(conversationRef, messageId, turnId)) {
202
+ noteStaleTurnSuppressed(deps, conversationRef, {
203
+ messageId,
204
+ threadId,
205
+ turnId,
206
+ stage: 'failure',
207
+ reason: 'session advanced before turn recovery attempt became user-visible',
208
+ });
209
+ return null;
210
+ }
211
+
212
+ try {
213
+ const recovered = await deps.runtime.recoverTurnResult(threadId, turnId);
214
+ if (!recovered) {
215
+ return null;
216
+ }
217
+ return finishRecoveredTurnResult(
218
+ deps,
219
+ conversationRef,
220
+ threadId,
221
+ turnId,
222
+ messageId,
223
+ recoveryKind,
224
+ recovered,
225
+ true,
226
+ );
227
+ } catch (recoveryError) {
228
+ logWarn('receiver', 'turn_recovery_failed', {
229
+ conversationId: conversationRef.conversationId,
230
+ threadId,
231
+ turnId,
232
+ error: recoveryError instanceof Error ? (recoveryError.stack || recoveryError.message) : String(recoveryError),
233
+ });
234
+ return null;
235
+ }
236
+ }