omp-superagent 0.1.10 → 0.1.13

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 (154) hide show
  1. package/DESIGN.md +71 -15
  2. package/README.ko.md +10 -1
  3. package/README.md +10 -1
  4. package/THIRD_PARTY_NOTICES.md +35 -436
  5. package/assets/architecture-dark.svg +7 -12
  6. package/assets/architecture.ko-dark.svg +7 -12
  7. package/assets/architecture.ko.svg +7 -12
  8. package/assets/architecture.mmd +5 -13
  9. package/assets/architecture.svg +7 -12
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +282 -53
  12. package/docs/OPERATIONS.md +264 -45
  13. package/docs/design/execution.md +80 -52
  14. package/docs/design/messaging.md +113 -32
  15. package/docs/releases/0.1.11.md +20 -0
  16. package/docs/releases/0.1.13.md +13 -0
  17. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  18. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  19. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  21. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  23. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  25. package/package.json +13 -11
  26. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  27. package/scripts/upgrade-evidence-files.mjs +100 -0
  28. package/scripts/upgrade-evidence.mjs +192 -0
  29. package/scripts/upgrade-host-wire.mjs +162 -0
  30. package/skills/head/SKILL.md +12 -3
  31. package/skills/head/references/routing.md +1 -1
  32. package/skills/head/references/supervision.md +23 -26
  33. package/skills/lane/SKILL.md +28 -21
  34. package/skills/lane/references/workflow.md +15 -17
  35. package/src/cli.ts +33 -53
  36. package/src/{config.ts → config/config.ts} +7 -3
  37. package/src/config/wake-config.ts +36 -0
  38. package/src/contracts.ts +61 -12
  39. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  40. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  41. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  42. package/src/extension.ts +43 -25
  43. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  44. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  45. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  46. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  47. package/src/gateway-config.ts +1 -1
  48. package/src/gateway-restart-env.ts +3 -3
  49. package/src/{group-access.ts → group/group-access.ts} +8 -3
  50. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  51. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  52. package/src/host-extension.ts +164 -36
  53. package/src/host-sdk-helper.ts +66 -65
  54. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  55. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  56. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  57. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  58. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  59. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  60. package/src/lane-extension.ts +25 -7
  61. package/src/managed-memory-helper.ts +2 -2
  62. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  63. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  64. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  65. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  66. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  67. package/src/messaging/messenger-commands.ts +55 -0
  68. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  69. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  70. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  71. package/src/omp/head-resume.ts +123 -0
  72. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  73. package/src/{host-protocol.ts → omp/host-protocol.ts} +10 -2
  74. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  75. package/src/{host.ts → omp/host.ts} +26 -17
  76. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  77. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  78. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  79. package/src/omp/native-journal.ts +124 -0
  80. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  81. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  82. package/src/omp/native-sessions.ts +124 -0
  83. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  84. package/src/{soul.ts → omp/soul.ts} +2 -2
  85. package/src/omp/stock-head-launch.ts +31 -0
  86. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  87. package/src/{operator.ts → operator/operator.ts} +2 -2
  88. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  89. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  90. package/src/{setup.ts → operator/setup.ts} +5 -5
  91. package/src/operator/stop-lane.ts +25 -0
  92. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  93. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  94. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  95. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  96. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  97. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  98. package/src/{message-order.ts → routing/message-order.ts} +1 -1
  99. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  100. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  101. package/src/{runtime.ts → runtime/controller.ts} +867 -1213
  102. package/src/runtime/deferred-routing.ts +106 -0
  103. package/src/runtime/dm-timeline.ts +194 -0
  104. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  105. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  106. package/src/runtime/model-journal.ts +119 -0
  107. package/src/runtime/native-frames.ts +131 -0
  108. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  109. package/src/runtime/preset-sync.ts +232 -0
  110. package/src/runtime/preset-watch-paths.ts +137 -0
  111. package/src/runtime/result-attachments.ts +146 -0
  112. package/src/storage/deferred-routing.ts +149 -0
  113. package/src/{store.ts → storage/store.ts} +75 -42
  114. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  115. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  116. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  117. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  118. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  119. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  120. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  121. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  122. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  123. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  124. package/src/worker-serve-prepare.ts +4 -4
  125. package/src/board-extension.ts +0 -217
  126. package/src/board.ts +0 -467
  127. package/src/gateway-host-helper.ts +0 -13
  128. package/src/messenger-commands.ts +0 -15
  129. package/src/native-sessions.ts +0 -34
  130. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  131. /package/src/{lane-report.ts → lane/lane-report.ts} +0 -0
  132. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  133. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  134. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  135. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  136. /package/src/{host-reply-voice.ts → omp/host-reply-voice.ts} +0 -0
  137. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  138. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  139. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  140. /package/src/{repository.ts → operator/repository.ts} +0 -0
  141. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  142. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  143. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  144. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  145. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  146. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  147. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  148. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  149. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  150. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  151. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  152. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  153. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  154. /package/upstream/{ulw.json → super.json} +0 -0
@@ -0,0 +1,106 @@
1
+ import type { DeferredRoutingPort, Inbound } from "../contracts";
2
+ import { DeliveryError } from "../messaging/delivery";
3
+
4
+ export interface RecoveryControl {
5
+ readonly priority: "immediate" | "retry";
6
+ readonly laneId?: string;
7
+ }
8
+
9
+ interface DrainActions {
10
+ readonly stopped: () => boolean;
11
+ readonly fenced: () => boolean;
12
+ readonly recovery: (input: Inbound) => RecoveryControl | null;
13
+ readonly admit: (id: string) => Promise<void>;
14
+ readonly report: (error: unknown) => void;
15
+ readonly background: (task: Promise<void>) => void;
16
+ }
17
+
18
+ export class DeferredRoutingDrain {
19
+ private readonly pending = new Set<string>();
20
+ private readonly active = new Map<string, Promise<void>>();
21
+ private readonly retry = new Map<string, { readonly at: number; readonly delay: number }>();
22
+
23
+ constructor(private readonly queue: DeferredRoutingPort, private readonly actions: DrainActions) {}
24
+
25
+ restore(): void {
26
+ for (const conversation of this.queue.conversations()) this.pending.add(conversation);
27
+ this.resume();
28
+ }
29
+
30
+ available(conversation: string): void {
31
+ this.pending.add(conversation);
32
+ this.drain(conversation);
33
+ }
34
+
35
+ retrying(conversation: string): boolean {
36
+ return this.retry.has(conversation);
37
+ }
38
+
39
+ resume(): void {
40
+ if (!this.pending.size || this.held()) return;
41
+ for (const conversation of this.pending) this.drain(conversation);
42
+ }
43
+
44
+ async settled(): Promise<void> {
45
+ while (this.active.size) await Promise.allSettled([...this.active.values()]);
46
+ }
47
+
48
+ private held(): boolean {
49
+ return this.actions.stopped() || this.actions.fenced();
50
+ }
51
+
52
+ private next(conversation: string, head: string, failed: ReadonlySet<string>): string | null {
53
+ const retry = this.retry.get(conversation);
54
+ const headReady = (!retry || retry.at <= Date.now()) && !failed.has(head);
55
+ const includeBare = !headReady && retry !== undefined;
56
+ // A persisted exact stop can bypass a blocked history read so work from
57
+ // another conversation cannot resume the target lane out of order.
58
+ for (const input of this.queue.priority(conversation, includeBare)) {
59
+ if (input.id === head && !headReady || failed.has(input.id)) continue;
60
+ const control = this.actions.recovery(input);
61
+ if (control?.priority === "immediate" || includeBare && control?.priority === "retry") return input.id;
62
+ }
63
+ return headReady ? head : null;
64
+ }
65
+
66
+ private drain(conversation: string): void {
67
+ if (this.active.has(conversation) || this.held()) return;
68
+ // The job starts after registration; removal and the final queue read
69
+ // are synchronous so a new receipt cannot miss its drain.
70
+ const job = Promise.resolve().then(async () => {
71
+ const failed = new Set<string>();
72
+ try {
73
+ while (!this.held()) {
74
+ const head = this.queue.head(conversation);
75
+ if (head === null) {
76
+ this.pending.delete(conversation);
77
+ return;
78
+ }
79
+ const id = this.next(conversation, head, failed);
80
+ if (id === null) return;
81
+ try {
82
+ await this.actions.admit(id);
83
+ } catch (error) {
84
+ if (this.actions.stopped()) return;
85
+ this.actions.report(error);
86
+ if (!(error instanceof DeliveryError && error.certainty === "rejected")) {
87
+ failed.add(id);
88
+ if (id === head) {
89
+ // Keep the failed receipt first, with bounded retry backoff.
90
+ const delay = Math.min((this.retry.get(conversation)?.delay ?? 125) * 2, 30_000);
91
+ this.retry.set(conversation, { at: Date.now() + delay, delay });
92
+ }
93
+ continue;
94
+ }
95
+ }
96
+ this.queue.remove(id);
97
+ if (id === head) this.retry.delete(conversation);
98
+ }
99
+ } finally {
100
+ this.active.delete(conversation);
101
+ }
102
+ });
103
+ this.active.set(conversation, job);
104
+ this.actions.background(job);
105
+ }
106
+ }
@@ -0,0 +1,194 @@
1
+ import { createHash } from "node:crypto";
2
+ import { physicalRoute, physicalRouteKey, type Inbound, type Route, type StorePort } from "../contracts";
3
+ import { compareMessageIds } from "../routing/message-order";
4
+
5
+ interface DmBoundary {
6
+ eventId: string;
7
+ messageId: string;
8
+ receivedAt: number;
9
+ topicId: string | null;
10
+ }
11
+ interface DmCommandBoundary {
12
+ eventId: string;
13
+ invocationId: string;
14
+ anchorMessageId: string | null;
15
+ insertionOrder: number;
16
+ topicId: string | null;
17
+ }
18
+
19
+ export function newLogicalTopicId(sourceId: string): string {
20
+ return `topic-${createHash("sha256").update(sourceId).digest("hex").slice(0, 24)}`;
21
+ }
22
+
23
+ export function eventOrderId(input: Inbound): string | null {
24
+ if (typeof input.messageId === "string" && input.messageId.length) {
25
+ if (input.route.platform === "slack" && compareMessageIds("slack", input.messageId, input.messageId) === null) throw new Error("Cannot order a Slack input without an actual timestamp");
26
+ return input.messageId;
27
+ }
28
+ if (input.messageId === null && input.route.platform === "discord" && typeof input.interactionId === "string" && /^[1-9]\d{0,19}$/.test(input.interactionId)) {
29
+ return input.interactionId;
30
+ }
31
+ if (input.messageId === null && input.route.platform === "slack" && input.route.threadId === null
32
+ && typeof input.invocationId === "string" && /^[a-f0-9]{64}$/.test(input.invocationId)) return null;
33
+ throw new Error("Inbound event requires a real message ID, Discord interaction snowflake, or scoped Slack invocation");
34
+ }
35
+
36
+ export class DmTimeline {
37
+ constructor(private readonly store: Pick<StorePort, "getMeta" | "admittedMessageIds" | "input">) {}
38
+
39
+ admit(input: Inbound, eventId: string | null, commandBlocked: boolean): { input: Inbound; metadata: Record<string, string> } {
40
+ if (input.route.platform === "slack") return this.slackDmAdmission(input);
41
+ let metadata: Record<string, string> = {};
42
+ if (eventId === null) throw new Error("Cannot order this DM input");
43
+ const physical = physicalRoute(input.route);
44
+ const command = commandBlocked ? "" : input.text.trim();
45
+ const boundaries = this.topicBoundaries(physical);
46
+ const originalBoundary = boundaries.find(boundary => {
47
+ const order = compareMessageIds(physical.platform, boundary.messageId, eventId);
48
+ if (order === null) throw new Error("Cannot order this message against the DM topic timeline");
49
+ return order === 0;
50
+ });
51
+ let topicId: string | null;
52
+ if (originalBoundary) {
53
+ // Edit events are new inputs, not permission to rewrite the original
54
+ // command boundary or switch today's topic selection back in time.
55
+ topicId = originalBoundary.topicId;
56
+ const original = this.store.input(originalBoundary.eventId)?.text.trim();
57
+ if (original !== undefined && (/^\/new(?:\s|$)/.test(original) || original === "/main")) {
58
+ metadata = { [`dm:control-edit:${input.id}`]: "true" };
59
+ }
60
+ } else if (/^\/new(?:\s|$)/.test(command)) {
61
+ topicId = newLogicalTopicId(input.id);
62
+ metadata = this.topicMetadata(input, topicId);
63
+ } else if (command === "/main") {
64
+ topicId = null;
65
+ metadata = this.topicMetadata(input, null);
66
+ } else {
67
+ const eligible = boundaries.filter(boundary => {
68
+ const order = compareMessageIds(physical.platform, boundary.messageId, eventId);
69
+ if (order === null) throw new Error("Cannot order this message against the DM topic timeline");
70
+ return order <= 0;
71
+ });
72
+ topicId = eligible.length ? eligible[eligible.length - 1]!.topicId
73
+ : boundaries.length ? null : this.store.getMeta(`dm:active:${physicalRouteKey(physical)}`);
74
+ }
75
+ return { input: { ...input, route: topicId ? { ...physical, topicId } : physical }, metadata };
76
+ }
77
+
78
+ isExplicitTopic(route: Route): boolean {
79
+ if (!route.topicId || route.guildId !== null || route.threadId !== null) return false;
80
+ const boundary = this.topicBoundaries(route).find(item => item.topicId === route.topicId)
81
+ ?? (route.platform === "slack" ? this.commandBoundaries(route).find(item => item.topicId === route.topicId) : undefined);
82
+ return boundary !== undefined && this.store.input(boundary.eventId)?.text.trim() === "/new";
83
+ }
84
+
85
+ private topicBoundaries(route: Route): DmBoundary[] {
86
+ return JSON.parse(this.store.getMeta(`dm:boundaries:${physicalRouteKey(route)}`) ?? "[]") as DmBoundary[];
87
+ }
88
+
89
+ private commandBoundaries(route: Route): DmCommandBoundary[] {
90
+ return JSON.parse(this.store.getMeta(`dm:command-boundaries:${physicalRouteKey(route)}`) ?? "[]") as DmCommandBoundary[];
91
+ }
92
+
93
+ private slackTimeline(route: Route, messages = this.topicBoundaries(route), commands = this.commandBoundaries(route)) {
94
+ return [
95
+ ...messages.map(boundary => ({ anchor: boundary.messageId as string | null, command: false, order: 0, topicId: boundary.topicId })),
96
+ ...commands.map(boundary => ({ anchor: boundary.anchorMessageId, command: true, order: boundary.insertionOrder, topicId: boundary.topicId })),
97
+ ].sort((left, right) => {
98
+ const order = left.anchor === null ? right.anchor === null ? 0 : -1 : right.anchor === null ? 1
99
+ : compareMessageIds("slack", left.anchor, right.anchor);
100
+ if (order === null) throw new Error("Cannot order the persisted Slack DM topic timeline");
101
+ return order || Number(left.command) - Number(right.command) || left.order - right.order;
102
+ });
103
+ }
104
+
105
+ private slackAnchor(input: Inbound): string | null {
106
+ const stored = this.store.getMeta(`dm:invocation-anchor:${input.id}`);
107
+ if (stored !== null) {
108
+ const anchor = JSON.parse(stored) as { invocationId: string; anchorMessageId: string | null };
109
+ if (anchor.invocationId !== input.invocationId) throw new Error("Slack invocation anchor identity conflict");
110
+ return anchor.anchorMessageId;
111
+ }
112
+ let latest: string | null = null;
113
+ for (const messageId of this.store.admittedMessageIds(input.route)) {
114
+ const order = compareMessageIds("slack", messageId, latest ?? messageId);
115
+ if (order === null) throw new Error("Cannot order durable Slack owner messages");
116
+ if (latest === null || order > 0) latest = messageId;
117
+ }
118
+ return latest;
119
+ }
120
+
121
+ private slackDmAdmission(input: Inbound): { input: Inbound; metadata: Record<string, string> } {
122
+ const physical = physicalRoute(input.route);
123
+ const command = input.text.trim();
124
+ const control = /^\/new(?:\s|$)/.test(command) || command === "/main";
125
+ const anchorMessageId = input.messageId === null ? this.slackAnchor(input) : undefined;
126
+ let metadata: Record<string, string> = {};
127
+ let topicId: string | null;
128
+ if (anchorMessageId !== undefined) {
129
+ metadata[`dm:invocation-anchor:${input.id}`] = JSON.stringify({ invocationId: input.invocationId, anchorMessageId });
130
+ }
131
+ if (control) {
132
+ topicId = command === "/main" ? null : newLogicalTopicId(input.id);
133
+ metadata = { ...metadata, ...this.topicMetadata(input, topicId, anchorMessageId) };
134
+ } else if (input.messageId === null) {
135
+ topicId = this.store.getMeta(`dm:active:${physicalRouteKey(physical)}`) || null;
136
+ } else {
137
+ const timeline = this.slackTimeline(physical);
138
+ const eligible = timeline.filter(boundary => {
139
+ if (boundary.anchor === null) return true;
140
+ const order = compareMessageIds("slack", boundary.anchor, input.messageId!);
141
+ if (order === null) throw new Error("Cannot order this message against the DM topic timeline");
142
+ return boundary.command ? order < 0 : order <= 0;
143
+ });
144
+ topicId = eligible.length ? eligible[eligible.length - 1]!.topicId : timeline.length ? null
145
+ : this.store.getMeta(`dm:active:${physicalRouteKey(physical)}`) || null;
146
+ }
147
+ return { input: { ...input, route: topicId ? { ...physical, topicId } : physical }, metadata };
148
+ }
149
+
150
+ topicMetadata(input: Inbound, topicId: string | null, anchorMessageId?: string | null): Record<string, string> {
151
+ const eventId = eventOrderId(input);
152
+ if (eventId === null) {
153
+ const boundaries = this.commandBoundaries(input.route);
154
+ const existing = boundaries.find(boundary => boundary.invocationId === input.invocationId);
155
+ if (existing) {
156
+ if (existing.eventId !== input.id || existing.topicId !== topicId) throw new Error("Slack command boundary identity conflict");
157
+ return {}; // Reusing an invocation never resets the active selection.
158
+ }
159
+ // Slack has no slash clock. This is observed-admission order after the
160
+ // latest durable real owner message, not cross-connection chronology.
161
+ boundaries.push({ eventId: input.id, invocationId: input.invocationId!,
162
+ anchorMessageId: anchorMessageId === undefined ? this.slackAnchor(input) : anchorMessageId,
163
+ insertionOrder: (boundaries[boundaries.length - 1]?.insertionOrder ?? 0) + 1, topicId });
164
+ const timeline = this.slackTimeline(input.route, undefined, boundaries);
165
+ const identity = physicalRouteKey(input.route);
166
+ return { [`dm:command-boundaries:${identity}`]: JSON.stringify(boundaries),
167
+ [`dm:active:${identity}`]: timeline[timeline.length - 1]!.topicId ?? "" };
168
+ }
169
+ if (compareMessageIds(input.route.platform, eventId, eventId) === null) {
170
+ throw new Error("A DM topic boundary requires an authoritative platform event ID");
171
+ }
172
+ const boundaries = this.topicBoundaries(input.route);
173
+ for (const boundary of boundaries) {
174
+ const order = compareMessageIds(input.route.platform, boundary.messageId, eventId);
175
+ if (order === null) throw new Error("Cannot order the persisted DM topic timeline");
176
+ if (order === 0 && boundary.topicId !== topicId) throw new Error("A message cannot establish conflicting DM topic boundaries");
177
+ }
178
+ if (!boundaries.some(boundary => boundary.eventId === input.id)) boundaries.push({
179
+ eventId: input.id, messageId: eventId, receivedAt: input.receivedAt, topicId,
180
+ });
181
+ boundaries.sort((left, right) => {
182
+ const order = compareMessageIds(input.route.platform, left.messageId, right.messageId);
183
+ if (order === null) throw new Error("Cannot order the persisted DM topic timeline");
184
+ return order;
185
+ });
186
+ const identity = physicalRouteKey(input.route);
187
+ const active = input.route.platform === "slack" ? this.slackTimeline(input.route, boundaries).at(-1)!.topicId
188
+ : boundaries[boundaries.length - 1]!.topicId;
189
+ return {
190
+ [`dm:boundaries:${identity}`]: JSON.stringify(boundaries),
191
+ [`dm:active:${identity}`]: active ?? "",
192
+ };
193
+ }
194
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { HeadRecoveryAttempt } from "./contracts";
2
+ import type { HeadRecoveryAttempt } from "../contracts";
3
3
 
4
4
  export interface HeadQuotaFailure {
5
5
  readonly model: { readonly provider: "openai-codex"; readonly id: string };
@@ -1,19 +1,36 @@
1
- import { basename, dirname, join } from "node:path";
2
- import type { LanePresetSnapshot } from "./contracts";
1
+ import { basename, dirname, isAbsolute, join } from "node:path";
2
+ import type { ServiceTier, ServiceTierByFamily } from "@oh-my-pi/pi-ai";
3
+ import type { LanePresetSnapshot } from "../contracts";
4
+ import type { NativeProfile } from "../omp/native-sessions";
3
5
 
4
6
  export const HEAD_ROTATION_KEY = "gateway:head-rotation";
5
7
  export const HEAD_SESSION_FILE_KEY = "main:sessionFile";
6
8
  export const HEAD_ROTATION_PROBE = "superagent:head-rotation-probe";
7
9
  export const HEAD_ROTATION_GUARD = "superagent:head-rotation-guard";
10
+ export const HEAD_SLEEP_PROBE_READY = "superagent:head-sleep-probe-ready";
8
11
  export const MIN_HEAD_IDLE_MS = 30 * 60 * 1000;
9
12
 
13
+ /** Omission preserves the original idle rotation wire contract. */
14
+ export type HeadLifecycleMode = "hibernate";
15
+
16
+ export function hasBoundNativeProfile(profile: NativeProfile | undefined): profile is NativeProfile {
17
+ return profile?.version === 2 && [profile.agentDir, profile.dataDir, profile.sessionsDir]
18
+ .every(path => typeof path === "string" && isAbsolute(path));
19
+ }
20
+
10
21
  export interface RotationSelection {
11
22
  readonly provider: string;
12
23
  readonly modelId: string;
24
+ /** Canonical stock selector, including any provider route. */
25
+ readonly modelIdentity?: string;
13
26
  readonly reasoning: boolean;
14
27
  readonly thinkingLevel: string | null;
15
28
  readonly configuredThinkingLevel: string | null;
16
29
  readonly modelSettings: LanePresetSnapshot;
30
+ readonly serviceTier?: Readonly<ServiceTierByFamily>;
31
+ readonly serviceTierDefaults?: Readonly<ServiceTierByFamily>;
32
+ readonly effectiveServiceTier?: ServiceTier | "none";
33
+ readonly stockLaunchReplay?: true;
17
34
  }
18
35
 
19
36
  export interface RotationNative {
@@ -21,8 +38,9 @@ export interface RotationNative {
21
38
  readonly sessionId: string;
22
39
  readonly sessionFile: string;
23
40
  readonly nativeRun: number;
24
- readonly contextPercent: number;
41
+ readonly contextPercent: number | null;
25
42
  readonly selection: RotationSelection;
43
+ readonly hibernation?: NativeProfile;
26
44
  }
27
45
 
28
46
  export interface RotationResident {
@@ -42,14 +60,16 @@ export interface RotationAttestation {
42
60
  readonly generation: number;
43
61
  readonly nativeRun: number;
44
62
  readonly idleMs: number;
45
- readonly contextPercent: number;
63
+ readonly contextPercent: number | null;
46
64
  readonly selection: RotationSelection;
47
65
  readonly residents: readonly RotationResident[];
66
+ readonly hibernation?: NativeProfile;
48
67
  }
49
68
 
50
69
  export interface HeadRotation {
51
70
  readonly id: string;
52
- readonly stage: "stopping" | "starting" | "launching" | "complete" | "refused";
71
+ readonly mode?: HeadLifecycleMode;
72
+ readonly stage: "stopping" | "sleeping" | "starting" | "launching" | "complete" | "refused";
53
73
  readonly original: {
54
74
  readonly pid: number;
55
75
  readonly sessionId: string;
@@ -59,19 +79,26 @@ export interface HeadRotation {
59
79
  readonly stopBoundary: string | null;
60
80
  readonly attestation: RotationAttestation;
61
81
  readonly replacementSessionId: string | null;
82
+ readonly replacementOwnerPid?: number | null;
62
83
  }
63
84
 
64
85
  export interface RotationProbeEvent {
86
+ readonly mode: HeadLifecycleMode | undefined;
65
87
  readonly state: RotationNative;
66
88
  readonly respond: (attestation: Promise<RotationAttestation | null>) => void;
67
89
  }
68
90
 
69
91
  export interface RotationGuardEvent {
70
92
  readonly id: string;
93
+ readonly mode: HeadLifecycleMode | undefined;
71
94
  readonly state: RotationNative;
72
95
  readonly respond: (allowed: boolean) => void;
73
96
  }
74
97
 
98
+ export interface HeadSleepProbeReadyEvent {
99
+ readonly respond: (ready: boolean) => void;
100
+ }
101
+
75
102
  export function readHeadRotation(encoded: string | null): HeadRotation | null {
76
103
  return encoded === null ? null : JSON.parse(encoded);
77
104
  }
@@ -0,0 +1,119 @@
1
+ import type { Api, Model } from "@oh-my-pi/pi-ai";
2
+ import { resolveRoutedModelSelector } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
3
+ import { EPHEMERAL_MODEL_CHANGE_ROLE } from "@oh-my-pi/pi-coding-agent/session/session-entries";
4
+ import type { LaneModel } from "../contracts";
5
+ import { LANE_MODEL_PROMOTION_RECEIPT } from "../omp/host-protocol";
6
+ import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
7
+ import { record } from "./native-frames";
8
+
9
+ type JournaledModelChange = {
10
+ readonly id: string;
11
+ readonly model: string;
12
+ readonly role?: string;
13
+ readonly resolvedModelIsFallback?: boolean;
14
+ };
15
+
16
+ /** Prefer exact catalog IDs over optional native selector suffixes, never a prefix match. */
17
+ function recordedModel(selector: string, catalog: unknown[]): LaneModel | undefined {
18
+ const models = catalog.filter(isLaneModel);
19
+ const literal = models.find(model => laneModelArgument(model) === selector);
20
+ if (literal) return literal;
21
+ return resolveRoutedModelSelector({
22
+ find: (provider, id) => models.find(model => model.provider === provider && model.id === id) as Model<Api> | undefined,
23
+ }, selector)?.model;
24
+ }
25
+
26
+ /** Read model evidence on the exact RPC leaf, newest first. An invalid path is not evidence. */
27
+ function activeModelJournal(entries: unknown, leafId: string, after?: string):
28
+ { readonly changes: JournaledModelChange[]; readonly branch: Record<string, unknown>[] } | null {
29
+ if (!Array.isArray(entries)) return null;
30
+ const byId = new Map<string, Record<string, unknown>>();
31
+ for (const value of entries) {
32
+ const entry = record(value);
33
+ if (typeof entry.id !== "string" || !entry.id || byId.has(entry.id)) return null;
34
+ byId.set(entry.id, entry);
35
+ }
36
+ const changes: JournaledModelChange[] = [];
37
+ const branch: Record<string, unknown>[] = [];
38
+ const seen = new Set<string>();
39
+ let crossed = after === undefined;
40
+ let cursor: string | null = leafId;
41
+ while (cursor !== null) {
42
+ const entry = byId.get(cursor);
43
+ if (!entry || seen.has(cursor) || (entry.parentId !== null && (typeof entry.parentId !== "string" || !entry.parentId))) return null;
44
+ seen.add(cursor);
45
+ branch.push(entry);
46
+ if (cursor === after) {
47
+ if (!changes.length) return null; // The newest model entry must be strictly after the boundary.
48
+ crossed = true;
49
+ }
50
+ if (entry.type === "model_change") {
51
+ const { model, role, resolvedModelIsFallback } = entry;
52
+ if (typeof model !== "string" || !model || (role !== undefined && typeof role !== "string")
53
+ || (resolvedModelIsFallback !== undefined && typeof resolvedModelIsFallback !== "boolean")) return null;
54
+ changes.push({ id: cursor, model, role, resolvedModelIsFallback });
55
+ }
56
+ cursor = entry.parentId;
57
+ }
58
+ return crossed ? { changes, branch } : null;
59
+ }
60
+
61
+ /** Read the configured default; the caller still fences against a moving native leaf. */
62
+ export function nativeDefaultModelEvidence(result: Record<string, unknown>, catalog: unknown[], laneId: string):
63
+ { readonly leaf: string | null; readonly selected?: LaneModel } {
64
+ const leaf = result.leafId;
65
+ if (leaf === null && Array.isArray(result.entries) && result.entries.length === 0) return { leaf };
66
+ const journal = typeof leaf === "string" && leaf ? activeModelJournal(result.entries, leaf) : null;
67
+ if (typeof leaf !== "string" || !journal) throw new Error(`Lane ${laneId} native default model journal is unavailable`);
68
+ const saved = journal.changes.find(change => (change.role ?? "default") === "default");
69
+ if (saved?.resolvedModelIsFallback === true) throw new Error(`Lane ${laneId} native default journal contains an ambiguous fallback entry`);
70
+ let selected: LaneModel | undefined;
71
+ if (saved) {
72
+ const index = journal.branch.findIndex(entry => entry.id === saved.id);
73
+ const receipt = journal.branch.slice(0, index).find(entry => entry.type === "custom"
74
+ && entry.customType === LANE_MODEL_PROMOTION_RECEIPT && record(entry.data).entryId === saved.id);
75
+ if (receipt) {
76
+ const data = record(receipt.data);
77
+ const exact = data.model;
78
+ if (!isLaneModel(exact) || data.selector !== saved.model
79
+ || saved.model !== laneModelArgument(exact) && !saved.model.startsWith(`${laneModelArgument(exact)}@`))
80
+ throw new Error(`Lane ${laneId} native model promotion receipt does not match its default journal entry`);
81
+ selected = exact;
82
+ } else {
83
+ const legacy = recordedModel(saved.model, catalog);
84
+ if (!legacy || catalog.some(candidate => isLaneModel(candidate) && !sameLaneModel(candidate, legacy)
85
+ && laneModelArgument(candidate) === laneModelArgument(legacy))) {
86
+ throw new Error(`Lane ${laneId} cannot resolve its journaled native default model unambiguously`);
87
+ }
88
+ selected = legacy;
89
+ }
90
+ }
91
+ return { leaf, selected };
92
+ }
93
+
94
+ /** Check the fallback chain on the exact active branch, not unrelated journal rows. */
95
+ export function recordedFallbackEvidence(evidence: Record<string, unknown>, models: {
96
+ readonly configured: LaneModel;
97
+ readonly actual: LaneModel;
98
+ readonly catalog: unknown[];
99
+ }, after?: string): { readonly leaf: string; readonly entryId: string } | null {
100
+ const leaf = evidence.leafId;
101
+ if (typeof leaf !== "string" || !leaf) return null;
102
+ const changes = activeModelJournal(evidence.entries, leaf, after)?.changes;
103
+ if (!changes) return null;
104
+ // Consecutive flagged retry hops belong to the same configured selection.
105
+ // An unflagged ephemeral change can also be context promotion, not retry.
106
+ const firstNonRetry = changes.findIndex(change =>
107
+ change.role !== EPHEMERAL_MODEL_CHANGE_ROLE || change.resolvedModelIsFallback !== true);
108
+ if (firstNonRetry < 1) return null;
109
+ const configured = changes[firstNonRetry];
110
+ // A fresh flagged retry may follow an unflagged row on the configured
111
+ // model after cooldown. That row is only the source, never the evidence
112
+ // that another model is permitted now.
113
+ if ((configured.role !== undefined && configured.role !== "default" && configured.role !== EPHEMERAL_MODEL_CHANGE_ROLE)
114
+ || configured.resolvedModelIsFallback === true
115
+ || !sameLaneModel(recordedModel(configured.model, models.catalog), models.configured)) return null;
116
+ const latest = changes[0];
117
+ if (!sameLaneModel(recordedModel(latest.model, models.catalog), models.actual)) return null;
118
+ return { leaf, entryId: latest.id };
119
+ }
@@ -0,0 +1,131 @@
1
+ import type { DialogResponse, LaneModel, LanePresetSnapshot } from "../contracts";
2
+ import type { FastModeState } from "../omp/host-protocol";
3
+ import { laneQuotaExhausted } from "./head-recovery";
4
+
5
+ export interface RuntimeState {
6
+ sessionFile?: string;
7
+ sessionId: string;
8
+ readonly journalCursorVersion?: 1;
9
+ readonly replyVoiceVersion?: 1 | 2;
10
+ readonly fastMode?: FastModeState;
11
+ model?: LaneModel | null;
12
+ thinkingLevel?: string;
13
+ configuredThinkingLevel?: string | null;
14
+ thinkingLevels?: readonly string[];
15
+ isCompacting?: boolean;
16
+ queuedMessageCount?: number;
17
+ contextUsage?: { tokens: number | null; contextWindow: number; percent: number | null } | null;
18
+ settingsScope?: "session" | "persistent";
19
+ modelSettings?: LanePresetSnapshot;
20
+ mutationHeld?: boolean;
21
+ hostPid?: number;
22
+ readonly instanceKey?: string;
23
+ isSettled: boolean;
24
+ isStreaming: boolean;
25
+ hasPendingAsyncWork?: boolean;
26
+ hasOwnedRunningWork?: boolean;
27
+ headJobs?: { running: readonly string[]; awaitingOnly: boolean };
28
+ pendingUiRequests?: Record<string, unknown>[];
29
+ goal?: { enabled?: boolean; mode?: string; goal?: { id?: string; status?: string } } | null;
30
+ }
31
+ /** The production adapter is HostConnection; tests inject only its transport boundary. */
32
+ export interface RuntimeHost {
33
+ assertPrReviewOnly?(cwd: string): Promise<void>;
34
+ client: {
35
+ getState(): Promise<RuntimeState>;
36
+ abortAndRestoreQueue(): Promise<unknown>;
37
+ getSubagents(): Promise<Array<{ id: string }>>;
38
+ cancelSubagent(id: string): Promise<unknown>;
39
+ };
40
+ exited: Promise<unknown>;
41
+ request(command: Record<string, unknown>, id?: string): Promise<unknown>;
42
+ uiResponse(id: string, response: DialogResponse): void;
43
+ onFrame(listener: (frame: Record<string, unknown>) => void): () => void;
44
+ close(): Promise<void>;
45
+ }
46
+
47
+ export interface NativePromptResult {
48
+ readonly status: string;
49
+ readonly agentInvoked: boolean;
50
+ readonly goalResume?: true;
51
+ readonly quota?: true;
52
+ readonly httpStatus?: number;
53
+ readonly retryable?: boolean;
54
+ }
55
+
56
+ export function record(value: unknown): Record<string, unknown> {
57
+ return value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
58
+ }
59
+ export function successful(value: unknown, operation: string): Record<string, unknown> {
60
+ const envelope = record(value);
61
+ if (envelope.success !== true) throw new Error(`${operation} was not acknowledged by the native host`);
62
+ return record(envelope.data);
63
+ }
64
+ export function nativePromptResult(frame: Record<string, unknown>): NativePromptResult {
65
+ const result = { status: String(frame.status), agentInvoked: frame.agentInvoked === true };
66
+ if (frame.status !== "error") return result;
67
+ const error = record(frame.error);
68
+ return { ...result, ...(laneQuotaExhausted(error) ? { quota: true } : {}),
69
+ ...(typeof error.httpStatus === "number" && Number.isInteger(error.httpStatus) && error.httpStatus >= 400 && error.httpStatus <= 599
70
+ ? { httpStatus: error.httpStatus } : {}),
71
+ ...(typeof error.retryable === "boolean" ? { retryable: error.retryable } : {}) };
72
+ }
73
+
74
+ export function restartPromptReceipt(entries: unknown[], state: Pick<RuntimeState, "sessionId" | "sessionFile">, requestId: string): NativePromptResult | undefined {
75
+ const receipt = entries.map(record).find(entry => entry.type === "custom" && entry.customType === "rpc_prompt_result"
76
+ && record(entry.data).sessionId === state.sessionId && record(entry.data).sessionFile === state.sessionFile
77
+ && record(record(entry.data).frame).id === requestId);
78
+ const frame = record(record(receipt).data).frame;
79
+ return frame ? nativePromptResult(record(frame)) : undefined;
80
+ }
81
+
82
+ function textSignature(part: unknown): { id?: string; phase?: "commentary" | "final_answer" } {
83
+ const signature = record(part).textSignature;
84
+ if (typeof signature !== "string") return {};
85
+ try {
86
+ const parsed = record(JSON.parse(signature));
87
+ return parsed.v === 1 && typeof parsed.id === "string"
88
+ ? { id: parsed.id, ...(parsed.phase === "commentary" || parsed.phase === "final_answer" ? { phase: parsed.phase } : {}) }
89
+ : {};
90
+ } catch (error) {
91
+ if (error instanceof SyntaxError) return {};
92
+ throw error;
93
+ }
94
+ }
95
+ export function assistantText(value: unknown): string | null {
96
+ const message = record(value);
97
+ if (message.role !== "assistant" || !Array.isArray(message.content)) return null;
98
+ const text = message.content.filter(part => record(part).type === "text"
99
+ && textSignature(part).phase !== "commentary"
100
+ && (message.stopReason !== "toolUse" || textSignature(part).phase === "final_answer"))
101
+ .map(part => String(record(part).text ?? "")).join("");
102
+ return text.trim() ? text : null;
103
+ }
104
+ export function assistantProgress(value: unknown): { text: string; identity: string } | null {
105
+ const message = record(value);
106
+ if (message.role !== "assistant" || !Array.isArray(message.content)
107
+ || !["stop", "length", "toolUse"].includes(String(message.stopReason))) return null;
108
+ const parts = message.content.filter(part => record(part).type === "text"
109
+ && (textSignature(part).phase === "commentary"
110
+ || message.stopReason === "toolUse" && textSignature(part).phase !== "final_answer"));
111
+ const text = parts.map(part => String(record(part).text ?? "")).join("");
112
+ if (!text.trim()) return null;
113
+ const ids = parts.map(part => textSignature(part).id).filter((id): id is string => id !== undefined);
114
+ return { text, identity: typeof message.id === "string" ? message.id : ids.length ? JSON.stringify(ids) : text };
115
+ }
116
+
117
+ export function headJobResults(message: Record<string, unknown>): Map<string, string> {
118
+ const batch = new Map<string, string>();
119
+ const jobs = record(message.details).jobs;
120
+ if (!Array.isArray(jobs) || !jobs.length) return batch;
121
+ const content = typeof message.content === "string" ? message.content
122
+ : Array.isArray(message.content) ? message.content.filter(part => record(part).type === "text")
123
+ .map(part => String(record(part).text ?? "")).join("") : "";
124
+ for (const job of jobs) {
125
+ const { jobId, status } = record(job);
126
+ if (typeof jobId !== "string") { batch.set("", ""); continue; }
127
+ batch.set(jobId, jobs.length === 1 && content.trim() ? content
128
+ : `백그라운드 작업 ${jobId}: ${typeof status === "string" ? status : "결과 도착"}`);
129
+ }
130
+ return batch;
131
+ }
@@ -1,4 +1,4 @@
1
- import { ownerRoutingProse } from "./topic-history";
1
+ import { ownerRoutingProse } from "../routing/topic-history";
2
2
 
3
3
  const observationSubject = /\b(?:presence|online|pr|ci|lane|pull request|watches|monitors)\b|github\.com\/[^ ]+\/pull\/\d+|#\d+|온라인|오프라인|접속\s*표시|레인|작업|봇/iu;
4
4
  const watchTarget = /^(?:watch|monitor|track|untrack|(?:start|stop) (?:watching|monitoring|tracking)|keep an eye on)\s+(?:(?:this|that|the|our|my)\s+)?(?:pr\b|pull request\b|lane\b|ci(?=[.?!\s]*$|\s+(?:checks?|runs?|status|on|for|of|and)\b)|https?:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+\b|[\w.-]+\/[\w.-]+#\d+\b|#\d+\b)/i;