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,143 @@
1
+ import { errorMessageFromUnknown } from './receiver-helpers.ts';
2
+ import { noteStaleTurnSuppressed, isMessageStillLatest, isTurnStillCurrent, markTurnSuppressed } from './receiver-turn-coordination.ts';
3
+ import { normalizeErrorReplyText } from './receiver-runtime-policy.ts';
4
+ import { runtimeRecoveryKindFor } from './receiver-recovery.ts';
5
+ import type { SessionStore } from './session-store.ts';
6
+ import type { ConversationRef, InboundMessage, RuntimeTurnResult } from './types.ts';
7
+
8
+ interface SendLike {
9
+ (
10
+ outbound: {
11
+ type: 'error_reply';
12
+ conversationRef: ConversationRef;
13
+ text: string;
14
+ },
15
+ extra?: Record<string, unknown>,
16
+ delivery?: { trackTurnId?: string | null },
17
+ ): Promise<boolean>;
18
+ }
19
+
20
+ interface RuntimeRecoveryRegistry {
21
+ clear(conversationRef: ConversationRef): void;
22
+ }
23
+
24
+ interface SupportLike {
25
+ tryRecoverTurnResult(
26
+ conversationRef: ConversationRef,
27
+ threadId: string,
28
+ turnId: string | null,
29
+ messageId: string,
30
+ errorText: string,
31
+ startedAt: string | null,
32
+ callbacks: {
33
+ isTurnStillCurrent(conversationRef: ConversationRef, messageId: string, turnId: string | null): boolean;
34
+ markTurnSuppressed(conversationRef: ConversationRef, turnId: string | null, threadId: string | null, reason: string): void;
35
+ },
36
+ ): Promise<RuntimeTurnResult | null>;
37
+ sendRuntimeRecoveryNotice(
38
+ conversationRef: ConversationRef,
39
+ threadId: string,
40
+ turnId: string | null,
41
+ errorText: string,
42
+ recoveryKind: 'infrastructure' | 'final_state_unconfirmed',
43
+ ): Promise<void>;
44
+ }
45
+
46
+ interface HandleFailedTurnDeps {
47
+ sessionStore: SessionStore;
48
+ runtimeRecovery: RuntimeRecoveryRegistry;
49
+ support: SupportLike;
50
+ send: SendLike;
51
+ }
52
+
53
+ interface HandleFailedTurnArgs {
54
+ message: InboundMessage;
55
+ threadId: string;
56
+ currentTurnId: string | null;
57
+ turnEntryMessageId: string;
58
+ startedAt: string;
59
+ error: unknown;
60
+ }
61
+
62
+ export async function handleFailedTurnExecution(
63
+ deps: HandleFailedTurnDeps,
64
+ args: HandleFailedTurnArgs,
65
+ ): Promise<RuntimeTurnResult | null> {
66
+ const { message, threadId, currentTurnId, turnEntryMessageId, startedAt, error } = args;
67
+ const errorText = errorMessageFromUnknown(error);
68
+
69
+ if (currentTurnId && !isTurnStillCurrent(deps.sessionStore, message.conversationRef, turnEntryMessageId, currentTurnId)) {
70
+ noteStaleTurnSuppressed({ sessionStore: deps.sessionStore }, message.conversationRef, {
71
+ messageId: message.messageId,
72
+ threadId,
73
+ turnId: currentTurnId,
74
+ stage: 'failure',
75
+ reason: 'session advanced before stale turn failure surfaced',
76
+ });
77
+ return null;
78
+ }
79
+
80
+ const recovered = await deps.support.tryRecoverTurnResult(
81
+ message.conversationRef,
82
+ threadId,
83
+ currentTurnId,
84
+ message.messageId,
85
+ errorText,
86
+ startedAt,
87
+ {
88
+ isTurnStillCurrent: (ref, currentMessageId, turnId) => isTurnStillCurrent(deps.sessionStore, ref, currentMessageId, turnId),
89
+ markTurnSuppressed: (ref, turnId, currentThreadId, reason) => markTurnSuppressed(deps.sessionStore, ref, turnId, currentThreadId, reason),
90
+ },
91
+ );
92
+ if (recovered) {
93
+ return recovered;
94
+ }
95
+
96
+ if (currentTurnId && !isTurnStillCurrent(deps.sessionStore, message.conversationRef, turnEntryMessageId, currentTurnId)) {
97
+ noteStaleTurnSuppressed({ sessionStore: deps.sessionStore }, message.conversationRef, {
98
+ messageId: message.messageId,
99
+ threadId,
100
+ turnId: currentTurnId,
101
+ stage: 'failure',
102
+ reason: 'session advanced while runtime recovery was in progress',
103
+ });
104
+ return null;
105
+ }
106
+
107
+ if (currentTurnId) {
108
+ deps.sessionStore.recordTurn(message.conversationRef, {
109
+ turnId: currentTurnId,
110
+ threadId,
111
+ status: 'failed',
112
+ prompt: message.text,
113
+ reply: '',
114
+ startedAt,
115
+ completedAt: new Date().toISOString(),
116
+ error: errorText,
117
+ });
118
+ }
119
+
120
+ const recoveryKind = runtimeRecoveryKindFor(errorText);
121
+ if (recoveryKind && currentTurnId) {
122
+ if (isMessageStillLatest(deps.sessionStore, message.conversationRef, message.messageId)) {
123
+ await deps.support.sendRuntimeRecoveryNotice(message.conversationRef, threadId, currentTurnId, errorText, recoveryKind);
124
+ } else {
125
+ noteStaleTurnSuppressed({ sessionStore: deps.sessionStore }, message.conversationRef, {
126
+ messageId: message.messageId,
127
+ threadId,
128
+ turnId: currentTurnId,
129
+ stage: 'failure',
130
+ reason: 'session advanced before recovery-required notice became user-visible',
131
+ });
132
+ }
133
+ return null;
134
+ }
135
+
136
+ deps.runtimeRecovery.clear(message.conversationRef);
137
+ await deps.send({
138
+ type: 'error_reply',
139
+ conversationRef: message.conversationRef,
140
+ text: normalizeErrorReplyText(errorText),
141
+ }, {}, { trackTurnId: currentTurnId });
142
+ return null;
143
+ }
@@ -0,0 +1,185 @@
1
+ import { logInfo } from './logger.ts';
2
+ import type { OutboundEnvelope } from './channel-types.ts';
3
+ import type { SessionStore } from './session-store.ts';
4
+ import type { StaleTurnSuppressedDetails } from './receiver-recovery.ts';
5
+ import { completionWithoutReplyStatusMessage, runtimeFinalStateRecoveryRequiredMessage, runtimeInfrastructureErrorMessage, systemNoticeMessage } from './translator.ts';
6
+ import type { ConversationRef, RuntimeTurnResult } 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 FinalizeTurnResultDeps {
17
+ sessionStore: SessionStore;
18
+ send: SendLike;
19
+ clearRuntimeRecovery(conversationRef: ConversationRef): void;
20
+ isTurnStillCurrent(conversationRef: ConversationRef, messageId: string, turnId: string | null): boolean;
21
+ noteStaleTurnSuppressed(conversationRef: ConversationRef, details: StaleTurnSuppressedDetails): void;
22
+ markTurnSuppressed(conversationRef: ConversationRef, turnId: string | null, threadId: string | null, reason: string): void;
23
+ recordPendingFinalReplyDelivery(conversationRef: ConversationRef, threadId: string, turnId: string, text: string): string;
24
+ markFinalReplyDelivered(conversationRef: ConversationRef, threadId: string, turnId: string): void;
25
+ isRuntimeInfrastructureError(text: string): boolean;
26
+ normalizeErrorReplyText(text: string): string;
27
+ consumeUserRequestedStop(turnId: string): boolean;
28
+ hasSuppressedInterruptedTurn(turnId: string): boolean;
29
+ clearSuppressedInterruptedTurn(turnId: string): void;
30
+ }
31
+
32
+ interface FinalizeTurnResultArgs {
33
+ conversationRef: ConversationRef;
34
+ messageId: string;
35
+ prompt: string;
36
+ startedAt: string;
37
+ result: RuntimeTurnResult;
38
+ }
39
+
40
+ export async function finalizeTurnResult(
41
+ deps: FinalizeTurnResultDeps,
42
+ args: FinalizeTurnResultArgs,
43
+ ): Promise<boolean> {
44
+ const { conversationRef, messageId, prompt, startedAt, result } = args;
45
+
46
+ if (!deps.isTurnStillCurrent(conversationRef, messageId, result.turnId)) {
47
+ deps.noteStaleTurnSuppressed(conversationRef, {
48
+ messageId,
49
+ threadId: result.threadId,
50
+ turnId: result.turnId,
51
+ stage: 'result',
52
+ reason: 'session advanced before stale turn completed',
53
+ status: result.status,
54
+ });
55
+ deps.clearSuppressedInterruptedTurn(result.turnId);
56
+ return true;
57
+ }
58
+
59
+ const interrupted = result.status === 'interrupted' || result.error === 'turn interrupted';
60
+ const userRequestedStop = deps.consumeUserRequestedStop(result.turnId);
61
+
62
+ logInfo('receiver', 'turn_completed', {
63
+ messageId,
64
+ conversationId: conversationRef.conversationId,
65
+ threadId: result.threadId,
66
+ turnId: result.turnId,
67
+ status: result.status,
68
+ replyLength: result.reply.length,
69
+ });
70
+ deps.sessionStore.recordTurn(conversationRef, {
71
+ turnId: result.turnId,
72
+ threadId: result.threadId,
73
+ status: result.status,
74
+ prompt,
75
+ reply: result.reply,
76
+ startedAt,
77
+ completedAt: new Date().toISOString(),
78
+ error: userRequestedStop ? 'user requested stop' : (result.error || null),
79
+ });
80
+
81
+ if (result.status !== 'completed') {
82
+ if (interrupted && deps.hasSuppressedInterruptedTurn(result.turnId)) {
83
+ deps.clearSuppressedInterruptedTurn(result.turnId);
84
+ deps.markTurnSuppressed(conversationRef, result.turnId, result.threadId, 'turn interrupted after session advanced');
85
+ return true;
86
+ }
87
+ deps.clearRuntimeRecovery(conversationRef);
88
+ const terminalReplyText = String(result.reply || '').trim();
89
+ if (terminalReplyText) {
90
+ deps.recordPendingFinalReplyDelivery(conversationRef, result.threadId, result.turnId, result.reply);
91
+ const delivered = await deps.send({
92
+ type: 'final_reply',
93
+ conversationRef,
94
+ text: result.reply,
95
+ }, {
96
+ source: 'non_completed_turn_with_reply',
97
+ thread_id: result.threadId,
98
+ turn_id: result.turnId,
99
+ runtime_status: result.status,
100
+ }, { trackTurnId: result.turnId });
101
+ if (delivered) {
102
+ deps.markFinalReplyDelivered(conversationRef, result.threadId, result.turnId);
103
+ }
104
+ return true;
105
+ }
106
+ if (interrupted) {
107
+ if (userRequestedStop) {
108
+ await deps.send({
109
+ type: 'status_reply',
110
+ conversationRef,
111
+ text: '当前任务已停止。',
112
+ }, {}, { trackTurnId: result.turnId });
113
+ return true;
114
+ }
115
+
116
+ if (deps.isRuntimeInfrastructureError(result.error || '')) {
117
+ await deps.send({
118
+ type: 'error_reply',
119
+ conversationRef,
120
+ text: systemNoticeMessage(runtimeInfrastructureErrorMessage()),
121
+ }, {
122
+ source: 'interrupted_without_reply_runtime_disconnect',
123
+ thread_id: result.threadId,
124
+ turn_id: result.turnId,
125
+ }, { trackTurnId: result.turnId });
126
+ return true;
127
+ }
128
+
129
+ await deps.send({
130
+ type: 'error_reply',
131
+ conversationRef,
132
+ text: systemNoticeMessage(runtimeFinalStateRecoveryRequiredMessage()),
133
+ }, {
134
+ source: 'interrupted_without_reply_unconfirmed',
135
+ thread_id: result.threadId,
136
+ turn_id: result.turnId,
137
+ }, { trackTurnId: result.turnId });
138
+ return true;
139
+ }
140
+ await deps.send({
141
+ type: 'error_reply',
142
+ conversationRef,
143
+ text: deps.normalizeErrorReplyText(result.error || '处理失败。'),
144
+ }, {}, { trackTurnId: result.turnId });
145
+ return true;
146
+ }
147
+
148
+ deps.clearRuntimeRecovery(conversationRef);
149
+ const finalReplyText = String(result.reply || '').trim();
150
+ if (finalReplyText) {
151
+ deps.recordPendingFinalReplyDelivery(conversationRef, result.threadId, result.turnId, result.reply);
152
+ const delivered = await deps.send({
153
+ type: 'final_reply',
154
+ conversationRef,
155
+ text: result.reply,
156
+ }, {}, { trackTurnId: result.turnId });
157
+ if (delivered) {
158
+ deps.markFinalReplyDelivered(conversationRef, result.threadId, result.turnId);
159
+ }
160
+ logInfo('receiver', 'final_reply_sent', {
161
+ messageId,
162
+ conversationId: conversationRef.conversationId,
163
+ replyLength: result.reply.length,
164
+ delivered,
165
+ });
166
+ return true;
167
+ }
168
+
169
+ await deps.send({
170
+ type: 'status_reply',
171
+ conversationRef,
172
+ text: completionWithoutReplyStatusMessage(),
173
+ }, {
174
+ source: 'completion_without_reply',
175
+ thread_id: result.threadId,
176
+ turn_id: result.turnId,
177
+ }, { trackTurnId: result.turnId });
178
+ logInfo('receiver', 'completion_without_reply_sent', {
179
+ messageId,
180
+ conversationId: conversationRef.conversationId,
181
+ threadId: result.threadId,
182
+ turnId: result.turnId,
183
+ });
184
+ return true;
185
+ }
@@ -0,0 +1,70 @@
1
+ import type { OutboundEnvelope } from './channel-types.ts';
2
+ import { errorDetailsFromUnknown, errorMessageFromUnknown } from './receiver-helpers.ts';
3
+ import { buildPrompt, isMissingThreadError, isStaleTurnError, normalizeErrorReplyText } from './receiver-runtime-policy.ts';
4
+ import type { SessionStore } from './session-store.ts';
5
+ import type { InboundMessage, SessionMeta } from './types.ts';
6
+
7
+ interface SendLike {
8
+ (
9
+ outbound: OutboundEnvelope,
10
+ extra?: Record<string, unknown>,
11
+ delivery?: { trackTurnId?: string | null },
12
+ ): Promise<boolean>;
13
+ }
14
+
15
+ interface RuntimeSteerLike {
16
+ steerTurn?(threadId: string, turnId: string, prompt: string): Promise<void>;
17
+ }
18
+
19
+ interface SteerActiveTurnDeps {
20
+ sessionStore: SessionStore;
21
+ runtime: RuntimeSteerLike;
22
+ send: SendLike;
23
+ reactEmoji?: string | null;
24
+ }
25
+
26
+ export async function steerActiveTurn(
27
+ deps: SteerActiveTurnDeps,
28
+ message: InboundMessage,
29
+ session: SessionMeta,
30
+ runtimeWaitingState: 'approval' | 'user_input' | null,
31
+ ): Promise<'handled' | 'retry_start' | null> {
32
+ if (!session.threadId || !session.activeTurnId || typeof deps.runtime.steerTurn !== 'function') {
33
+ return null;
34
+ }
35
+
36
+ deps.sessionStore.noteLatestInbound(message.conversationRef, {
37
+ messageId: message.messageId,
38
+ promptPreview: message.text,
39
+ });
40
+ await deps.send({
41
+ type: 'ack_received',
42
+ conversationRef: message.conversationRef,
43
+ messageId: message.messageId,
44
+ emoji: deps.reactEmoji || undefined,
45
+ });
46
+
47
+ try {
48
+ await deps.runtime.steerTurn(session.threadId, session.activeTurnId, buildPrompt(message));
49
+ return 'handled';
50
+ } catch (error) {
51
+ const errorDetails = errorDetailsFromUnknown(error);
52
+ if (isMissingThreadError(error) || isStaleTurnError(error) || runtimeWaitingState === null) {
53
+ deps.sessionStore.clearActiveTurn(message.conversationRef);
54
+ return 'retry_start';
55
+ }
56
+ const errorText = errorMessageFromUnknown(error);
57
+ await deps.send({
58
+ type: 'error_reply',
59
+ conversationRef: message.conversationRef,
60
+ text: normalizeErrorReplyText(errorText),
61
+ }, {
62
+ source: 'turn_steer_blocked_by_visible_waiting_state',
63
+ message_id: message.messageId,
64
+ thread_id: session.threadId,
65
+ turn_id: session.activeTurnId,
66
+ waiting_state: runtimeWaitingState,
67
+ });
68
+ return 'handled';
69
+ }
70
+ }
@@ -0,0 +1,76 @@
1
+ import type { ConversationRef, WorkSessionMeta } from './types.ts';
2
+ import { conversationKey } from './utils.ts';
3
+ import { WorkSessionStore } from './work-session-store.ts';
4
+
5
+ interface ReceiverWorkSessionDeps {
6
+ assistantName: string;
7
+ workSessionStore: WorkSessionStore;
8
+ }
9
+
10
+ interface EnsureLinkedWorkSessionDeps extends ReceiverWorkSessionDeps {
11
+ assistantCodexHome: string | null;
12
+ workspaceRoot: string;
13
+ }
14
+
15
+ export function resolveDeliveryConversationKey(ref: ConversationRef): string {
16
+ return conversationKey(ref.channel, ref.conversationId);
17
+ }
18
+
19
+ export function activeWorkSessionFor(
20
+ deps: ReceiverWorkSessionDeps,
21
+ ref: ConversationRef,
22
+ ): WorkSessionMeta | null {
23
+ return deps.workSessionStore.getActiveWorkSessionForDelivery(ref.channel, resolveDeliveryConversationKey(ref));
24
+ }
25
+
26
+ export function ensureLinkedWorkSessionForThread(
27
+ deps: EnsureLinkedWorkSessionDeps,
28
+ ref: ConversationRef,
29
+ runtimeThreadId: string | null | undefined,
30
+ ): WorkSessionMeta | null {
31
+ const nextRuntimeThreadId = typeof runtimeThreadId === 'string' ? runtimeThreadId.trim() : '';
32
+ if (!nextRuntimeThreadId) {
33
+ return activeWorkSessionFor(deps, ref);
34
+ }
35
+
36
+ const linked = activeWorkSessionFor(deps, ref);
37
+ if (linked) {
38
+ if (linked.runtimeThreadId === nextRuntimeThreadId) {
39
+ return linked;
40
+ }
41
+ return deps.workSessionStore.rebindRuntimeThread(linked.workSessionId, nextRuntimeThreadId);
42
+ }
43
+
44
+ return deps.workSessionStore.createWorkSession({
45
+ assistantName: deps.assistantName,
46
+ assistantCodexHome: deps.assistantCodexHome,
47
+ workspaceRoot: deps.workspaceRoot,
48
+ runtimeThreadId: nextRuntimeThreadId,
49
+ cliResumeRef: nextRuntimeThreadId,
50
+ cliResumeRefType: 'session_id',
51
+ origin: 'work_ally',
52
+ deliveryChannel: ref.channel,
53
+ deliveryConversationKey: resolveDeliveryConversationKey(ref),
54
+ activeSurface: 'work_ally_channel',
55
+ ownershipSource: 'new_session',
56
+ });
57
+ }
58
+
59
+ export function syncLinkedWorkSessionThread(
60
+ deps: ReceiverWorkSessionDeps,
61
+ ref: ConversationRef,
62
+ runtimeThreadId: string | null | undefined,
63
+ ): WorkSessionMeta | null {
64
+ const nextRuntimeThreadId = typeof runtimeThreadId === 'string' ? runtimeThreadId.trim() : '';
65
+ if (!nextRuntimeThreadId) {
66
+ return activeWorkSessionFor(deps, ref);
67
+ }
68
+ const linked = activeWorkSessionFor(deps, ref);
69
+ if (!linked) {
70
+ return null;
71
+ }
72
+ if (linked.runtimeThreadId === nextRuntimeThreadId) {
73
+ return linked;
74
+ }
75
+ return deps.workSessionStore.rebindRuntimeThread(linked.workSessionId, nextRuntimeThreadId);
76
+ }