omp-superagent 0.1.1 → 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.
- package/DESIGN.md +189 -48
- package/README.ko.md +30 -16
- package/README.md +39 -20
- package/THIRD_PARTY_NOTICES.md +81 -6
- package/docs/OPERATIONS.md +178 -30
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +13 -7
- package/scripts/ci.ts +10 -5
- package/scripts/release.ts +14 -6
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +82 -241
- package/skills/head/references/model-selection.md +81 -261
- package/skills/head/references/routing.md +179 -354
- package/skills/head/references/supervision.md +120 -310
- package/skills/lane/SKILL.md +53 -175
- package/skills/lane/references/workflow.md +93 -347
- package/src/cli.ts +96 -10
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +77 -2
- package/src/contracts.ts +70 -6
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +10 -0
- package/src/discord-context.ts +118 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +312 -45
- package/src/extension.ts +178 -21
- package/src/gateway-client.ts +11 -4
- package/src/gateway-server.ts +52 -4
- package/src/gateway-store.ts +16 -2
- package/src/gateway.ts +27 -11
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +159 -47
- package/src/host-owner.ts +16 -0
- package/src/host-protocol.ts +9 -1
- package/src/host-services.ts +54 -0
- package/src/host.ts +3 -2
- package/src/installed-omp.ts +34 -26
- package/src/lane-extension.ts +5 -0
- package/src/lane-rows.ts +12 -0
- package/src/messengers.ts +38 -9
- package/src/native-presets.ts +91 -3
- package/src/native-settings.ts +3 -1
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/runtime.ts +419 -54
- package/src/slack.ts +14 -11
- package/src/store.ts +86 -30
- package/src/telegram.ts +28 -12
- package/scripts/check-omp.ts +0 -4
|
@@ -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
|
+
}
|
package/src/decisions.ts
ADDED
|
@@ -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
|
+
}
|
package/src/delivery.ts
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
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
|
+
|
|
1
11
|
/** An ambiguous transport mutation must never be retried as a known rejection. */
|
|
2
12
|
export class DeliveryError extends Error {
|
|
3
13
|
constructor(message: string, public readonly certainty: "rejected" | "uncertain" = "uncertain", public readonly retryAfterMs?: number, options?: ErrorOptions) {
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { Type } from "@sinclair/typebox/type";
|
|
3
|
+
import { Value } from "@sinclair/typebox/value";
|
|
4
|
+
import { physicalRoute, physicalRouteKey, type DiscordPurposeNote, type DiscordPurposeRequest, type Route, type StorePort } from "./contracts";
|
|
5
|
+
import { DeliveryError } from "./delivery";
|
|
6
|
+
|
|
7
|
+
const PURPOSES = "discord:purposes";
|
|
8
|
+
type Metadata = Pick<StorePort, "getMeta" | "setMeta">;
|
|
9
|
+
interface Purposes {
|
|
10
|
+
readonly notes: Readonly<Record<string, DiscordPurposeNote>>;
|
|
11
|
+
readonly receipts: Readonly<Record<string, { readonly request: DiscordPurposeRequest; readonly result: readonly DiscordPurposeNote[] }>>;
|
|
12
|
+
}
|
|
13
|
+
const routeSchema = Type.Object({
|
|
14
|
+
platform: Type.Literal("discord"), accountId: Type.String({ minLength: 1 }),
|
|
15
|
+
authorityId: Type.String({ minLength: 1 }), channelId: Type.String({ minLength: 1 }),
|
|
16
|
+
guildId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
|
|
17
|
+
threadId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
|
|
18
|
+
}, { additionalProperties: false });
|
|
19
|
+
const purposeSchema = Type.String({ minLength: 1, maxLength: 4000, pattern: "\\S" });
|
|
20
|
+
const noteSchema = Type.Object({ route: routeSchema, purpose: purposeSchema }, { additionalProperties: false });
|
|
21
|
+
const requestFields = { sourceId: Type.String({ minLength: 1, maxLength: 1000 }), route: routeSchema };
|
|
22
|
+
const stateSchema = Type.Object({
|
|
23
|
+
notes: Type.Record(Type.String(), noteSchema),
|
|
24
|
+
receipts: Type.Record(Type.String(), Type.Object({
|
|
25
|
+
request: Type.Union([
|
|
26
|
+
Type.Object({ ...requestFields, action: Type.Literal("set"), purpose: purposeSchema }, { additionalProperties: false }),
|
|
27
|
+
Type.Object({ ...requestFields, action: Type.Literal("clear") }, { additionalProperties: false }),
|
|
28
|
+
]),
|
|
29
|
+
result: Type.Array(noteSchema),
|
|
30
|
+
}, { additionalProperties: false })),
|
|
31
|
+
}, { additionalProperties: false });
|
|
32
|
+
|
|
33
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
34
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Parse the local IPC/tool boundary without accepting extra route selectors. */
|
|
38
|
+
export function discordPurposeRequest(value: unknown): DiscordPurposeRequest {
|
|
39
|
+
const reject = () => new DeliveryError("Invalid Discord purpose request", "rejected");
|
|
40
|
+
if (!record(value)) throw reject();
|
|
41
|
+
const data = value;
|
|
42
|
+
if (typeof data.sourceId !== "string" || !data.sourceId.trim() || data.sourceId.length > 1000 ||
|
|
43
|
+
!record(data.route)) throw reject();
|
|
44
|
+
const route = data.route;
|
|
45
|
+
if (route.platform !== "discord" || typeof route.accountId !== "string" || !route.accountId ||
|
|
46
|
+
typeof route.authorityId !== "string" || !route.authorityId || typeof route.channelId !== "string" || !route.channelId ||
|
|
47
|
+
!(route.guildId === null || typeof route.guildId === "string" && route.guildId.length > 0) ||
|
|
48
|
+
!(route.threadId === null || typeof route.threadId === "string" && route.threadId.length > 0) ||
|
|
49
|
+
route.guildId === null && route.threadId !== null ||
|
|
50
|
+
Object.keys(route).some(key => !["platform", "accountId", "authorityId", "guildId", "channelId", "threadId"].includes(key)) ||
|
|
51
|
+
Object.keys(data).some(key => !["sourceId", "route", "action", "purpose"].includes(key))) throw reject();
|
|
52
|
+
const destination: Route = { platform: "discord", accountId: route.accountId, authorityId: route.authorityId,
|
|
53
|
+
channelId: route.channelId, guildId: route.guildId, threadId: route.threadId };
|
|
54
|
+
const common = { sourceId: data.sourceId, route: destination };
|
|
55
|
+
switch (data.action) {
|
|
56
|
+
case "list":
|
|
57
|
+
case "clear":
|
|
58
|
+
if (Object.hasOwn(data, "purpose")) throw reject();
|
|
59
|
+
return { ...common, action: data.action };
|
|
60
|
+
case "set":
|
|
61
|
+
if (typeof data.purpose !== "string" || !data.purpose.trim() || data.purpose.length > 4000) throw reject();
|
|
62
|
+
return { ...common, action: "set", purpose: data.purpose };
|
|
63
|
+
default: throw reject();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Only the original conversation or its exact parent; never another allowed channel/sibling. */
|
|
68
|
+
export function authorizeDiscordPurpose(source: Route, destination: Route): void {
|
|
69
|
+
const parent = { ...physicalRoute(source), threadId: null };
|
|
70
|
+
if (source.platform !== "discord" || destination.platform !== "discord" ||
|
|
71
|
+
physicalRouteKey(destination) !== physicalRouteKey(source) && physicalRouteKey(destination) !== physicalRouteKey(parent)) {
|
|
72
|
+
throw new DeliveryError("Discord purpose destination is unrelated to the original source", "rejected");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function state(store: Metadata): Purposes {
|
|
77
|
+
const saved = store.getMeta(PURPOSES);
|
|
78
|
+
if (saved === null) return { notes: {}, receipts: {} };
|
|
79
|
+
const reject = () => new DeliveryError("Discord purpose state is damaged; existing notes were preserved", "rejected");
|
|
80
|
+
let parsed: unknown;
|
|
81
|
+
try { parsed = JSON.parse(saved); }
|
|
82
|
+
catch (error) { if (error instanceof SyntaxError) throw reject(); throw error; }
|
|
83
|
+
if (!Value.Check(stateSchema, parsed)) throw reject();
|
|
84
|
+
for (const [key, note] of Object.entries(parsed.notes))
|
|
85
|
+
if (key !== physicalRouteKey(note.route) || note.route.guildId === null && note.route.threadId !== null) throw reject();
|
|
86
|
+
for (const [key, receipt] of Object.entries(parsed.receipts))
|
|
87
|
+
if (key !== JSON.stringify([receipt.request.sourceId, physicalRouteKey(receipt.request.route)])) throw reject();
|
|
88
|
+
return parsed;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function discordPurposeNotes(store: Metadata, route: Route): readonly DiscordPurposeNote[] {
|
|
92
|
+
const notes = state(store).notes;
|
|
93
|
+
const parent = { ...physicalRoute(route), threadId: null };
|
|
94
|
+
const keys = [...new Set([physicalRouteKey(parent), physicalRouteKey(route)])];
|
|
95
|
+
return keys.flatMap(key => notes[key] ? [notes[key]] : []);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** One synchronous metadata write atomically preserves the note and its source-bound receipt. */
|
|
99
|
+
export function changeDiscordPurpose(store: Metadata, request: DiscordPurposeRequest): readonly DiscordPurposeNote[] {
|
|
100
|
+
if (request.action === "list") return discordPurposeNotes(store, request.route);
|
|
101
|
+
const previous = state(store);
|
|
102
|
+
const receiptKey = JSON.stringify([request.sourceId, physicalRouteKey(request.route)]);
|
|
103
|
+
const saved = previous.receipts[receiptKey];
|
|
104
|
+
if (saved) {
|
|
105
|
+
if (!isDeepStrictEqual(saved.request, request)) throw new DeliveryError("Discord purpose source identity conflict", "rejected");
|
|
106
|
+
return saved.result;
|
|
107
|
+
}
|
|
108
|
+
const notes = { ...previous.notes };
|
|
109
|
+
const key = physicalRouteKey(request.route);
|
|
110
|
+
switch (request.action) {
|
|
111
|
+
case "set": notes[key] = { route: physicalRoute(request.route), purpose: request.purpose }; break;
|
|
112
|
+
case "clear": delete notes[key]; break;
|
|
113
|
+
}
|
|
114
|
+
const parent = { ...physicalRoute(request.route), threadId: null };
|
|
115
|
+
const result = [...new Set([physicalRouteKey(parent), key])].flatMap(id => notes[id] ? [notes[id]] : []);
|
|
116
|
+
store.setMeta(PURPOSES, JSON.stringify({ notes, receipts: { ...previous.receipts, [receiptKey]: { request, result } } }));
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { ChannelType, MessageFlags, MessageReferenceType, MessageType, type Message, type TextChannel } from "discord.js";
|
|
2
|
+
import { DeliveryError } from "./delivery.ts";
|
|
3
|
+
|
|
4
|
+
const CONFIRM = "/voice confirm";
|
|
5
|
+
export const VOICE_DRAFT_HEADER = "Proposed work from the live voice session (not yet submitted).\n";
|
|
6
|
+
const PROPOSAL_TTL_MS = 5 * 60 * 1000;
|
|
7
|
+
const MESSAGE_LIMIT = 2000;
|
|
8
|
+
|
|
9
|
+
type PostedDraft = {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly createdTimestamp: number;
|
|
12
|
+
readonly accountId: string;
|
|
13
|
+
readonly ownerId: string;
|
|
14
|
+
readonly guildId: string;
|
|
15
|
+
readonly channelId: string;
|
|
16
|
+
readonly work: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type Draft = {
|
|
20
|
+
readonly signal: AbortSignal;
|
|
21
|
+
readonly startedAt: number;
|
|
22
|
+
readonly posted?: PostedDraft;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export class VoiceDrafts {
|
|
26
|
+
private draft: Draft | null = null;
|
|
27
|
+
private sending = false;
|
|
28
|
+
|
|
29
|
+
/** The caller supplies the session's already allowlisted, bound guild text channel. */
|
|
30
|
+
async propose(channel: TextChannel, ownerId: string, text: string, signal: AbortSignal): Promise<void> {
|
|
31
|
+
signal.throwIfAborted();
|
|
32
|
+
if (this.sending || this.current()) {
|
|
33
|
+
throw new DeliveryError("A voice work proposal is already outstanding.", "rejected");
|
|
34
|
+
}
|
|
35
|
+
const accountId = channel.client.user?.id;
|
|
36
|
+
if (!accountId || !channel.guildId || channel.type !== ChannelType.GuildText) {
|
|
37
|
+
throw new DeliveryError("Voice work proposals require a bound Discord guild text channel.", "rejected");
|
|
38
|
+
}
|
|
39
|
+
if (text.length > MESSAGE_LIMIT) {
|
|
40
|
+
throw new DeliveryError("Voice work proposal is too long to review in one Discord message.", "rejected");
|
|
41
|
+
}
|
|
42
|
+
const work = text.trim();
|
|
43
|
+
if (!work) throw new DeliveryError("Voice work proposal is empty.", "rejected");
|
|
44
|
+
|
|
45
|
+
// A fenced literal cannot render links, custom emoji or Discord mentions.
|
|
46
|
+
// Escape backticks, controls (including bidi overrides), and the escape
|
|
47
|
+
// character itself so the displayed text cannot impersonate the instructions.
|
|
48
|
+
const literal = work.replace(/[\\`\p{Cc}\p{Cf}\p{Cs}\p{Default_Ignorable_Code_Point}]/gu, character => character === "\n"
|
|
49
|
+
? character : `\\u{${character.codePointAt(0)!.toString(16)}}`);
|
|
50
|
+
const content = VOICE_DRAFT_HEADER +
|
|
51
|
+
`\`\`\`\n${literal}\n\`\`\`\n` +
|
|
52
|
+
`To submit this proposal to HEAD, reply to this message with exactly \`${CONFIRM}\` ` +
|
|
53
|
+
"while the voice session is active and within five minutes.\n" +
|
|
54
|
+
"HEAD replies in Discord text. OpenAI Live does not receive the reply content. " +
|
|
55
|
+
"Risky actions still require separate approval.";
|
|
56
|
+
if (content.length > MESSAGE_LIMIT) {
|
|
57
|
+
throw new DeliveryError("Voice work proposal is too long to review in one Discord message.", "rejected");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const draft = { signal, startedAt: Date.now() };
|
|
61
|
+
const { guildId, id: channelId } = channel;
|
|
62
|
+
this.draft = draft;
|
|
63
|
+
this.sending = true;
|
|
64
|
+
try {
|
|
65
|
+
const sent = await channel.send({
|
|
66
|
+
content, allowedMentions: { parse: [], repliedUser: false }, flags: MessageFlags.SuppressEmbeds,
|
|
67
|
+
}).catch(() => {
|
|
68
|
+
// Discord may have posted the card despite the failure. Keep the slot
|
|
69
|
+
// until expiry or session end; never bind a guess to an unknown message.
|
|
70
|
+
throw new DeliveryError("Voice work proposal delivery is uncertain; it cannot be confirmed.", "uncertain");
|
|
71
|
+
});
|
|
72
|
+
if (this.current() !== draft) {
|
|
73
|
+
throw new DeliveryError("The voice work proposal is no longer active and cannot be confirmed.", "rejected");
|
|
74
|
+
}
|
|
75
|
+
if (!/^[0-9]{1,20}$/.test(sent.id) || sent.author.id !== accountId || !sent.author.bot ||
|
|
76
|
+
sent.channelId !== channelId || sent.guildId !== guildId || sent.content !== content ||
|
|
77
|
+
!Number.isSafeInteger(sent.createdTimestamp)) {
|
|
78
|
+
throw new DeliveryError("Discord did not verify the voice work proposal; it cannot be confirmed.", "uncertain");
|
|
79
|
+
}
|
|
80
|
+
this.draft = {
|
|
81
|
+
signal, startedAt: Date.now(),
|
|
82
|
+
posted: { id: sent.id, createdTimestamp: sent.createdTimestamp, accountId, ownerId, guildId, channelId, work },
|
|
83
|
+
};
|
|
84
|
+
} finally {
|
|
85
|
+
this.sending = false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Call only for fresh MessageCreate events, never for updates or fetched history. */
|
|
90
|
+
consume(message: Message): string | null {
|
|
91
|
+
const draft = this.current()?.posted;
|
|
92
|
+
if (!draft || message.content !== CONFIRM || message.type !== MessageType.Reply ||
|
|
93
|
+
message.editedTimestamp !== null || message.webhookId !== null ||
|
|
94
|
+
message.author.id !== draft.ownerId || message.author.bot || message.client.user?.id !== draft.accountId ||
|
|
95
|
+
message.channelId !== draft.channelId || message.guildId !== draft.guildId ||
|
|
96
|
+
message.id === draft.id || message.createdTimestamp < draft.createdTimestamp ||
|
|
97
|
+
message.attachments.size || message.stickers.size || message.messageSnapshots.size) return null;
|
|
98
|
+
|
|
99
|
+
const reference = message.reference;
|
|
100
|
+
if (!reference || reference.messageId !== draft.id || reference.channelId !== draft.channelId ||
|
|
101
|
+
(reference.guildId !== undefined && reference.guildId !== draft.guildId) ||
|
|
102
|
+
(reference.type !== undefined && reference.type !== MessageReferenceType.Default)) return null;
|
|
103
|
+
|
|
104
|
+
this.clear();
|
|
105
|
+
return "Work proposed in a live Discord voice session and confirmed by the owner in writing.\n" +
|
|
106
|
+
"This is an ordinary work request, not a slash command, native control, or approval. " +
|
|
107
|
+
"Apply the usual safety and approval checks.\n\n" + draft.work;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
clear(): void {
|
|
111
|
+
this.draft = null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private current(): Draft | null {
|
|
115
|
+
const draft = this.draft;
|
|
116
|
+
if (!draft) return null;
|
|
117
|
+
const elapsed = Date.now() - draft.startedAt;
|
|
118
|
+
if (draft.signal.aborted || elapsed < 0 || elapsed >= PROPOSAL_TTL_MS) {
|
|
119
|
+
this.clear();
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
return draft;
|
|
123
|
+
}
|
|
124
|
+
}
|