@particle-academy/fancy-chat-js 0.0.0-stage → 0.2.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/AGENTS.md +56 -0
- package/CHANGELOG.md +140 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/conformance/chat-v1.json +619 -0
- package/contract/machines.json +76 -0
- package/dist/index.cjs +1024 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +604 -0
- package/dist/index.d.ts +604 -0
- package/dist/index.js +981 -0
- package/dist/index.js.map +1 -0
- package/dist/metafile-cjs.json +1 -0
- package/dist/metafile-esm.json +1 -0
- package/package.json +82 -5
- package/scripts/check-install.mjs +53 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1024 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/types.ts
|
|
4
|
+
var CONTRACT_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
// src/events.ts
|
|
7
|
+
var CORE_EVENT_TYPES = [
|
|
8
|
+
"thread.snapshot",
|
|
9
|
+
"thread.reset",
|
|
10
|
+
"run.started",
|
|
11
|
+
"run.finished",
|
|
12
|
+
"run.failed",
|
|
13
|
+
"run.cancelled",
|
|
14
|
+
"turn.started",
|
|
15
|
+
"turn.transition",
|
|
16
|
+
"turn.settled",
|
|
17
|
+
"message.created",
|
|
18
|
+
"message.updated",
|
|
19
|
+
"message.retracted",
|
|
20
|
+
"delivery.changed",
|
|
21
|
+
"part.started",
|
|
22
|
+
"part.delta",
|
|
23
|
+
"part.completed",
|
|
24
|
+
"thinking.started",
|
|
25
|
+
"thinking.delta",
|
|
26
|
+
"thinking.completed",
|
|
27
|
+
"tool.called",
|
|
28
|
+
"tool.progress",
|
|
29
|
+
"tool.result",
|
|
30
|
+
"plan.updated",
|
|
31
|
+
"approval.requested",
|
|
32
|
+
"approval.decided",
|
|
33
|
+
"approval.applied",
|
|
34
|
+
"approval.withdrawn",
|
|
35
|
+
"question.asked",
|
|
36
|
+
"question.answered",
|
|
37
|
+
"undo.opened",
|
|
38
|
+
"undo.committed",
|
|
39
|
+
"undo.reverted",
|
|
40
|
+
"agent.status",
|
|
41
|
+
"usage",
|
|
42
|
+
"provider.fallback",
|
|
43
|
+
"control.handoff"
|
|
44
|
+
];
|
|
45
|
+
var CORE = new Set(CORE_EVENT_TYPES);
|
|
46
|
+
var EXTENSION = /^x-[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*$/;
|
|
47
|
+
var TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
48
|
+
var ACTOR_KINDS = /* @__PURE__ */ new Set(["agent", "human", "system"]);
|
|
49
|
+
var OPTIONAL_IDS = ["runId", "turnId", "parentRunId", "rootRunId"];
|
|
50
|
+
function isTimestamp(value) {
|
|
51
|
+
return typeof value === "string" && TIMESTAMP.test(value);
|
|
52
|
+
}
|
|
53
|
+
function isEventType(type) {
|
|
54
|
+
return typeof type === "string" && (CORE.has(type) || EXTENSION.test(type));
|
|
55
|
+
}
|
|
56
|
+
function isPlainObject(value) {
|
|
57
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
58
|
+
}
|
|
59
|
+
function validateEvent(input) {
|
|
60
|
+
if (!isPlainObject(input)) return { ok: false, error: "event.shape" };
|
|
61
|
+
const e = input;
|
|
62
|
+
if (e.v !== 1) return { ok: false, error: "contract.version" };
|
|
63
|
+
if (typeof e.seq !== "number" || !Number.isInteger(e.seq) || e.seq < 1) return { ok: false, error: "event.seq" };
|
|
64
|
+
if (typeof e.threadId !== "string" || e.threadId === "") return { ok: false, error: "event.threadId" };
|
|
65
|
+
if (!isEventType(e.type)) return { ok: false, error: "event.type" };
|
|
66
|
+
if (typeof e.at !== "string" || !TIMESTAMP.test(e.at)) return { ok: false, error: "event.at" };
|
|
67
|
+
const actor = e.actor;
|
|
68
|
+
if (!isPlainObject(actor) || typeof actor.kind !== "string" || !ACTOR_KINDS.has(actor.kind) || typeof actor.id !== "string") {
|
|
69
|
+
return { ok: false, error: "event.actor" };
|
|
70
|
+
}
|
|
71
|
+
if (!isPlainObject(e.data)) return { ok: false, error: "event.data" };
|
|
72
|
+
for (const key of OPTIONAL_IDS) {
|
|
73
|
+
const value = e[key];
|
|
74
|
+
if (value !== void 0 && value !== null && typeof value !== "string") return { ok: false, error: `event.${key}` };
|
|
75
|
+
}
|
|
76
|
+
return { ok: true, event: e };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// contract/machines.json
|
|
80
|
+
var machines_default = {
|
|
81
|
+
v: 1,
|
|
82
|
+
turn: {
|
|
83
|
+
initial: "pending",
|
|
84
|
+
states: ["pending", "running", "awaiting-human", "cancelling", "settled"],
|
|
85
|
+
outcomes: ["completed", "failed", "refused", "cancelled", "interrupted"],
|
|
86
|
+
transitions: [
|
|
87
|
+
{ from: "pending", action: "start", to: "running" },
|
|
88
|
+
{ from: "running", action: "park", to: "awaiting-human" },
|
|
89
|
+
{ from: "awaiting-human", action: "resume", to: "running" },
|
|
90
|
+
{ from: "pending", action: "cancel", to: "cancelling" },
|
|
91
|
+
{ from: "running", action: "cancel", to: "cancelling" },
|
|
92
|
+
{ from: "awaiting-human", action: "cancel", to: "cancelling" },
|
|
93
|
+
{ from: "cancelling", action: "cancelled", to: "settled", outcome: "cancelled" },
|
|
94
|
+
{ from: "cancelling", action: "interrupted", to: "settled", outcome: "interrupted" },
|
|
95
|
+
{ from: "running", action: "finish", to: "settled", outcome: "completed" },
|
|
96
|
+
{ from: "running", action: "fail", to: "settled", outcome: "failed" },
|
|
97
|
+
{ from: "running", action: "refuse", to: "settled", outcome: "refused" },
|
|
98
|
+
{ from: "pending", action: "fail", to: "settled", outcome: "failed" },
|
|
99
|
+
{ from: "pending", action: "reap", to: "settled", outcome: "failed", reason: "stalled" },
|
|
100
|
+
{ from: "running", action: "reap", to: "settled", outcome: "failed", reason: "stalled" },
|
|
101
|
+
{ from: "awaiting-human", action: "reap", to: "settled", outcome: "failed", reason: "stalled" },
|
|
102
|
+
{ from: "cancelling", action: "reap", to: "settled", outcome: "failed", reason: "stalled" }
|
|
103
|
+
]
|
|
104
|
+
},
|
|
105
|
+
delivery: {
|
|
106
|
+
initial: "sending",
|
|
107
|
+
states: ["sending", "sent", "queued", "steered", "delivered", "decided", "failed", "dropped", "unsent"],
|
|
108
|
+
final: ["steered", "delivered", "decided", "failed", "dropped", "unsent"],
|
|
109
|
+
transitions: [
|
|
110
|
+
{ from: "sending", action: "ack", to: "sent" },
|
|
111
|
+
{ from: "sending", action: "fail", to: "failed" },
|
|
112
|
+
{ from: "sent", action: "queue", to: "queued" },
|
|
113
|
+
{ from: "sent", action: "steer", to: "steered" },
|
|
114
|
+
{ from: "sent", action: "deliver", to: "delivered" },
|
|
115
|
+
{ from: "sent", action: "drop", to: "dropped" },
|
|
116
|
+
{ from: "queued", action: "steer", to: "steered" },
|
|
117
|
+
{ from: "queued", action: "deliver", to: "delivered" },
|
|
118
|
+
{ from: "queued", action: "drop", to: "dropped" },
|
|
119
|
+
{ from: "queued", action: "unsend", to: "unsent" },
|
|
120
|
+
{ from: "sent", action: "decide", to: "decided" },
|
|
121
|
+
{ from: "queued", action: "decide", to: "decided" }
|
|
122
|
+
]
|
|
123
|
+
},
|
|
124
|
+
approval: {
|
|
125
|
+
initial: "pending",
|
|
126
|
+
states: ["pending", "deciding", "approved", "rejected", "edited", "applied", "apply-failed", "withdrawn", "expired"],
|
|
127
|
+
final: ["rejected", "applied", "apply-failed", "withdrawn", "expired"],
|
|
128
|
+
actionable: ["pending"],
|
|
129
|
+
transitions: [
|
|
130
|
+
{ from: "pending", action: "begin-decision", to: "deciding" },
|
|
131
|
+
{ from: "deciding", action: "decision-failed", to: "pending" },
|
|
132
|
+
{ from: "deciding", action: "approve", to: "approved" },
|
|
133
|
+
{ from: "deciding", action: "reject", to: "rejected" },
|
|
134
|
+
{ from: "deciding", action: "edit", to: "edited" },
|
|
135
|
+
{ from: "approved", action: "apply", to: "applied" },
|
|
136
|
+
{ from: "edited", action: "apply", to: "applied" },
|
|
137
|
+
{ from: "approved", action: "apply-fail", to: "apply-failed" },
|
|
138
|
+
{ from: "edited", action: "apply-fail", to: "apply-failed" },
|
|
139
|
+
{ from: "pending", action: "withdraw", to: "withdrawn" },
|
|
140
|
+
{ from: "pending", action: "expire", to: "expired" }
|
|
141
|
+
]
|
|
142
|
+
},
|
|
143
|
+
reservedTools: {
|
|
144
|
+
about: "Tool names an agent may never be offered or call: they are the human's confirmation channel. Matched case-insensitively.",
|
|
145
|
+
exact: ["question_answer", "send_as_human"],
|
|
146
|
+
contains: ["approv", "confirm", "permission", "decide"]
|
|
147
|
+
},
|
|
148
|
+
optionKinds: {
|
|
149
|
+
"allow-once": { tone: "positive", decision: "approve" },
|
|
150
|
+
"allow-always": { tone: "positive", decision: "approve" },
|
|
151
|
+
"reject-once": { tone: "negative", decision: "reject" },
|
|
152
|
+
"reject-always": { tone: "negative", decision: "reject" },
|
|
153
|
+
edit: { tone: "neutral", decision: "edit" }
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// src/machines.ts
|
|
158
|
+
var machines = machines_default;
|
|
159
|
+
function find(rows, from, action) {
|
|
160
|
+
return rows.find((r) => r.from === from && r.action === action);
|
|
161
|
+
}
|
|
162
|
+
function transitionTurn(from, action) {
|
|
163
|
+
const row = find(machines_default.turn.transitions, from, action);
|
|
164
|
+
if (!row) return { ok: false, error: "turn.illegal" };
|
|
165
|
+
return { ok: true, to: row.to, outcome: row.outcome ?? null, reason: row.reason ?? null };
|
|
166
|
+
}
|
|
167
|
+
function isSettlingTurnAction(action) {
|
|
168
|
+
return machines_default.turn.transitions.some((r) => r.action === action && r.to === "settled");
|
|
169
|
+
}
|
|
170
|
+
function transitionDelivery(from, action) {
|
|
171
|
+
const row = find(machines_default.delivery.transitions, from, action);
|
|
172
|
+
return row ? { ok: true, to: row.to } : { ok: false, error: "delivery.illegal" };
|
|
173
|
+
}
|
|
174
|
+
function transitionApproval(from, action) {
|
|
175
|
+
const row = find(machines_default.approval.transitions, from, action);
|
|
176
|
+
return row ? { ok: true, to: row.to } : { ok: false, error: "approval.illegal" };
|
|
177
|
+
}
|
|
178
|
+
function optionTone(kind) {
|
|
179
|
+
const kinds = machines_default.optionKinds;
|
|
180
|
+
const hit = Object.prototype.hasOwnProperty.call(kinds, kind) ? kinds[kind] : void 0;
|
|
181
|
+
return hit ? { tone: hit.tone, decision: hit.decision } : { tone: null, decision: null };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/typed-approval.ts
|
|
185
|
+
var DEFAULT_TYPED_APPROVAL = { enabled: false, locale: "en", phrases: {} };
|
|
186
|
+
var ENGLISH_TYPED_APPROVAL_PHRASES = { approve: ["approve", "yes, approve"], reject: ["reject", "no, reject"] };
|
|
187
|
+
var TRAILING_PUNCTUATION = /* @__PURE__ */ new Set([".", "!", "?", "\u3002", "\uFF01", "\uFF1F"]);
|
|
188
|
+
function normalizePhrase(text) {
|
|
189
|
+
let s = text.normalize("NFKC").toLowerCase().trim();
|
|
190
|
+
let end = s.length;
|
|
191
|
+
while (end > 0 && TRAILING_PUNCTUATION.has(s[end - 1])) end -= 1;
|
|
192
|
+
s = s.slice(0, end).trim();
|
|
193
|
+
let out = "";
|
|
194
|
+
let space = false;
|
|
195
|
+
for (const ch of s) {
|
|
196
|
+
if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v") {
|
|
197
|
+
space = true;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (space && out !== "") out += " ";
|
|
201
|
+
space = false;
|
|
202
|
+
out += ch;
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
function pick(options, decision) {
|
|
207
|
+
const once = decision === "approve" ? "allow-once" : "reject-once";
|
|
208
|
+
return options.find((o) => o.kind === once && optionTone(o.kind).decision === decision) ?? null;
|
|
209
|
+
}
|
|
210
|
+
function matchTypedApproval(text, approval, config = {}) {
|
|
211
|
+
const cfg = { ...DEFAULT_TYPED_APPROVAL, ...config };
|
|
212
|
+
if (!cfg.enabled || !approval || approval.state !== "pending") return null;
|
|
213
|
+
const lists = cfg.phrases[cfg.locale];
|
|
214
|
+
if (!lists) return null;
|
|
215
|
+
const typed = normalizePhrase(text);
|
|
216
|
+
if (typed === "") return null;
|
|
217
|
+
let decision = null;
|
|
218
|
+
if ((lists.approve ?? []).some((p) => normalizePhrase(p) === typed)) decision = "approve";
|
|
219
|
+
else if ((lists.reject ?? []).some((p) => normalizePhrase(p) === typed)) decision = "reject";
|
|
220
|
+
if (!decision) return null;
|
|
221
|
+
const option = pick(approval.options ?? [], decision);
|
|
222
|
+
return option ? { optionId: option.id, decision } : null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// src/undo.ts
|
|
226
|
+
function undoWindow(entry, now) {
|
|
227
|
+
if (entry.state !== "open") return { remainingMs: 0, canRevert: false };
|
|
228
|
+
const deadline = isTimestamp(entry.deadline) ? Date.parse(entry.deadline) : Number.NaN;
|
|
229
|
+
if (!Number.isFinite(deadline)) return { remainingMs: 0, canRevert: false };
|
|
230
|
+
const remainingMs = Math.max(0, deadline - now);
|
|
231
|
+
return { remainingMs, canRevert: remainingMs > 0 };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// src/plan.ts
|
|
235
|
+
var PLAN_STEP_STATUSES = ["pending", "running", "held", "done", "failed", "skipped"];
|
|
236
|
+
var RELEASED_BY = /* @__PURE__ */ new Set(["approved", "edited", "applied"]);
|
|
237
|
+
var REFUSED_BY = /* @__PURE__ */ new Set(["rejected", "withdrawn", "expired", "apply-failed"]);
|
|
238
|
+
function checkPlanUpdate(prev, next, approvals) {
|
|
239
|
+
for (const step of next) {
|
|
240
|
+
if (typeof step !== "object" || step === null || Array.isArray(step)) return { ok: false, error: "plan.step" };
|
|
241
|
+
if (!PLAN_STEP_STATUSES.includes(step.status) || step.owner !== "agent" && step.owner !== "human") {
|
|
242
|
+
return { ok: false, error: "plan.step" };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const before of prev) {
|
|
246
|
+
if (before.status !== "held") continue;
|
|
247
|
+
const after = next.find((s) => s.id === before.id);
|
|
248
|
+
if (!after) return { ok: false, error: "plan.held" };
|
|
249
|
+
if (after.status === "held") continue;
|
|
250
|
+
const approval = before.approvalId ? approvals.find((a) => a.approvalId === before.approvalId) : void 0;
|
|
251
|
+
if (!approval) return { ok: false, error: "plan.held" };
|
|
252
|
+
if (RELEASED_BY.has(approval.state)) continue;
|
|
253
|
+
if (REFUSED_BY.has(approval.state) && (after.status === "skipped" || after.status === "failed")) continue;
|
|
254
|
+
return { ok: false, error: "plan.held" };
|
|
255
|
+
}
|
|
256
|
+
return { ok: true };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/parts.ts
|
|
260
|
+
var CORE_PART_KINDS = [
|
|
261
|
+
"text",
|
|
262
|
+
"code",
|
|
263
|
+
"table",
|
|
264
|
+
"chart",
|
|
265
|
+
"file",
|
|
266
|
+
"image",
|
|
267
|
+
"tool-call",
|
|
268
|
+
"tool-result",
|
|
269
|
+
"card",
|
|
270
|
+
"question",
|
|
271
|
+
"approval"
|
|
272
|
+
];
|
|
273
|
+
var CHART_TYPES = ["line", "bar", "area", "pie", "scatter"];
|
|
274
|
+
var CORE2 = new Set(CORE_PART_KINDS);
|
|
275
|
+
var EXTENSION_KIND = /^x-[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*$/;
|
|
276
|
+
var DEFAULT_PART_LIMITS = { maxPartBytes: 65536, maxDepth: 3, maxParts: 64 };
|
|
277
|
+
function createPartRegistry(definitions = []) {
|
|
278
|
+
const map = /* @__PURE__ */ new Map();
|
|
279
|
+
const registry = {
|
|
280
|
+
register(definition) {
|
|
281
|
+
if (CORE2.has(definition.kind)) throw new TypeError(`Core part kind "${definition.kind}" cannot be redefined.`);
|
|
282
|
+
if (!EXTENSION_KIND.test(definition.kind)) throw new TypeError("An app part kind must be named x-<app>.<name>.");
|
|
283
|
+
if (map.has(definition.kind)) throw new TypeError(`Part kind "${definition.kind}" is already registered.`);
|
|
284
|
+
map.set(definition.kind, definition);
|
|
285
|
+
return registry;
|
|
286
|
+
},
|
|
287
|
+
get: (kind) => map.get(kind),
|
|
288
|
+
kinds: () => [...map.keys()]
|
|
289
|
+
};
|
|
290
|
+
for (const d of definitions) registry.register(d);
|
|
291
|
+
return registry;
|
|
292
|
+
}
|
|
293
|
+
var str = (v) => typeof v === "string";
|
|
294
|
+
var optStr = (v) => v === void 0 || v === null || typeof v === "string";
|
|
295
|
+
var optNum = (v) => v === void 0 || v === null || typeof v === "number" && Number.isFinite(v);
|
|
296
|
+
function jsonBytes(value) {
|
|
297
|
+
return new TextEncoder().encode(JSON.stringify(value)).length;
|
|
298
|
+
}
|
|
299
|
+
function fail(error) {
|
|
300
|
+
return { ok: false, error };
|
|
301
|
+
}
|
|
302
|
+
function validateAt(input, ctx, limits, depth) {
|
|
303
|
+
if (depth > limits.maxDepth) return fail("part.depth");
|
|
304
|
+
if (!isPlainObject(input)) return fail("part.shape");
|
|
305
|
+
const p = input;
|
|
306
|
+
if (!str(p.id) || p.id === "") return fail("part.id");
|
|
307
|
+
if (depth === 1 && jsonBytes(p) > limits.maxPartBytes) return fail("part.size");
|
|
308
|
+
if (!str(p.kind)) return fail("part.kind");
|
|
309
|
+
if (!CORE2.has(p.kind)) {
|
|
310
|
+
if (!EXTENSION_KIND.test(p.kind)) return fail("part.kind");
|
|
311
|
+
const def = ctx.registry?.get(p.kind);
|
|
312
|
+
if (def?.validate) {
|
|
313
|
+
const verdict = def.validate(p);
|
|
314
|
+
if (verdict !== true) return fail(typeof verdict === "string" ? verdict : `part.${p.kind}`);
|
|
315
|
+
}
|
|
316
|
+
return { ok: true };
|
|
317
|
+
}
|
|
318
|
+
switch (p.kind) {
|
|
319
|
+
case "text":
|
|
320
|
+
return (p.format === "markdown" || p.format === "plain") && str(p.text) && (p.interim === void 0 || typeof p.interim === "boolean") ? { ok: true } : fail("part.text");
|
|
321
|
+
case "code":
|
|
322
|
+
return str(p.language) && str(p.code) && optStr(p.filename) ? { ok: true } : fail("part.code");
|
|
323
|
+
case "table": {
|
|
324
|
+
const cols = p.columns;
|
|
325
|
+
if (!Array.isArray(cols) || !Array.isArray(p.rows) || !optStr(p.caption)) return fail("part.table");
|
|
326
|
+
const colsOk = cols.every((c) => isPlainObject(c) && str(c.key) && c.key !== "" && str(c.label) && optStr(c.type));
|
|
327
|
+
const rowsOk = p.rows.every(isPlainObject);
|
|
328
|
+
return colsOk && rowsOk ? { ok: true } : fail("part.table");
|
|
329
|
+
}
|
|
330
|
+
case "chart": {
|
|
331
|
+
if (!optStr(p.title)) return fail("part.chart");
|
|
332
|
+
if (p.echarts !== void 0) {
|
|
333
|
+
if (ctx.origin !== "server") return fail("part.chart.raw");
|
|
334
|
+
return isPlainObject(p.echarts) ? { ok: true } : fail("part.chart");
|
|
335
|
+
}
|
|
336
|
+
const spec = p.spec;
|
|
337
|
+
if (!isPlainObject(spec) || !str(spec.type) || !CHART_TYPES.includes(spec.type)) return fail("part.chart");
|
|
338
|
+
if (!Array.isArray(spec.series) || !spec.series.every((s) => isPlainObject(s) && Array.isArray(s.data) && optStr(s.name))) {
|
|
339
|
+
return fail("part.chart");
|
|
340
|
+
}
|
|
341
|
+
return { ok: true };
|
|
342
|
+
}
|
|
343
|
+
case "file":
|
|
344
|
+
return str(p.name) && str(p.mimeType) && typeof p.size === "number" && Number.isInteger(p.size) && p.size >= 0 && str(p.ref) ? { ok: true } : fail("part.file");
|
|
345
|
+
case "image":
|
|
346
|
+
return str(p.ref) && str(p.alt) && optNum(p.width) && optNum(p.height) ? { ok: true } : fail("part.image");
|
|
347
|
+
case "tool-call":
|
|
348
|
+
return str(p.toolCallId) && str(p.name) && isPlainObject(p.args) ? { ok: true } : fail("part.tool-call");
|
|
349
|
+
case "tool-result": {
|
|
350
|
+
const outcomeOk = p.outcome === "ok" || p.outcome === "failure" || p.outcome === "refusal";
|
|
351
|
+
const contentOk = str(p.content) || Array.isArray(p.content);
|
|
352
|
+
return str(p.toolCallId) && outcomeOk && contentOk && optNum(p.durationMs) ? { ok: true } : fail("part.tool-result");
|
|
353
|
+
}
|
|
354
|
+
case "card": {
|
|
355
|
+
if (!str(p.cardType) || !optStr(p.title) || !Array.isArray(p.body)) return fail("part.card");
|
|
356
|
+
if (p.fields !== void 0 && !(Array.isArray(p.fields) && p.fields.every((f) => isPlainObject(f) && str(f.label) && str(f.value)))) {
|
|
357
|
+
return fail("part.card");
|
|
358
|
+
}
|
|
359
|
+
if (p.actions !== void 0) {
|
|
360
|
+
if (!Array.isArray(p.actions)) return fail("part.card.action");
|
|
361
|
+
for (const a of p.actions) {
|
|
362
|
+
if (!isPlainObject(a) || !str(a.id) || !str(a.label)) return fail("part.card.action");
|
|
363
|
+
if (a.kind === "link") {
|
|
364
|
+
if (!str(a.href) || !/^https?:\/\//i.test(a.href)) return fail("part.card.action");
|
|
365
|
+
} else if (a.kind !== "post-back") {
|
|
366
|
+
return fail("part.card.action");
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
for (const child of p.body) {
|
|
371
|
+
const r = validateAt(child, ctx, limits, depth + 1);
|
|
372
|
+
if (!r.ok) return r;
|
|
373
|
+
}
|
|
374
|
+
return { ok: true };
|
|
375
|
+
}
|
|
376
|
+
case "question":
|
|
377
|
+
case "approval": {
|
|
378
|
+
if (ctx.origin !== "server") return fail("part.hitl.origin");
|
|
379
|
+
const ref = p.kind === "question" ? p.questionId : p.approvalId;
|
|
380
|
+
return str(ref) && ref !== "" ? { ok: true } : fail(`part.${p.kind}`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return fail("part.kind");
|
|
384
|
+
}
|
|
385
|
+
function validatePart(part, context) {
|
|
386
|
+
const limits = { ...DEFAULT_PART_LIMITS, ...context.limits ?? {} };
|
|
387
|
+
return validateAt(part, context, limits, 1);
|
|
388
|
+
}
|
|
389
|
+
function validateParts(parts, context) {
|
|
390
|
+
const limits = { ...DEFAULT_PART_LIMITS, ...context.limits ?? {} };
|
|
391
|
+
if (!Array.isArray(parts)) return fail("message.parts");
|
|
392
|
+
if (parts.length > limits.maxParts) return fail("message.parts.count");
|
|
393
|
+
for (const part of parts) {
|
|
394
|
+
const r = validateAt(part, context, limits, 1);
|
|
395
|
+
if (!r.ok) return r;
|
|
396
|
+
}
|
|
397
|
+
return { ok: true };
|
|
398
|
+
}
|
|
399
|
+
var FENCE = "```";
|
|
400
|
+
function partToText(part, registry) {
|
|
401
|
+
switch (part.kind) {
|
|
402
|
+
case "text":
|
|
403
|
+
return String(part.text ?? "");
|
|
404
|
+
case "code":
|
|
405
|
+
return `${FENCE}${String(part.language ?? "")}
|
|
406
|
+
${String(part.code ?? "")}
|
|
407
|
+
${FENCE}`;
|
|
408
|
+
case "table": {
|
|
409
|
+
const cols = part.columns ?? [];
|
|
410
|
+
const cell = (v) => (v === void 0 || v === null ? "" : String(v)).replace(/[\t\n\r]/g, " ");
|
|
411
|
+
const lines = [cols.map((c) => cell(c.label)).join(" ")];
|
|
412
|
+
for (const row of part.rows ?? []) lines.push(cols.map((c) => cell(row[c.key])).join(" "));
|
|
413
|
+
return lines.join("\n");
|
|
414
|
+
}
|
|
415
|
+
case "chart":
|
|
416
|
+
return typeof part.title === "string" && part.title !== "" ? `[chart: ${part.title}]` : "[chart]";
|
|
417
|
+
case "file":
|
|
418
|
+
return `[file: ${String(part.name ?? "")}]`;
|
|
419
|
+
case "image":
|
|
420
|
+
return `[image: ${String(part.alt ?? "")}]`;
|
|
421
|
+
case "tool-call":
|
|
422
|
+
return `[tool: ${String(part.name ?? "")}]`;
|
|
423
|
+
case "tool-result":
|
|
424
|
+
return typeof part.content === "string" ? part.content : `[tool result: ${String(part.outcome ?? "")}]`;
|
|
425
|
+
case "card": {
|
|
426
|
+
const lines = [];
|
|
427
|
+
if (typeof part.title === "string" && part.title !== "") lines.push(part.title);
|
|
428
|
+
for (const child of part.body ?? []) {
|
|
429
|
+
const t = partToText(child, registry);
|
|
430
|
+
if (t !== "") lines.push(t);
|
|
431
|
+
}
|
|
432
|
+
return lines.join("\n");
|
|
433
|
+
}
|
|
434
|
+
case "question":
|
|
435
|
+
return "[question]";
|
|
436
|
+
case "approval":
|
|
437
|
+
return "[approval]";
|
|
438
|
+
}
|
|
439
|
+
const def = registry?.get(part.kind);
|
|
440
|
+
return def?.toText ? def.toText(part) : `[${part.kind}]`;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// src/hitl.ts
|
|
444
|
+
function canDecide(actor) {
|
|
445
|
+
return isPlainObject(actor) && actor.kind === "human" && typeof actor.id === "string" && actor.id !== "";
|
|
446
|
+
}
|
|
447
|
+
function isReservedToolName(name) {
|
|
448
|
+
const lower = name.toLowerCase();
|
|
449
|
+
const reserved = machines.reservedTools;
|
|
450
|
+
return reserved.exact.includes(lower) || reserved.contains.some((needle) => lower.includes(needle));
|
|
451
|
+
}
|
|
452
|
+
function hasValue(type, value) {
|
|
453
|
+
if (value === void 0 || value === null) return false;
|
|
454
|
+
if (type === "multi") return Array.isArray(value) && value.length > 0;
|
|
455
|
+
return typeof value === "string" && value.trim() !== "";
|
|
456
|
+
}
|
|
457
|
+
function canSubmitAnswer(question, draft) {
|
|
458
|
+
const fields = new Map(question.fields.map((f) => [f.id, f]));
|
|
459
|
+
const values = isPlainObject(draft.values) ? draft.values : {};
|
|
460
|
+
const notes = isPlainObject(draft.notes) ? draft.notes : {};
|
|
461
|
+
for (const [id, value] of Object.entries(values)) {
|
|
462
|
+
const field = fields.get(id);
|
|
463
|
+
if (!field) return { ok: false, error: "question.field" };
|
|
464
|
+
if (value === void 0 || value === null) continue;
|
|
465
|
+
if (field.type === "multi") {
|
|
466
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) return { ok: false, error: "question.value" };
|
|
467
|
+
} else if (typeof value !== "string") {
|
|
468
|
+
return { ok: false, error: "question.value" };
|
|
469
|
+
}
|
|
470
|
+
if (field.type !== "text") {
|
|
471
|
+
const offered = new Set((field.options ?? []).map((o) => o.id));
|
|
472
|
+
const chosen = Array.isArray(value) ? value : [value];
|
|
473
|
+
if (chosen.some((v) => !offered.has(v))) return { ok: false, error: "question.option" };
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
for (const field of question.fields) {
|
|
477
|
+
if (!field.required) continue;
|
|
478
|
+
if (hasValue(field.type, values[field.id])) continue;
|
|
479
|
+
const note = notes[field.id];
|
|
480
|
+
if (question.allowNote && typeof note === "string" && note.trim() !== "") continue;
|
|
481
|
+
return { ok: false, error: "question.required" };
|
|
482
|
+
}
|
|
483
|
+
return { ok: true };
|
|
484
|
+
}
|
|
485
|
+
var ACTIONABLE = { approval: "pending", question: "open" };
|
|
486
|
+
var IN_FLIGHT = { approval: "deciding", question: "answering" };
|
|
487
|
+
function pickActionable(items, kinds) {
|
|
488
|
+
const scoped = kinds ? items.filter((i) => kinds.includes(i.kind)) : items;
|
|
489
|
+
if (scoped.some((i) => IN_FLIGHT[i.kind] === i.state)) return null;
|
|
490
|
+
let best = null;
|
|
491
|
+
for (const item of scoped) {
|
|
492
|
+
if (ACTIONABLE[item.kind] !== item.state) continue;
|
|
493
|
+
if (!best || item.seq < best.seq) best = item;
|
|
494
|
+
}
|
|
495
|
+
return best ? best.id : null;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// src/status.ts
|
|
499
|
+
var AGENT_STATUSES = [
|
|
500
|
+
"not-started",
|
|
501
|
+
"starting",
|
|
502
|
+
"working",
|
|
503
|
+
"cooling",
|
|
504
|
+
"idle",
|
|
505
|
+
"sleeping",
|
|
506
|
+
"parked",
|
|
507
|
+
"paused-limit",
|
|
508
|
+
"signed-out",
|
|
509
|
+
"broken"
|
|
510
|
+
];
|
|
511
|
+
var DEFAULT_STATUS_CONFIG = { coolingMs: 15e3, sleepAfterMs: 6e5 };
|
|
512
|
+
var DEFAULT_RECOVERY = {
|
|
513
|
+
"not-started": [],
|
|
514
|
+
starting: ["stop"],
|
|
515
|
+
working: ["stop"],
|
|
516
|
+
cooling: [],
|
|
517
|
+
idle: [],
|
|
518
|
+
sleeping: [],
|
|
519
|
+
parked: ["open-hitl"],
|
|
520
|
+
"paused-limit": ["wait"],
|
|
521
|
+
"signed-out": ["sign-in"],
|
|
522
|
+
broken: ["restart"]
|
|
523
|
+
};
|
|
524
|
+
function deriveAgentStatus(snapshot, config = {}) {
|
|
525
|
+
const cfg = { ...DEFAULT_STATUS_CONFIG, ...config };
|
|
526
|
+
const recovery = (status, fallback) => [...cfg.recovery?.[status] ?? fallback ?? DEFAULT_RECOVERY[status]];
|
|
527
|
+
const out = (status, detail, since, rec) => ({
|
|
528
|
+
status,
|
|
529
|
+
detail,
|
|
530
|
+
since,
|
|
531
|
+
recovery: recovery(status, rec)
|
|
532
|
+
});
|
|
533
|
+
const now = snapshot.now;
|
|
534
|
+
const turn = snapshot.turn ?? null;
|
|
535
|
+
const background = snapshot.background ?? 0;
|
|
536
|
+
const pending = snapshot.pendingHitl ?? 0;
|
|
537
|
+
const lastSettledAt = snapshot.lastSettledAt ?? null;
|
|
538
|
+
if (typeof snapshot.broken === "string" && snapshot.broken !== "") return out("broken", { reason: snapshot.broken }, null);
|
|
539
|
+
if (snapshot.signedIn === false) return out("signed-out", null, null);
|
|
540
|
+
if (snapshot.limit && snapshot.limit.until > now) return out("paused-limit", { until: snapshot.limit.until }, null);
|
|
541
|
+
if (turn && turn.state === "awaiting-human" || pending > 0) {
|
|
542
|
+
return out("parked", { pending }, turn && turn.state === "awaiting-human" ? turn.since : null);
|
|
543
|
+
}
|
|
544
|
+
if (turn && turn.state === "pending") return out("starting", null, turn.since);
|
|
545
|
+
if (turn && (turn.state === "running" || turn.state === "cancelling")) {
|
|
546
|
+
const cancelling = turn.state === "cancelling";
|
|
547
|
+
return out("working", { background, plan: snapshot.plan ?? null, cancelling }, turn.since, cancelling ? [] : void 0);
|
|
548
|
+
}
|
|
549
|
+
if (background > 0) return out("working", { background, plan: snapshot.plan ?? null, cancelling: false }, null, []);
|
|
550
|
+
if (lastSettledAt === null) {
|
|
551
|
+
return snapshot.everStarted ? out("idle", null, null) : out("not-started", null, null);
|
|
552
|
+
}
|
|
553
|
+
const idleFor = now - lastSettledAt;
|
|
554
|
+
if (idleFor < cfg.coolingMs) return out("cooling", null, lastSettledAt);
|
|
555
|
+
if (idleFor >= cfg.sleepAfterMs) return out("sleeping", null, lastSettledAt + cfg.sleepAfterMs);
|
|
556
|
+
return out("idle", null, lastSettledAt + cfg.coolingMs);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// src/sequence.ts
|
|
560
|
+
var JUMPS = /* @__PURE__ */ new Set(["thread.reset", "thread.snapshot"]);
|
|
561
|
+
function createSeqLog(after = 0) {
|
|
562
|
+
return { lastSeq: after, held: /* @__PURE__ */ new Map() };
|
|
563
|
+
}
|
|
564
|
+
function ingestEvents(log, events) {
|
|
565
|
+
let lastSeq = log.lastSeq;
|
|
566
|
+
const held = new Map(log.held);
|
|
567
|
+
const applied = [];
|
|
568
|
+
const drain = () => {
|
|
569
|
+
for (let next = held.get(lastSeq + 1); next; next = held.get(lastSeq + 1)) {
|
|
570
|
+
held.delete(next.seq);
|
|
571
|
+
applied.push(next);
|
|
572
|
+
lastSeq = next.seq;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
for (const event of events) {
|
|
576
|
+
if (event.seq <= lastSeq) continue;
|
|
577
|
+
if (JUMPS.has(event.type)) {
|
|
578
|
+
applied.push(event);
|
|
579
|
+
lastSeq = event.seq;
|
|
580
|
+
for (const seq of [...held.keys()]) if (seq <= lastSeq) held.delete(seq);
|
|
581
|
+
} else if (!held.has(event.seq)) {
|
|
582
|
+
held.set(event.seq, event);
|
|
583
|
+
}
|
|
584
|
+
drain();
|
|
585
|
+
}
|
|
586
|
+
let missing = null;
|
|
587
|
+
if (held.size > 0) missing = { after: lastSeq, before: Math.min(...held.keys()) };
|
|
588
|
+
return { log: { lastSeq, held }, applied, missing };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// src/projection.ts
|
|
592
|
+
function emptyThreadState() {
|
|
593
|
+
return { lastSeq: 0, illegal: 0, order: [], messages: [], turns: [], thinking: [], tools: [], plans: [], approvals: [], questions: [], undos: [], branches: [] };
|
|
594
|
+
}
|
|
595
|
+
var NO_RUN = "_";
|
|
596
|
+
function clone(value) {
|
|
597
|
+
return JSON.parse(JSON.stringify(value));
|
|
598
|
+
}
|
|
599
|
+
function decidedByActor(event, claimed) {
|
|
600
|
+
return canDecide(event.actor) && isPlainObject(claimed) && claimed.kind === event.actor.kind && claimed.id === event.actor.id;
|
|
601
|
+
}
|
|
602
|
+
var byId = (list, key, id) => list.find((x) => x[key] === id);
|
|
603
|
+
function applyEvent(state, event) {
|
|
604
|
+
if (event.seq <= state.lastSeq) return false;
|
|
605
|
+
try {
|
|
606
|
+
return reduce(state, event);
|
|
607
|
+
} catch {
|
|
608
|
+
state.illegal += 1;
|
|
609
|
+
state.lastSeq = event.seq;
|
|
610
|
+
return true;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
function reduce(state, event) {
|
|
614
|
+
const data = isPlainObject(event.data) ? event.data : {};
|
|
615
|
+
const illegal = () => {
|
|
616
|
+
state.illegal += 1;
|
|
617
|
+
};
|
|
618
|
+
switch (event.type) {
|
|
619
|
+
case "thread.snapshot":
|
|
620
|
+
case "thread.reset": {
|
|
621
|
+
const snap = data.snapshot;
|
|
622
|
+
if (!isPlainObject(snap)) {
|
|
623
|
+
illegal();
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
Object.assign(state, emptyThreadState(), clone(snap));
|
|
627
|
+
break;
|
|
628
|
+
}
|
|
629
|
+
case "message.created": {
|
|
630
|
+
const m = data.message;
|
|
631
|
+
if (!isPlainObject(m) || typeof m.id !== "string" || byId(state.messages, "id", m.id)) {
|
|
632
|
+
illegal();
|
|
633
|
+
break;
|
|
634
|
+
}
|
|
635
|
+
const supersedes = typeof m.supersedes === "string" ? m.supersedes : null;
|
|
636
|
+
state.messages.push({
|
|
637
|
+
id: m.id,
|
|
638
|
+
role: typeof m.role === "string" ? m.role : "assistant",
|
|
639
|
+
author: isPlainObject(m.author) ? clone(m.author) : clone(event.actor),
|
|
640
|
+
turnId: typeof data.turnId === "string" ? data.turnId : event.turnId ?? null,
|
|
641
|
+
parts: Array.isArray(m.parts) ? clone(m.parts) : [],
|
|
642
|
+
open: [],
|
|
643
|
+
delivery: typeof m.delivery === "string" ? m.delivery : null,
|
|
644
|
+
supersedes,
|
|
645
|
+
retracted: false,
|
|
646
|
+
superseded: false
|
|
647
|
+
});
|
|
648
|
+
const targetAt = supersedes ? state.order.findIndex((o) => o.kind === "message" && o.id === supersedes) : -1;
|
|
649
|
+
if (supersedes) {
|
|
650
|
+
const target = byId(state.messages, "id", supersedes);
|
|
651
|
+
if (target) target.superseded = true;
|
|
652
|
+
}
|
|
653
|
+
if (supersedes && targetAt >= 0) {
|
|
654
|
+
state.branches.push({ supersededId: supersedes, byId: m.id, rowIds: state.order.slice(targetAt + 1).map((o) => o.id) });
|
|
655
|
+
}
|
|
656
|
+
state.order.push({ kind: "message", id: m.id });
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
659
|
+
case "message.updated": {
|
|
660
|
+
const msg = byId(state.messages, "id", data.messageId);
|
|
661
|
+
if (!msg || !Array.isArray(data.parts)) {
|
|
662
|
+
illegal();
|
|
663
|
+
break;
|
|
664
|
+
}
|
|
665
|
+
msg.parts = clone(data.parts);
|
|
666
|
+
msg.open = msg.open.filter((id) => msg.parts.some((p) => p.id === id));
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
case "message.retracted": {
|
|
670
|
+
const msg = byId(state.messages, "id", data.messageId);
|
|
671
|
+
if (!msg) illegal();
|
|
672
|
+
else msg.retracted = true;
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
675
|
+
case "delivery.changed": {
|
|
676
|
+
const msg = byId(state.messages, "id", data.messageId);
|
|
677
|
+
const next = msg && msg.delivery !== null && typeof data.action === "string" ? transitionDelivery(msg.delivery, data.action) : null;
|
|
678
|
+
if (!msg || !next || !next.ok) illegal();
|
|
679
|
+
else msg.delivery = next.to;
|
|
680
|
+
break;
|
|
681
|
+
}
|
|
682
|
+
case "part.started": {
|
|
683
|
+
const msg = byId(state.messages, "id", data.messageId);
|
|
684
|
+
const part = data.part;
|
|
685
|
+
if (!msg || !isPlainObject(part) || typeof part.id !== "string" || msg.parts.some((p) => p.id === part.id)) {
|
|
686
|
+
illegal();
|
|
687
|
+
break;
|
|
688
|
+
}
|
|
689
|
+
msg.parts.push(clone(part));
|
|
690
|
+
msg.open.push(part.id);
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
693
|
+
case "part.delta": {
|
|
694
|
+
const msg = byId(state.messages, "id", data.messageId);
|
|
695
|
+
const index = msg ? msg.parts.findIndex((p) => p.id === data.partId) : -1;
|
|
696
|
+
if (!msg || index < 0) {
|
|
697
|
+
illegal();
|
|
698
|
+
break;
|
|
699
|
+
}
|
|
700
|
+
const current = msg.parts[index];
|
|
701
|
+
if (current.kind === "text" && typeof data.text === "string") {
|
|
702
|
+
current.text = String(current.text ?? "") + data.text;
|
|
703
|
+
} else if (isPlainObject(data.part)) {
|
|
704
|
+
msg.parts[index] = { ...clone(data.part), id: current.id };
|
|
705
|
+
} else {
|
|
706
|
+
illegal();
|
|
707
|
+
}
|
|
708
|
+
break;
|
|
709
|
+
}
|
|
710
|
+
case "part.completed": {
|
|
711
|
+
const msg = byId(state.messages, "id", data.messageId);
|
|
712
|
+
if (!msg || !msg.parts.some((p) => p.id === data.partId)) illegal();
|
|
713
|
+
else msg.open = msg.open.filter((id) => id !== data.partId);
|
|
714
|
+
break;
|
|
715
|
+
}
|
|
716
|
+
case "thinking.started":
|
|
717
|
+
case "thinking.delta":
|
|
718
|
+
case "thinking.completed": {
|
|
719
|
+
const runId = event.runId ?? NO_RUN;
|
|
720
|
+
if (data.thinkingId !== void 0 && typeof data.thinkingId !== "string") {
|
|
721
|
+
illegal();
|
|
722
|
+
break;
|
|
723
|
+
}
|
|
724
|
+
const explicit = typeof data.thinkingId === "string" ? data.thinkingId : null;
|
|
725
|
+
const ofRun = state.thinking.filter((t) => t.runId === runId);
|
|
726
|
+
const latest = ofRun.length > 0 ? ofRun[ofRun.length - 1] : void 0;
|
|
727
|
+
let entry = explicit !== null ? byId(state.thinking, "thinkingId", explicit) : latest && (latest.live || event.type === "thinking.completed") ? latest : void 0;
|
|
728
|
+
if (!entry) {
|
|
729
|
+
if (event.type === "thinking.completed") {
|
|
730
|
+
illegal();
|
|
731
|
+
break;
|
|
732
|
+
}
|
|
733
|
+
const thinkingId = explicit ?? (ofRun.length === 0 ? runId : `${runId}#${ofRun.length + 1}`);
|
|
734
|
+
if (byId(state.thinking, "thinkingId", thinkingId)) {
|
|
735
|
+
illegal();
|
|
736
|
+
break;
|
|
737
|
+
}
|
|
738
|
+
entry = { thinkingId, runId, text: "", live: true };
|
|
739
|
+
state.thinking.push(entry);
|
|
740
|
+
state.order.push({ kind: "thinking", id: thinkingId });
|
|
741
|
+
}
|
|
742
|
+
if (event.type === "thinking.started") entry.live = true;
|
|
743
|
+
else if (event.type === "thinking.delta" && typeof data.text === "string") entry.text += data.text;
|
|
744
|
+
else if (event.type === "thinking.completed") entry.live = false;
|
|
745
|
+
break;
|
|
746
|
+
}
|
|
747
|
+
case "tool.called": {
|
|
748
|
+
if (typeof data.toolCallId !== "string" || typeof data.name !== "string" || byId(state.tools, "toolCallId", data.toolCallId)) {
|
|
749
|
+
illegal();
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
state.tools.push({
|
|
753
|
+
toolCallId: data.toolCallId,
|
|
754
|
+
runId: event.runId ?? null,
|
|
755
|
+
name: data.name,
|
|
756
|
+
args: isPlainObject(data.args) ? clone(data.args) : {},
|
|
757
|
+
startedAt: typeof data.startedAt === "string" ? data.startedAt : null,
|
|
758
|
+
progress: null,
|
|
759
|
+
outcome: null,
|
|
760
|
+
durationMs: null,
|
|
761
|
+
durationExact: true,
|
|
762
|
+
outputRef: null,
|
|
763
|
+
truncated: false,
|
|
764
|
+
output: null,
|
|
765
|
+
outputLanguage: null
|
|
766
|
+
});
|
|
767
|
+
state.order.push({ kind: "tool", id: data.toolCallId });
|
|
768
|
+
break;
|
|
769
|
+
}
|
|
770
|
+
case "tool.progress": {
|
|
771
|
+
const tool = byId(state.tools, "toolCallId", data.toolCallId);
|
|
772
|
+
if (!tool) {
|
|
773
|
+
illegal();
|
|
774
|
+
break;
|
|
775
|
+
}
|
|
776
|
+
tool.progress = {
|
|
777
|
+
fraction: typeof data.fraction === "number" ? data.fraction : null,
|
|
778
|
+
text: typeof data.text === "string" ? data.text : null
|
|
779
|
+
};
|
|
780
|
+
break;
|
|
781
|
+
}
|
|
782
|
+
case "tool.result": {
|
|
783
|
+
const tool = byId(state.tools, "toolCallId", data.toolCallId);
|
|
784
|
+
if (!tool || data.outcome !== "ok" && data.outcome !== "failure" && data.outcome !== "refusal") {
|
|
785
|
+
illegal();
|
|
786
|
+
break;
|
|
787
|
+
}
|
|
788
|
+
tool.outcome = data.outcome;
|
|
789
|
+
tool.durationMs = typeof data.durationMs === "number" ? data.durationMs : null;
|
|
790
|
+
tool.durationExact = data.durationExact !== false;
|
|
791
|
+
tool.outputRef = typeof data.outputRef === "string" ? data.outputRef : null;
|
|
792
|
+
tool.truncated = data.truncated === true;
|
|
793
|
+
tool.output = typeof data.output === "string" ? data.output : null;
|
|
794
|
+
tool.outputLanguage = typeof data.outputLanguage === "string" ? data.outputLanguage : null;
|
|
795
|
+
break;
|
|
796
|
+
}
|
|
797
|
+
case "plan.updated": {
|
|
798
|
+
if (!Array.isArray(data.steps)) {
|
|
799
|
+
illegal();
|
|
800
|
+
break;
|
|
801
|
+
}
|
|
802
|
+
const runId = event.runId ?? NO_RUN;
|
|
803
|
+
let plan = byId(state.plans, "runId", runId);
|
|
804
|
+
if (!checkPlanUpdate(plan?.steps ?? [], data.steps, state.approvals).ok) {
|
|
805
|
+
illegal();
|
|
806
|
+
break;
|
|
807
|
+
}
|
|
808
|
+
if (!plan) {
|
|
809
|
+
plan = { runId, steps: [] };
|
|
810
|
+
state.plans.push(plan);
|
|
811
|
+
state.order.push({ kind: "plan", id: runId });
|
|
812
|
+
}
|
|
813
|
+
plan.steps = clone(data.steps);
|
|
814
|
+
break;
|
|
815
|
+
}
|
|
816
|
+
case "turn.started": {
|
|
817
|
+
if (typeof data.turnId !== "string" || byId(state.turns, "turnId", data.turnId)) {
|
|
818
|
+
illegal();
|
|
819
|
+
break;
|
|
820
|
+
}
|
|
821
|
+
const origin = typeof data.messageId === "string" ? byId(state.messages, "id", data.messageId) : void 0;
|
|
822
|
+
state.turns.push({ turnId: data.turnId, state: "pending", outcome: null, reason: null, messageId: origin ? origin.id : null });
|
|
823
|
+
if (origin && origin.turnId === null) origin.turnId = data.turnId;
|
|
824
|
+
break;
|
|
825
|
+
}
|
|
826
|
+
case "turn.transition":
|
|
827
|
+
case "turn.settled": {
|
|
828
|
+
const turn = byId(state.turns, "turnId", data.turnId);
|
|
829
|
+
const action = typeof data.action === "string" ? data.action : "";
|
|
830
|
+
const settling = isSettlingTurnAction(action);
|
|
831
|
+
if (!turn || settling !== (event.type === "turn.settled")) {
|
|
832
|
+
illegal();
|
|
833
|
+
break;
|
|
834
|
+
}
|
|
835
|
+
const next = transitionTurn(turn.state, action);
|
|
836
|
+
if (!next.ok) {
|
|
837
|
+
illegal();
|
|
838
|
+
break;
|
|
839
|
+
}
|
|
840
|
+
turn.state = next.to;
|
|
841
|
+
turn.outcome = next.outcome;
|
|
842
|
+
turn.reason = typeof data.reason === "string" ? data.reason : next.reason;
|
|
843
|
+
break;
|
|
844
|
+
}
|
|
845
|
+
case "approval.requested": {
|
|
846
|
+
const a = data.approval;
|
|
847
|
+
if (!isPlainObject(a) || typeof a.approvalId !== "string" || byId(state.approvals, "approvalId", a.approvalId)) {
|
|
848
|
+
illegal();
|
|
849
|
+
break;
|
|
850
|
+
}
|
|
851
|
+
state.approvals.push({ ...clone(a), state: "pending" });
|
|
852
|
+
state.order.push({ kind: "approval", id: a.approvalId });
|
|
853
|
+
break;
|
|
854
|
+
}
|
|
855
|
+
case "approval.decided": {
|
|
856
|
+
const record = byId(state.approvals, "approvalId", data.approvalId);
|
|
857
|
+
if (!record || !decidedByActor(event, data.decidedBy) || typeof data.decision !== "string") {
|
|
858
|
+
illegal();
|
|
859
|
+
break;
|
|
860
|
+
}
|
|
861
|
+
const from = record.state === "pending" ? transitionApproval("pending", "begin-decision") : { ok: true, to: record.state };
|
|
862
|
+
const next = from.ok ? transitionApproval(from.to, data.decision) : from;
|
|
863
|
+
if (!next.ok) {
|
|
864
|
+
illegal();
|
|
865
|
+
break;
|
|
866
|
+
}
|
|
867
|
+
record.state = next.to;
|
|
868
|
+
record.decision = data.decision;
|
|
869
|
+
record.decidedBy = clone(data.decidedBy);
|
|
870
|
+
record.optionId = typeof data.optionId === "string" ? data.optionId : null;
|
|
871
|
+
record.note = typeof data.note === "string" ? data.note : null;
|
|
872
|
+
break;
|
|
873
|
+
}
|
|
874
|
+
case "approval.applied": {
|
|
875
|
+
const record = byId(state.approvals, "approvalId", data.approvalId);
|
|
876
|
+
const next = record ? transitionApproval(record.state, data.ok === true ? "apply" : "apply-fail") : null;
|
|
877
|
+
if (!record || !next || !next.ok) {
|
|
878
|
+
illegal();
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
record.state = next.to;
|
|
882
|
+
record.error = typeof data.error === "string" ? data.error : null;
|
|
883
|
+
break;
|
|
884
|
+
}
|
|
885
|
+
case "approval.withdrawn": {
|
|
886
|
+
const record = byId(state.approvals, "approvalId", data.approvalId);
|
|
887
|
+
const next = record ? transitionApproval(record.state, data.expired === true ? "expire" : "withdraw") : null;
|
|
888
|
+
if (!record || !next || !next.ok) illegal();
|
|
889
|
+
else record.state = next.to;
|
|
890
|
+
break;
|
|
891
|
+
}
|
|
892
|
+
case "question.asked": {
|
|
893
|
+
const q = data.question;
|
|
894
|
+
if (!isPlainObject(q) || typeof q.questionId !== "string" || byId(state.questions, "questionId", q.questionId)) {
|
|
895
|
+
illegal();
|
|
896
|
+
break;
|
|
897
|
+
}
|
|
898
|
+
state.questions.push({ ...clone(q), state: "open" });
|
|
899
|
+
state.order.push({ kind: "question", id: q.questionId });
|
|
900
|
+
break;
|
|
901
|
+
}
|
|
902
|
+
case "question.answered": {
|
|
903
|
+
const q = byId(state.questions, "questionId", data.questionId);
|
|
904
|
+
if (!q || q.state !== "open" || !decidedByActor(event, data.answeredBy)) {
|
|
905
|
+
illegal();
|
|
906
|
+
break;
|
|
907
|
+
}
|
|
908
|
+
q.state = "answered";
|
|
909
|
+
q.answeredBy = clone(data.answeredBy);
|
|
910
|
+
q.values = isPlainObject(data.values) ? clone(data.values) : {};
|
|
911
|
+
q.notes = isPlainObject(data.notes) ? clone(data.notes) : {};
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
case "undo.opened": {
|
|
915
|
+
if (typeof data.actionId !== "string" || typeof data.label !== "string" || !isTimestamp(data.deadline) || byId(state.undos, "actionId", data.actionId)) {
|
|
916
|
+
illegal();
|
|
917
|
+
break;
|
|
918
|
+
}
|
|
919
|
+
state.undos.push({ actionId: data.actionId, label: data.label, deadline: data.deadline, state: "open" });
|
|
920
|
+
state.order.push({ kind: "undo", id: data.actionId });
|
|
921
|
+
break;
|
|
922
|
+
}
|
|
923
|
+
case "undo.committed":
|
|
924
|
+
case "undo.reverted": {
|
|
925
|
+
const entry = byId(state.undos, "actionId", data.actionId);
|
|
926
|
+
const allowed = event.type === "undo.committed" || decidedByActor(event, data.revertedBy);
|
|
927
|
+
if (!entry || entry.state !== "open" || !allowed) {
|
|
928
|
+
illegal();
|
|
929
|
+
break;
|
|
930
|
+
}
|
|
931
|
+
entry.state = event.type === "undo.committed" ? "committed" : "reverted";
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
state.lastSeq = event.seq;
|
|
936
|
+
return true;
|
|
937
|
+
}
|
|
938
|
+
function turnsToCancelForBranch(state, supersededId) {
|
|
939
|
+
const branch = (state.branches ?? []).find((b) => b.supersededId === supersededId);
|
|
940
|
+
if (!branch) return [];
|
|
941
|
+
const ids = /* @__PURE__ */ new Set([supersededId, ...branch.rowIds]);
|
|
942
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
943
|
+
for (const m of state.messages) if (ids.has(m.id) && m.turnId) referenced.add(m.turnId);
|
|
944
|
+
for (const a of state.approvals) if (ids.has(a.approvalId) && typeof a.turnId === "string") referenced.add(a.turnId);
|
|
945
|
+
return state.turns.filter((t) => t.state !== "settled" && referenced.has(t.turnId)).map((t) => t.turnId);
|
|
946
|
+
}
|
|
947
|
+
function rowsOf(state) {
|
|
948
|
+
const rows = [];
|
|
949
|
+
for (const { kind, id } of state.order) {
|
|
950
|
+
if (kind === "message") {
|
|
951
|
+
const m = byId(state.messages, "id", id);
|
|
952
|
+
if (m) rows.push({ kind, ...m });
|
|
953
|
+
} else if (kind === "thinking") {
|
|
954
|
+
const t = byId(state.thinking, "thinkingId", id);
|
|
955
|
+
if (t) rows.push({ kind, id, ...t });
|
|
956
|
+
} else if (kind === "tool") {
|
|
957
|
+
const t = byId(state.tools, "toolCallId", id);
|
|
958
|
+
if (t) rows.push({ kind, id, ...t });
|
|
959
|
+
} else if (kind === "plan") {
|
|
960
|
+
const p = byId(state.plans, "runId", id);
|
|
961
|
+
if (p) rows.push({ kind, id, ...p });
|
|
962
|
+
} else if (kind === "approval") {
|
|
963
|
+
const a = byId(state.approvals, "approvalId", id);
|
|
964
|
+
if (a) rows.push({ kind, id, approvalId: a.approvalId, state: a.state });
|
|
965
|
+
} else if (kind === "question") {
|
|
966
|
+
const q = byId(state.questions, "questionId", id);
|
|
967
|
+
if (q) rows.push({ kind, id, questionId: q.questionId, state: q.state ?? "open" });
|
|
968
|
+
} else if (kind === "undo") {
|
|
969
|
+
const u = byId(state.undos, "actionId", id);
|
|
970
|
+
if (u) rows.push({ kind, id, ...u });
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
return rows;
|
|
974
|
+
}
|
|
975
|
+
function projectThread(events, initial) {
|
|
976
|
+
const state = initial ? clone(initial) : emptyThreadState();
|
|
977
|
+
for (const event of events) applyEvent(state, event);
|
|
978
|
+
return { lastSeq: state.lastSeq, illegal: state.illegal, rows: rowsOf(state), turns: state.turns, approvals: state.approvals, questions: state.questions, state };
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
exports.AGENT_STATUSES = AGENT_STATUSES;
|
|
982
|
+
exports.CHART_TYPES = CHART_TYPES;
|
|
983
|
+
exports.CONTRACT_VERSION = CONTRACT_VERSION;
|
|
984
|
+
exports.CORE_EVENT_TYPES = CORE_EVENT_TYPES;
|
|
985
|
+
exports.CORE_PART_KINDS = CORE_PART_KINDS;
|
|
986
|
+
exports.DEFAULT_PART_LIMITS = DEFAULT_PART_LIMITS;
|
|
987
|
+
exports.DEFAULT_RECOVERY = DEFAULT_RECOVERY;
|
|
988
|
+
exports.DEFAULT_STATUS_CONFIG = DEFAULT_STATUS_CONFIG;
|
|
989
|
+
exports.DEFAULT_TYPED_APPROVAL = DEFAULT_TYPED_APPROVAL;
|
|
990
|
+
exports.ENGLISH_TYPED_APPROVAL_PHRASES = ENGLISH_TYPED_APPROVAL_PHRASES;
|
|
991
|
+
exports.PLAN_STEP_STATUSES = PLAN_STEP_STATUSES;
|
|
992
|
+
exports.applyEvent = applyEvent;
|
|
993
|
+
exports.canDecide = canDecide;
|
|
994
|
+
exports.canSubmitAnswer = canSubmitAnswer;
|
|
995
|
+
exports.checkPlanUpdate = checkPlanUpdate;
|
|
996
|
+
exports.createPartRegistry = createPartRegistry;
|
|
997
|
+
exports.createSeqLog = createSeqLog;
|
|
998
|
+
exports.deriveAgentStatus = deriveAgentStatus;
|
|
999
|
+
exports.emptyThreadState = emptyThreadState;
|
|
1000
|
+
exports.ingestEvents = ingestEvents;
|
|
1001
|
+
exports.isEventType = isEventType;
|
|
1002
|
+
exports.isPlainObject = isPlainObject;
|
|
1003
|
+
exports.isReservedToolName = isReservedToolName;
|
|
1004
|
+
exports.isSettlingTurnAction = isSettlingTurnAction;
|
|
1005
|
+
exports.isTimestamp = isTimestamp;
|
|
1006
|
+
exports.jsonBytes = jsonBytes;
|
|
1007
|
+
exports.machines = machines;
|
|
1008
|
+
exports.matchTypedApproval = matchTypedApproval;
|
|
1009
|
+
exports.normalizePhrase = normalizePhrase;
|
|
1010
|
+
exports.optionTone = optionTone;
|
|
1011
|
+
exports.partToText = partToText;
|
|
1012
|
+
exports.pickActionable = pickActionable;
|
|
1013
|
+
exports.projectThread = projectThread;
|
|
1014
|
+
exports.rowsOf = rowsOf;
|
|
1015
|
+
exports.transitionApproval = transitionApproval;
|
|
1016
|
+
exports.transitionDelivery = transitionDelivery;
|
|
1017
|
+
exports.transitionTurn = transitionTurn;
|
|
1018
|
+
exports.turnsToCancelForBranch = turnsToCancelForBranch;
|
|
1019
|
+
exports.undoWindow = undoWindow;
|
|
1020
|
+
exports.validateEvent = validateEvent;
|
|
1021
|
+
exports.validatePart = validatePart;
|
|
1022
|
+
exports.validateParts = validateParts;
|
|
1023
|
+
//# sourceMappingURL=index.cjs.map
|
|
1024
|
+
//# sourceMappingURL=index.cjs.map
|