@openlegion/platform 0.0.0-stage → 0.1.0
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/LICENSE +202 -0
- package/README.md +1189 -2
- package/dist/body.d.ts +9 -0
- package/dist/body.js +28 -0
- package/dist/chat-history.d.ts +53 -0
- package/dist/chat-history.js +11 -0
- package/dist/client.d.ts +217 -0
- package/dist/client.js +367 -0
- package/dist/core.d.ts +47 -0
- package/dist/core.js +1 -0
- package/dist/crypto.d.ts +25 -0
- package/dist/crypto.js +81 -0
- package/dist/errors.d.ts +111 -0
- package/dist/errors.js +134 -0
- package/dist/events.d.ts +131 -0
- package/dist/events.js +5 -0
- package/dist/generated/api.d.ts +5505 -0
- package/dist/generated/api.js +446 -0
- package/dist/handler.d.ts +201 -0
- package/dist/handler.js +682 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +12 -0
- package/dist/kit-agents.d.ts +95 -0
- package/dist/kit-agents.js +280 -0
- package/dist/kit-codes.d.ts +279 -0
- package/dist/kit-codes.js +44 -0
- package/dist/kit-connections.d.ts +21 -0
- package/dist/kit-connections.js +189 -0
- package/dist/kit-files.d.ts +8 -0
- package/dist/kit-files.js +117 -0
- package/dist/kit-model-keys.d.ts +8 -0
- package/dist/kit-model-keys.js +86 -0
- package/dist/kit-threads.d.ts +3 -0
- package/dist/kit-threads.js +92 -0
- package/dist/kit-tools.d.ts +21 -0
- package/dist/kit-tools.js +47 -0
- package/dist/kit.d.ts +130 -0
- package/dist/kit.js +155 -0
- package/dist/mcp-server.d.ts +27 -0
- package/dist/mcp-server.js +166 -0
- package/dist/next.d.ts +24 -0
- package/dist/next.js +6 -0
- package/dist/ol-signed.d.ts +82 -0
- package/dist/ol-signed.js +115 -0
- package/dist/react/add-server.d.ts +90 -0
- package/dist/react/add-server.js +183 -0
- package/dist/react/agent-chat.d.ts +925 -0
- package/dist/react/agent-chat.js +1917 -0
- package/dist/react/agent-editor.d.ts +133 -0
- package/dist/react/agent-editor.js +222 -0
- package/dist/react/agent-kit.d.ts +160 -0
- package/dist/react/agent-kit.js +279 -0
- package/dist/react/agent-list.d.ts +247 -0
- package/dist/react/agent-list.js +248 -0
- package/dist/react/approval-card.d.ts +272 -0
- package/dist/react/approval-card.js +372 -0
- package/dist/react/artifact-card.d.ts +38 -0
- package/dist/react/artifact-card.js +39 -0
- package/dist/react/avatar.d.ts +21 -0
- package/dist/react/avatar.js +33 -0
- package/dist/react/card-ledger.d.ts +30 -0
- package/dist/react/card-ledger.js +49 -0
- package/dist/react/chat-timing.d.ts +121 -0
- package/dist/react/chat-timing.js +229 -0
- package/dist/react/computer-view.d.ts +309 -0
- package/dist/react/computer-view.js +543 -0
- package/dist/react/computer-viewer.d.ts +175 -0
- package/dist/react/computer-viewer.js +555 -0
- package/dist/react/computer-wire.d.ts +178 -0
- package/dist/react/computer-wire.js +244 -0
- package/dist/react/connect-button.d.ts +145 -0
- package/dist/react/connect-button.js +212 -0
- package/dist/react/connection-request.d.ts +16 -0
- package/dist/react/connection-request.js +18 -0
- package/dist/react/connections-list.d.ts +90 -0
- package/dist/react/connections-list.js +76 -0
- package/dist/react/errors.d.ts +250 -0
- package/dist/react/errors.js +146 -0
- package/dist/react/files.d.ts +41 -0
- package/dist/react/files.js +78 -0
- package/dist/react/index.d.ts +35 -0
- package/dist/react/index.js +26 -0
- package/dist/react/limit-words.d.ts +80 -0
- package/dist/react/limit-words.js +53 -0
- package/dist/react/markdown.d.ts +42 -0
- package/dist/react/markdown.js +56 -0
- package/dist/react/md-parse.d.ts +106 -0
- package/dist/react/md-parse.js +638 -0
- package/dist/react/model-keys-card.d.ts +94 -0
- package/dist/react/model-keys-card.js +123 -0
- package/dist/react/reload.d.ts +211 -0
- package/dist/react/reload.js +339 -0
- package/dist/react/reveal.d.ts +17 -0
- package/dist/react/reveal.js +22 -0
- package/dist/react/schedule-editor.d.ts +107 -0
- package/dist/react/schedule-editor.js +172 -0
- package/dist/react/schedule-time.d.ts +66 -0
- package/dist/react/schedule-time.js +90 -0
- package/dist/react/styles.css +1274 -0
- package/dist/react/transport.d.ts +49 -0
- package/dist/react/transport.js +380 -0
- package/dist/react/use-connections.d.ts +155 -0
- package/dist/react/use-connections.js +231 -0
- package/dist/react/use-model-keys.d.ts +47 -0
- package/dist/react/use-model-keys.js +57 -0
- package/dist/react/use-threads.d.ts +63 -0
- package/dist/react/use-threads.js +73 -0
- package/dist/react/vault-form.d.ts +92 -0
- package/dist/react/vault-form.js +151 -0
- package/dist/schema.d.ts +47 -0
- package/dist/schema.js +16 -0
- package/dist/secrets.d.ts +15 -0
- package/dist/secrets.js +18 -0
- package/dist/stream.d.ts +129 -0
- package/dist/stream.js +192 -0
- package/dist/testing.d.ts +33 -0
- package/dist/testing.js +40 -0
- package/dist/webhooks.d.ts +31 -0
- package/dist/webhooks.js +72 -0
- package/package.json +85 -3
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { limitOf } from "./limit-words.js";
|
|
2
|
+
import { computerSessionOf } from "./computer-wire.js";
|
|
3
|
+
import { vaultRequestOf } from "./vault-form.js";
|
|
4
|
+
export const MAX_READS = 8;
|
|
5
|
+
export const IN_FLIGHT = 2;
|
|
6
|
+
export function kitBaseFor(api) {
|
|
7
|
+
if (api && /\/chat\/?$/.test(api))
|
|
8
|
+
return api.replace(/\/chat\/?$/, "");
|
|
9
|
+
return "/api/openlegion";
|
|
10
|
+
}
|
|
11
|
+
const RUN_RE = /^run_[0-9A-Za-z]{1,64}$/;
|
|
12
|
+
const APPROVAL_RE = /^apr_[0-9A-Za-z]{1,64}$/;
|
|
13
|
+
const MESSAGE_RE = /^msg_[0-9A-Za-z]{1,64}$/;
|
|
14
|
+
export function unansweredRuns(messages, only) {
|
|
15
|
+
const out = [];
|
|
16
|
+
messages.forEach((m, i) => {
|
|
17
|
+
if (m.role !== "user" || (only && !only.has(m.id)))
|
|
18
|
+
return;
|
|
19
|
+
const run = m.run;
|
|
20
|
+
if (typeof run !== "string" || !RUN_RE.test(run))
|
|
21
|
+
return;
|
|
22
|
+
let answered = false;
|
|
23
|
+
for (let j = i + 1; j < messages.length && messages[j].role !== "user"; j++)
|
|
24
|
+
if (messages[j].role === "assistant")
|
|
25
|
+
answered = true;
|
|
26
|
+
if (!answered)
|
|
27
|
+
out.push({ message: m.id, run });
|
|
28
|
+
});
|
|
29
|
+
return out.slice(-MAX_READS);
|
|
30
|
+
}
|
|
31
|
+
export function sentMessageOf(part) {
|
|
32
|
+
if (part.type !== "data-message")
|
|
33
|
+
return null;
|
|
34
|
+
const d = part.data;
|
|
35
|
+
if (!d || typeof d.id !== "string" || !MESSAGE_RE.test(d.id) || typeof d.text !== "string")
|
|
36
|
+
return null;
|
|
37
|
+
return { id: d.id, text: d.text, created: typeof d.created === "string" ? d.created : null, tainted: d.tainted !== false };
|
|
38
|
+
}
|
|
39
|
+
export function sentMessageIds(parts) {
|
|
40
|
+
const ids = new Set();
|
|
41
|
+
for (const p of parts) {
|
|
42
|
+
const m = sentMessageOf(p);
|
|
43
|
+
if (m)
|
|
44
|
+
ids.add(m.id);
|
|
45
|
+
}
|
|
46
|
+
return ids;
|
|
47
|
+
}
|
|
48
|
+
export function runSettled(read, run, sent = new Set()) {
|
|
49
|
+
return replyOf(read, run, sent) !== null;
|
|
50
|
+
}
|
|
51
|
+
export function replyOf(read, run, sent) {
|
|
52
|
+
for (let i = read.length - 1; i >= 0; i--) {
|
|
53
|
+
const m = read[i];
|
|
54
|
+
if (m.role === "assistant" && m.run === run && !sent.has(m.id))
|
|
55
|
+
return m;
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
export function runStillUnanswered(messages, message) {
|
|
60
|
+
const i = messages.findIndex((m) => m.id === message && m.role === "user");
|
|
61
|
+
if (i < 0)
|
|
62
|
+
return false;
|
|
63
|
+
for (let j = i + 1; j < messages.length && messages[j].role !== "user"; j++)
|
|
64
|
+
if (messages[j].role === "assistant")
|
|
65
|
+
return false;
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
export function historyVaultAsks(messages, only) {
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const m of messages) {
|
|
71
|
+
if (m.role !== "assistant" || !MESSAGE_RE.test(m.id) || (only && !only.has(m.id)))
|
|
72
|
+
continue;
|
|
73
|
+
m.parts.forEach((p, i) => {
|
|
74
|
+
if (p.type !== "data-vault-request")
|
|
75
|
+
return;
|
|
76
|
+
const request = vaultRequestOf(p.data);
|
|
77
|
+
if (request)
|
|
78
|
+
out.push({ key: `${m.id}:${i}`, message: m.id, name: request.name });
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return out.slice(-MAX_READS);
|
|
82
|
+
}
|
|
83
|
+
export function runOutcomeOf(body) {
|
|
84
|
+
if (!body || typeof body !== "object")
|
|
85
|
+
return null;
|
|
86
|
+
const b = body;
|
|
87
|
+
if (b["object"] === "run_outcome" && b["status"] === "cancelled")
|
|
88
|
+
return { refusal: null, tools: [], stopped: true };
|
|
89
|
+
if (b["object"] !== "run_outcome" || (b["status"] !== "completed" && b["status"] !== "failed") || !Array.isArray(b["actions"]))
|
|
90
|
+
return null;
|
|
91
|
+
const limit = limitOf(b["limit"]);
|
|
92
|
+
const refusal = b["status"] === "failed" && typeof b["message"] === "string" && b["message"] !== "" ? { code: typeof b["code"] === "string" ? b["code"] : null, message: b["message"].slice(0, 500), ...(limit ? { limit } : {}) } : null;
|
|
93
|
+
const tools = [];
|
|
94
|
+
for (const a of b["actions"]) {
|
|
95
|
+
if (!a || typeof a !== "object")
|
|
96
|
+
continue;
|
|
97
|
+
const { id, tool, status, outcome, approval } = a;
|
|
98
|
+
if (typeof tool !== "string" || !/^[A-Za-z0-9_-]{1,120}$/.test(tool))
|
|
99
|
+
continue;
|
|
100
|
+
const action = typeof id === "string" && /^act_[0-9A-Za-z]{1,64}$/.test(id) ? { action: id } : {};
|
|
101
|
+
const apr = typeof approval === "string" && APPROVAL_RE.test(approval) ? { approval, ...action } : {};
|
|
102
|
+
if (outcome === "failed" || outcome === "refused" || outcome === "unknown")
|
|
103
|
+
tools.push({ tool, state: "output-error", ...apr });
|
|
104
|
+
else if (outcome === "succeeded")
|
|
105
|
+
tools.push({ tool, state: "output-available", ...apr });
|
|
106
|
+
else if (status === "requires_approval" && "approval" in apr)
|
|
107
|
+
tools.push({ tool, state: "output-available", ...apr });
|
|
108
|
+
else
|
|
109
|
+
tools.push({ tool, state: "input-available", ...apr });
|
|
110
|
+
}
|
|
111
|
+
return refusal === null && tools.length === 0 ? null : { refusal, tools };
|
|
112
|
+
}
|
|
113
|
+
export async function answeredBy(load, followed, waiting) {
|
|
114
|
+
const startOf = async (run) => {
|
|
115
|
+
const body = await read(load.fetch, `${load.base}/runs/${encodeURIComponent(run)}`);
|
|
116
|
+
const b = body && typeof body === "object" ? body : null;
|
|
117
|
+
return b && b["object"] === "run_outcome" && typeof b["started_at"] === "string" && b["started_at"] !== "" ? b["started_at"] : null;
|
|
118
|
+
};
|
|
119
|
+
const answered = new Set();
|
|
120
|
+
const start = await startOf(followed);
|
|
121
|
+
if (start === null)
|
|
122
|
+
return answered;
|
|
123
|
+
for (const w of waiting.slice(-MAX_READS))
|
|
124
|
+
if ((await startOf(w.run)) === start)
|
|
125
|
+
answered.add(w.message);
|
|
126
|
+
return answered;
|
|
127
|
+
}
|
|
128
|
+
export function afterReconnect(messages, dropped) {
|
|
129
|
+
if (!dropped || messages[messages.length - 1]?.role === "assistant")
|
|
130
|
+
return messages;
|
|
131
|
+
return [...messages, dropped];
|
|
132
|
+
}
|
|
133
|
+
export function mergeReread(current, initialCount, read) {
|
|
134
|
+
if (current.length !== initialCount)
|
|
135
|
+
return current;
|
|
136
|
+
const known = new Set(current.map((m) => m.id));
|
|
137
|
+
const missed = read.filter((m) => !known.has(m.id));
|
|
138
|
+
return missed.length === 0 ? current : [...current, ...missed];
|
|
139
|
+
}
|
|
140
|
+
export function rereadOnLoad(current, initialCount, read, drawnRuns, ownRun = () => null) {
|
|
141
|
+
const merged = mergeReread(current, initialCount, read);
|
|
142
|
+
return merged !== current ? merged : missedReplies(current, read, drawnRuns, ownRun);
|
|
143
|
+
}
|
|
144
|
+
function runOfMessage(m) {
|
|
145
|
+
const r = m.run;
|
|
146
|
+
return typeof r === "string" ? r : null;
|
|
147
|
+
}
|
|
148
|
+
function ownRuns(current, read, ownRun) {
|
|
149
|
+
const stored = new Set(read.map((m) => m.id));
|
|
150
|
+
const runs = new Set();
|
|
151
|
+
for (const m of current) {
|
|
152
|
+
if (m.role !== "user" || stored.has(m.id))
|
|
153
|
+
continue;
|
|
154
|
+
const run = ownRun(m.id);
|
|
155
|
+
if (run === null)
|
|
156
|
+
return null;
|
|
157
|
+
runs.add(run);
|
|
158
|
+
}
|
|
159
|
+
return runs;
|
|
160
|
+
}
|
|
161
|
+
export function missedReplies(current, read, drawnRuns = new Set(), ownRun = () => null) {
|
|
162
|
+
return freshSessions(current, missedRepliesAs(current, read, drawnRuns, ownRun), read);
|
|
163
|
+
}
|
|
164
|
+
function missedRepliesAs(current, read, drawnRuns, ownRun) {
|
|
165
|
+
if (current.length === 0)
|
|
166
|
+
return read.length > 0 ? [...read] : current;
|
|
167
|
+
const mine = ownRuns(current, read, ownRun);
|
|
168
|
+
const ids = new Set(current.map((m) => m.id));
|
|
169
|
+
const runs = new Set([...drawnRuns, ...current.flatMap((m) => (m.role === "assistant" && runOfMessage(m) ? [runOfMessage(m)] : []))]);
|
|
170
|
+
const shows = (m) => ids.has(m.id) || (m.role === "assistant" ? runs.has(runOfMessage(m) ?? "") : mine?.has(runOfMessage(m) ?? "") === true);
|
|
171
|
+
let anchor = -1;
|
|
172
|
+
read.forEach((m, i) => {
|
|
173
|
+
if (shows(m))
|
|
174
|
+
anchor = i;
|
|
175
|
+
});
|
|
176
|
+
if (anchor < 0)
|
|
177
|
+
return current;
|
|
178
|
+
const after = read.slice(anchor + 1);
|
|
179
|
+
if (after.length === 0 || (mine === null && after.some((m) => m.role !== "assistant")))
|
|
180
|
+
return current;
|
|
181
|
+
return [...current, ...after];
|
|
182
|
+
}
|
|
183
|
+
export function reconcileReply(current, liveId, run, read, ownRun = () => null) {
|
|
184
|
+
return freshSessions(current, reconcileReplyAs(current, liveId, run, read, ownRun), read, liveId);
|
|
185
|
+
}
|
|
186
|
+
function reconcileReplyAs(current, liveId, run, read, ownRun) {
|
|
187
|
+
const at = current.findIndex((m) => m.id === liveId);
|
|
188
|
+
if (at < 0 || current[at].role !== "assistant")
|
|
189
|
+
return current;
|
|
190
|
+
const sent = sentMessageIds(current[at].parts);
|
|
191
|
+
const all = read.filter((m) => m.role === "assistant" && m.run === run);
|
|
192
|
+
const fromThread = all.filter((m) => !sent.has(m.id));
|
|
193
|
+
if (fromThread.length === 0)
|
|
194
|
+
return current;
|
|
195
|
+
const shown = new Set(current.map((m) => m.id));
|
|
196
|
+
const asked = read.find((m) => m.role === "user" && runOfMessage(m) === run);
|
|
197
|
+
const mine = ownRuns(current, read, ownRun);
|
|
198
|
+
if (asked && !shown.has(asked.id) && mine !== null && !mine.has(run)) {
|
|
199
|
+
return reconcileReplyAs([...current.slice(0, at), asked, ...current.slice(at)], liveId, run, read, ownRun);
|
|
200
|
+
}
|
|
201
|
+
if (shown.has(fromThread[0].id))
|
|
202
|
+
return current;
|
|
203
|
+
const incoming = fromThread.filter((m, i) => i === 0 || !shown.has(m.id));
|
|
204
|
+
const live = current[at];
|
|
205
|
+
const liveParts = live.parts.filter((p) => p.type !== "data-message");
|
|
206
|
+
const stopped = (m) => m.stopped === true;
|
|
207
|
+
const trigger = (m) => m.trigger ?? null;
|
|
208
|
+
const drawsSame = incoming.length === 1 && drawnAs(liveParts) === drawnAs(incoming[0].parts) && stopped(live) === stopped(incoming[0]);
|
|
209
|
+
if (drawsSame && trigger(live) === trigger(incoming[0]))
|
|
210
|
+
return current;
|
|
211
|
+
if (drawsSame && sent.size > 0) {
|
|
212
|
+
const r = incoming[0];
|
|
213
|
+
const kept = { ...live, trigger: r.trigger ?? null, schedule: r.schedule ?? null, run: r.run ?? run, tainted: r.tainted };
|
|
214
|
+
return [...current.slice(0, at), kept, ...current.slice(at + 1)];
|
|
215
|
+
}
|
|
216
|
+
const first = { ...incoming[0], id: live.id, ...(live.metadata !== undefined ? { metadata: live.metadata } : {}) };
|
|
217
|
+
const carried = all.filter((m) => sent.has(m.id) && !shown.has(m.id));
|
|
218
|
+
return [...current.slice(0, at), ...carried, first, ...incoming.slice(1), ...current.slice(at + 1)];
|
|
219
|
+
}
|
|
220
|
+
function sessionOfPart(p) {
|
|
221
|
+
return p.type === "data-computer" ? (computerSessionOf(p.data)?.id ?? null) : null;
|
|
222
|
+
}
|
|
223
|
+
export function freshSessions(before, after, read, liveId) {
|
|
224
|
+
const newest = new Map();
|
|
225
|
+
for (const list of [before, read])
|
|
226
|
+
for (const m of list)
|
|
227
|
+
for (const p of m.parts) {
|
|
228
|
+
const id = sessionOfPart(p);
|
|
229
|
+
if (id !== null)
|
|
230
|
+
newest.set(id, p);
|
|
231
|
+
}
|
|
232
|
+
if (newest.size === 0)
|
|
233
|
+
return after;
|
|
234
|
+
const left = new Set(newest.keys());
|
|
235
|
+
const from = liveId === undefined ? -1 : after.findIndex((m) => m.id === liveId);
|
|
236
|
+
for (const m of from < 0 ? after : after.slice(from))
|
|
237
|
+
for (const p of m.parts) {
|
|
238
|
+
const id = sessionOfPart(p);
|
|
239
|
+
if (id !== null)
|
|
240
|
+
left.delete(id);
|
|
241
|
+
}
|
|
242
|
+
const drawnIn = liveId === undefined ? undefined : before.find((m) => m.id === liveId);
|
|
243
|
+
const keep = drawnIn ? drawnIn.parts.filter((p) => { const id = sessionOfPart(p); return id !== null && left.has(id); }) : [];
|
|
244
|
+
let changed = false;
|
|
245
|
+
const out = after.map((m) => {
|
|
246
|
+
let mine = false;
|
|
247
|
+
const parts = m.parts.map((p) => {
|
|
248
|
+
const id = sessionOfPart(p);
|
|
249
|
+
const fresh = id === null ? undefined : newest.get(id);
|
|
250
|
+
if (!fresh || fresh === p || JSON.stringify(fresh.data) === JSON.stringify(p.data))
|
|
251
|
+
return p;
|
|
252
|
+
mine = true;
|
|
253
|
+
return { ...p, data: fresh.data };
|
|
254
|
+
});
|
|
255
|
+
const extra = keep.length > 0 && m.id === liveId ? keep.map((p) => { const id = sessionOfPart(p); return { ...p, data: newest.get(id).data }; }) : [];
|
|
256
|
+
if (!mine && extra.length === 0)
|
|
257
|
+
return m;
|
|
258
|
+
changed = true;
|
|
259
|
+
return { ...m, parts: [...parts, ...extra] };
|
|
260
|
+
});
|
|
261
|
+
return changed ? out : after;
|
|
262
|
+
}
|
|
263
|
+
export function drawnAs(parts) {
|
|
264
|
+
return JSON.stringify(parts.map((p) => {
|
|
265
|
+
const o = p;
|
|
266
|
+
if (p.type === "text")
|
|
267
|
+
return o["text"] === "" ? null : { t: "text", text: o["text"] };
|
|
268
|
+
if (p.type.startsWith("data-"))
|
|
269
|
+
return { t: p.type, data: o["data"] };
|
|
270
|
+
if (p.type === "tool-agent_finish" || (p.type === "dynamic-tool" && o["toolName"] === "agent_finish"))
|
|
271
|
+
return null;
|
|
272
|
+
if (p.type.startsWith("tool-") || p.type === "dynamic-tool") {
|
|
273
|
+
const out = o["output"];
|
|
274
|
+
return { t: p.type, name: o["toolName"], state: o["state"], status: out?.status, outcome: out?.outcome, approval: out?.approval, error: o["errorText"] };
|
|
275
|
+
}
|
|
276
|
+
return null;
|
|
277
|
+
}).filter((x) => x !== null));
|
|
278
|
+
}
|
|
279
|
+
export async function readEarlier(load, before) {
|
|
280
|
+
const body = await read(load.fetch, `${load.base}/chat/${encodeURIComponent(load.threadId)}/messages?before=${encodeURIComponent(before)}`);
|
|
281
|
+
const messages = asMessages(body);
|
|
282
|
+
if (!messages)
|
|
283
|
+
return null;
|
|
284
|
+
const b = body;
|
|
285
|
+
return { messages, next: b.has_more === true && typeof b.next_before === "string" && MESSAGE_RE.test(b.next_before) ? b.next_before : null };
|
|
286
|
+
}
|
|
287
|
+
export function placeEarlier(current, page) {
|
|
288
|
+
const drawn = new Set(current.map((m) => m.id));
|
|
289
|
+
const fresh = page.filter((m) => !drawn.has(m.id));
|
|
290
|
+
return fresh.length === 0 ? current : [...fresh, ...current];
|
|
291
|
+
}
|
|
292
|
+
export async function readThreadHistory(load) {
|
|
293
|
+
return asMessages(await read(load.fetch, `${load.base}/chat/${encodeURIComponent(load.threadId)}/messages`));
|
|
294
|
+
}
|
|
295
|
+
function asMessages(body) {
|
|
296
|
+
const data = body && typeof body === "object" ? body.data : undefined;
|
|
297
|
+
if (!Array.isArray(data))
|
|
298
|
+
return null;
|
|
299
|
+
return data.filter((m) => !!m && typeof m === "object" && typeof m.id === "string" && MESSAGE_RE.test(m.id) && (m.role === "user" || m.role === "assistant") && Array.isArray(m.parts));
|
|
300
|
+
}
|
|
301
|
+
export async function runStopped(load, run) {
|
|
302
|
+
const body = await read(load.fetch, `${load.base}/runs/${encodeURIComponent(run)}`);
|
|
303
|
+
const b = body && typeof body === "object" ? body : null;
|
|
304
|
+
if (!b || b["object"] !== "run_outcome")
|
|
305
|
+
return "no";
|
|
306
|
+
if (b["status"] === "cancelled")
|
|
307
|
+
return "stopped";
|
|
308
|
+
return b["status"] === "queued" || b["status"] === "running" ? "again" : "no";
|
|
309
|
+
}
|
|
310
|
+
async function read(f, url) {
|
|
311
|
+
try {
|
|
312
|
+
const res = await f(url, { method: "GET", headers: { accept: "application/json" }, credentials: "same-origin" });
|
|
313
|
+
return res.ok ? (await res.json()) : null;
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
export async function loadHistoryState(history, load, on, only) {
|
|
320
|
+
const tasks = [
|
|
321
|
+
...unansweredRuns(history, only).map(({ message, run }) => async () => {
|
|
322
|
+
const outcome = runOutcomeOf(await read(load.fetch, `${load.base}/runs/${encodeURIComponent(run)}`));
|
|
323
|
+
if (outcome)
|
|
324
|
+
on.outcome(message, outcome);
|
|
325
|
+
}),
|
|
326
|
+
...historyVaultAsks(history, only).map(({ key, message, name }) => async () => {
|
|
327
|
+
const q = new URLSearchParams({ thread: load.threadId, message, name }).toString();
|
|
328
|
+
const body = await read(load.fetch, `${load.vaultApi}?${q}`);
|
|
329
|
+
if (body && typeof body === "object" && body["object"] === "vault_item_state" && body["saved"] === true)
|
|
330
|
+
on.saved(key);
|
|
331
|
+
}),
|
|
332
|
+
];
|
|
333
|
+
let next = 0;
|
|
334
|
+
const worker = async () => {
|
|
335
|
+
while (next < tasks.length)
|
|
336
|
+
await tasks[next++]();
|
|
337
|
+
};
|
|
338
|
+
await Promise.all(Array.from({ length: Math.min(IN_FLIGHT, tasks.length) }, worker));
|
|
339
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brings a note fully into view: the nearest edge, instantly (never a smooth scroll, so nothing moves under reduced
|
|
3
|
+
* motion). Inside the chat too (a ConnectButton or a vault form on a card): the chat's own scroller is moved, nearest
|
|
4
|
+
* edge, like the page.
|
|
5
|
+
*/
|
|
6
|
+
export declare function revealNote(el: Element | null): void;
|
|
7
|
+
/**
|
|
8
|
+
* The ref's body, apart from React: reveals the element when it appears (or its words change) after the component's
|
|
9
|
+
* first render, never on load. An empty `words` is a line with nothing to read yet.
|
|
10
|
+
*/
|
|
11
|
+
export declare function noteRef(afterFirstRender: () => boolean, words?: unknown): (el: Element | null) => void;
|
|
12
|
+
/**
|
|
13
|
+
* The callback ref for a note shown after a press. `words`: for a line that is always there and only changes its words
|
|
14
|
+
* (a live status line), pass the words, so the ref runs again when they change. A note drawn only when it has
|
|
15
|
+
* something to say needs none: the ref runs when it appears.
|
|
16
|
+
*/
|
|
17
|
+
export declare function useNoteInView(words?: unknown): (el: Element | null) => void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useEffect, useMemo, useRef } from "react";
|
|
2
|
+
export function revealNote(el) {
|
|
3
|
+
if (!el || typeof el.scrollIntoView !== "function")
|
|
4
|
+
return;
|
|
5
|
+
el.scrollIntoView({ block: "nearest", inline: "nearest" });
|
|
6
|
+
}
|
|
7
|
+
export function noteRef(afterFirstRender, words) {
|
|
8
|
+
return (el) => {
|
|
9
|
+
if (el && afterFirstRender() && words !== "" && words !== null && words !== false)
|
|
10
|
+
revealNote(el);
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export function useNoteInView(words) {
|
|
14
|
+
const mounted = useRef(false);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
mounted.current = true;
|
|
17
|
+
return () => {
|
|
18
|
+
mounted.current = false;
|
|
19
|
+
};
|
|
20
|
+
}, []);
|
|
21
|
+
return useMemo(() => noteRef(() => mounted.current, words), [words]);
|
|
22
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { type AgentKitErrorLabels, type KitAgent, type KitSchedule, type UseAgentKitOptions } from "./agent-kit.ts";
|
|
2
|
+
import { type BoundsProblem, type ScheduleBounds, type WeeklyTime } from "./schedule-time.ts";
|
|
3
|
+
export interface ScheduleEditorLabels {
|
|
4
|
+
heading: string;
|
|
5
|
+
empty: string;
|
|
6
|
+
/** Seven short day names, Sunday first. */
|
|
7
|
+
days: [string, string, string, string, string, string, string];
|
|
8
|
+
everyDay: string;
|
|
9
|
+
weekdays: string;
|
|
10
|
+
weekends: string;
|
|
11
|
+
/** `{days}` and `{time}` are replaced. */
|
|
12
|
+
when: string;
|
|
13
|
+
custom: string;
|
|
14
|
+
/** `{when}` is replaced: a one-off run's date and time. */
|
|
15
|
+
once: string;
|
|
16
|
+
/** `{when}` and `{zone}` are replaced: the time in the schedule's zone, and that zone in words (`zoneName`). */
|
|
17
|
+
next: string;
|
|
18
|
+
fromTemplate: string;
|
|
19
|
+
fromAgent: string;
|
|
20
|
+
paused: string;
|
|
21
|
+
finished: string;
|
|
22
|
+
addHeading: string;
|
|
23
|
+
editHeading: string;
|
|
24
|
+
daysLegend: string;
|
|
25
|
+
time: string;
|
|
26
|
+
hour: string;
|
|
27
|
+
minute: string;
|
|
28
|
+
instructions: string;
|
|
29
|
+
instructionsHint: string;
|
|
30
|
+
/** Before a schedule's instructions in its row: what it will ask the assistant to do. */
|
|
31
|
+
does: string;
|
|
32
|
+
description: string;
|
|
33
|
+
add: string;
|
|
34
|
+
/** Beside Add while it can't be pressed because "What it should do" is empty. */
|
|
35
|
+
needsInstructions: string;
|
|
36
|
+
save: string;
|
|
37
|
+
cancelEdit: string;
|
|
38
|
+
saving: string;
|
|
39
|
+
edit: string;
|
|
40
|
+
pause: string;
|
|
41
|
+
resume: string;
|
|
42
|
+
remove: string;
|
|
43
|
+
/** `{description}` is replaced. For the remove button's accessible name. */
|
|
44
|
+
removeNamed: string;
|
|
45
|
+
/** The person's schedules are at the template's most. */
|
|
46
|
+
full: string;
|
|
47
|
+
bounds: Record<BoundsProblem, string>;
|
|
48
|
+
/** Shown when the template admits no schedules made by a person. */
|
|
49
|
+
notOffered: string;
|
|
50
|
+
loading: string;
|
|
51
|
+
errors?: Partial<AgentKitErrorLabels>;
|
|
52
|
+
}
|
|
53
|
+
export declare const DEFAULT_SCHEDULE_EDITOR_LABELS: ScheduleEditorLabels;
|
|
54
|
+
/**
|
|
55
|
+
* "Weekdays at 9:00 AM", "Mon, Thu at 17:30" (the page's hour cycle, `locale`), or null for a shape the picker
|
|
56
|
+
* doesn't draw. Pure: `labels` over OpenLegion's (`when`, `days`, `everyDay`, `weekdays`, `weekends`).
|
|
57
|
+
*/
|
|
58
|
+
export declare function describeWeekly(w: WeeklyTime | null, labels?: Partial<ScheduleEditorLabels>, locale?: string): string | null;
|
|
59
|
+
/** A moment in a time zone, for a person: "Thu, Nov 12, 9:00 AM" (en-US), "Thu 12 Nov, 09:00" (en-GB). The page's language and hour cycle; the schedule's zone. Pure. */
|
|
60
|
+
export declare function inZone(iso: string, zone: string | null, locale?: string): string;
|
|
61
|
+
/**
|
|
62
|
+
* A time zone in a person's words, in the page's language: "Eastern Time", "Central European Time". UTC
|
|
63
|
+
* itself (or no zone) is "UTC". An id the browser doesn't know stays the id.
|
|
64
|
+
*/
|
|
65
|
+
export declare function zoneName(zone: string | null, locale?: string, at?: Date): string;
|
|
66
|
+
/**
|
|
67
|
+
* What a schedule's line says it does, and when: "Mon at 9:00 AM", "Once, Mon, Nov 23, 9:00 AM", or "Custom
|
|
68
|
+
* schedule". Pure: `labels` over OpenLegion's; `locale` for the language and hour cycle.
|
|
69
|
+
*/
|
|
70
|
+
export declare function scheduleWhen(s: Pick<KitSchedule, "cron" | "run_at" | "time_zone">, labels?: Partial<ScheduleEditorLabels>, locale?: string): string;
|
|
71
|
+
/** The person's schedules that count toward `max`: theirs, not finished. */
|
|
72
|
+
export declare function personScheduleCount(list: readonly KitSchedule[]): number;
|
|
73
|
+
export interface ScheduleDraft {
|
|
74
|
+
weekly: WeeklyTime;
|
|
75
|
+
instructions: string;
|
|
76
|
+
description: string;
|
|
77
|
+
}
|
|
78
|
+
export declare function emptyDraft(b: ScheduleBounds | null | undefined): ScheduleDraft;
|
|
79
|
+
export interface ScheduleEditorViewProps {
|
|
80
|
+
schedules: KitSchedule[] | null;
|
|
81
|
+
bounds: ScheduleBounds | null;
|
|
82
|
+
draft: ScheduleDraft;
|
|
83
|
+
/** The schedule being changed, or null: adding one. */
|
|
84
|
+
editing: string | null;
|
|
85
|
+
busy: boolean;
|
|
86
|
+
error: Error | null;
|
|
87
|
+
onDraft: (d: ScheduleDraft) => void;
|
|
88
|
+
onSubmit: () => void;
|
|
89
|
+
onEdit: (id: string | null) => void;
|
|
90
|
+
onPause: (id: string) => void;
|
|
91
|
+
onResume: (id: string) => void;
|
|
92
|
+
onRemove: (id: string) => void;
|
|
93
|
+
labels?: Partial<ScheduleEditorLabels> | undefined;
|
|
94
|
+
locale?: string | undefined;
|
|
95
|
+
className?: string | undefined;
|
|
96
|
+
}
|
|
97
|
+
/** The editor's markup alone, from its state (what `<ScheduleEditor>` draws). */
|
|
98
|
+
export declare function ScheduleEditorView(p: ScheduleEditorViewProps): import("react").JSX.Element;
|
|
99
|
+
export interface ScheduleEditorProps extends UseAgentKitOptions {
|
|
100
|
+
/** The assistant (from `useAgents`): its id, and its `customizable.schedules` bounds. */
|
|
101
|
+
agent: KitAgent;
|
|
102
|
+
labels?: Partial<ScheduleEditorLabels>;
|
|
103
|
+
/** The language dates are written in. Default: the page's. */
|
|
104
|
+
locale?: string;
|
|
105
|
+
className?: string;
|
|
106
|
+
}
|
|
107
|
+
export declare function ScheduleEditor(props: ScheduleEditorProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useId, useRef, useState } from "react";
|
|
4
|
+
import { agentKitErrorText, AgentKitError, newIdempotencyKey, useSchedules } from "./agent-kit.js";
|
|
5
|
+
import { useNoteInView } from "./reveal.js";
|
|
6
|
+
import { allowedDays, allowedHours, clock, cronToWeekly, timeOfDayOptions, weeklyOutsideBounds, weeklyToCron } from "./schedule-time.js";
|
|
7
|
+
export const DEFAULT_SCHEDULE_EDITOR_LABELS = {
|
|
8
|
+
heading: "Schedules",
|
|
9
|
+
empty: "No schedules yet.",
|
|
10
|
+
days: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
|
|
11
|
+
everyDay: "Every day",
|
|
12
|
+
weekdays: "Weekdays",
|
|
13
|
+
weekends: "Weekends",
|
|
14
|
+
when: "{days} at {time}",
|
|
15
|
+
custom: "Custom schedule",
|
|
16
|
+
once: "Once, {when}",
|
|
17
|
+
next: "Next run: {when} {zone}",
|
|
18
|
+
fromTemplate: "Built in",
|
|
19
|
+
fromAgent: "Set by the assistant",
|
|
20
|
+
paused: "Paused",
|
|
21
|
+
finished: "Finished",
|
|
22
|
+
addHeading: "Add a schedule",
|
|
23
|
+
editHeading: "Change this schedule",
|
|
24
|
+
daysLegend: "Days",
|
|
25
|
+
time: "Time",
|
|
26
|
+
hour: "Hour",
|
|
27
|
+
minute: "Minute",
|
|
28
|
+
instructions: "What it should do",
|
|
29
|
+
instructionsHint: "Never put passwords or keys here.",
|
|
30
|
+
does: "What it does:",
|
|
31
|
+
description: "Name (optional)",
|
|
32
|
+
add: "Add schedule",
|
|
33
|
+
needsInstructions: "Say what it should do first.",
|
|
34
|
+
save: "Save schedule",
|
|
35
|
+
cancelEdit: "Cancel",
|
|
36
|
+
saving: "Saving…",
|
|
37
|
+
edit: "Change",
|
|
38
|
+
pause: "Pause",
|
|
39
|
+
resume: "Resume",
|
|
40
|
+
remove: "Remove",
|
|
41
|
+
removeNamed: "Remove {description}",
|
|
42
|
+
full: "This assistant has as many schedules as it can have. Remove one to add another.",
|
|
43
|
+
bounds: {
|
|
44
|
+
no_days: "Choose at least one day.",
|
|
45
|
+
day: "Choose only the days offered.",
|
|
46
|
+
hour: "Choose a time inside the hours offered.",
|
|
47
|
+
interval: "Those days are too close together. Leave more time between them.",
|
|
48
|
+
},
|
|
49
|
+
notOffered: "Schedules can't be added here.",
|
|
50
|
+
loading: "Loading…",
|
|
51
|
+
};
|
|
52
|
+
const MINUTES = [0, 15, 30, 45];
|
|
53
|
+
export function describeWeekly(w, labels, locale) {
|
|
54
|
+
if (!w)
|
|
55
|
+
return null;
|
|
56
|
+
const l = { ...DEFAULT_SCHEDULE_EDITOR_LABELS, ...labels };
|
|
57
|
+
const set = w.days.join(",");
|
|
58
|
+
const days = set === "0,1,2,3,4,5,6" ? l.everyDay : set === "1,2,3,4,5" ? l.weekdays : set === "0,6" ? l.weekends : w.days.map((d) => l.days[d]).join(", ");
|
|
59
|
+
return l.when.replace("{days}", days).replace("{time}", clock(w.hour, w.minute, locale));
|
|
60
|
+
}
|
|
61
|
+
export function inZone(iso, zone, locale) {
|
|
62
|
+
const d = new Date(iso);
|
|
63
|
+
if (Number.isNaN(d.getTime()))
|
|
64
|
+
return iso;
|
|
65
|
+
try {
|
|
66
|
+
return new Intl.DateTimeFormat(locale, { timeZone: zone ?? "UTC", weekday: "short", day: "numeric", month: "short", ...timeOfDayOptions(locale) }).format(d);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return d.toISOString();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export function zoneName(zone, locale, at = new Date()) {
|
|
73
|
+
if (!zone || /^(Etc\/)?(UTC|UCT|Universal|Zulu|GMT)$/i.test(zone))
|
|
74
|
+
return "UTC";
|
|
75
|
+
try {
|
|
76
|
+
const part = new Intl.DateTimeFormat(locale, { timeZone: zone, timeZoneName: "longGeneric" }).formatToParts(at).find((x) => x.type === "timeZoneName");
|
|
77
|
+
return part?.value ?? zone;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return zone;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function scheduleWhen(s, labels, locale) {
|
|
84
|
+
const l = { ...DEFAULT_SCHEDULE_EDITOR_LABELS, ...labels };
|
|
85
|
+
if (s.run_at)
|
|
86
|
+
return l.once.replace("{when}", inZone(s.run_at, s.time_zone, locale));
|
|
87
|
+
return describeWeekly(cronToWeekly(s.cron), l, locale) ?? l.custom;
|
|
88
|
+
}
|
|
89
|
+
export function personScheduleCount(list) {
|
|
90
|
+
return list.filter((s) => s.origin === "api" && (s.status === "active" || s.status === "paused")).length;
|
|
91
|
+
}
|
|
92
|
+
export function emptyDraft(b) {
|
|
93
|
+
const days = allowedDays(b);
|
|
94
|
+
const hours = allowedHours(b);
|
|
95
|
+
const weekdays = days.filter((d) => d >= 1 && d <= 5);
|
|
96
|
+
return { weekly: { days: weekdays.length > 0 ? weekdays : days.slice(0, 1), hour: hours.includes(9) ? 9 : (hours[0] ?? 9), minute: 0 }, instructions: "", description: "" };
|
|
97
|
+
}
|
|
98
|
+
const col = { display: "flex", flexDirection: "column", gap: "var(--ol-gap, 0.75rem)" };
|
|
99
|
+
const row = { display: "flex", flexWrap: "wrap", gap: "var(--ol-gap-small, 0.5rem)", alignItems: "center" };
|
|
100
|
+
export function ScheduleEditorView(p) {
|
|
101
|
+
const l = { ...DEFAULT_SCHEDULE_EDITOR_LABELS, ...p.labels, bounds: { ...DEFAULT_SCHEDULE_EDITOR_LABELS.bounds, ...p.labels?.bounds } };
|
|
102
|
+
const id = useId();
|
|
103
|
+
const formNoteInView = useNoteInView(p.error ?? weeklyOutsideBounds(p.draft.weekly, p.bounds));
|
|
104
|
+
const listNoteInView = useNoteInView(p.error);
|
|
105
|
+
if (p.schedules === null)
|
|
106
|
+
return _jsx("p", { role: "status", "data-ol-schedule-loading": true, children: l.loading });
|
|
107
|
+
const problem = weeklyOutsideBounds(p.draft.weekly, p.bounds);
|
|
108
|
+
const full = !p.editing && p.bounds?.max !== undefined && personScheduleCount(p.schedules) >= p.bounds.max;
|
|
109
|
+
const apiParam = p.error instanceof AgentKitError ? p.error.param : null;
|
|
110
|
+
const message = p.error ? agentKitErrorText(p.error, { ...l.errors, refusals: { schedule_limit_reached: l.full, ...l.errors?.refusals } }) : null;
|
|
111
|
+
const days = allowedDays(p.bounds);
|
|
112
|
+
const hours = allowedHours(p.bounds);
|
|
113
|
+
const set = (patch) => p.onDraft({ ...p.draft, ...patch });
|
|
114
|
+
const setWeekly = (patch) => set({ weekly: { ...p.draft.weekly, ...patch } });
|
|
115
|
+
const toggle = (d) => setWeekly({ days: p.draft.weekly.days.includes(d) ? p.draft.weekly.days.filter((x) => x !== d) : [...p.draft.weekly.days, d].sort((a, b) => a - b) });
|
|
116
|
+
const submit = (e) => {
|
|
117
|
+
e.preventDefault();
|
|
118
|
+
if (!p.busy && !problem && p.draft.instructions.trim() !== "")
|
|
119
|
+
p.onSubmit();
|
|
120
|
+
};
|
|
121
|
+
const needsInstructions = problem === null && p.draft.instructions.trim() === "";
|
|
122
|
+
const timeBad = apiParam === "cron" || problem === "hour";
|
|
123
|
+
const daysBad = apiParam === "cron" || problem === "day" || problem === "no_days" || problem === "interval";
|
|
124
|
+
return (_jsxs("section", { className: p.className, "data-ol-schedule-editor": true, "aria-labelledby": `${id}-h`, style: col, children: [_jsx("h3", { id: `${id}-h`, style: { margin: 0 }, children: l.heading }), p.schedules.length === 0 ? (_jsx("p", { "data-ol-schedule-empty": true, children: l.empty })) : (_jsx("ul", { "data-ol-schedule-list": true, style: { ...col, listStyle: "none", margin: 0, padding: 0 }, children: p.schedules.map((s) => {
|
|
125
|
+
const words = s.description?.trim() ? s.description : null;
|
|
126
|
+
const does = s.instructions?.trim() ? s.instructions.trim() : null;
|
|
127
|
+
const when = scheduleWhen(s, l, p.locale);
|
|
128
|
+
const name = words ?? when;
|
|
129
|
+
const editable = s.origin === "api" && s.status !== "completed" && !s.run_at && cronToWeekly(s.cron) !== null;
|
|
130
|
+
const removable = s.origin !== "template" && s.status !== "completed";
|
|
131
|
+
return (_jsxs("li", { "data-ol-schedule": true, "data-ol-schedule-status": s.status, "data-ol-schedule-origin": s.origin, style: col, children: [_jsxs("div", { style: row, children: [_jsx("strong", { "data-ol-schedule-name": true, children: name.slice(0, 120) }), s.origin === "template" ? _jsx("span", { "data-ol-schedule-badge": true, children: l.fromTemplate }) : s.origin === "agent" ? _jsx("span", { "data-ol-schedule-badge": true, children: l.fromAgent }) : null, s.status === "paused" ? _jsx("span", { "data-ol-schedule-badge": true, children: l.paused }) : s.status === "completed" ? _jsx("span", { "data-ol-schedule-badge": true, children: l.finished }) : null] }), words !== null ? _jsx("span", { "data-ol-schedule-when": true, children: when }) : null, does !== null ? (_jsxs("p", { "data-ol-schedule-does": true, title: does, style: { margin: 0 }, children: [_jsx("span", { "data-ol-schedule-does-label": true, children: l.does }), " ", does] })) : null, s.next_run_at && s.status === "active" ? (_jsx("span", { "data-ol-schedule-next": true, style: { opacity: 0.7 }, children: l.next.replace("{when}", inZone(s.next_run_at, s.time_zone, p.locale)).replace("{zone}", zoneName(s.time_zone, p.locale, new Date(s.next_run_at))) })) : null, _jsxs("div", { style: row, children: [editable ? (_jsx("button", { type: "button", "data-ol-schedule-edit": true, disabled: p.busy, onClick: () => p.onEdit(s.id), children: l.edit })) : null, s.status === "active" ? (_jsx("button", { type: "button", "data-ol-schedule-pause": true, disabled: p.busy, onClick: () => p.onPause(s.id), children: l.pause })) : s.status === "paused" ? (_jsx("button", { type: "button", "data-ol-schedule-resume": true, disabled: p.busy, onClick: () => p.onResume(s.id), children: l.resume })) : null, removable ? (_jsx("button", { type: "button", "data-ol-schedule-remove": true, disabled: p.busy, "aria-label": l.removeNamed.replace("{description}", name.slice(0, 80)), onClick: () => p.onRemove(s.id), children: l.remove })) : null] })] }, s.id));
|
|
132
|
+
}) })), !p.bounds ? (_jsx("p", { "data-ol-schedule-not-offered": true, children: l.notOffered })) : full ? (_jsx("p", { "data-ol-schedule-full": true, role: "status", children: l.full })) : (_jsxs("form", { "data-ol-schedule-form": true, onSubmit: submit, "aria-labelledby": `${id}-fh`, "aria-busy": p.busy, style: col, children: [_jsx("h4", { id: `${id}-fh`, style: { margin: 0 }, children: p.editing ? l.editHeading : l.addHeading }), _jsxs("fieldset", { "data-ol-schedule-days": true, "aria-invalid": daysBad ? true : undefined, "aria-describedby": daysBad ? `${id}-err` : undefined, style: { border: "none", margin: 0, padding: 0, ...row }, children: [_jsx("legend", { children: l.daysLegend }), days.map((d) => (_jsxs("label", { "data-ol-schedule-day": true, style: { display: "inline-flex", gap: "0.25rem", alignItems: "center", minHeight: "2.75rem" }, children: [_jsx("input", { type: "checkbox", checked: p.draft.weekly.days.includes(d), onChange: () => toggle(d) }), l.days[d]] }, d)))] }), _jsxs("fieldset", { "data-ol-schedule-time": true, "aria-invalid": timeBad ? true : undefined, style: { border: "none", margin: 0, padding: 0, ...row }, children: [_jsx("legend", { children: l.time }), _jsx("select", { "aria-label": l.hour, "data-ol-schedule-hour": true, value: p.draft.weekly.hour, onChange: (e) => setWeekly({ hour: Number(e.target.value) }), children: hours.map((h) => (_jsx("option", { value: h, children: String(h).padStart(2, "0") }, h))) }), _jsx("span", { "aria-hidden": "true", children: ":" }), _jsx("select", { "aria-label": l.minute, "data-ol-schedule-minute": true, value: p.draft.weekly.minute, onChange: (e) => setWeekly({ minute: Number(e.target.value) }), children: (MINUTES.includes(p.draft.weekly.minute) ? MINUTES : [...MINUTES, p.draft.weekly.minute].sort((a, b) => a - b)).map((m) => (_jsx("option", { value: m, children: String(m).padStart(2, "0") }, m))) })] }), _jsxs("div", { style: col, children: [_jsx("label", { htmlFor: `${id}-ins`, children: l.instructions }), _jsx("textarea", { id: `${id}-ins`, "data-ol-schedule-instructions": true, rows: 3, required: true, maxLength: 1000, value: p.draft.instructions, "aria-invalid": apiParam === "instructions" ? true : undefined, "aria-describedby": `${id}-hint${apiParam === "instructions" ? ` ${id}-err` : ""}`, onChange: (e) => set({ instructions: e.target.value }), style: { font: "inherit", resize: "vertical" } }), _jsx("span", { id: `${id}-hint`, style: { fontSize: "var(--ol-small, 0.875em)", opacity: 0.7 }, children: l.instructionsHint })] }), _jsxs("div", { style: col, children: [_jsx("label", { htmlFor: `${id}-desc`, children: l.description }), _jsx("input", { id: `${id}-desc`, "data-ol-schedule-description": true, maxLength: 200, value: p.draft.description, onChange: (e) => set({ description: e.target.value }) })] }), problem || message ? (_jsx("p", { id: `${id}-err`, role: "alert", "data-ol-schedule-error": true, style: { margin: 0, color: "var(--ol-danger, inherit)" }, ref: formNoteInView, children: problem ? l.bounds[problem] : message })) : null, _jsxs("div", { style: row, children: [_jsx("button", { type: "submit", "data-ol-schedule-submit": true, disabled: p.busy || problem !== null || needsInstructions, "aria-describedby": needsInstructions ? `${id}-why` : undefined, children: p.busy ? l.saving : p.editing ? l.save : l.add }), needsInstructions ? (_jsx("span", { id: `${id}-why`, "data-ol-schedule-why": true, style: { fontSize: "var(--ol-small, 0.875em)", opacity: 0.7 }, children: l.needsInstructions })) : null, p.editing ? (_jsx("button", { type: "button", "data-ol-schedule-cancel-edit": true, onClick: () => p.onEdit(null), children: l.cancelEdit })) : null] })] })), message && (!p.bounds || full) ? (_jsx("p", { role: "alert", "data-ol-schedule-error": true, style: { margin: 0 }, ref: listNoteInView, children: message })) : null] }));
|
|
133
|
+
}
|
|
134
|
+
export function ScheduleEditor(props) {
|
|
135
|
+
const bounds = (props.agent.customizable?.schedules ?? null);
|
|
136
|
+
const s = useSchedules(props.agent.id, props);
|
|
137
|
+
const [draft, setDraft] = useState(() => emptyDraft(bounds));
|
|
138
|
+
const [editing, setEditing] = useState(null);
|
|
139
|
+
const [busy, setBusy] = useState(false);
|
|
140
|
+
const [error, setError] = useState(null);
|
|
141
|
+
const key = useRef(newIdempotencyKey());
|
|
142
|
+
const run = (p, after) => {
|
|
143
|
+
setBusy(true);
|
|
144
|
+
setError(null);
|
|
145
|
+
p.then(() => after?.())
|
|
146
|
+
.catch((err) => {
|
|
147
|
+
setError(err);
|
|
148
|
+
props.onError?.(err);
|
|
149
|
+
})
|
|
150
|
+
.finally(() => setBusy(false));
|
|
151
|
+
};
|
|
152
|
+
const onSubmit = () => {
|
|
153
|
+
const body = { cron: weeklyToCron(draft.weekly), instructions: draft.instructions, description: draft.description.trim() === "" ? null : draft.description.trim() };
|
|
154
|
+
const done = () => {
|
|
155
|
+
key.current = newIdempotencyKey();
|
|
156
|
+
setEditing(null);
|
|
157
|
+
setDraft(emptyDraft(bounds));
|
|
158
|
+
};
|
|
159
|
+
if (editing)
|
|
160
|
+
run(s.update(editing, body, key.current), done);
|
|
161
|
+
else
|
|
162
|
+
run(s.create({ ...body, description: body.description ?? undefined }, key.current), done);
|
|
163
|
+
};
|
|
164
|
+
const onEdit = (id) => {
|
|
165
|
+
setError(null);
|
|
166
|
+
setEditing(id);
|
|
167
|
+
const found = id ? s.schedules?.find((x) => x.id === id) : null;
|
|
168
|
+
const weekly = found ? cronToWeekly(found.cron) : null;
|
|
169
|
+
setDraft(found && weekly ? { weekly, instructions: found.instructions ?? "", description: found.description ?? "" } : emptyDraft(bounds));
|
|
170
|
+
};
|
|
171
|
+
return (_jsx(ScheduleEditorView, { schedules: s.error && !s.schedules ? [] : s.schedules, bounds: bounds, draft: draft, editing: editing, busy: busy, error: error ?? (s.schedules ? null : s.error), onDraft: setDraft, onSubmit: onSubmit, onEdit: onEdit, onPause: (id) => run(s.pause(id)), onResume: (id) => run(s.resume(id)), onRemove: (id) => run(s.cancel(id), () => (editing === id ? onEdit(null) : undefined)), labels: props.labels, locale: props.locale, className: props.className }));
|
|
172
|
+
}
|