dsh-asteme 0.0.1 → 0.12.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 +1 -0
- package/NOTICE +12 -0
- package/README.md +16 -8
- package/brain/acp.mjs +208 -0
- package/brain/fonts.mjs +135 -0
- package/brain/mind.mjs +1723 -0
- package/brain/page/0-base.js +217 -0
- package/brain/page/1-sky.js +71 -0
- package/brain/page/2-stars.js +1564 -0
- package/brain/page/3-beginning.js +324 -0
- package/brain/page/4-conversation.js +685 -0
- package/brain/page/5-sheets.js +1040 -0
- package/brain/page/6-handing.js +352 -0
- package/brain/page/7-aloud.js +198 -0
- package/brain/page/8-start.js +739 -0
- package/brain/page/shell.html +31 -0
- package/brain/page/style.css +371 -0
- package/brain/page.mjs +38 -0
- package/brain/server.mjs +331 -0
- package/brain/voice.mjs +252 -0
- package/brain/wake.mjs +203 -0
- package/client/copy.mjs +846 -0
- package/client/dist/client.js +905 -0
- package/client/icon.mjs +12 -0
- package/client/locales/de.mjs +802 -0
- package/client/locales/es.mjs +802 -0
- package/client/locales/fr.mjs +802 -0
- package/client/locales/ja.mjs +813 -0
- package/client/locales/pt.mjs +802 -0
- package/client/locales/ru.mjs +802 -0
- package/client/locales/zh.mjs +813 -0
- package/cordis.patch.yml +4 -0
- package/eval/harness.mjs +68 -0
- package/eval/scenarios.mjs +175 -0
- package/icon.svg +6 -0
- package/locale/en.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +59 -11
- package/plugin/calls.mjs +131 -0
- package/plugin/events.mjs +110 -0
- package/plugin/files.mjs +335 -0
- package/plugin/host.mjs +728 -0
- package/plugin/index.mjs +193 -0
- package/plugin/prompt.mjs +55 -0
- package/plugin/settings.mjs +310 -0
- package/plugin/surface.mjs +88 -0
- package/plugin/tunables.mjs +52 -0
- package/plugin/voice.mjs +14 -0
- package/plugin/worker.mjs +101 -0
- package/src/LICENSE +21 -0
- package/src/archive.mjs +485 -0
- package/src/attend.mjs +395 -0
- package/src/charter.mjs +31 -0
- package/src/core.mjs +93 -0
- package/src/diary.locales.mjs +40 -0
- package/src/embed-worker.mjs +28 -0
- package/src/embedding.mjs +90 -0
- package/src/explain.mjs +82 -0
- package/src/habits.mjs +237 -0
- package/src/jev.mjs +20 -0
- package/src/journal.mjs +44 -0
- package/src/judge.mjs +89 -0
- package/src/log.mjs +484 -0
- package/src/memory.mjs +460 -0
- package/src/mind.mjs +78 -0
- package/src/model-json.mjs +86 -0
- package/src/outcome.mjs +225 -0
- package/src/package.json +23 -0
- package/src/policy.mjs +119 -0
- package/src/prompts.mjs +248 -0
- package/src/recall.mjs +261 -0
- package/src/reflect.mjs +134 -0
- package/src/sleep.mjs +356 -0
- package/src/user.mjs +172 -0
- package/index.js +0 -6
package/brain/mind.mjs
ADDED
|
@@ -0,0 +1,1723 @@
|
|
|
1
|
+
// The brain: Asteme as the one the user talks to.
|
|
2
|
+
//
|
|
3
|
+
// One conversation that never ends, kept in Asteme's own store. Every moment
|
|
4
|
+
// it attends to has a cause (wake.mjs): the user spoke, a worker came back, a
|
|
5
|
+
// time it set itself arrived. One model call reads the situation, decides
|
|
6
|
+
// what memory applies, says the reply and names what to do (speakBody in
|
|
7
|
+
// src/prompts.mjs). It has no hands: work goes to workers through one door
|
|
8
|
+
// (acp.mjs), and what comes back is something it read, never something the
|
|
9
|
+
// user said. docs/BRAIN.md has the reasons.
|
|
10
|
+
import { Log, profile } from "../src/log.mjs";
|
|
11
|
+
import { Asteme, plain, accessibility, useStats } from "../src/core.mjs";
|
|
12
|
+
import { Wakefulness, EVERY } from "./wake.mjs";
|
|
13
|
+
import { forVoice, plainWav } from "./voice.mjs";
|
|
14
|
+
import { mkdirSync, writeFileSync, readFileSync, openSync, readSync, closeSync, existsSync, rmSync } from "node:fs";
|
|
15
|
+
import { dirname, join, extname } from "node:path";
|
|
16
|
+
import { tmpdir } from "node:os";
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
|
|
19
|
+
const THREAD = "thread",
|
|
20
|
+
STAGE = "experienced";
|
|
21
|
+
const cut = (s, n) => {
|
|
22
|
+
const t = String(s ?? "");
|
|
23
|
+
return t.length > n ? `${t.slice(0, n)}…` : t;
|
|
24
|
+
};
|
|
25
|
+
export const DEFAULTS = {
|
|
26
|
+
drowsyAfterMs: 300000,
|
|
27
|
+
settleMs: 20000,
|
|
28
|
+
restEveryMs: 30000,
|
|
29
|
+
watchMs: 1200000,
|
|
30
|
+
leash: 8,
|
|
31
|
+
recent: 14,
|
|
32
|
+
resultChars: 6000,
|
|
33
|
+
presentChars: 12000,
|
|
34
|
+
earlier: 10,
|
|
35
|
+
promptChars: 80000,
|
|
36
|
+
// What every speaking call carries whatever is said: the rules, the charter, the shape of the answer. A test holds this to the real size, so the rules cannot grow past it unnoticed.
|
|
37
|
+
fixedChars: 24500,
|
|
38
|
+
candidateChars: 28000,
|
|
39
|
+
fileBytes: 25000000,
|
|
40
|
+
filesAtOnce: 6,
|
|
41
|
+
fileText: 4000,
|
|
42
|
+
// Between two messages said one after the other: a moment, longer for more words, the way a second message takes a moment to write.
|
|
43
|
+
pauseMs: 700,
|
|
44
|
+
pauseChar: 25,
|
|
45
|
+
pauseMax: 2600,
|
|
46
|
+
// How long the user was not here before coming back counts as coming back, and how many things are kept to bring up then.
|
|
47
|
+
absenceMs: 3 * 3600000,
|
|
48
|
+
held: 8,
|
|
49
|
+
};
|
|
50
|
+
// Kinds of file whose beginning can be read as text. The bytes decide in the
|
|
51
|
+
// end: a file with one of these names that is not text is not read.
|
|
52
|
+
const TEXTUAL = new Set([
|
|
53
|
+
".txt",
|
|
54
|
+
".md",
|
|
55
|
+
".markdown",
|
|
56
|
+
".csv",
|
|
57
|
+
".tsv",
|
|
58
|
+
".json",
|
|
59
|
+
".jsonl",
|
|
60
|
+
".yaml",
|
|
61
|
+
".yml",
|
|
62
|
+
".toml",
|
|
63
|
+
".ini",
|
|
64
|
+
".xml",
|
|
65
|
+
".html",
|
|
66
|
+
".htm",
|
|
67
|
+
".css",
|
|
68
|
+
".js",
|
|
69
|
+
".mjs",
|
|
70
|
+
".cjs",
|
|
71
|
+
".ts",
|
|
72
|
+
".tsx",
|
|
73
|
+
".jsx",
|
|
74
|
+
".py",
|
|
75
|
+
".rb",
|
|
76
|
+
".go",
|
|
77
|
+
".rs",
|
|
78
|
+
".java",
|
|
79
|
+
".kt",
|
|
80
|
+
".c",
|
|
81
|
+
".h",
|
|
82
|
+
".cpp",
|
|
83
|
+
".cs",
|
|
84
|
+
".php",
|
|
85
|
+
".sh",
|
|
86
|
+
".ps1",
|
|
87
|
+
".bat",
|
|
88
|
+
".sql",
|
|
89
|
+
".log",
|
|
90
|
+
".tex",
|
|
91
|
+
".srt",
|
|
92
|
+
".vue",
|
|
93
|
+
".svelte",
|
|
94
|
+
".swift",
|
|
95
|
+
".lua",
|
|
96
|
+
".r",
|
|
97
|
+
]);
|
|
98
|
+
|
|
99
|
+
// Inside a host that already has the store open, `shared` is { log, core }:
|
|
100
|
+
// the conversation is then one more session in the same memory, and reading
|
|
101
|
+
// turns in and consolidating are left to the host, which does them already.
|
|
102
|
+
// `models`, `hear` and `voice` are what a host lends: which model speaks (and
|
|
103
|
+
// the ones it could be changed to), turning a recording into words, and a
|
|
104
|
+
// voice to read replies aloud with. Without them the conversation uses the one
|
|
105
|
+
// model it was started with, has no microphone, and is read aloud only by the
|
|
106
|
+
// voice the device has.
|
|
107
|
+
export function openMind({
|
|
108
|
+
path = ":memory:",
|
|
109
|
+
shared = null,
|
|
110
|
+
identity = { userId: "local", agentId: "assistant" },
|
|
111
|
+
infer,
|
|
112
|
+
embed,
|
|
113
|
+
judge = null,
|
|
114
|
+
workers = {},
|
|
115
|
+
models = null,
|
|
116
|
+
hear = null,
|
|
117
|
+
voice = null,
|
|
118
|
+
now,
|
|
119
|
+
timers = {},
|
|
120
|
+
config = {},
|
|
121
|
+
} = {}) {
|
|
122
|
+
if (typeof infer !== "function") throw new Error("The brain needs a model to think with");
|
|
123
|
+
const cfg = { ...DEFAULTS, ...config };
|
|
124
|
+
const log = shared?.log ?? new Log(path, now),
|
|
125
|
+
core = shared?.core ?? new Asteme({ log, identity, embed });
|
|
126
|
+
const scope = { ...identity, projectId: "asteme" };
|
|
127
|
+
const listeners = new Set(),
|
|
128
|
+
emit = (event) => {
|
|
129
|
+
for (const l of listeners) {
|
|
130
|
+
try {
|
|
131
|
+
l(plain(event));
|
|
132
|
+
} catch {
|
|
133
|
+
/* a listener's failure is its own */
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
// What is being thought about for the conversation can be stopped by the user; the rest of what it does cannot.
|
|
138
|
+
let halt = null;
|
|
139
|
+
// Writing is told apart from thinking, as it is between people: the dots that say "is writing" belong to the moment its words begin, not to the time it spends
|
|
140
|
+
// recalling and making up its mind. A host that streams (infer.reports) says when the first word of an answer comes; with one that does not, writing is taken
|
|
141
|
+
// to begin when the call that speaks goes out, which is at least after memory was called up. Once it has begun it stays until the moment is over: what it wrote may be
|
|
142
|
+
// looked at again with more of what it remembers before it is said, and dots that came, went and came back read as words that were lost.
|
|
143
|
+
let writing = false,
|
|
144
|
+
greeting = null;
|
|
145
|
+
// On an occasion where saying nothing is the ordinary case, the dots do not come up for words that may never be said: they would appear and go, answering nothing.
|
|
146
|
+
let hushed = false;
|
|
147
|
+
const write = (on) => {
|
|
148
|
+
if (writing === on || (on && hushed)) return;
|
|
149
|
+
writing = on;
|
|
150
|
+
emit({ type: "writing", on });
|
|
151
|
+
};
|
|
152
|
+
const model = async (purpose, prompt, tokens) => {
|
|
153
|
+
const started = Date.now(),
|
|
154
|
+
speaks = purpose === "asteme-think" && thinking,
|
|
155
|
+
hooks = speaks
|
|
156
|
+
? {
|
|
157
|
+
wrote: () => {
|
|
158
|
+
if (thinking) write(true);
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
: undefined;
|
|
162
|
+
if (speaks && !infer.reports) hooks.wrote();
|
|
163
|
+
if (shared) return infer(purpose, prompt, tokens, halt?.signal, hooks); // the host keeps the journal
|
|
164
|
+
try {
|
|
165
|
+
const v = await infer(purpose, prompt, tokens, halt?.signal, hooks);
|
|
166
|
+
core.note("call", { purpose, ok: true, ms: Date.now() - started, tokens });
|
|
167
|
+
return v;
|
|
168
|
+
} catch (e) {
|
|
169
|
+
core.note("call", {
|
|
170
|
+
purpose,
|
|
171
|
+
ok: false,
|
|
172
|
+
ms: Date.now() - started,
|
|
173
|
+
tokens,
|
|
174
|
+
error: cut(e.message, 200),
|
|
175
|
+
...(e.name === "TimeoutError" ? { timeout: true } : {}),
|
|
176
|
+
});
|
|
177
|
+
throw e;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
// Files the user hands over are kept beside the store, on this computer only.
|
|
181
|
+
const filesDir =
|
|
182
|
+
cfg.files ?? (log.path && log.path !== ":memory:" ? join(dirname(log.path), "files") : join(tmpdir(), `asteme-files-${process.pid}`));
|
|
183
|
+
const fileOf = (id) => {
|
|
184
|
+
const f = typeof id === "string" && /^[0-9a-f-]{36}$/.test(id) ? log.state(`brain:file:${id}`, null) : null;
|
|
185
|
+
return f && existsSync(join(filesDir, f.file)) ? { ...f, path: join(filesDir, f.file) } : null;
|
|
186
|
+
};
|
|
187
|
+
// The beginning of a file that reads as text. Anything else is not read here.
|
|
188
|
+
const beginning = (f) => {
|
|
189
|
+
if (!TEXTUAL.has(extname(f.name).toLowerCase()) && !/^text\//.test(f.type)) return null;
|
|
190
|
+
const buffer = Buffer.alloc(Math.min(f.size, cfg.fileText * 4)),
|
|
191
|
+
fd = openSync(f.path, "r");
|
|
192
|
+
try {
|
|
193
|
+
readSync(fd, buffer, 0, buffer.length, 0);
|
|
194
|
+
} finally {
|
|
195
|
+
closeSync(fd);
|
|
196
|
+
}
|
|
197
|
+
if (buffer.includes(0)) return null;
|
|
198
|
+
return cut(buffer.toString("utf8").replace(/\uFFFD+$/, ""), cfg.fileText);
|
|
199
|
+
};
|
|
200
|
+
const add = (role, content, kind = `${role}/message`, metadata) => {
|
|
201
|
+
log.ingest(scope, THREAD, [{ seq: log.cursor(scope, THREAD), role, kind, content, occurredAt: log.now(), ...(metadata ? { metadata } : {}) }]);
|
|
202
|
+
return log.events(scope, THREAD).at(-1);
|
|
203
|
+
};
|
|
204
|
+
// Work that is out with workers. Handles live in this process; what is kept
|
|
205
|
+
// is enough to say, after a restart, what was lost.
|
|
206
|
+
const tasks = new Map((log.state("brain:tasks", []) ?? []).map((t) => [t.id, t.state === "running" ? { ...t, state: "lost" } : t]));
|
|
207
|
+
const handles = new Map(),
|
|
208
|
+
asks = new Map();
|
|
209
|
+
const keepTasks = () => log.save("brain:tasks", [...tasks.values()].slice(-60));
|
|
210
|
+
const brief = (t) => ({
|
|
211
|
+
id: t.id,
|
|
212
|
+
to: t.to,
|
|
213
|
+
task: cut(t.task, 300),
|
|
214
|
+
state: t.state,
|
|
215
|
+
startedAt: t.startedAt,
|
|
216
|
+
...(t.endedAt ? { endedAt: t.endedAt } : {}),
|
|
217
|
+
...(t.where ? { where: t.where } : {}),
|
|
218
|
+
...(t.error ? { error: t.error } : {}),
|
|
219
|
+
...(t.session ? { session: t.session } : {}),
|
|
220
|
+
});
|
|
221
|
+
let turnOpen = false,
|
|
222
|
+
origin = null,
|
|
223
|
+
steps = 0,
|
|
224
|
+
thinking = false,
|
|
225
|
+
thinkingSince = null,
|
|
226
|
+
lastRecall = null;
|
|
227
|
+
// The way of speaking for now: a mood the user asked for, with an end. The
|
|
228
|
+
// charter is not touched by it, and when it ends the usual voice is back.
|
|
229
|
+
const manner = () => {
|
|
230
|
+
const m = log.state("brain:manner", null);
|
|
231
|
+
if (m?.until && m.until <= log.now()) {
|
|
232
|
+
log.save("brain:manner", null);
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
return m?.text ? m : null;
|
|
236
|
+
};
|
|
237
|
+
const setManner = (text, until) => {
|
|
238
|
+
const t = typeof text === "string" ? cut(text.trim(), 300) : "";
|
|
239
|
+
log.save("brain:manner", t ? { text: t, until: Number.isFinite(until) && until > log.now() ? until : null, at: log.now() } : null);
|
|
240
|
+
emit({ type: "manner" });
|
|
241
|
+
return t;
|
|
242
|
+
};
|
|
243
|
+
const running = () => [...tasks.values()].filter((t) => t.state === "running");
|
|
244
|
+
// The end of a matter says how it ended, as a host's turn does: without it every one of these counted as "ended, reason not recorded".
|
|
245
|
+
const endTurn = () => {
|
|
246
|
+
if (turnOpen) {
|
|
247
|
+
add("unknown", "", "turn/end", { ended: { kind: "completed" } });
|
|
248
|
+
turnOpen = false;
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const wake = new Wakefulness({
|
|
253
|
+
now: () => log.now(),
|
|
254
|
+
...timers,
|
|
255
|
+
drowsyAfterMs: cfg.drowsyAfterMs,
|
|
256
|
+
restEveryMs: cfg.restEveryMs,
|
|
257
|
+
settleMs: cfg.settleMs,
|
|
258
|
+
load: () => log.state("brain:wake", null),
|
|
259
|
+
save: (v) => log.save("brain:wake", v),
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// --- Workers -----------------------------------------------------------------
|
|
263
|
+
const finish = (task, outcome, error) => {
|
|
264
|
+
if (task.state !== "running") return;
|
|
265
|
+
task.state = error?.stopped ? "stopped" : error ? "failed" : outcome.stopReason === "cancelled" ? "cancelled" : "done";
|
|
266
|
+
task.endedAt = log.now();
|
|
267
|
+
if (error) task.error = cut(error.message, 400);
|
|
268
|
+
// One line for each round of work, so that one which never came back can be traced afterwards.
|
|
269
|
+
core.note("work", {
|
|
270
|
+
to: task.to,
|
|
271
|
+
task: task.id,
|
|
272
|
+
...(task.session ? { session: task.session } : {}),
|
|
273
|
+
ok: !error,
|
|
274
|
+
state: task.state,
|
|
275
|
+
ms: log.now() - (task.sentAt ?? task.startedAt),
|
|
276
|
+
...(task.last ? { last: task.last } : {}),
|
|
277
|
+
...(error ? { error: task.error } : {}),
|
|
278
|
+
});
|
|
279
|
+
wake.forget(`watch:${task.id}`);
|
|
280
|
+
keepTasks();
|
|
281
|
+
emit({ type: "task", task: brief(task) });
|
|
282
|
+
wake.stimulus({ kind: "worker", task: task.id, ...(error ? { error: cut(error.message, 400) } : { outcome }) });
|
|
283
|
+
};
|
|
284
|
+
const dispatch = async (task, text, first) => {
|
|
285
|
+
const worker = workers[task.to];
|
|
286
|
+
task.state = "running";
|
|
287
|
+
task.sentAt = log.now();
|
|
288
|
+
task.last = null;
|
|
289
|
+
keepTasks();
|
|
290
|
+
emit({ type: "task", task: brief(task) });
|
|
291
|
+
wake.intend(log.now() + cfg.watchMs, `Nothing has come back from ${task.to} on "${cut(task.task, 80)}"`, `watch:${task.id}`);
|
|
292
|
+
try {
|
|
293
|
+
let handle = handles.get(task.id);
|
|
294
|
+
const onPermission = (ask) => {
|
|
295
|
+
// Permission is the user's to give. It goes to them as it is, and the
|
|
296
|
+
// brain is not asked: a model must not be the one to say yes.
|
|
297
|
+
const id = `${task.id}:${asks.size + 1}:${log.now()}`;
|
|
298
|
+
asks.set(id, { id, task: task.id, to: task.to, title: ask.title, detail: ask.detail, answer: ask.answer });
|
|
299
|
+
emit({ type: "ask", ask: { id, task: task.id, to: task.to, title: ask.title, detail: ask.detail } });
|
|
300
|
+
};
|
|
301
|
+
// A worker may also ask something with choices. It is shown to the user as it is; unless it asks leave to act, Asteme is told too, and may answer from what it already knows.
|
|
302
|
+
const onQuestion = (asked) =>
|
|
303
|
+
new Promise((answer, fail) => {
|
|
304
|
+
const id = `${task.id}:q${asks.size + 1}:${log.now()}`;
|
|
305
|
+
const questions = (asked.questions ?? []).map((q, i) => ({
|
|
306
|
+
id: String(q.id ?? i),
|
|
307
|
+
question: cut(q.question ?? q.header ?? "", 600),
|
|
308
|
+
detail: cut(typeof q.detail === "string" ? q.detail : q.detail ? JSON.stringify(q.detail) : "", 800),
|
|
309
|
+
options: (q.options ?? []).map((o) => ({ label: String(o.label ?? o), description: cut(o.description ?? "", 300) })),
|
|
310
|
+
multi: q.multiSelect === true,
|
|
311
|
+
approval: q.intent?.kind === "approval",
|
|
312
|
+
}));
|
|
313
|
+
if (!questions.length) return fail(new Error("Nothing was asked"));
|
|
314
|
+
const ask = { id, kind: "question", task: task.id, to: task.to, questions, answer };
|
|
315
|
+
asks.set(id, ask);
|
|
316
|
+
emit({ type: "ask", ask: { id, kind: "question", task: task.id, to: task.to, questions } });
|
|
317
|
+
asked.signal?.addEventListener?.(
|
|
318
|
+
"abort",
|
|
319
|
+
() => {
|
|
320
|
+
if (asks.delete(id)) {
|
|
321
|
+
emit({ type: "answered", id, by: "nobody" });
|
|
322
|
+
fail(new Error("The question was withdrawn"));
|
|
323
|
+
}
|
|
324
|
+
},
|
|
325
|
+
{ once: true },
|
|
326
|
+
);
|
|
327
|
+
if (!questions.some((q) => q.approval)) wake.stimulus({ kind: "question", ask: id });
|
|
328
|
+
});
|
|
329
|
+
const done =
|
|
330
|
+
first || !handle
|
|
331
|
+
? ((handle = await worker.start({
|
|
332
|
+
where: task.where || undefined,
|
|
333
|
+
text,
|
|
334
|
+
onPermission,
|
|
335
|
+
onQuestion,
|
|
336
|
+
onUpdate: (u) => {
|
|
337
|
+
task.last = { kind: u.kind, text: cut(u.text, 80), after: log.now() - task.sentAt };
|
|
338
|
+
emit({ type: "progress", task: task.id, ...u, text: cut(u.text, 200), ...(handle?.sessionId ? { session: handle.sessionId } : {}) });
|
|
339
|
+
},
|
|
340
|
+
})),
|
|
341
|
+
handles.set(task.id, handle),
|
|
342
|
+
(task.session = handle.sessionId ?? null),
|
|
343
|
+
handle.done)
|
|
344
|
+
: handle.tell(text);
|
|
345
|
+
finish(task, await done);
|
|
346
|
+
} catch (e) {
|
|
347
|
+
finish(task, null, e);
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
const act = (a, present) => {
|
|
351
|
+
if (!a || typeof a !== "object") return null;
|
|
352
|
+
if (a.act === "delegate" || a.act === "tell") {
|
|
353
|
+
if (a.act === "delegate" && !workers[a.to]) return { refused: "delegate", why: `there is no worker named ${cut(a.to, 40)}` };
|
|
354
|
+
// The leash: how many times work may go out before the user speaks again.
|
|
355
|
+
if (steps >= cfg.leash)
|
|
356
|
+
return { refused: a.act, why: `the limit of ${cfg.leash} hand-offs since the user last spoke is reached; report and ask` };
|
|
357
|
+
if (a.act === "delegate") {
|
|
358
|
+
if (typeof a.task !== "string" || a.task.trim().length < 8) return { refused: "delegate", why: "the task says too little" };
|
|
359
|
+
const task = {
|
|
360
|
+
id: `t${tasks.size + 1}-${Math.round(log.now() % 1e5)}`,
|
|
361
|
+
to: a.to,
|
|
362
|
+
task: a.task.trim(),
|
|
363
|
+
where: typeof a.where === "string" ? a.where.trim() : "",
|
|
364
|
+
origin,
|
|
365
|
+
startedAt: log.now(),
|
|
366
|
+
state: "running",
|
|
367
|
+
};
|
|
368
|
+
tasks.set(task.id, task);
|
|
369
|
+
steps++;
|
|
370
|
+
add("tool", `To ${task.to}: ${task.task}`, "tool/call", { tool: { phase: "call", name: task.to }, task: task.id });
|
|
371
|
+
void dispatch(task, task.task, true);
|
|
372
|
+
return { started: task.id };
|
|
373
|
+
}
|
|
374
|
+
const task = tasks.get(a.task);
|
|
375
|
+
if (!task || !handles.has(task.id) || task.state === "running") return { refused: "tell", why: "that task cannot be continued" };
|
|
376
|
+
if (typeof a.message !== "string" || !a.message.trim()) return { refused: "tell", why: "nothing to say" };
|
|
377
|
+
steps++;
|
|
378
|
+
task.endedAt = undefined;
|
|
379
|
+
add("tool", `To ${task.to}, continuing: ${a.message.trim()}`, "tool/call", { tool: { phase: "call", name: task.to }, task: task.id });
|
|
380
|
+
void dispatch(task, a.message.trim(), false);
|
|
381
|
+
return { continued: task.id };
|
|
382
|
+
}
|
|
383
|
+
if (a.act === "cancel") {
|
|
384
|
+
const h = handles.get(a.task);
|
|
385
|
+
if (h && tasks.get(a.task)?.state === "running") {
|
|
386
|
+
h.cancel();
|
|
387
|
+
return { cancelling: a.task };
|
|
388
|
+
}
|
|
389
|
+
return { refused: "cancel", why: "that task is not running" };
|
|
390
|
+
}
|
|
391
|
+
if (a.act === "manner") {
|
|
392
|
+
const t = setManner(a.text, Date.parse(a.until));
|
|
393
|
+
return t ? { speaking: t } : { speaking: "as usual" };
|
|
394
|
+
}
|
|
395
|
+
if (a.act === "wake") {
|
|
396
|
+
const at = Date.parse(a.at);
|
|
397
|
+
if (!Number.isFinite(at) || at <= log.now() || typeof a.why !== "string" || !a.why.trim())
|
|
398
|
+
return { refused: "wake", why: "a time in the future and a reason are needed" };
|
|
399
|
+
const every = EVERY.includes(a.every) ? a.every : null;
|
|
400
|
+
const id = wake.intend(at, cut(a.why.trim(), 300), null, every);
|
|
401
|
+
emit({ type: "intention", at, why: cut(a.why.trim(), 300) });
|
|
402
|
+
return { waking: new Date(at).toISOString(), promised: { id, at, why: cut(a.why.trim(), 300), ...(every ? { every } : {}) } };
|
|
403
|
+
}
|
|
404
|
+
// A small sign on what the user just said, the way a person nods. Only a pictograph is one; anything else is words and belongs in the reply.
|
|
405
|
+
if (a.act === "react") {
|
|
406
|
+
if (!feel().react || present?.kind !== "the user wrote" || !origin)
|
|
407
|
+
return { refused: "react", why: "there is nothing of the user's to react to now" };
|
|
408
|
+
const emoji = typeof a.emoji === "string" ? a.emoji.trim() : "";
|
|
409
|
+
if (!emoji || emoji.length > 16 || !/^(\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u.test(emoji))
|
|
410
|
+
return { refused: "react", why: "a reaction is one pictograph" };
|
|
411
|
+
add("unknown", JSON.stringify({ to: origin, emoji }), "reaction");
|
|
412
|
+
emit({ type: "reaction", to: origin, emoji });
|
|
413
|
+
return { reacted: emoji };
|
|
414
|
+
}
|
|
415
|
+
// A face of its own, from the ones the user gave it: it goes with the words of this moment.
|
|
416
|
+
if (a.act === "express") {
|
|
417
|
+
const mine = expressions().find((x) => x.name === a.name);
|
|
418
|
+
if (!feel().express || !mine) return { refused: "express", why: "there is no such expression" };
|
|
419
|
+
return { expressed: mine.name };
|
|
420
|
+
}
|
|
421
|
+
// A worker's question, answered from what is already known. One that asks leave to act is the user's alone.
|
|
422
|
+
if (a.act === "answer") {
|
|
423
|
+
const ask = asks.get(a.ask);
|
|
424
|
+
if (!ask || ask.kind !== "question") return { refused: "answer", why: "that question is no longer open" };
|
|
425
|
+
if (ask.questions.some((q) => q.approval)) return { refused: "answer", why: "leave to act is the user's to give" };
|
|
426
|
+
try {
|
|
427
|
+
settle(ask, a.answers, "asteme");
|
|
428
|
+
} catch (e) {
|
|
429
|
+
return { refused: "answer", why: e.message };
|
|
430
|
+
}
|
|
431
|
+
return { answered: ask.id };
|
|
432
|
+
}
|
|
433
|
+
// Something to bring up when the user is next around: kept in its own words, with no time on it.
|
|
434
|
+
if (a.act === "hold") {
|
|
435
|
+
const about = typeof a.about === "string" ? cut(a.about.trim(), 300) : "";
|
|
436
|
+
if (!about) return { refused: "hold", why: "what is kept needs words" };
|
|
437
|
+
const list = held();
|
|
438
|
+
if (list.length >= cfg.held) return { refused: "hold", why: `${cfg.held} things are kept already; let one go first` };
|
|
439
|
+
const kept = { id: `held-${randomUUID().slice(0, 8)}`, at: log.now(), about, ...(origin ? { from: origin } : {}) };
|
|
440
|
+
log.save("brain:mind", [...list, kept]);
|
|
441
|
+
emit({ type: "intention" });
|
|
442
|
+
return { holding: kept.id };
|
|
443
|
+
}
|
|
444
|
+
if (a.act === "unwake") {
|
|
445
|
+
if (held().some((h) => h.id === a.id)) {
|
|
446
|
+
log.save(
|
|
447
|
+
"brain:mind",
|
|
448
|
+
held().filter((h) => h.id !== a.id),
|
|
449
|
+
);
|
|
450
|
+
emit({ type: "intention" });
|
|
451
|
+
return { unset: a.id };
|
|
452
|
+
}
|
|
453
|
+
if (!standing().some((w) => w.id === a.id)) return { refused: "unwake", why: "there is no such time set" };
|
|
454
|
+
wake.forget(a.id);
|
|
455
|
+
emit({ type: "intention" });
|
|
456
|
+
return { unset: a.id };
|
|
457
|
+
}
|
|
458
|
+
return null;
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
// How it may show feeling besides words: a pictograph on what the user said, and faces the user gave it. Both can be turned off.
|
|
462
|
+
const feel = () => ({ react: true, express: true, seen: true, ...(log.state("brain:feel", null) ?? {}) });
|
|
463
|
+
// Who has had what in front of them. A message of the user's is read when Asteme takes it up; a reply of Asteme's is seen when the page had it in view. Each is kept by the message's id with the time, the last few hundred.
|
|
464
|
+
const marks = (key) => log.state(key, null) ?? {},
|
|
465
|
+
mark = (key, id, at) => {
|
|
466
|
+
const all = marks(key);
|
|
467
|
+
if (all[id]) return false;
|
|
468
|
+
const next = Object.fromEntries([...Object.entries(all), [id, at]].slice(-300));
|
|
469
|
+
log.save(key, next);
|
|
470
|
+
return true;
|
|
471
|
+
};
|
|
472
|
+
const expressions = () => (log.state("brain:expressions", []) ?? []).filter((x) => x && typeof x.name === "string" && typeof x.image === "string");
|
|
473
|
+
// A face is chosen by its name. A model that can see pictures is also shown each face once and says in a few words what it shows; that goes beside the name from then on. Nothing is waited for, and a model that cannot see is not asked.
|
|
474
|
+
const seen = async (name, image) => {
|
|
475
|
+
if (!models?.see) return;
|
|
476
|
+
try {
|
|
477
|
+
const said = await models.see(
|
|
478
|
+
image,
|
|
479
|
+
'This picture was given to an assistant as a face it may send to show how it takes something. Say what the face shows, as a person would name the expression, in at most twelve words, in the language of its name ("' +
|
|
480
|
+
cut(name, 40) +
|
|
481
|
+
'"). Return {"shows":"..."}.',
|
|
482
|
+
);
|
|
483
|
+
const shows = typeof said?.shows === "string" ? cut(said.shows.trim(), 120) : "";
|
|
484
|
+
if (!shows) return;
|
|
485
|
+
log.save(
|
|
486
|
+
"brain:expressions",
|
|
487
|
+
expressions().map((x) => (x.name === name && x.image === image ? { ...x, shows } : x)),
|
|
488
|
+
);
|
|
489
|
+
emit({ type: "look" });
|
|
490
|
+
} catch {
|
|
491
|
+
/* it is still chosen by its name */
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
// A worker's question is settled once, by the user or by Asteme: each of its questions gets one or more of its own options, or words.
|
|
495
|
+
const settle = (ask, answers, by) => {
|
|
496
|
+
const given = Array.isArray(answers) ? answers : [];
|
|
497
|
+
const out = ask.questions.map((q) => {
|
|
498
|
+
const a = given.find((x) => x?.id === q.id) ?? (ask.questions.length === 1 ? given[0] : null);
|
|
499
|
+
if (!a) throw new Error(`no answer for "${cut(q.question, 60)}"`);
|
|
500
|
+
const selected = (Array.isArray(a.choose) ? a.choose : typeof a.choose === "string" ? [a.choose] : []).filter((l) =>
|
|
501
|
+
q.options.some((o) => o.label === l),
|
|
502
|
+
),
|
|
503
|
+
custom = typeof a.say === "string" && a.say.trim() ? cut(a.say.trim(), 1000) : undefined;
|
|
504
|
+
if (!selected.length && !custom) throw new Error(`"${cut(q.question, 60)}" needs one of its options or words`);
|
|
505
|
+
if (selected.length > 1 && !q.multi) throw new Error(`"${cut(q.question, 60)}" takes one option`);
|
|
506
|
+
return { id: q.id, selected, ...(custom ? { custom } : {}) };
|
|
507
|
+
});
|
|
508
|
+
asks.delete(ask.id);
|
|
509
|
+
ask.answer({ answers: out });
|
|
510
|
+
const text = out
|
|
511
|
+
.map((o, i) => `${cut(ask.questions[i].question, 120)} → ${[...o.selected, ...(o.custom ? [o.custom] : [])].join(", ")}`)
|
|
512
|
+
.join("; ");
|
|
513
|
+
add("tool", `${by === "user" ? "The user answered" : "You answered"} ${ask.to}'s question: ${text}`, "tool/result", {
|
|
514
|
+
tool: { phase: "result", name: ask.to, execution: "completed" },
|
|
515
|
+
task: ask.task,
|
|
516
|
+
});
|
|
517
|
+
emit({ type: "answered", id: ask.id, by, text });
|
|
518
|
+
};
|
|
519
|
+
// The signs put on what was said, by which message; the last one on each stands, and an empty one takes it off. Asteme's are on the user's words, the user's on Asteme's.
|
|
520
|
+
const reactions = () => {
|
|
521
|
+
const its = new Map(),
|
|
522
|
+
theirs = new Map();
|
|
523
|
+
for (const e of log.events(scope, THREAD))
|
|
524
|
+
if (e.kind === "reaction") {
|
|
525
|
+
try {
|
|
526
|
+
const r = JSON.parse(e.content);
|
|
527
|
+
if (!r?.to) continue;
|
|
528
|
+
const on = r.by === "user" ? theirs : its;
|
|
529
|
+
if (r.emoji) on.set(r.to, r.emoji);
|
|
530
|
+
else on.delete(r.to);
|
|
531
|
+
} catch {
|
|
532
|
+
/* not one */
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return { its, theirs };
|
|
536
|
+
};
|
|
537
|
+
// What it said since the user last wrote, with when each was said and when it was first in front of the user, if it was. For it to know whether it was heard; nothing is done with this in code.
|
|
538
|
+
const unanswered = (present) => {
|
|
539
|
+
if (!feel().seen) return {};
|
|
540
|
+
const said = log.events(scope, THREAD).filter((e) => e.content && ["user", "assistant"].includes(e.role)),
|
|
541
|
+
seen = marks("brain:seen"),
|
|
542
|
+
theirs = reactions().theirs;
|
|
543
|
+
let end = said.length;
|
|
544
|
+
if (present?.kind === "the user wrote") end = said.map((e) => e.id).lastIndexOf(origin);
|
|
545
|
+
if (end < 0) end = said.length;
|
|
546
|
+
const mine = [];
|
|
547
|
+
for (let i = end - 1; i >= 0 && said[i].role === "assistant" && mine.length < 4; i--)
|
|
548
|
+
mine.unshift({
|
|
549
|
+
said: new Date(said[i].occurredAt).toISOString(),
|
|
550
|
+
seen: seen[said[i].id] ? new Date(seen[said[i].id]).toISOString() : null,
|
|
551
|
+
words: cut(said[i].content, 60),
|
|
552
|
+
...(theirs.get(said[i].id) ? { reaction: theirs.get(said[i].id) } : {}),
|
|
553
|
+
});
|
|
554
|
+
return mine.length ? { unanswered: mine } : {};
|
|
555
|
+
};
|
|
556
|
+
// The times it has set to look at something or to speak, soonest first. A watch on a worker is its own business.
|
|
557
|
+
const standing = () => wake.alarms.filter((a) => !String(a.ref ?? "").startsWith("watch:")).sort((a, b) => a.at - b.at);
|
|
558
|
+
|
|
559
|
+
// What it keeps to bring up when the user is next around. No time is set on these; each is in its own words, from the moment it kept it.
|
|
560
|
+
const held = () => (log.state("brain:mind", null) ?? []).filter((h) => h && typeof h.id === "string" && typeof h.about === "string");
|
|
561
|
+
|
|
562
|
+
// --- One moment of attention ---------------------------------------------------
|
|
563
|
+
const think = async (request, present) => {
|
|
564
|
+
// An earlier message that came with files says so, by name, where the model reads it.
|
|
565
|
+
// After a new page, only what was said since is in front of it (and the words it is answering, whenever they were said).
|
|
566
|
+
const page = log.state("brain:page", null) ?? 0;
|
|
567
|
+
const recent = log
|
|
568
|
+
.events(scope, THREAD)
|
|
569
|
+
.filter((e) => e.content && ["user", "assistant", "tool"].includes(e.role) && ((e.occurredAt ?? 0) > page || e.id === request.id))
|
|
570
|
+
.slice(-cfg.recent)
|
|
571
|
+
.map((e) =>
|
|
572
|
+
e.metadata?.files?.length && e.id !== request.id
|
|
573
|
+
? { ...e, content: `${e.content}\n[handed over: ${e.metadata.files.map((f) => f.name).join(", ")}]` }
|
|
574
|
+
: e,
|
|
575
|
+
);
|
|
576
|
+
let reply = "",
|
|
577
|
+
more = [],
|
|
578
|
+
acts = [];
|
|
579
|
+
const zone = cfg.zone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
580
|
+
const here = new Intl.DateTimeFormat("sv-SE", { timeZone: zone, dateStyle: "short", timeStyle: "short" }).format(new Date(log.now()));
|
|
581
|
+
// The conversation never ends and is never summarised away: every word of
|
|
582
|
+
// it stays in the store. What is in front of the model at one moment is
|
|
583
|
+
// the last few records, what memory brings, and this: one line for each
|
|
584
|
+
// earlier exchange that has been read into memory, so it knows where the
|
|
585
|
+
// conversation has been without carrying it.
|
|
586
|
+
const first = recent[0]?.occurredAt ?? log.now(),
|
|
587
|
+
shown = new Set(recent.map((e) => e.id));
|
|
588
|
+
const earlier = core
|
|
589
|
+
.episodes()
|
|
590
|
+
.filter((e) => e.sessionId === THREAD && e.scene && e.at < first && e.at > page && !(e.events ?? []).some((id) => shown.has(id)))
|
|
591
|
+
.sort((a, b) => a.at - b.at)
|
|
592
|
+
.slice(-cfg.earlier)
|
|
593
|
+
.map((e) => ({
|
|
594
|
+
at: new Intl.DateTimeFormat("sv-SE", { timeZone: zone, dateStyle: "short", timeStyle: "short" }).format(new Date(e.at)),
|
|
595
|
+
about: e.scene,
|
|
596
|
+
}));
|
|
597
|
+
const input = (found) => ({
|
|
598
|
+
present,
|
|
599
|
+
clock: { zone, here },
|
|
600
|
+
...(earlier.length ? { earlier } : {}),
|
|
601
|
+
...(manner() ? { manner: manner().text } : {}),
|
|
602
|
+
workers: Object.entries(workers).map(([name, w]) => ({ name, about: w.about ?? "" })),
|
|
603
|
+
tasks: [...tasks.values()].slice(-8).map(brief),
|
|
604
|
+
...(standing().length
|
|
605
|
+
? {
|
|
606
|
+
waking: standing()
|
|
607
|
+
.slice(0, 8)
|
|
608
|
+
.map((w) => ({ id: w.id, at: new Date(w.at).toISOString(), why: w.why, ...(w.every ? { every: w.every } : {}) })),
|
|
609
|
+
}
|
|
610
|
+
: {}),
|
|
611
|
+
...unanswered(present),
|
|
612
|
+
...(held().length ? { mind: held().map((h) => ({ id: h.id, since: new Date(h.at).toISOString(), about: h.about })) } : {}),
|
|
613
|
+
...(feel().express && expressions().length
|
|
614
|
+
? { expressions: expressions().map((x) => ({ name: x.name, ...(x.shows ? { shows: x.shows } : {}) })) }
|
|
615
|
+
: {}),
|
|
616
|
+
...(feel().react ? {} : { reactions: "off" }),
|
|
617
|
+
...([...asks.values()].some((a) => a.kind === "question")
|
|
618
|
+
? {
|
|
619
|
+
questions: [...asks.values()]
|
|
620
|
+
.filter((a) => a.kind === "question")
|
|
621
|
+
.map((a) => ({
|
|
622
|
+
ask: a.id,
|
|
623
|
+
task: a.task,
|
|
624
|
+
from: a.to,
|
|
625
|
+
questions: a.questions.map((q) => ({
|
|
626
|
+
id: q.id,
|
|
627
|
+
question: q.question,
|
|
628
|
+
options: q.options.map((o) => o.label),
|
|
629
|
+
...(q.multi ? { many: true } : {}),
|
|
630
|
+
...(q.approval ? { leave: true } : {}),
|
|
631
|
+
})),
|
|
632
|
+
})),
|
|
633
|
+
}
|
|
634
|
+
: {}),
|
|
635
|
+
...(present.away ? { away: { from: new Date(present.away.from).toISOString(), to: new Date(present.away.to).toISOString() } } : {}),
|
|
636
|
+
...(found ? { found } : {}),
|
|
637
|
+
});
|
|
638
|
+
const speak = (found) => ({
|
|
639
|
+
input: input(found),
|
|
640
|
+
draft: () => ({ reply, acts }),
|
|
641
|
+
heard: (a) => {
|
|
642
|
+
// What follows the reply belongs to that reply: a later answer that says the reply again says what follows it again, or that nothing does.
|
|
643
|
+
if (typeof a.reply === "string") {
|
|
644
|
+
reply = a.reply;
|
|
645
|
+
more = Array.isArray(a.more) ? a.more : [];
|
|
646
|
+
}
|
|
647
|
+
if (Array.isArray(a.acts)) acts = a.acts;
|
|
648
|
+
},
|
|
649
|
+
});
|
|
650
|
+
// One moment has a ceiling. The length of the conversation does not add
|
|
651
|
+
// to a call: the records shown, the lines of `earlier` and the candidates
|
|
652
|
+
// are each a fixed number of bounded pieces. What can be large is what
|
|
653
|
+
// arrives at once: a long message and files with it. Those are fitted to
|
|
654
|
+
// the model that speaks (seven tenths of its window when the host knows
|
|
655
|
+
// it, counted as one token a character, which is the worst case), and
|
|
656
|
+
// what was cut is marked as cut, so it is said and not guessed past.
|
|
657
|
+
let window = null;
|
|
658
|
+
try {
|
|
659
|
+
window = await models?.window?.();
|
|
660
|
+
} catch {
|
|
661
|
+
/* not known */
|
|
662
|
+
}
|
|
663
|
+
const budget = Math.min(cfg.promptChars, Number.isFinite(window) && window > 0 ? Math.floor(window * 0.7) : Infinity);
|
|
664
|
+
// Of what is left after the fixed part (the rules, the charter), memory's candidates may take a little under half, and what is said takes the rest.
|
|
665
|
+
const open = Math.max(12000, budget - cfg.fixedChars),
|
|
666
|
+
candidateChars = Math.min(cfg.candidateChars, Math.max(6000, Math.floor(open * 0.45)));
|
|
667
|
+
const older = recent.filter((e) => e.id !== request.id).reduce((n, e) => n + Math.min(e.content.length, 1200), 0);
|
|
668
|
+
const texts = (present.files ?? []).filter((f) => typeof f.text === "string");
|
|
669
|
+
let left = Math.max(2000, open - candidateChars - older);
|
|
670
|
+
const mine = Math.min(cfg.presentChars, Math.max(2000, Math.floor(left * (texts.length ? 0.5 : 1))));
|
|
671
|
+
left = Math.max(0, left - Math.min(mine, request.content.length));
|
|
672
|
+
if (texts.length) {
|
|
673
|
+
const each = Math.max(400, Math.floor(left / texts.length));
|
|
674
|
+
for (const f of texts)
|
|
675
|
+
if (f.text.length > each) {
|
|
676
|
+
f.text = cut(f.text, each);
|
|
677
|
+
f.cut = true;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
let trace = await core.prepare({
|
|
681
|
+
request,
|
|
682
|
+
recent,
|
|
683
|
+
infer: model,
|
|
684
|
+
judge,
|
|
685
|
+
admission: judge ? "shadow" : "model",
|
|
686
|
+
reading: "one",
|
|
687
|
+
wide: { ids: new Set([request.id]), n: mine },
|
|
688
|
+
candidateChars,
|
|
689
|
+
speak: speak(),
|
|
690
|
+
});
|
|
691
|
+
// Deliberate recall: once, and then it answers with what was found.
|
|
692
|
+
const search = acts.find((a) => a?.act === "search" && typeof a.query === "string" && a.query.trim());
|
|
693
|
+
if (search && !trace.error) {
|
|
694
|
+
const found = { query: cut(search.query, 200), ...core.search(search.query) };
|
|
695
|
+
acts = acts.filter((a) => a !== search);
|
|
696
|
+
trace = await core.prepare({
|
|
697
|
+
request,
|
|
698
|
+
recent,
|
|
699
|
+
infer: model,
|
|
700
|
+
judge,
|
|
701
|
+
admission: judge ? "shadow" : "model",
|
|
702
|
+
reading: "one",
|
|
703
|
+
wide: { ids: new Set([request.id]), n: mine },
|
|
704
|
+
candidateChars,
|
|
705
|
+
speak: speak(found),
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
// How the last calling of memories went, for whoever watches it grow: the time is recall's own, without the model.
|
|
709
|
+
lastRecall = {
|
|
710
|
+
ms: trace.recallMs ?? null,
|
|
711
|
+
candidates: trace.candidates?.length ?? 0,
|
|
712
|
+
crowded: trace.crowded ?? 0,
|
|
713
|
+
memories: core.items().length,
|
|
714
|
+
at: log.now(),
|
|
715
|
+
};
|
|
716
|
+
const opening = typeof reply === "string" ? reply.trim() : "";
|
|
717
|
+
return {
|
|
718
|
+
reply: opening,
|
|
719
|
+
// Two more at most, and only after a first: a reply in pieces is still one reply.
|
|
720
|
+
more: opening
|
|
721
|
+
? more
|
|
722
|
+
.filter((m) => typeof m === "string" && m.trim())
|
|
723
|
+
.map((m) => m.trim())
|
|
724
|
+
.slice(0, 2)
|
|
725
|
+
: [],
|
|
726
|
+
acts: acts.filter((a) => a?.act !== "search"),
|
|
727
|
+
trace,
|
|
728
|
+
};
|
|
729
|
+
};
|
|
730
|
+
const attend = async (event) => {
|
|
731
|
+
thinking = true;
|
|
732
|
+
const since = log.now();
|
|
733
|
+
halt = new AbortController();
|
|
734
|
+
const mine = halt;
|
|
735
|
+
emit({ type: "thinking", on: true, since });
|
|
736
|
+
thinkingSince = since;
|
|
737
|
+
try {
|
|
738
|
+
let request, present;
|
|
739
|
+
hushed = event.kind === "return";
|
|
740
|
+
own();
|
|
741
|
+
if (event.kind === "user") {
|
|
742
|
+
const files = (event.files ?? []).map(fileOf).filter(Boolean),
|
|
743
|
+
listed = files.map(({ id, name, type, size }) => ({ id, name, type, size }));
|
|
744
|
+
// Words are the user's; a message of files alone is recorded by their names.
|
|
745
|
+
const about = event.replyTo ? log.events(scope, THREAD).find((e) => e.id === event.replyTo && e.content) : null,
|
|
746
|
+
replyTo = about ? { id: about.id, role: about.role, words: cut(about.content, 140) } : null;
|
|
747
|
+
endTurn();
|
|
748
|
+
request = add(
|
|
749
|
+
"user",
|
|
750
|
+
event.text || `[${files.map((f) => f.name).join(", ")}]`,
|
|
751
|
+
undefined,
|
|
752
|
+
files.length || replyTo ? { ...(files.length ? { files: listed } : {}), ...(replyTo ? { replyTo: replyTo.id } : {}) } : undefined,
|
|
753
|
+
);
|
|
754
|
+
turnOpen = true;
|
|
755
|
+
origin = request.id;
|
|
756
|
+
steps = 0;
|
|
757
|
+
present = {
|
|
758
|
+
kind: "the user wrote",
|
|
759
|
+
...(replyTo
|
|
760
|
+
? {
|
|
761
|
+
replying: {
|
|
762
|
+
to: replyTo.role === "assistant" ? "something you said" : "something they said",
|
|
763
|
+
at: new Date(about.occurredAt).toISOString(),
|
|
764
|
+
words: cut(about.content, 600),
|
|
765
|
+
},
|
|
766
|
+
}
|
|
767
|
+
: {}),
|
|
768
|
+
...(files.length
|
|
769
|
+
? {
|
|
770
|
+
files: files.map((f) => {
|
|
771
|
+
const text = beginning(f);
|
|
772
|
+
return {
|
|
773
|
+
name: f.name,
|
|
774
|
+
type: f.type,
|
|
775
|
+
size: f.size,
|
|
776
|
+
path: f.path,
|
|
777
|
+
...(text !== null ? { text, ...(text.endsWith("…") ? { cut: true } : {}) } : {}),
|
|
778
|
+
};
|
|
779
|
+
}),
|
|
780
|
+
}
|
|
781
|
+
: {}),
|
|
782
|
+
...(event.away ? { away: event.away } : {}),
|
|
783
|
+
};
|
|
784
|
+
emit({
|
|
785
|
+
type: "message",
|
|
786
|
+
role: "user",
|
|
787
|
+
text: request.content,
|
|
788
|
+
at: request.occurredAt,
|
|
789
|
+
id: request.id,
|
|
790
|
+
...(files.length ? { files: listed } : {}),
|
|
791
|
+
...(replyTo ? { replyTo } : {}),
|
|
792
|
+
});
|
|
793
|
+
// A picture is looked at before it is answered, where the model that speaks can see: it is shown the picture with the user's words and says what is there,
|
|
794
|
+
// and that stands with the file as what was seen. Three at most, and none larger than a model will take. Where no model can see, the picture stays unseen
|
|
795
|
+
// and can still be handed to a worker with its path, as any file can.
|
|
796
|
+
if (models?.see && present.files) {
|
|
797
|
+
const pictures = present.files.filter((f) => /^image\/(png|jpeg|webp|gif)$/.test(f.type) && f.size <= 4000000).slice(0, 3);
|
|
798
|
+
await Promise.all(
|
|
799
|
+
pictures.map(async (f) => {
|
|
800
|
+
try {
|
|
801
|
+
const said = await models.see(
|
|
802
|
+
`data:${f.type};base64,${readFileSync(f.path).toString("base64")}`,
|
|
803
|
+
`A person handed this picture to an assistant with these words: "${cut(request.content, 300)}". Say what the picture shows, and whatever in it bears on those words; give short text in it word for word. At most 120 words, in the language of the person's words. Return {"shows":"..."}.`,
|
|
804
|
+
);
|
|
805
|
+
const shows = typeof said?.shows === "string" ? cut(said.shows.trim(), 900) : "";
|
|
806
|
+
if (shows) f.seen = shows;
|
|
807
|
+
} catch {
|
|
808
|
+
/* it stays unseen */
|
|
809
|
+
}
|
|
810
|
+
}),
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
// It has this in front of it now: read, as a person's message is read when they take it up. Anything of the user's said before it and not yet taken up is read with it.
|
|
814
|
+
for (const e of log.events(scope, THREAD))
|
|
815
|
+
if (e.role === "user" && e.content && mark("brain:read", e.id, log.now())) emit({ type: "read", id: e.id, at: log.now() });
|
|
816
|
+
} else if (event.kind === "worker") {
|
|
817
|
+
const task = tasks.get(event.task);
|
|
818
|
+
const where = task.session ? ` (its session: ${task.session})` : "";
|
|
819
|
+
const text = event.error
|
|
820
|
+
? `${task.to} failed on "${cut(task.task, 200)}"${where}: ${event.error}`
|
|
821
|
+
: `${task.to} ${event.outcome.stopReason === "end_turn" ? "finished" : `stopped (${event.outcome.stopReason})`} "${cut(task.task, 200)}".\nIt said: ${cut(event.outcome.said || "(nothing)", cfg.resultChars)}${event.outcome.did.length ? `\nIt did: ${cut(event.outcome.did.map((d) => `${d.title} [${d.status}]`).join("; "), 1200)}` : ""}`;
|
|
822
|
+
request = add("tool", text, "tool/result", {
|
|
823
|
+
tool: { phase: "result", name: task.to, execution: event.error ? "failed" : "completed" },
|
|
824
|
+
task: task.id,
|
|
825
|
+
});
|
|
826
|
+
if (!turnOpen) turnOpen = true;
|
|
827
|
+
present = { kind: event.error ? "a worker failed" : "a worker came back", task: task.id, ...(event.away ? { away: event.away } : {}) };
|
|
828
|
+
} else if (event.kind === "question") {
|
|
829
|
+
const ask = asks.get(event.ask);
|
|
830
|
+
if (!ask) return;
|
|
831
|
+
const task = tasks.get(ask.task);
|
|
832
|
+
request = add(
|
|
833
|
+
"tool",
|
|
834
|
+
`${ask.to}, working on "${cut(task?.task ?? "", 200)}", asks before going on:\n${ask.questions.map((q) => `${q.question}${q.detail ? `\n${q.detail}` : ""}\nOptions: ${q.options.map((o) => o.label + (o.description ? ` (${o.description})` : "")).join(" | ") || "(none: words)"}`).join("\n")}`,
|
|
835
|
+
"tool/result",
|
|
836
|
+
{ tool: { phase: "result", name: ask.to, execution: "completed" }, task: ask.task },
|
|
837
|
+
);
|
|
838
|
+
if (!turnOpen) turnOpen = true;
|
|
839
|
+
present = { kind: "a worker asks", ask: ask.id, task: ask.task };
|
|
840
|
+
} else if (event.kind === "alarm") {
|
|
841
|
+
const lost = event.ref?.startsWith?.("watch:") ? tasks.get(event.ref.slice(6)) : null;
|
|
842
|
+
if (lost && lost.state !== "running") return;
|
|
843
|
+
request = add(
|
|
844
|
+
"tool",
|
|
845
|
+
`A time you set has come${event.late ? `, ${Math.round(event.late / 60000)} minutes late because you were not running` : ""}: ${event.why}`,
|
|
846
|
+
"tool/result",
|
|
847
|
+
{ tool: { phase: "result", name: "clock", execution: "completed" } },
|
|
848
|
+
);
|
|
849
|
+
if (!turnOpen) turnOpen = true;
|
|
850
|
+
present = { kind: "a time you set has come", why: event.why, ...(event.away ? { away: event.away } : {}) };
|
|
851
|
+
} else if (event.kind === "return") {
|
|
852
|
+
// The user is here again after a time away, and something was kept to bring up. Whether it is brought up is its own to decide; mostly it is not.
|
|
853
|
+
if (!held().length) return;
|
|
854
|
+
const hours = Math.max(1, Math.round((event.gone.to - event.gone.from) / 3600000));
|
|
855
|
+
request = add("tool", `The user is here again, after about ${hours} ${hours === 1 ? "hour" : "hours"} away.`, "tool/result", {
|
|
856
|
+
tool: { phase: "result", name: "clock", execution: "completed" },
|
|
857
|
+
});
|
|
858
|
+
if (!turnOpen) turnOpen = true;
|
|
859
|
+
present = {
|
|
860
|
+
kind: "the user is back",
|
|
861
|
+
gone: { from: new Date(event.gone.from).toISOString(), to: new Date(event.gone.to).toISOString() },
|
|
862
|
+
note: "Nothing is asked of you and the user has said nothing yet.",
|
|
863
|
+
};
|
|
864
|
+
} else if (event.kind === "born") {
|
|
865
|
+
request = add("tool", "You have just been woken for the first time.", "tool/result", {
|
|
866
|
+
tool: { phase: "result", name: "clock", execution: "completed" },
|
|
867
|
+
});
|
|
868
|
+
if (!turnOpen) turnOpen = true;
|
|
869
|
+
present = {
|
|
870
|
+
kind: "you were just woken for the first time",
|
|
871
|
+
...(event.language ? { language: event.language } : {}),
|
|
872
|
+
note: "Nothing has been said yet and nothing is asked of you. Greet the person, briefly, in your own voice, in the language their screen is in (language, when given, is its tag).",
|
|
873
|
+
};
|
|
874
|
+
} else return;
|
|
875
|
+
const { reply, more, acts, trace } = await think(request, present);
|
|
876
|
+
// Stopped by the user while it thought: nothing is said and nothing is done, and it is on record that this is why.
|
|
877
|
+
if (mine.signal.aborted) {
|
|
878
|
+
add("tool", "The user stopped this before you answered. Nothing was said and nothing was done.", "tool/result", {
|
|
879
|
+
tool: { phase: "result", name: "asteme", execution: "cancelled" },
|
|
880
|
+
});
|
|
881
|
+
emit({ type: "stopped" });
|
|
882
|
+
if (!running().length) endTurn();
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (trace.error && !reply) wrong(`Thinking failed: ${cut(trace.error, 200)}. Your message is kept.`);
|
|
886
|
+
// Silence is never left unexplained: words from the user that got neither words nor a sign nor anything done say so.
|
|
887
|
+
else if (event.kind === "user" && !reply && !acts.length)
|
|
888
|
+
wrong(
|
|
889
|
+
trace.private
|
|
890
|
+
? "Nothing was read: this conversation was marked as not remembered. The mark has been taken off; say it again."
|
|
891
|
+
: // With a judge beside the model, a call that fails is set aside so the judge can still admit memories; nothing then speaks. The reason is the call's, and is said.
|
|
892
|
+
trace.sceneError
|
|
893
|
+
? `The model could not be reached: ${cut(trace.sceneError, 200)}. Your message is kept.`
|
|
894
|
+
: "Nothing came back from the model. Your message is kept; say it again.",
|
|
895
|
+
);
|
|
896
|
+
const did = acts.map((a) => act(a, present)).filter(Boolean);
|
|
897
|
+
const refused = did.filter((d) => d.refused);
|
|
898
|
+
if (refused.length)
|
|
899
|
+
add("tool", `Not done: ${refused.map((r) => `${r.refused} (${r.why})`).join("; ")}`, "tool/result", {
|
|
900
|
+
tool: { phase: "result", name: "asteme", execution: "failed" },
|
|
901
|
+
});
|
|
902
|
+
// What it promised in this moment is kept with the words it said then: the line under them is that record.
|
|
903
|
+
const promised = did
|
|
904
|
+
.filter((d) => d.promised)
|
|
905
|
+
.map((d) => ({ at: d.promised.at, why: d.promised.why, ...(d.promised.every ? { every: d.promised.every } : {}) })),
|
|
906
|
+
expression = did.find((d) => d.expressed)?.expressed;
|
|
907
|
+
const with_ = { ...(promised.length ? { promised } : {}), ...(expression ? { expression } : {}) };
|
|
908
|
+
if (reply) {
|
|
909
|
+
const said = add("assistant", reply, undefined, Object.keys(with_).length ? with_ : undefined);
|
|
910
|
+
emit({
|
|
911
|
+
type: "message",
|
|
912
|
+
role: "assistant",
|
|
913
|
+
text: reply,
|
|
914
|
+
at: said.occurredAt,
|
|
915
|
+
id: said.id,
|
|
916
|
+
...with_,
|
|
917
|
+
used: trace.delivered.map((i) => ({ id: i.id, use: i.use, text: cut(i.text, 200) })),
|
|
918
|
+
});
|
|
919
|
+
// What it says right after, each a message of its own, a moment apart. Stopped in between, the rest is not said.
|
|
920
|
+
if (more.length) {
|
|
921
|
+
hushed = false;
|
|
922
|
+
write(true);
|
|
923
|
+
}
|
|
924
|
+
for (const text of more) {
|
|
925
|
+
await new Promise((done) => {
|
|
926
|
+
const t = setTimeout(done, Math.min(cfg.pauseMax, cfg.pauseMs + text.length * cfg.pauseChar));
|
|
927
|
+
mine.signal.addEventListener(
|
|
928
|
+
"abort",
|
|
929
|
+
() => {
|
|
930
|
+
clearTimeout(t);
|
|
931
|
+
done();
|
|
932
|
+
},
|
|
933
|
+
{ once: true },
|
|
934
|
+
);
|
|
935
|
+
});
|
|
936
|
+
if (mine.signal.aborted) break;
|
|
937
|
+
const next = add("assistant", text);
|
|
938
|
+
emit({ type: "message", role: "assistant", text, at: next.occurredAt, id: next.id });
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
// The matter is closed for now when nothing is out; reflection reads it whole.
|
|
942
|
+
if (!running().length) endTurn();
|
|
943
|
+
} finally {
|
|
944
|
+
thinking = false;
|
|
945
|
+
thinkingSince = null;
|
|
946
|
+
if (halt === mine) halt = null;
|
|
947
|
+
hushed = false;
|
|
948
|
+
write(false);
|
|
949
|
+
emit({ type: "thinking", on: false });
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
// --- Quiet moments ---------------------------------------------------------------
|
|
953
|
+
// light: what just happened is read into memory. deep (asleep): outcomes and consolidation too.
|
|
954
|
+
const rest = async (depth) => {
|
|
955
|
+
const before = core.items().length;
|
|
956
|
+
try {
|
|
957
|
+
return await round(depth);
|
|
958
|
+
} finally {
|
|
959
|
+
if (core.items().length !== before) emit({ type: "learned", memories: core.items().length });
|
|
960
|
+
}
|
|
961
|
+
};
|
|
962
|
+
const round = async (depth) => {
|
|
963
|
+
if (shared) return false;
|
|
964
|
+
const turn = log.pending(identity, STAGE)[0];
|
|
965
|
+
if (turn) {
|
|
966
|
+
await core.reflect(turn, model);
|
|
967
|
+
return true;
|
|
968
|
+
}
|
|
969
|
+
if (core.outcomeCandidates(log.now(), { delay: depth === "deep" ? 0 : 60000 }).length) {
|
|
970
|
+
await core.outcomes({ infer: model, judge, mode: "shadow", ...(depth === "deep" ? { delay: 0 } : {}) });
|
|
971
|
+
return log.pending(identity, STAGE).length > 0;
|
|
972
|
+
}
|
|
973
|
+
if (depth === "deep" && (await core.sleepDue())) {
|
|
974
|
+
await core.sleep({ infer: model, budget: 1 });
|
|
975
|
+
return true;
|
|
976
|
+
}
|
|
977
|
+
return false;
|
|
978
|
+
};
|
|
979
|
+
// What went wrong is said on the page and also kept, where a report can find it afterwards: a page nobody was looking at is not a record.
|
|
980
|
+
const wrong = (text) => {
|
|
981
|
+
try {
|
|
982
|
+
core.note("brain-error", { text: cut(text, 300) });
|
|
983
|
+
} catch {
|
|
984
|
+
/* the store is closed */
|
|
985
|
+
}
|
|
986
|
+
emit({ type: "error", text });
|
|
987
|
+
};
|
|
988
|
+
wake.failed = (e, event) => wrong(`${event.kind}: ${cut(e.message, 200)}`);
|
|
989
|
+
// The conversation with Asteme is its memory: it cannot be one that is "not remembered". A store where that was set (the panel once offered it) answered nothing, without a word; the mark is taken off wherever it is found.
|
|
990
|
+
const own = () => {
|
|
991
|
+
try {
|
|
992
|
+
if (core.quiet?.(THREAD)) core.setQuiet(THREAD, false);
|
|
993
|
+
if (core.projectOff?.(scope.projectId)) core.setProjectOff(scope.projectId, false);
|
|
994
|
+
} catch {
|
|
995
|
+
/* an older core */
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
wake.on({ attend, rest, holds: () => running().length > 0 || thinking, changed: (state) => emit({ type: "state", state }) });
|
|
999
|
+
|
|
1000
|
+
return {
|
|
1001
|
+
core,
|
|
1002
|
+
log,
|
|
1003
|
+
wake,
|
|
1004
|
+
start() {
|
|
1005
|
+
own();
|
|
1006
|
+
for (const t of tasks.values())
|
|
1007
|
+
if (t.state === "lost") {
|
|
1008
|
+
t.state = "failed";
|
|
1009
|
+
t.endedAt = log.now();
|
|
1010
|
+
wake.stimulus({ kind: "worker", task: t.id, error: "Asteme stopped while this was out; the result was not seen" });
|
|
1011
|
+
}
|
|
1012
|
+
keepTasks();
|
|
1013
|
+
wake.start();
|
|
1014
|
+
return this;
|
|
1015
|
+
},
|
|
1016
|
+
/** The user speaks. */
|
|
1017
|
+
say(text, files = [], replyTo = null) {
|
|
1018
|
+
const ids = Array.isArray(files) ? files.filter((id) => fileOf(id)).slice(0, cfg.filesAtOnce) : [];
|
|
1019
|
+
if (typeof text !== "string" || (!text.trim() && !ids.length)) throw new Error("Say something");
|
|
1020
|
+
if (log.state("brain:draft", null)) log.save("brain:draft", null);
|
|
1021
|
+
// Whoever speaks is here.
|
|
1022
|
+
log.save("brain:here", log.now());
|
|
1023
|
+
// Said in answer to one thing that was said before: it is named, so that "that one" has something to point at.
|
|
1024
|
+
const about =
|
|
1025
|
+
typeof replyTo === "string"
|
|
1026
|
+
? log.events(scope, THREAD).find((e) => e.id === replyTo && e.content && ["user", "assistant"].includes(e.role))
|
|
1027
|
+
: null;
|
|
1028
|
+
wake.stimulus({ kind: "user", text: text.trim(), ...(ids.length ? { files: ids } : {}), ...(about ? { replyTo: about.id } : {}) });
|
|
1029
|
+
},
|
|
1030
|
+
/** A file the user hands over: kept beside the store until a message carries it. */
|
|
1031
|
+
keep({ name, type, bytes }) {
|
|
1032
|
+
if (!(bytes instanceof Uint8Array) || !bytes.length) throw new Error("The file is empty");
|
|
1033
|
+
if (bytes.length > cfg.fileBytes) throw new Error(`The file is larger than ${Math.round(cfg.fileBytes / 1e6)} MB`);
|
|
1034
|
+
const id = randomUUID(),
|
|
1035
|
+
clean = cut(
|
|
1036
|
+
String(name ?? "file")
|
|
1037
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_")
|
|
1038
|
+
.replace(/^\.+/, "")
|
|
1039
|
+
.trim() || "file",
|
|
1040
|
+
120,
|
|
1041
|
+
).replace(/…$/, "");
|
|
1042
|
+
const kept = {
|
|
1043
|
+
id,
|
|
1044
|
+
name: clean,
|
|
1045
|
+
type: /^[\w.+-]+\/[\w.+-]+$/.test(type ?? "") ? type : "application/octet-stream",
|
|
1046
|
+
size: bytes.length,
|
|
1047
|
+
file: `${id}${extname(clean)
|
|
1048
|
+
.toLowerCase()
|
|
1049
|
+
.replace(/[^.a-z0-9]/g, "")}`,
|
|
1050
|
+
at: log.now(),
|
|
1051
|
+
};
|
|
1052
|
+
mkdirSync(filesDir, { recursive: true });
|
|
1053
|
+
writeFileSync(join(filesDir, kept.file), bytes, { mode: 0o600 });
|
|
1054
|
+
log.save(`brain:file:${id}`, kept);
|
|
1055
|
+
return { id, name: kept.name, type: kept.type, size: kept.size };
|
|
1056
|
+
},
|
|
1057
|
+
file: (id) => fileOf(id),
|
|
1058
|
+
/** Which model speaks, and which it could be changed to. A host lends these; alone there is the one it was started with. */
|
|
1059
|
+
async models() {
|
|
1060
|
+
const now = (await models?.now?.()) ?? null;
|
|
1061
|
+
let window = null;
|
|
1062
|
+
try {
|
|
1063
|
+
window = (await models?.window?.()) ?? null;
|
|
1064
|
+
} catch {
|
|
1065
|
+
/* not known */
|
|
1066
|
+
}
|
|
1067
|
+
return plain({ now: now && { ...now, window }, list: (await models?.list?.()) ?? [] });
|
|
1068
|
+
},
|
|
1069
|
+
async model(choice) {
|
|
1070
|
+
if (!models?.choose) throw new Error("The model is set where Asteme was started");
|
|
1071
|
+
// How hard it thinks before it speaks is chosen apart from which model: `effort` alone changes only that.
|
|
1072
|
+
if (choice && typeof choice.effort === "string" && !("model" in choice)) {
|
|
1073
|
+
if (!models.effort) throw new Error("This model has nothing to choose there");
|
|
1074
|
+
await models.effort(choice.effort || null);
|
|
1075
|
+
} else
|
|
1076
|
+
await models.choose(
|
|
1077
|
+
choice && typeof choice.provider === "string" && typeof choice.model === "string"
|
|
1078
|
+
? { provider: choice.provider, model: choice.model }
|
|
1079
|
+
: null,
|
|
1080
|
+
);
|
|
1081
|
+
emit({ type: "model" });
|
|
1082
|
+
return this.models();
|
|
1083
|
+
},
|
|
1084
|
+
/** A recording turned into words, by the host's own recognizer. Nothing is sent as a message and the sound is not kept. */
|
|
1085
|
+
async hear(bytes) {
|
|
1086
|
+
if (!hear?.transcribe) throw new Error("There is no speech recognition here");
|
|
1087
|
+
if (!(bytes instanceof Uint8Array) || bytes.length < 100) throw new Error("Nothing was recorded");
|
|
1088
|
+
return plain(await hear.transcribe(plainWav(bytes)));
|
|
1089
|
+
},
|
|
1090
|
+
/** A time it set is taken back by the user. What it said when it set it stays said. */
|
|
1091
|
+
unwake(id) {
|
|
1092
|
+
if (held().some((h) => h.id === id))
|
|
1093
|
+
log.save(
|
|
1094
|
+
"brain:mind",
|
|
1095
|
+
held().filter((h) => h.id !== id),
|
|
1096
|
+
);
|
|
1097
|
+
else {
|
|
1098
|
+
if (!standing().some((w) => w.id === id)) throw new Error("That time is no longer set");
|
|
1099
|
+
wake.forget(id);
|
|
1100
|
+
}
|
|
1101
|
+
emit({ type: "intention" });
|
|
1102
|
+
return plain({
|
|
1103
|
+
intentions: standing()
|
|
1104
|
+
.slice(0, 8)
|
|
1105
|
+
.map((a) => ({ id: a.id, at: a.at, why: a.why, ...(a.every ? { every: a.every } : {}) })),
|
|
1106
|
+
});
|
|
1107
|
+
},
|
|
1108
|
+
/**
|
|
1109
|
+
* One of its own replies, for reading aloud. What is read is the stored
|
|
1110
|
+
* reply and nothing else. `as: "text"` gives the words for the device's
|
|
1111
|
+
* own voice; otherwise the lent voice reads them and its sound is handed
|
|
1112
|
+
* back as it comes. Nothing of the sound is kept.
|
|
1113
|
+
*/
|
|
1114
|
+
async aloud(id, { as = "sound", voice: which, signal } = {}) {
|
|
1115
|
+
const said = log.events(scope, THREAD).find((e) => e.id === id && e.role === "assistant" && e.content);
|
|
1116
|
+
if (!said) throw new Error("There is no such reply");
|
|
1117
|
+
const text = forVoice(said.content);
|
|
1118
|
+
if (as === "text") return plain({ text });
|
|
1119
|
+
if (!voice?.speak) throw new Error("No voice was lent here");
|
|
1120
|
+
if (!text) throw new Error("There are no words in it to read");
|
|
1121
|
+
const chosen = typeof which === "string" && which ? which : (log.state("brain:look", null) ?? {}).voice;
|
|
1122
|
+
return voice.speak(text, { voice: chosen, signal });
|
|
1123
|
+
},
|
|
1124
|
+
/** The user puts a sign on something Asteme said, or takes it off with an empty one. It is not a message: nothing is thought about because of it, and Asteme learns of it the next time it thinks. */
|
|
1125
|
+
react(id, emoji) {
|
|
1126
|
+
const said = log.events(scope, THREAD).find((e) => e.id === id && e.role === "assistant" && e.content);
|
|
1127
|
+
if (!said) throw new Error("There is no such reply");
|
|
1128
|
+
const sign = typeof emoji === "string" ? emoji.trim() : "";
|
|
1129
|
+
if (sign && (sign.length > 16 || !/^(\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u.test(sign)))
|
|
1130
|
+
throw new Error("A reaction is one pictograph");
|
|
1131
|
+
add("unknown", JSON.stringify({ to: id, emoji: sign, by: "user" }), "reaction");
|
|
1132
|
+
emit({ type: "reaction", to: id, emoji: sign, by: "user" });
|
|
1133
|
+
return plain({ to: id, emoji: sign });
|
|
1134
|
+
},
|
|
1135
|
+
/** The page had these replies in view: the user has seen them. */
|
|
1136
|
+
/** The store under it has been wiped. What it was holding in its head goes too: work that was out, questions waiting, times it had set, and the files it was handed. Whoever shows it is told to start over. */
|
|
1137
|
+
wiped() {
|
|
1138
|
+
halt?.abort();
|
|
1139
|
+
for (const h of handles.values()) {
|
|
1140
|
+
try {
|
|
1141
|
+
h.cancel?.();
|
|
1142
|
+
} catch {
|
|
1143
|
+
/* it is gone either way */
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
handles.clear();
|
|
1147
|
+
tasks.clear();
|
|
1148
|
+
asks.clear();
|
|
1149
|
+
wake.alarms = [];
|
|
1150
|
+
wake.queue = [];
|
|
1151
|
+
wake.keep();
|
|
1152
|
+
clearTimeout(greeting);
|
|
1153
|
+
greeting = null;
|
|
1154
|
+
turnOpen = false;
|
|
1155
|
+
origin = null;
|
|
1156
|
+
steps = 0;
|
|
1157
|
+
thinking = false;
|
|
1158
|
+
thinkingSince = null;
|
|
1159
|
+
lastRecall = null;
|
|
1160
|
+
try {
|
|
1161
|
+
rmSync(filesDir, { recursive: true, force: true });
|
|
1162
|
+
} catch {
|
|
1163
|
+
/* nothing was handed over */
|
|
1164
|
+
}
|
|
1165
|
+
emit({ type: "wiped" });
|
|
1166
|
+
},
|
|
1167
|
+
/** How many things Asteme has said that have not been in front of the user: for a mark on a tab or beside its name, where the conversation itself is not in view. Counted from when the conversation was last looked at, and from the user's own last words. */
|
|
1168
|
+
unseen() {
|
|
1169
|
+
const shown = log.state("brain:shown", 0) ?? 0,
|
|
1170
|
+
events = log.events(scope, THREAD);
|
|
1171
|
+
let from = 0;
|
|
1172
|
+
events.forEach((e, i) => {
|
|
1173
|
+
if (e.role === "user" && e.content) from = i + 1;
|
|
1174
|
+
});
|
|
1175
|
+
const seen = marks("brain:seen"),
|
|
1176
|
+
waiting = events.slice(from).filter((e) => e.role === "assistant" && e.content && e.occurredAt > shown && !seen[e.id]);
|
|
1177
|
+
return plain({ n: waiting.length, at: waiting.at(-1)?.occurredAt ?? null });
|
|
1178
|
+
},
|
|
1179
|
+
/** What the user is in the middle of writing, kept with the store so that it is still there after the program is closed, restarted or crashes. It is not said and not read: only held, and let go when it is sent or emptied. */
|
|
1180
|
+
draft(text) {
|
|
1181
|
+
const kept = typeof text === "string" && text ? cut(text, 20000) : null;
|
|
1182
|
+
if (kept !== log.state("brain:draft", null)) log.save("brain:draft", kept);
|
|
1183
|
+
return plain({ kept: !!kept });
|
|
1184
|
+
},
|
|
1185
|
+
/**
|
|
1186
|
+
* The user is in front of the conversation. After a time away, when
|
|
1187
|
+
* something was kept to bring up, that is an occasion: it is woken to
|
|
1188
|
+
* decide for itself whether to say it. Nothing is kept, nothing happens.
|
|
1189
|
+
*/
|
|
1190
|
+
here() {
|
|
1191
|
+
const now = log.now(),
|
|
1192
|
+
last = log.state("brain:here", null);
|
|
1193
|
+
if (!last || now - last > 60000) log.save("brain:here", now);
|
|
1194
|
+
const back = !!last && now - last >= cfg.absenceMs && held().length > 0 && !thinking && !running().length;
|
|
1195
|
+
if (back) wake.stimulus({ kind: "return", gone: { from: last, to: now } });
|
|
1196
|
+
return plain({ here: true, back });
|
|
1197
|
+
},
|
|
1198
|
+
seen(ids) {
|
|
1199
|
+
if (!Array.isArray(ids)) return plain({ seen: 0 });
|
|
1200
|
+
log.save("brain:shown", log.now());
|
|
1201
|
+
if (!feel().seen) return plain({ seen: 0 });
|
|
1202
|
+
const mine = new Set(
|
|
1203
|
+
log
|
|
1204
|
+
.events(scope, THREAD)
|
|
1205
|
+
.filter((e) => e.role === "assistant" && e.content)
|
|
1206
|
+
.map((e) => e.id),
|
|
1207
|
+
);
|
|
1208
|
+
const at = log.now();
|
|
1209
|
+
let n = 0;
|
|
1210
|
+
for (const id of ids.slice(0, 50)) if (mine.has(id) && mark("brain:seen", id, at)) n++;
|
|
1211
|
+
return plain({ seen: n, at });
|
|
1212
|
+
},
|
|
1213
|
+
/**
|
|
1214
|
+
* The user takes back something they said. Its words are erased from the
|
|
1215
|
+
* store, and with them anything remembered from them; what is left is
|
|
1216
|
+
* that a message was taken back, and when. If it was being thought about,
|
|
1217
|
+
* the thinking is ended. What Asteme already answered stays said.
|
|
1218
|
+
*/
|
|
1219
|
+
async retract(id) {
|
|
1220
|
+
const said = log.events(scope, THREAD).find((e) => e.id === id && e.role === "user" && e.content);
|
|
1221
|
+
if (!said) throw new Error("There is no such message of yours");
|
|
1222
|
+
if (thinking && origin === id) halt?.abort();
|
|
1223
|
+
// What was said in answer goes with it: the answer rests on the words that are being taken back, and may repeat them. So does work that was handed out for it and is still out.
|
|
1224
|
+
const all = log.events(scope, THREAD),
|
|
1225
|
+
from = all.findIndex((e) => e.id === id),
|
|
1226
|
+
answers = [];
|
|
1227
|
+
for (let i = from + 1; i < all.length; i++) {
|
|
1228
|
+
const e = all[i];
|
|
1229
|
+
if (e.role === "user" && e.content && e.kind !== "retraction") break;
|
|
1230
|
+
if (["assistant", "tool"].includes(e.role) && e.content) answers.push(e.id);
|
|
1231
|
+
}
|
|
1232
|
+
for (const t of tasks.values()) if (t.origin === id && t.state === "running") handles.get(t.id)?.cancel?.();
|
|
1233
|
+
const gone = all.filter((e) => answers.includes(e.id) && e.role === "assistant").map((e) => e.id);
|
|
1234
|
+
log.erase([id, ...answers]);
|
|
1235
|
+
add("unknown", JSON.stringify({ of: id, at: said.occurredAt }), "retraction");
|
|
1236
|
+
add(
|
|
1237
|
+
"tool",
|
|
1238
|
+
"The user took back a message they had sent. Its words are gone, and so is anything that was remembered from them. Do not refer to it.",
|
|
1239
|
+
"tool/result",
|
|
1240
|
+
{ tool: { phase: "result", name: "asteme", execution: "completed" } },
|
|
1241
|
+
);
|
|
1242
|
+
emit({ type: "retracted", id, also: gone });
|
|
1243
|
+
emit({ type: "learned", memories: core.items().length });
|
|
1244
|
+
await shared?.afterForget?.();
|
|
1245
|
+
return plain({ retracted: id });
|
|
1246
|
+
},
|
|
1247
|
+
/**
|
|
1248
|
+
* A new page in the one conversation. Nothing is erased: every word stays in the store, memories and their sources are as they were, and work and times set go on.
|
|
1249
|
+
* What changes is what is carried: from here it speaks without the last exchanges in front of it, as if the talk had just begun, and still with all it remembers.
|
|
1250
|
+
* Turned off, the conversation is one piece again.
|
|
1251
|
+
*/
|
|
1252
|
+
fresh(on = true) {
|
|
1253
|
+
log.save("brain:page", on === false ? null : log.now());
|
|
1254
|
+
emit({ type: "look" });
|
|
1255
|
+
return plain({ page: log.state("brain:page", null) ?? 0 });
|
|
1256
|
+
},
|
|
1257
|
+
/** The user stops what is being thought about for them. What they said is kept; nothing is answered and nothing is done. */
|
|
1258
|
+
stop() {
|
|
1259
|
+
if (!thinking || !halt || halt.signal.aborted) return plain({ stopped: false });
|
|
1260
|
+
halt.abort();
|
|
1261
|
+
return plain({ stopped: true });
|
|
1262
|
+
},
|
|
1263
|
+
/** Something was changed from outside the conversation (the panel that manages memory): whoever is looking at the page is told to look again. */
|
|
1264
|
+
touched() {
|
|
1265
|
+
emit({ type: "learned", memories: core.items().length });
|
|
1266
|
+
},
|
|
1267
|
+
/** The user answers a worker: leave to act (yes or no), or a question with its options. */
|
|
1268
|
+
answer(id, allow, answers) {
|
|
1269
|
+
const ask = asks.get(id);
|
|
1270
|
+
if (!ask) throw new Error("That question is no longer open");
|
|
1271
|
+
if (ask.kind === "question") return settle(ask, answers, "user");
|
|
1272
|
+
asks.delete(id);
|
|
1273
|
+
ask.answer(allow === true);
|
|
1274
|
+
add("unknown", JSON.stringify({ id, outcome: allow === true ? "allowed" : "denied", title: ask.title, to: ask.to }), "approval/decided");
|
|
1275
|
+
emit({ type: "answered", id, allow: allow === true });
|
|
1276
|
+
},
|
|
1277
|
+
// --- What the page opens: a memory, the list, itself, what it has been doing ---
|
|
1278
|
+
/** One memory in full, with the words it rests on. Asked for by the user, so a private one is shown. */
|
|
1279
|
+
memory(id) {
|
|
1280
|
+
const i = core.item(id);
|
|
1281
|
+
if (!i) throw new Error("Unknown memory");
|
|
1282
|
+
const why = core.why(id),
|
|
1283
|
+
stats = useStats(
|
|
1284
|
+
core.feedback().filter((f) => f.item === id),
|
|
1285
|
+
i.revision,
|
|
1286
|
+
);
|
|
1287
|
+
return plain({
|
|
1288
|
+
id: i.id,
|
|
1289
|
+
revision: i.revision,
|
|
1290
|
+
kind: i.kind === "concern" ? "matter" : i.level === "lesson" ? "lesson" : "noted",
|
|
1291
|
+
text: i.text,
|
|
1292
|
+
private: !!i.sensitive?.length,
|
|
1293
|
+
status: i.status,
|
|
1294
|
+
paused: !!i.paused,
|
|
1295
|
+
grounds: core.grounds(i),
|
|
1296
|
+
at: i.learnedAt,
|
|
1297
|
+
strength: accessibility(i, stats),
|
|
1298
|
+
...(i.closure?.when ? { closes: i.closure.when } : {}),
|
|
1299
|
+
sources: (i.evidence ?? []).slice(-3).map((e) => {
|
|
1300
|
+
const ev = log.event(e.id);
|
|
1301
|
+
return { quote: cut(e.quote, 300), role: ev?.role ?? "", at: ev?.occurredAt ?? null };
|
|
1302
|
+
}),
|
|
1303
|
+
helped: stats.helped,
|
|
1304
|
+
why: !!why,
|
|
1305
|
+
});
|
|
1306
|
+
},
|
|
1307
|
+
/** What the user does to one memory. The revision says which version they were looking at. */
|
|
1308
|
+
async change(id, revision, what) {
|
|
1309
|
+
const item = core.items({ closed: true }).find((i) => i.id === id);
|
|
1310
|
+
if (!item || item.revision !== revision) throw new Error("That memory has changed. Look at it again.");
|
|
1311
|
+
log.transaction(() => {
|
|
1312
|
+
if (what === "confirm") core.userConfirm(id, revision);
|
|
1313
|
+
else if (what === "retire") core.userRetire(id, revision, "");
|
|
1314
|
+
else if (what === "pause" || what === "resume") {
|
|
1315
|
+
core.write({ ...item, paused: what === "pause", revision: revision + 1 }, "User " + what);
|
|
1316
|
+
core.propagate(id, what === "pause" ? "was paused by the user" : "was resumed by the user");
|
|
1317
|
+
} else if (what === "forget") log.erase([...new Set(item.evidence.map((e) => e.id))]);
|
|
1318
|
+
else throw new Error("Unknown change");
|
|
1319
|
+
});
|
|
1320
|
+
// Forgetting is not finished while a copy made earlier still holds it.
|
|
1321
|
+
if (what === "forget") await shared?.afterForget?.();
|
|
1322
|
+
emit({ type: "learned", memories: core.items().length });
|
|
1323
|
+
return { done: what };
|
|
1324
|
+
},
|
|
1325
|
+
settle(a, b, keep) {
|
|
1326
|
+
core.userSettle(a, b, keep);
|
|
1327
|
+
emit({ type: "learned", memories: core.items().length });
|
|
1328
|
+
return { done: "settle" };
|
|
1329
|
+
},
|
|
1330
|
+
find(query) {
|
|
1331
|
+
const all = core.items().filter((i) => !i.paused),
|
|
1332
|
+
brief = (i) => ({
|
|
1333
|
+
id: i.id,
|
|
1334
|
+
kind: i.kind === "concern" ? "matter" : i.level === "lesson" ? "lesson" : "noted",
|
|
1335
|
+
text: i.sensitive?.length ? "" : cut(i.text, 200),
|
|
1336
|
+
private: !!i.sensitive?.length,
|
|
1337
|
+
at: i.learnedAt,
|
|
1338
|
+
...(i.id === (log.state("brain:born", null)?.star ?? 0) ? { first: true } : {}),
|
|
1339
|
+
});
|
|
1340
|
+
const q = String(query ?? "").trim();
|
|
1341
|
+
if (!q)
|
|
1342
|
+
return plain(
|
|
1343
|
+
all
|
|
1344
|
+
.sort((x, y) => (y.learnedAt ?? 0) - (x.learnedAt ?? 0))
|
|
1345
|
+
.slice(0, 60)
|
|
1346
|
+
.map(brief),
|
|
1347
|
+
);
|
|
1348
|
+
// What the search ranks comes first, in its order; then whatever merely has the words in it, newest first. A page lists them a screen at a time, so there is room for many.
|
|
1349
|
+
const ranked = core.search(q).understanding.map((u) => u.id),
|
|
1350
|
+
rank = new Map(ranked.map((id, n) => [id, n])),
|
|
1351
|
+
low = q.toLowerCase();
|
|
1352
|
+
const hits = all
|
|
1353
|
+
.filter((i) => rank.has(i.id) || i.text.toLowerCase().includes(low))
|
|
1354
|
+
.sort((x, y) => (rank.get(x.id) ?? Infinity) - (rank.get(y.id) ?? Infinity) || (y.learnedAt ?? 0) - (x.learnedAt ?? 0));
|
|
1355
|
+
return plain(hits.slice(0, 200).map(brief));
|
|
1356
|
+
},
|
|
1357
|
+
/** How the page looks for this person: a picture behind the sky, a colour, a text size. It travels with the person. */
|
|
1358
|
+
look(patch) {
|
|
1359
|
+
const now = log.state("brain:look", null) ?? {};
|
|
1360
|
+
if (patch && typeof patch === "object") {
|
|
1361
|
+
const next = { ...now };
|
|
1362
|
+
if (
|
|
1363
|
+
typeof patch.wall === "string" &&
|
|
1364
|
+
(patch.wall === "" || (/^data:image\/(png|jpeg|webp);base64,/.test(patch.wall) && patch.wall.length < 1600000))
|
|
1365
|
+
)
|
|
1366
|
+
next.wall = patch.wall || null;
|
|
1367
|
+
for (const [k, lo, hi] of [
|
|
1368
|
+
["dim", 0, 0.9],
|
|
1369
|
+
["blur", 0, 24],
|
|
1370
|
+
])
|
|
1371
|
+
if (Number.isFinite(patch[k])) next[k] = Math.min(hi, Math.max(lo, patch[k]));
|
|
1372
|
+
if (typeof patch.accent === "string" && /^(#[0-9a-f]{6})?$/i.test(patch.accent)) next.accent = patch.accent;
|
|
1373
|
+
if (["s", "m", "l"].includes(patch.size)) next.size = patch.size;
|
|
1374
|
+
// The ground it stands on (as the host has it, white, black or a colour of the user's), the colour under its own words, and looks the user saved to come back to.
|
|
1375
|
+
const HEX = /^#[0-9a-f]{6}$/i,
|
|
1376
|
+
ground = (v) => typeof v === "string" && (["", "auto", "white", "black"].includes(v) || HEX.test(v)),
|
|
1377
|
+
tone = (v) => typeof v === "string" && (v === "" || HEX.test(v));
|
|
1378
|
+
if (ground(patch.ground)) next.ground = patch.ground || "auto";
|
|
1379
|
+
if (tone(patch.its)) next.its = patch.its;
|
|
1380
|
+
// The colour of the letters, on the ground and under each kind of words: the user's own, or left to whichever ink can be read there.
|
|
1381
|
+
for (const k of ["ink", "itsInk", "mineInk"]) if (tone(patch[k])) next[k] = patch[k];
|
|
1382
|
+
if (Array.isArray(patch.themes))
|
|
1383
|
+
next.themes = patch.themes
|
|
1384
|
+
.filter((t) => t && typeof t.name === "string" && t.name.trim() && ground(t.ground ?? "") && tone(t.its ?? "") && tone(t.mine ?? ""))
|
|
1385
|
+
.slice(0, 12)
|
|
1386
|
+
.map((t) => ({
|
|
1387
|
+
name: t.name.trim().slice(0, 30),
|
|
1388
|
+
ground: t.ground || "auto",
|
|
1389
|
+
its: t.its ?? "",
|
|
1390
|
+
mine: t.mine ?? "",
|
|
1391
|
+
...Object.fromEntries(["ink", "itsInk", "mineInk"].filter((k) => tone(t[k]) && t[k]).map((k) => [k, t[k]])),
|
|
1392
|
+
}));
|
|
1393
|
+
// Any typeface the device has, by its name, and letters of any size within reason.
|
|
1394
|
+
if (typeof patch.font === "string" && /^[^"'\\;{}<>]{0,80}$/.test(patch.font)) next.font = patch.font.trim();
|
|
1395
|
+
if (Number.isFinite(patch.px)) next.px = Math.min(24, Math.max(12, Math.round(patch.px * 2) / 2));
|
|
1396
|
+
// Whether its name stands at the top and by its words, and whether a star says what it is when the pointer rests on it in the conversation.
|
|
1397
|
+
for (const k of ["showName", "tips", "comet"]) if (typeof patch[k] === "boolean") next[k] = patch[k];
|
|
1398
|
+
// Among the stars: whether a pull moves the sky or turns it (Shift does the other).
|
|
1399
|
+
if (["move", "turn"].includes(patch.pull)) next.pull = patch.pull;
|
|
1400
|
+
// Reading replies aloud: when (only when asked, after the user spoke, or always) and with which of the voices a host lends.
|
|
1401
|
+
if (["press", "spoke", "always"].includes(patch.aloud)) next.aloud = patch.aloud;
|
|
1402
|
+
if (typeof patch.voice === "string" && /^[\w .:-]{0,60}$/.test(patch.voice)) next.voice = patch.voice || null;
|
|
1403
|
+
log.save("brain:look", next);
|
|
1404
|
+
emit({ type: "look" });
|
|
1405
|
+
return plain(next);
|
|
1406
|
+
}
|
|
1407
|
+
return plain(now);
|
|
1408
|
+
},
|
|
1409
|
+
/** Who it is: the names, and what it holds to. Only the names are changed from the page. */
|
|
1410
|
+
self(patch) {
|
|
1411
|
+
// It has been woken (or the person chose to begin without the scene): the first-run scene is not shown again for this store.
|
|
1412
|
+
// With a name given, being woken is the first thing it remembers: a memory like any other, resting on what the person gave it, and the first star of its sky.
|
|
1413
|
+
// The words of the memory come from whoever shows the scene (they are in the person's language); what is checked here is that there is something they rest on.
|
|
1414
|
+
if (patch && patch.born === true && !log.state("brain:born", null)) {
|
|
1415
|
+
const born = { at: log.now(), star: null };
|
|
1416
|
+
const given = [patch.name, patch.userName].filter((v) => typeof v === "string" && v.trim()).map((v) => v.trim().slice(0, 60));
|
|
1417
|
+
if (given.length && typeof patch.firstMemory === "string" && patch.firstMemory.trim()) {
|
|
1418
|
+
try {
|
|
1419
|
+
// Each waking is a record of its own: a store that was wiped and is woken again does not find the first one's place taken.
|
|
1420
|
+
const where = `beginning-${born.at}`;
|
|
1421
|
+
log.ingest(scope, where, [{ seq: 0, role: "user", kind: "user/message", content: given.join(" / "), occurredAt: log.now() }]);
|
|
1422
|
+
const e = log.events(scope, where).at(-1);
|
|
1423
|
+
born.star =
|
|
1424
|
+
core.apply(
|
|
1425
|
+
[
|
|
1426
|
+
{
|
|
1427
|
+
op: "put",
|
|
1428
|
+
kind: "understanding",
|
|
1429
|
+
certainty: "explicit",
|
|
1430
|
+
reason:
|
|
1431
|
+
typeof patch.firstWhy === "string" && patch.firstWhy.trim() ? cut(patch.firstWhy.trim(), 120) : "Given when it was first woken",
|
|
1432
|
+
text: cut(patch.firstMemory.trim(), 200),
|
|
1433
|
+
about: "the day it was woken and given its name",
|
|
1434
|
+
concrete: "The user asks how it got its name, or about the day it was first woken",
|
|
1435
|
+
general: "Someone asks about its own beginning",
|
|
1436
|
+
tested: "It happened once",
|
|
1437
|
+
hypothesis: "",
|
|
1438
|
+
entities: [],
|
|
1439
|
+
evidence: [{ id: e.id, quote: e.content }],
|
|
1440
|
+
},
|
|
1441
|
+
],
|
|
1442
|
+
[e],
|
|
1443
|
+
).applied[0]?.id ?? null;
|
|
1444
|
+
} catch {
|
|
1445
|
+
/* woken all the same, without a star */
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
log.save("brain:born", born);
|
|
1449
|
+
// Woken, it speaks first.
|
|
1450
|
+
// In the language of the screen it was woken on: nothing has been said yet for it to take the language from.
|
|
1451
|
+
// (Only where nothing has been said yet: a conversation already under way is not greeted as if it were the first moment.)
|
|
1452
|
+
// It says hello once the scene of its waking is over, not under it: whoever shows the scene says how long that is (greetIn, at most half a minute).
|
|
1453
|
+
const hello = () => {
|
|
1454
|
+
greeting = null;
|
|
1455
|
+
if (log.state("brain:born", null)?.at === born.at && !log.events(scope, THREAD).length)
|
|
1456
|
+
wake.stimulus({
|
|
1457
|
+
kind: "born",
|
|
1458
|
+
...(typeof patch.language === "string" && /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(patch.language) ? { language: patch.language } : {}),
|
|
1459
|
+
});
|
|
1460
|
+
};
|
|
1461
|
+
if (patch.greet !== false) {
|
|
1462
|
+
const after = Number.isFinite(patch.greetIn) ? Math.max(0, Math.min(30000, patch.greetIn)) : 0;
|
|
1463
|
+
if (after) {
|
|
1464
|
+
clearTimeout(greeting);
|
|
1465
|
+
greeting = setTimeout(hello, after);
|
|
1466
|
+
greeting.unref?.();
|
|
1467
|
+
} else hello();
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
if (patch && typeof patch.manner === "string") setManner(patch.manner, null);
|
|
1471
|
+
// Ways of speaking the user liked enough to keep, to be picked again.
|
|
1472
|
+
if (patch && typeof patch.keepManner === "string" && patch.keepManner.trim())
|
|
1473
|
+
log.save("brain:manners", [...new Set([cut(patch.keepManner.trim(), 300), ...(log.state("brain:manners", []) ?? [])])].slice(0, 8));
|
|
1474
|
+
if (patch && typeof patch.dropManner === "string")
|
|
1475
|
+
log.save(
|
|
1476
|
+
"brain:manners",
|
|
1477
|
+
(log.state("brain:manners", []) ?? []).filter((m) => m !== patch.dropManner),
|
|
1478
|
+
);
|
|
1479
|
+
// A picture for each side of the conversation: small, kept with the rest of this person.
|
|
1480
|
+
if (patch && typeof patch === "object")
|
|
1481
|
+
for (const k of ["face", "yourFace"])
|
|
1482
|
+
if (
|
|
1483
|
+
typeof patch[k] === "string" &&
|
|
1484
|
+
(patch[k] === "" || (/^data:image\/(png|jpeg|webp);base64,/.test(patch[k]) && patch[k].length < 300000))
|
|
1485
|
+
)
|
|
1486
|
+
log.save(`brain:${k}`, patch[k] || null);
|
|
1487
|
+
// How it shows feeling: reactions and faces on or off, and the faces themselves, each with the name it is chosen by.
|
|
1488
|
+
if (patch && patch.feel && typeof patch.feel === "object")
|
|
1489
|
+
log.save("brain:feel", {
|
|
1490
|
+
...feel(),
|
|
1491
|
+
...Object.fromEntries(["react", "express", "seen"].filter((k) => typeof patch.feel[k] === "boolean").map((k) => [k, patch.feel[k]])),
|
|
1492
|
+
});
|
|
1493
|
+
if (patch && patch.addExpression && typeof patch.addExpression === "object") {
|
|
1494
|
+
const name = typeof patch.addExpression.name === "string" ? patch.addExpression.name.trim().slice(0, 40) : "",
|
|
1495
|
+
image = patch.addExpression.image;
|
|
1496
|
+
if (!name) throw new Error("A face needs a name to be chosen by");
|
|
1497
|
+
if (typeof image !== "string" || !/^data:image\/(png|jpeg|webp|gif);base64,/.test(image) || image.length > 400000)
|
|
1498
|
+
throw new Error("That picture cannot be kept as a face");
|
|
1499
|
+
// Twenty-four faces are kept. A twenty-fifth used to push the oldest out without a word; it is refused, and says why.
|
|
1500
|
+
if (expressions().length >= 24 && !expressions().some((x) => x.name === name))
|
|
1501
|
+
throw new Error("Twenty-four faces are kept; take one away to add another");
|
|
1502
|
+
log.save("brain:expressions", [...expressions().filter((x) => x.name !== name), { name, image }]);
|
|
1503
|
+
void seen(name, image);
|
|
1504
|
+
}
|
|
1505
|
+
if (patch && typeof patch.dropExpression === "string")
|
|
1506
|
+
log.save(
|
|
1507
|
+
"brain:expressions",
|
|
1508
|
+
expressions().filter((x) => x.name !== patch.dropExpression),
|
|
1509
|
+
);
|
|
1510
|
+
if (patch && patch.renameExpression && typeof patch.renameExpression === "object") {
|
|
1511
|
+
const from = patch.renameExpression.from,
|
|
1512
|
+
to = typeof patch.renameExpression.to === "string" ? patch.renameExpression.to.trim().slice(0, 40) : "";
|
|
1513
|
+
if (!to) throw new Error("A face needs a name to be chosen by");
|
|
1514
|
+
if (expressions().some((x) => x.name === to && x.name !== from)) throw new Error("Another face is already called that");
|
|
1515
|
+
log.save(
|
|
1516
|
+
"brain:expressions",
|
|
1517
|
+
expressions().map((x) => (x.name === from ? { ...x, name: to } : x)),
|
|
1518
|
+
);
|
|
1519
|
+
}
|
|
1520
|
+
if (patch && typeof patch === "object")
|
|
1521
|
+
profile(
|
|
1522
|
+
log,
|
|
1523
|
+
identity,
|
|
1524
|
+
Object.fromEntries(["name", "userName"].filter((k) => typeof patch[k] === "string").map((k) => [k, patch[k].trim().slice(0, 60)])),
|
|
1525
|
+
);
|
|
1526
|
+
// How it speaks as a rule belongs to its charter, with its name: what it is told when it is first woken is that, not a mood for the day.
|
|
1527
|
+
if (patch && typeof patch.tone === "string")
|
|
1528
|
+
profile(log, identity, { style: { ...(core.core().style ?? {}), tone: cut(patch.tone.trim(), 300) } });
|
|
1529
|
+
const who = core.core();
|
|
1530
|
+
return plain({
|
|
1531
|
+
tone: who.style?.tone ?? "",
|
|
1532
|
+
feel: feel(),
|
|
1533
|
+
expressions: expressions(),
|
|
1534
|
+
manner: manner(),
|
|
1535
|
+
manners: log.state("brain:manners", []) ?? [],
|
|
1536
|
+
name: who.name ?? "",
|
|
1537
|
+
userName: who.userName ?? "",
|
|
1538
|
+
purpose: who.purpose ?? "",
|
|
1539
|
+
values: who.values ?? [],
|
|
1540
|
+
promises: who.commitments ?? [],
|
|
1541
|
+
habits: Object.values(who.habits ?? {})
|
|
1542
|
+
.map((h) => (typeof h === "string" ? h : h?.text))
|
|
1543
|
+
.filter(Boolean),
|
|
1544
|
+
});
|
|
1545
|
+
},
|
|
1546
|
+
activity() {
|
|
1547
|
+
const d = core.diagnose();
|
|
1548
|
+
return plain({
|
|
1549
|
+
state: wake.state,
|
|
1550
|
+
tasks: [...tasks.values()].slice(-8).reverse().map(brief),
|
|
1551
|
+
intentions: standing()
|
|
1552
|
+
.slice(0, 8)
|
|
1553
|
+
.map((a) => ({ id: a.id, at: a.at, why: a.why, ...(a.every ? { every: a.every } : {}) })),
|
|
1554
|
+
held: held().map((h) => ({ id: h.id, at: h.at, about: h.about })),
|
|
1555
|
+
unread: log.pending(identity, STAGE).length,
|
|
1556
|
+
idle: d.sleep?.idle ?? [],
|
|
1557
|
+
lastSleep: d.sleep?.last ?? null,
|
|
1558
|
+
});
|
|
1559
|
+
},
|
|
1560
|
+
/** Every memory in use, for the sky itself: what each is, how easily it comes to mind, when it was learned, what a lesson was drawn from. A private one has no words here. */
|
|
1561
|
+
sky() {
|
|
1562
|
+
const outcomes = new Map();
|
|
1563
|
+
for (const f of core.feedback()) (outcomes.get(f.item) ?? outcomes.set(f.item, []).get(f.item)).push(f);
|
|
1564
|
+
return plain(
|
|
1565
|
+
core
|
|
1566
|
+
.items()
|
|
1567
|
+
.filter((i) => !i.paused)
|
|
1568
|
+
.map((i) => ({
|
|
1569
|
+
id: i.id,
|
|
1570
|
+
kind: i.kind === "concern" ? "matter" : i.level === "lesson" ? "lesson" : "noted",
|
|
1571
|
+
text: i.sensitive?.length ? "" : cut(i.text, 120),
|
|
1572
|
+
private: !!i.sensitive?.length,
|
|
1573
|
+
strength: Math.round(accessibility(i, useStats(outcomes.get(i.id) ?? [], i.revision)) * 1000) / 1000,
|
|
1574
|
+
from: i.premises ?? [],
|
|
1575
|
+
at: i.learnedAt,
|
|
1576
|
+
...(i.id === (log.state("brain:born", null)?.star ?? 0) ? { first: true } : {}),
|
|
1577
|
+
})),
|
|
1578
|
+
);
|
|
1579
|
+
},
|
|
1580
|
+
listen(listener) {
|
|
1581
|
+
listeners.add(listener);
|
|
1582
|
+
return () => listeners.delete(listener);
|
|
1583
|
+
},
|
|
1584
|
+
snapshot() {
|
|
1585
|
+
// The sign it put on something the user said, by which message: the last one stands.
|
|
1586
|
+
const readBy = feel().seen ? marks("brain:read") : {},
|
|
1587
|
+
seenBy = marks("brain:seen");
|
|
1588
|
+
// A message that was taken back keeps its place and its hour, and nothing else.
|
|
1589
|
+
// An erased record is no longer among the records; its place is found again by its hour: before whatever was said at or after it.
|
|
1590
|
+
const withTakenBack = (list) => {
|
|
1591
|
+
for (const [id, at] of [...takenBack].sort((a, b) => a[1] - b[1])) {
|
|
1592
|
+
if (list.length && at < (list[0].at ?? 0) && list.length >= 200) continue;
|
|
1593
|
+
const i = list.findIndex((m) => !m.retracted && (m.at ?? 0) >= at);
|
|
1594
|
+
list.splice(i < 0 ? list.length : i, 0, { id, role: "user", text: "", at, retracted: true });
|
|
1595
|
+
}
|
|
1596
|
+
return list;
|
|
1597
|
+
};
|
|
1598
|
+
const takenBack = new Map();
|
|
1599
|
+
for (const e of log.events(scope, THREAD))
|
|
1600
|
+
if (e.kind === "retraction") {
|
|
1601
|
+
try {
|
|
1602
|
+
const r = JSON.parse(e.content);
|
|
1603
|
+
if (r?.of) takenBack.set(r.of, r.at ?? e.occurredAt);
|
|
1604
|
+
} catch {
|
|
1605
|
+
/* not one */
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
const both = reactions(),
|
|
1609
|
+
reacted = new Map([...both.its, ...both.theirs]);
|
|
1610
|
+
// What a message answers is kept by its id alone and its words are looked up when shown: once that message is taken back, nothing of it is left standing in another.
|
|
1611
|
+
const byId = new Map(
|
|
1612
|
+
log
|
|
1613
|
+
.events(scope, THREAD)
|
|
1614
|
+
.filter((e) => e.content)
|
|
1615
|
+
.map((e) => [e.id, e]),
|
|
1616
|
+
),
|
|
1617
|
+
quoted = (id) => {
|
|
1618
|
+
const e = id && byId.get(id);
|
|
1619
|
+
return e ? { id: e.id, role: e.role, words: cut(e.content, 140) } : null;
|
|
1620
|
+
};
|
|
1621
|
+
const outcomes = new Map();
|
|
1622
|
+
for (const f of core.feedback()) (outcomes.get(f.item) ?? outcomes.set(f.item, []).get(f.item)).push(f);
|
|
1623
|
+
// Everything the page draws is a stored record: one star per memory in
|
|
1624
|
+
// use, as bright as it comes to mind; a lesson is joined to its cases.
|
|
1625
|
+
const sky = core
|
|
1626
|
+
.items()
|
|
1627
|
+
.filter((i) => !i.paused)
|
|
1628
|
+
.map((i) => ({
|
|
1629
|
+
id: i.id,
|
|
1630
|
+
kind: i.kind === "concern" ? "matter" : i.level === "lesson" ? "lesson" : "noted",
|
|
1631
|
+
text: i.sensitive?.length ? "" : cut(i.text, 240),
|
|
1632
|
+
private: !!i.sensitive?.length,
|
|
1633
|
+
strength: accessibility(i, useStats(outcomes.get(i.id) ?? [], i.revision)),
|
|
1634
|
+
from: i.premises ?? [],
|
|
1635
|
+
at: i.learnedAt,
|
|
1636
|
+
...(i.id === (log.state("brain:born", null)?.star ?? 0) ? { first: true } : {}),
|
|
1637
|
+
}))
|
|
1638
|
+
// A sky of thousands is a smear. The page is sent the four hundred that come to mind most easily; the count says how many there are.
|
|
1639
|
+
.sort((a, b) => b.strength - a.strength)
|
|
1640
|
+
.slice(0, 400);
|
|
1641
|
+
// The names the user gave: what it is called, and what it calls them.
|
|
1642
|
+
const who = core.core();
|
|
1643
|
+
// What it would like settled, a little at a time: asked in the conversation, not on a page of its own.
|
|
1644
|
+
const r = core.review(),
|
|
1645
|
+
textOf = (id) => {
|
|
1646
|
+
const i = core.item(id);
|
|
1647
|
+
return i && !i.sensitive?.length ? { id, revision: i.revision, text: cut(i.text, 240) } : null;
|
|
1648
|
+
};
|
|
1649
|
+
const review = [
|
|
1650
|
+
...r.disputes.map((d) => ({ kind: "dispute", a: textOf(d.a), b: textOf(d.b) })).filter((d) => d.a && d.b),
|
|
1651
|
+
...[...r.unsure, ...r.stale].map((id) => ({ kind: "check", item: textOf(id) })).filter((c) => c.item),
|
|
1652
|
+
].slice(0, 1);
|
|
1653
|
+
// Nothing said, nothing remembered and never woken: a store at its very beginning, a new one or one wiped clean.
|
|
1654
|
+
const fresh = !log.state("brain:born", null) && !log.events(scope, THREAD).length && !core.items().length;
|
|
1655
|
+
return plain({
|
|
1656
|
+
fresh,
|
|
1657
|
+
born: !!log.state("brain:born", null),
|
|
1658
|
+
review,
|
|
1659
|
+
look: log.state("brain:look", null) ?? {},
|
|
1660
|
+
manner: manner()?.text ?? "",
|
|
1661
|
+
face: log.state("brain:face", null),
|
|
1662
|
+
yourFace: log.state("brain:yourFace", null),
|
|
1663
|
+
name: typeof who?.name === "string" ? who.name.trim() : "",
|
|
1664
|
+
you: typeof who?.userName === "string" ? who.userName.trim() : "",
|
|
1665
|
+
state: wake.state,
|
|
1666
|
+
thinking,
|
|
1667
|
+
writing,
|
|
1668
|
+
next: wake.next(),
|
|
1669
|
+
sky,
|
|
1670
|
+
intentions: standing()
|
|
1671
|
+
.slice(0, 6)
|
|
1672
|
+
.map((a) => ({ id: a.id, at: a.at, why: a.why, ...(a.every ? { every: a.every } : {}) })),
|
|
1673
|
+
workers: Object.entries(workers).map(([name, w]) => ({ name, about: w.about ?? "" })),
|
|
1674
|
+
tasks: [...tasks.values()].slice(-20).map(brief),
|
|
1675
|
+
asks: [...asks.values()].map(({ answer, ...a }) => a),
|
|
1676
|
+
draft: log.state("brain:draft", null) ?? "",
|
|
1677
|
+
tone: core.core().style?.tone ?? "",
|
|
1678
|
+
page: log.state("brain:page", null) ?? 0,
|
|
1679
|
+
memories: core.items().length,
|
|
1680
|
+
messages: withTakenBack(
|
|
1681
|
+
log
|
|
1682
|
+
.events(scope, THREAD)
|
|
1683
|
+
.filter((e) => e.content && ["user", "assistant"].includes(e.role))
|
|
1684
|
+
.slice(-200)
|
|
1685
|
+
.map((e) => ({
|
|
1686
|
+
id: e.id,
|
|
1687
|
+
role: e.role,
|
|
1688
|
+
text: e.content,
|
|
1689
|
+
at: e.occurredAt,
|
|
1690
|
+
...(e.metadata?.files?.length ? { files: e.metadata.files } : {}),
|
|
1691
|
+
...(e.metadata?.promised?.length ? { promised: e.metadata.promised } : {}),
|
|
1692
|
+
...(e.metadata?.expression ? { expression: e.metadata.expression } : {}),
|
|
1693
|
+
...(quoted(e.metadata?.replyTo) ? { replyTo: quoted(e.metadata.replyTo) } : {}),
|
|
1694
|
+
...(reacted.has(e.id) ? { reaction: reacted.get(e.id) } : {}),
|
|
1695
|
+
...(e.role === "user" && readBy[e.id] ? { read: readBy[e.id] } : {}),
|
|
1696
|
+
...(e.role === "assistant" && seenBy[e.id] ? { seen: seenBy[e.id] } : {}),
|
|
1697
|
+
})),
|
|
1698
|
+
),
|
|
1699
|
+
// What this place can do beyond words: take files, and (lent by a host) hear and change the model.
|
|
1700
|
+
can: {
|
|
1701
|
+
files: true,
|
|
1702
|
+
hear: hear?.state?.() ?? null,
|
|
1703
|
+
model: !!models?.choose,
|
|
1704
|
+
speak: voice?.state?.() ?? null,
|
|
1705
|
+
...(voice && !voice.state?.() && voice.why ? { speakWhy: voice.why() } : {}),
|
|
1706
|
+
},
|
|
1707
|
+
...(thinking && thinkingSince ? { thinkingSince } : {}),
|
|
1708
|
+
feel: feel(),
|
|
1709
|
+
expressions: expressions(),
|
|
1710
|
+
...(lastRecall ? { recall: lastRecall } : {}),
|
|
1711
|
+
});
|
|
1712
|
+
},
|
|
1713
|
+
async idle() {
|
|
1714
|
+
while (wake.busy || wake.queue.length) await new Promise((r) => setImmediate(r));
|
|
1715
|
+
},
|
|
1716
|
+
close() {
|
|
1717
|
+
clearTimeout(greeting);
|
|
1718
|
+
wake.stop();
|
|
1719
|
+
for (const w of Object.values(workers)) w.close?.();
|
|
1720
|
+
if (!shared) log.close();
|
|
1721
|
+
},
|
|
1722
|
+
};
|
|
1723
|
+
}
|