omp-superagent 0.0.0-stage → 0.1.2

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 (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
@@ -0,0 +1,172 @@
1
+ import {
2
+ closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync,
3
+ renameSync, unlinkSync, writeFileSync, type Stats,
4
+ } from "node:fs";
5
+ import { randomUUID } from "node:crypto";
6
+ import { dirname, join } from "node:path";
7
+ import { parseEnv } from "node:util";
8
+ import { credentialEnvNames, type Config } from "./config";
9
+
10
+ export interface CredentialFile {
11
+ path: string;
12
+ values: Record<string, string>;
13
+ /** Kept private in memory, never included in diagnostics. */
14
+ bytes: Buffer;
15
+ stat: Stats;
16
+ }
17
+
18
+ function missing(error: unknown): boolean {
19
+ return (error as NodeJS.ErrnoException).code === "ENOENT";
20
+ }
21
+
22
+ function privateFile(stat: Stats): void {
23
+ if (!stat.isFile() || (stat.mode & 0o177) !== 0 ||
24
+ (process.getuid && stat.uid !== process.getuid()))
25
+ throw new Error("Credential file must be an owned, non-symlink private file (mode 0600)");
26
+ }
27
+
28
+ function decode(bytes: Buffer): string {
29
+ const value = bytes.toString("utf8");
30
+ if (!Buffer.from(value, "utf8").equals(bytes) || value.includes("\0"))
31
+ throw new Error("Credential file must contain valid UTF-8 without NUL bytes");
32
+ return value;
33
+ }
34
+
35
+ function parseCredentialValues(text: string): Record<string, string> {
36
+ const values: Record<string, string> = Object.create(null);
37
+ for (const [name, value] of Object.entries(parseEnv(text))) {
38
+ if (typeof value !== "string") throw new Error("Credential file is not valid dotenv");
39
+ values[name] = value;
40
+ }
41
+ return values;
42
+ }
43
+
44
+ /** This is deliberately not dotenv autoloading: callers opt in for start/doctor only. */
45
+ export function readCredentialFile(configPath: string): CredentialFile | undefined {
46
+ const path = `${configPath}.env`;
47
+ let fd: number;
48
+ try {
49
+ const stat = lstatSync(path);
50
+ if (stat.isSymbolicLink()) throw new Error("Credential file must not be a symlink");
51
+ privateFile(stat);
52
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
53
+ } catch (error) {
54
+ if (missing(error)) return undefined;
55
+ if (error instanceof Error && error.message.startsWith("Credential file")) throw error;
56
+ throw new Error("Cannot safely open credential file");
57
+ }
58
+ try {
59
+ const stat = fstatSync(fd);
60
+ privateFile(stat);
61
+ const bytes = readFileSync(fd);
62
+ const text = decode(bytes);
63
+ let values: Record<string, string>;
64
+ try { values = parseCredentialValues(text); }
65
+ catch { throw new Error("Credential file is not valid dotenv"); }
66
+ return { path, values, bytes, stat };
67
+ } finally { closeSync(fd); }
68
+ }
69
+
70
+ export function validateCredential(value: string): void {
71
+ if (!value || /[\r\n\0]/.test(value) || Buffer.from(value, "utf8").toString("utf8") !== value)
72
+ throw new Error("Credential must be a nonempty, single-line UTF-8 value without NUL bytes");
73
+ encodeValue(value);
74
+ }
75
+
76
+ function encodeValue(value: string): string {
77
+ // parseEnv, not shell syntax, is the authority. In particular, dollar signs and
78
+ // backslashes remain literal. Test the complete parse so quotes/comments cannot
79
+ // inject another assignment. No interpolation or shell evaluation is used.
80
+ const candidates = [value, `'${value}'`, `"${value}"`, `\`${value}\``];
81
+ for (const candidate of candidates) {
82
+ try {
83
+ const parsed = parseEnv(`VALUE=${candidate}\n`);
84
+ if (Object.keys(parsed).length === 1 && parsed.VALUE === value) return candidate;
85
+ } catch { /* Try another literal delimiter, never include the value in an error. */ }
86
+ }
87
+ throw new Error("Credential value cannot be stored losslessly in dotenv");
88
+ }
89
+
90
+ export function serializeCredentials(values: Record<string, string>): string {
91
+ const entries = Object.entries(values);
92
+ const text = entries.map(([name, value]) => {
93
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Credential file has an invalid variable name");
94
+ return `${name}=${encodeValue(value)}\n`;
95
+ }).join("");
96
+ let parsed: Record<string, string>;
97
+ try { parsed = parseCredentialValues(text); }
98
+ catch { throw new Error("Credential file cannot be stored losslessly in dotenv"); }
99
+ if (Object.keys(parsed).length !== entries.length || entries.some(([name, value]) => parsed[name] !== value))
100
+ throw new Error("Credential file cannot be stored losslessly in dotenv");
101
+ return text;
102
+ }
103
+
104
+ export function assertCredentialsUnchanged(configPath: string, previous: CredentialFile | undefined): void {
105
+ const current = readCredentialFile(configPath);
106
+ if (!!current !== !!previous || (current && previous &&
107
+ (current.stat.dev !== previous.stat.dev || current.stat.ino !== previous.stat.ino ||
108
+ current.stat.mtimeMs !== previous.stat.mtimeMs || current.stat.ctimeMs !== previous.stat.ctimeMs ||
109
+ !current.bytes.equals(previous.bytes))))
110
+ throw new Error("Credential file changed during setup; nothing was overwritten");
111
+ }
112
+
113
+ /** Stage privately beside the target. Caller must recheck snapshots before commit. */
114
+ export function stagePrivateFile(path: string, contents: string): string {
115
+ const temporary = join(dirname(path), `.setup-${randomUUID()}.tmp`);
116
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
117
+ try {
118
+ fchmodSync(fd, 0o600);
119
+ writeFileSync(fd, contents, "utf8");
120
+ fsyncSync(fd);
121
+ } catch {
122
+ unlinkSync(temporary);
123
+ throw new Error("Could not stage private setup file");
124
+ } finally { closeSync(fd); }
125
+ return temporary;
126
+ }
127
+
128
+ export function writeCredentials(configPath: string, values: Record<string, string>, previous: CredentialFile | undefined): void {
129
+ const path = `${configPath}.env`;
130
+ // Serialize cooperating publishers, then recheck the caller's original snapshot.
131
+ // Never steal an existing lock: after an interrupted writer the operator must
132
+ // first ensure it is no longer running before explicitly removing this file.
133
+ const lockPath = `${path}.lock`;
134
+ let lock: number;
135
+ try { lock = openSync(lockPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
136
+ catch { throw new Error(`Credential write lock unavailable: ${lockPath}; no files were overwritten`); }
137
+ const lockStat = fstatSync(lock);
138
+ let temporary: string | undefined;
139
+ try {
140
+ fchmodSync(lock, 0o600);
141
+ writeFileSync(lock, `${process.pid}\n`, "utf8");
142
+ temporary = stagePrivateFile(path, serializeCredentials(values));
143
+ assertCredentialsUnchanged(configPath, previous);
144
+ if (previous) renameSync(temporary, path);
145
+ // The link is a complete private publication. A crash before stage cleanup may
146
+ // leave an extra private link, which is harmless and does not prevent reads.
147
+ else linkSync(temporary, path);
148
+ } finally {
149
+ try {
150
+ if (temporary) {
151
+ try { unlinkSync(temporary); } catch (error) { if (!missing(error)) throw error; }
152
+ }
153
+ } finally {
154
+ closeSync(lock);
155
+ try {
156
+ const current = lstatSync(lockPath);
157
+ if (current.dev === lockStat.dev && current.ino === lockStat.ino) unlinkSync(lockPath);
158
+ } catch (error) { if (!missing(error)) throw error; }
159
+ }
160
+ }
161
+ }
162
+
163
+ /** Nonempty explicit environment wins; unrelated dotenv keys never enter a process. */
164
+ export function loadCredentials(config: Config): void {
165
+ const file = readCredentialFile(config.path);
166
+ if (!file) return;
167
+ for (const name of credentialEnvNames(config)) {
168
+ if (process.env[name]) continue;
169
+ const value = Object.hasOwn(file.values, name) ? file.values[name] : undefined;
170
+ if (value) { validateCredential(value); process.env[name] = value; }
171
+ }
172
+ }
@@ -0,0 +1,59 @@
1
+ import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { decisionId } from "./decisions";
4
+ import { parseDialog } from "./dialog";
5
+
6
+ /** Structured owner questions use the native host's UI, never a second messenger path. */
7
+ export function registerDecisionAsk(pi: ExtensionAPI): void {
8
+ const role = process.env.OMP_SUPERAGENT_ROLE;
9
+ if (role !== "head" && role !== "lane") return;
10
+ const restricted = "Owner decisions are restricted to the root managed HEAD or lane session";
11
+ // Public extension ToolDefinition has no concurrency field. Reject overlap
12
+ // instead of replacing the native host's single active dialog surface.
13
+ let asking = false;
14
+ pi.on("session_start", async (_event, ctx) => {
15
+ if (ctx.agent.kind === "main") return;
16
+ const active = pi.getActiveTools();
17
+ if (active.includes("decision_ask")) await pi.setActiveTools(active.filter(name => name !== "decision_ask"));
18
+ });
19
+ pi.on("tool_call", (event, ctx) => {
20
+ if (event.toolName === "decision_ask" && ctx.agent.kind !== "main") return { block: true, reason: restricted };
21
+ });
22
+ pi.registerTool({
23
+ name: "decision_ask", label: "Request a tracked decision", approval: "read", loadMode: "essential",
24
+ description: (role === "lane"
25
+ ? "Send structured questions to the HEAD first. The HEAD can select routine options within the original assignment; important or unresolved choices go to the owner. A submitted answer is not necessarily from the owner and does not grant execution approval or expand scope. "
26
+ : "Ask the owner structured questions on this managed session's native UI. ") +
27
+ "Returns a stable decision id and the actual submitted answers or cancellation, timeout, or chat state. Recommendations, timeouts and chat are not acceptance. No default answers, timeout, messenger routing, or automatic work resume.",
28
+ parameters: Type.Object({
29
+ questions: Type.Array(Type.Object({
30
+ question: Type.String(),
31
+ header: Type.Optional(Type.String()),
32
+ options: Type.Array(Type.Object({
33
+ label: Type.String({ minLength: 1 }),
34
+ description: Type.Optional(Type.String()),
35
+ preview: Type.Optional(Type.String()),
36
+ }, { additionalProperties: false })),
37
+ multi: Type.Optional(Type.Boolean()),
38
+ recommended: Type.Optional(Type.Integer({ minimum: 0 })),
39
+ }, { additionalProperties: false }), { minItems: 1 }),
40
+ }, { additionalProperties: false }),
41
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
42
+ if (ctx.agent.kind !== "main") throw new Error(restricted);
43
+ const id = decisionId(ctx.sessionManager.getSessionId(), toolCallId);
44
+ const dialog = parseDialog({ method: "ask", questions: Array.isArray(params.questions)
45
+ ? params.questions.map((question, index) => ({ ...question, id: `${id}:${index}` })) : params.questions });
46
+ if (dialog.method !== "ask") throw new Error("Expected structured decision questions");
47
+ if (!ctx.ui.askDialog) throw new Error("Native structured decision UI is unavailable on this host");
48
+ if (asking) throw new Error("An owner decision dialog is already pending in this native session");
49
+ asking = true;
50
+ try {
51
+ const answer = await ctx.ui.askDialog(dialog.questions, { signal });
52
+ const value = answer === undefined ? { id, status: "cancelled" }
53
+ : answer.kind === "chat" ? { id, status: "chat" }
54
+ : { id, status: answer.results.some(item => item.timedOut) ? "timed_out" : "submitted", answers: answer.results };
55
+ return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }], details: value };
56
+ } finally { asking = false; }
57
+ },
58
+ });
59
+ }
@@ -0,0 +1,143 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { Approval, ApprovalResolution, DialogResponse, StorePort } from "./contracts";
3
+ import { parseDialog, type Question } from "./dialog";
4
+ import { DeliveryError } from "./delivery";
5
+
6
+ interface Receipt {
7
+ approvalId: string;
8
+ createdAt: number;
9
+ response?: DialogResponse;
10
+ confirmedAt?: number;
11
+ withdrawal?: { at: number; reason: string; sourceId?: string };
12
+ headSelection?: ApprovalResolution["headSelection"];
13
+ }
14
+
15
+ export interface DecisionView {
16
+ id: string;
17
+ state: "pending" | "answering" | "answered" | "withdrawn";
18
+ sourceId: string | null;
19
+ target: string;
20
+ sessionId: string;
21
+ generation: number;
22
+ approvalId: string;
23
+ requestId: string;
24
+ route: Approval["route"];
25
+ remoteId: string | null;
26
+ questions: Question[];
27
+ createdAt: number;
28
+ response?: DialogResponse;
29
+ confirmedAt?: number;
30
+ withdrawal?: Receipt["withdrawal"];
31
+ headSelection?: Receipt["headSelection"];
32
+ }
33
+
34
+ export function decisionId(sessionId: string, toolCallId: string): string {
35
+ return `d-${createHash("sha256").update(JSON.stringify([sessionId, toolCallId])).digest("hex").slice(0, 24)}`;
36
+ }
37
+
38
+ /** Only the managed decision tool's structured questions enter this ledger. */
39
+ export function decisionRequestId(request: Record<string, unknown>): string | null {
40
+ if (request.method !== "ask" || request.secret === true || !Array.isArray(request.questions)) return null;
41
+ const first = request.questions[0] as { id?: unknown } | undefined;
42
+ const id = typeof first?.id === "string" ? /^(d-[a-f0-9]{24}):0$/.exec(first.id)?.[1] : undefined;
43
+ if (!id) return null;
44
+ const dialog = parseDialog(request);
45
+ if (dialog.method !== "ask" || dialog.questions.some((question, index) => question.id !== `${id}:${index}`))
46
+ throw new Error("Decision question identity changed");
47
+ return id;
48
+ }
49
+
50
+ const metadataKey = "decisions:v1";
51
+ const receipts = (store: StorePort): Record<string, Receipt> => JSON.parse(store.getMeta(metadataKey) ?? "{}");
52
+
53
+ /** Called inside the approval insert transaction, never before native UI exists. */
54
+ export function captureDecision(store: StorePort, approval: Approval): void {
55
+ if (!approval.decision) return;
56
+ const { id } = approval.decision;
57
+ if (decisionRequestId(approval.request) !== id) throw new Error("Decision does not match its native questions");
58
+ const records = receipts(store);
59
+ if (records[id]) throw new Error("Decision already has a native request; do not ask it again");
60
+ records[id] = { approvalId: approval.id, createdAt: Date.now() };
61
+ store.setMeta(metadataKey, JSON.stringify(records));
62
+ }
63
+
64
+ export function validateDecisionAnswer(question: Question, answer: NonNullable<DialogResponse["answers"]>[number]): void {
65
+ if (!answer || answer.id !== question.id || !Array.isArray(answer.selectedOptions)
66
+ || answer.selectedOptions.some(option => typeof option !== "string" || !question.options.some(choice => choice.label === option))
67
+ || new Set(answer.selectedOptions).size !== answer.selectedOptions.length
68
+ || answer.customInput !== undefined && typeof answer.customInput !== "string"
69
+ || !question.multi && (answer.selectedOptions.length > 1 || answer.selectedOptions.length > 0 && !!answer.customInput?.trim()
70
+ || answer.selectedOptions.length === 0 && !answer.customInput?.trim()))
71
+ throw new DeliveryError("Decision response does not match its original question and choices", "rejected");
72
+ }
73
+
74
+ /** Validate before any final admission or partial-question advance. */
75
+ export function validateDecisionResponse(approval: Approval, response: DialogResponse | undefined): void {
76
+ if (!approval.decision) return;
77
+ const dialog = parseDialog(approval.request);
78
+ if (!response || dialog.method !== "ask") throw new DeliveryError("Decision requires an exact owner answer", "rejected");
79
+ if (response.cancelled === true) {
80
+ if (response.answers !== undefined || response.value !== undefined || response.confirmed !== undefined)
81
+ throw new DeliveryError("A cancelled decision cannot contain an answer", "rejected");
82
+ } else {
83
+ if (response.value !== undefined || response.confirmed !== undefined
84
+ || !Array.isArray(response.answers) || response.answers.length !== dialog.questions.length)
85
+ throw new DeliveryError("Decision response must answer the original questions", "rejected");
86
+ for (const [index, question] of dialog.questions.entries()) validateDecisionAnswer(question, response.answers[index]!);
87
+ }
88
+ }
89
+
90
+ /** Called within the approval compare-and-set transaction, before any native effect. */
91
+ export function resolveDecision(store: StorePort, approval: Approval, state: "answered" | "cancelled",
92
+ resolution?: ApprovalResolution): void {
93
+ if (!approval.decision) return;
94
+ const records = receipts(store);
95
+ const receipt = records[approval.decision.id];
96
+ if (!receipt || receipt.approvalId !== approval.id) throw new Error("Decision receipt does not match its native request");
97
+ if (state === "cancelled") {
98
+ receipt.withdrawal = { at: Date.now(), reason: resolution?.reason ?? "Native question cancelled or no longer pending",
99
+ ...(resolution?.sourceId ? { sourceId: resolution.sourceId } : {}) };
100
+ } else {
101
+ validateDecisionResponse(approval, resolution?.response);
102
+ receipt.response = resolution!.response;
103
+ if (resolution?.headSelection) receipt.headSelection = resolution.headSelection;
104
+ }
105
+ store.setMeta(metadataKey, JSON.stringify(records));
106
+ }
107
+
108
+ /** Absence is acknowledged only against the exact live native session/generation. */
109
+ export function acknowledgeDecision(store: StorePort, approval: Approval, sessionId: string): void {
110
+ if (!approval.decision || approval.decision.sessionId !== sessionId || approval.state === "pending") return;
111
+ const records = receipts(store);
112
+ const receipt = records[approval.decision.id];
113
+ if (!receipt || receipt.approvalId !== approval.id || approval.state === "answered" && !receipt.response)
114
+ throw new Error("Decision answer receipt is missing");
115
+ if (receipt.confirmedAt !== undefined) return;
116
+ if (receipt.headSelection && receipt.response?.answers) {
117
+ const { reviewId, reason } = receipt.headSelection;
118
+ store.queueOutput({
119
+ id: `${reviewId}:selected`, sourceId: reviewId, route: approval.route,
120
+ text: `헤드가 레인 대신 선택했습니다: ${receipt.response.answers.flatMap(answer => answer.selectedOptions).join(", ")}\n이유: ${reason}`,
121
+ });
122
+ }
123
+ receipt.confirmedAt = Date.now();
124
+ if (receipt.response?.cancelled) receipt.withdrawal = { at: receipt.confirmedAt, reason: "Owner cancelled the original question" };
125
+ store.setMeta(metadataKey, JSON.stringify(records));
126
+ }
127
+
128
+ export function decisionViews(store: StorePort): DecisionView[] {
129
+ return Object.entries(receipts(store)).map(([id, receipt]) => {
130
+ const approval = store.approval(receipt.approvalId);
131
+ if (!approval?.decision || approval.decision.id !== id || decisionRequestId(approval.request) !== id)
132
+ throw new Error("Decision ledger is not bound to its original native question");
133
+ const dialog = parseDialog(approval.request);
134
+ if (dialog.method !== "ask") throw new Error("Decision question is unavailable");
135
+ const state = approval.state === "pending" ? "pending"
136
+ : approval.state === "cancelled" ? "withdrawn"
137
+ : receipt.confirmedAt === undefined ? "answering"
138
+ : receipt.response?.cancelled ? "withdrawn" : "answered";
139
+ return { id, state, ...receipt, sourceId: approval.decision.sourceId, target: approval.target,
140
+ sessionId: approval.decision.sessionId, generation: approval.generation, requestId: approval.requestId,
141
+ route: approval.route, remoteId: approval.remoteId, questions: dialog.questions };
142
+ });
143
+ }
@@ -0,0 +1,17 @@
1
+ import { createHash } from "node:crypto";
2
+ import { routeKey, type Approval } from "./contracts";
3
+
4
+ /** Existing cards and persisted dialog progress must keep this exact identity. */
5
+ export function approvalCardToken(approval: Approval): string {
6
+ return createHash("sha256")
7
+ .update(JSON.stringify([approval.id, approval.generation, approval.target, approval.requestId, routeKey(approval.route)]))
8
+ .digest("hex").slice(0, 24);
9
+ }
10
+
11
+ /** An ambiguous transport mutation must never be retried as a known rejection. */
12
+ export class DeliveryError extends Error {
13
+ constructor(message: string, public readonly certainty: "rejected" | "uncertain" = "uncertain", public readonly retryAfterMs?: number, options?: ErrorOptions) {
14
+ super(message, options);
15
+ this.name = "DeliveryError";
16
+ }
17
+ }
package/src/dialog.ts ADDED
@@ -0,0 +1,73 @@
1
+ /** Native OMP dialog semantics, independent of a transport's UI capacities. */
2
+ export interface Question {
3
+ id: string;
4
+ question: string;
5
+ header?: string;
6
+ options: { label: string; description?: string; preview?: string }[];
7
+ multi?: boolean;
8
+ recommended?: number;
9
+ }
10
+
11
+ export type Dialog =
12
+ | { method: "confirm"; title: string; message: string }
13
+ | { method: "select"; title: string; options: string[]; details: (string | undefined)[]; marker?: "radio" | "checkbox"; checked: number[]; markableCount: number; initialIndex?: number }
14
+ | { method: "input"; title: string; placeholder?: string; prefill?: string }
15
+ | { method: "editor"; title: string; placeholder?: string; prefill?: string }
16
+ | { method: "ask"; questions: Question[] };
17
+
18
+ function text(value: unknown): value is string { return typeof value === "string"; }
19
+ function object(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
20
+ function unsupported(reason: string): never { throw new Error(reason); }
21
+
22
+ /** Preserve native values and host-owned checked state; never collect secrets. */
23
+ export function parseDialog(request: Record<string, unknown>): Dialog {
24
+ if (request.secret === true) unsupported("Secret input cannot safely be collected through a messenger; use the local OMP interface.");
25
+ if (request.method === "ask") {
26
+ if (!Array.isArray(request.questions) || request.questions.length === 0) unsupported("Ask request has no questions.");
27
+ const questions: Question[] = request.questions.map((value: unknown) => {
28
+ if (!object(value) || !text(value.id) || !text(value.question) || !Array.isArray(value.options)) return unsupported("Malformed ask question.");
29
+ if (value.header !== undefined && !text(value.header)) unsupported("Malformed ask header.");
30
+ if (value.multi !== undefined && typeof value.multi !== "boolean") unsupported("Malformed ask selection mode.");
31
+ const options = value.options.map((option: unknown) => {
32
+ if (!object(option) || !text(option.label) || !option.label) return unsupported("Malformed ask option.");
33
+ if (option.description !== undefined && !text(option.description)) unsupported("Malformed ask description.");
34
+ if (option.preview !== undefined && !text(option.preview)) unsupported("Malformed ask preview.");
35
+ return { label: option.label, description: option.description as string | undefined, preview: option.preview as string | undefined };
36
+ });
37
+ if (new Set(options.map(option => option.label)).size !== options.length) unsupported("Ask option labels are not unique.");
38
+ if (value.recommended !== undefined && (!Number.isInteger(value.recommended) || (value.recommended as number) < 0 || (value.recommended as number) >= options.length)) unsupported("Malformed recommended option.");
39
+ return { id: value.id, question: value.question, header: value.header as string | undefined, multi: value.multi as boolean | undefined, recommended: value.recommended as number | undefined, options };
40
+ });
41
+ if (new Set(questions.map(question => question.id)).size !== questions.length) unsupported("Ask question IDs are not unique.");
42
+ return { method: "ask", questions };
43
+ }
44
+ if (!text(request.title)) unsupported("Dialog title is missing.");
45
+ if (request.method === "confirm") {
46
+ if (!text(request.message)) unsupported("Confirmation message is missing.");
47
+ return { method: "confirm", title: request.title, message: request.message };
48
+ }
49
+ if (request.method === "select") {
50
+ if (!Array.isArray(request.options) || request.options.length === 0 || !request.options.every(option => text(option) && option.length > 0) || new Set(request.options).size !== request.options.length) unsupported("Malformed or duplicate select options.");
51
+ if (request.selectionMarker !== undefined && request.selectionMarker !== "radio" && request.selectionMarker !== "checkbox") unsupported("Malformed select marker.");
52
+ const marker = request.selectionMarker as "radio" | "checkbox" | undefined;
53
+ const markableCount = request.markableCount ?? (marker ? request.options.length : 0);
54
+ if (!Number.isInteger(markableCount) || (markableCount as number) < 0 || (markableCount as number) > request.options.length) unsupported("Malformed marked-option count.");
55
+ const checked = request.checkedIndices ?? [];
56
+ if (!Array.isArray(checked) || checked.some(index => !Number.isInteger(index) || index < 0 || index >= (markableCount as number)) || new Set(checked).size !== checked.length) unsupported("Malformed checked-option state.");
57
+ if (request.initialIndex !== undefined && (!Number.isInteger(request.initialIndex) || (request.initialIndex as number) < 0 || (request.initialIndex as number) >= request.options.length)) unsupported("Malformed initial select index.");
58
+ if (request.optionDetails !== undefined && !Array.isArray(request.optionDetails)) unsupported("Malformed select details.");
59
+ const details = request.options.map((_, index) => {
60
+ const detail = Array.isArray(request.optionDetails) ? request.optionDetails[index] : undefined;
61
+ if (detail === undefined) return undefined;
62
+ if (!object(detail) || (detail.description !== undefined && !text(detail.description))) return unsupported("Malformed select description.");
63
+ return detail.description as string | undefined;
64
+ });
65
+ return { method: "select", title: request.title, options: request.options as string[], details, marker, checked, markableCount: markableCount as number, initialIndex: request.initialIndex as number | undefined };
66
+ }
67
+ if (request.method === "input" || request.method === "editor") {
68
+ if (request.placeholder !== undefined && !text(request.placeholder)) unsupported("Malformed input placeholder.");
69
+ if (request.prefill !== undefined && !text(request.prefill)) unsupported("Malformed editor content.");
70
+ return { method: request.method, title: request.title, placeholder: request.placeholder as string | undefined, prefill: request.prefill as string | undefined };
71
+ }
72
+ return unsupported(`Dialog method ${String(request.method)} cannot be represented safely in a messenger.`);
73
+ }