@wraith-ai/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,73 @@
1
+ import { type SessionBackend, type SessionEnds, sessionExists, sessionNotFound } from "./backend";
2
+ import type { SessionRecord } from "./format";
3
+ import { type SessionStore, createSessionStore } from "./store";
4
+
5
+ /**
6
+ * Sessions that live as long as the process, with no disk behind them.
7
+ *
8
+ * It goes through `createSessionStore` like the file store, so both answer the
9
+ * contract suite for the same reasons.
10
+ */
11
+
12
+ export interface MemorySessionStoreOptions {
13
+ newId?: () => string;
14
+ now?: () => number;
15
+ }
16
+
17
+ /**
18
+ * Records are cloned on the way in and out. Without this, a caller that
19
+ * mutates a message it was handed would quietly rewrite history here, and the
20
+ * backends would stop behaving alike.
21
+ */
22
+ function detach<T>(value: T): T {
23
+ return structuredClone(value);
24
+ }
25
+
26
+ export function createMemorySessionBackend(): SessionBackend {
27
+ const sessions = new Map<string, SessionRecord[]>();
28
+
29
+ const endsOf = (records: SessionRecord[]): SessionEnds | null => {
30
+ const first = records[0];
31
+ const last = records[records.length - 1];
32
+ return first === undefined || last === undefined ? null : detach({ first, last });
33
+ };
34
+
35
+ return {
36
+ async create(id: string, records: readonly SessionRecord[]): Promise<void> {
37
+ if (sessions.has(id)) throw sessionExists(id);
38
+ sessions.set(id, detach([...records]));
39
+ },
40
+
41
+ async append(id: string, records: readonly SessionRecord[]): Promise<void> {
42
+ const found = sessions.get(id);
43
+ if (found === undefined) throw sessionNotFound(id);
44
+ found.push(...detach([...records]));
45
+ },
46
+
47
+ async read(id: string): Promise<SessionRecord[] | null> {
48
+ const found = sessions.get(id);
49
+ return found === undefined ? null : detach(found);
50
+ },
51
+
52
+ async ends(id: string): Promise<SessionEnds | null> {
53
+ const found = sessions.get(id);
54
+ return found === undefined ? null : endsOf(found);
55
+ },
56
+
57
+ async list(): Promise<SessionEnds[]> {
58
+ return [...sessions.values()].flatMap((records) => endsOf(records) ?? []);
59
+ },
60
+
61
+ async delete(id: string): Promise<boolean> {
62
+ return sessions.delete(id);
63
+ },
64
+ };
65
+ }
66
+
67
+ export function createMemorySessionStore(options: MemorySessionStoreOptions = {}): SessionStore {
68
+ let counter = 0;
69
+ return createSessionStore(createMemorySessionBackend(), {
70
+ newId: options.newId ?? (() => `session-${++counter}`),
71
+ ...(options.now === undefined ? {} : { now: options.now }),
72
+ });
73
+ }
@@ -0,0 +1,153 @@
1
+ import type { ModelMessage } from "../agent/messages";
2
+ import type { Config, ReasoningEffort } from "../config/schema";
3
+ import type { Usage } from "../events/types";
4
+ import { explicitEffort, type ExplicitEffort } from "../providers/turn-effort";
5
+
6
+ /**
7
+ * A conversation and what it has cost so far.
8
+ *
9
+ * `messages` uses the SDK's message type, which means a major SDK release can
10
+ * invalidate stored sessions. The log records the format version and the major
11
+ * of `ai` that wrote it (`format.ts`).
12
+ *
13
+ * A projection of the stored log, never the storage itself. It holds the
14
+ * history as the model should see it, with compaction applied; the log keeps
15
+ * what actually happened.
16
+ */
17
+
18
+ export interface Session {
19
+ id: string;
20
+ createdAt: number;
21
+ updatedAt: number;
22
+ messages: ModelMessage[];
23
+ usage: Usage;
24
+ meta: Record<string, unknown>;
25
+ /**
26
+ * The system prompt this session was last sent with. A resumed run sends
27
+ * this rather than a fresh one, so the cached prefix still matches. Absent
28
+ * for a new session and for logs older than format 5.
29
+ */
30
+ system?: string;
31
+ }
32
+
33
+ export interface SessionSummary {
34
+ id: string;
35
+ createdAt: number;
36
+ updatedAt: number;
37
+ messageCount: number;
38
+ /**
39
+ * The first thing the user asked for, one line. Absent for sessions written
40
+ * before format 3, and for one that has no user turn yet. Never invented.
41
+ */
42
+ title?: string;
43
+ /** What the session is running now, from the last `meta` record. */
44
+ model?: string;
45
+ provider?: string;
46
+ /** Micro-dollars spent so far. Absent means unpriced, never free. */
47
+ costMicros?: number;
48
+ /**
49
+ * What started the session, copied from the header's `meta.source`. A free
50
+ * string: the CLI writes "run" and "chat", and is the only thing that reads
51
+ * them back. On the summary, so filtering by it never reads a log.
52
+ */
53
+ source?: string;
54
+ /**
55
+ * The git checkout the session started in, from the header's `meta.checkout`.
56
+ * Worktrees share a session directory, so `--continue` filters on this.
57
+ */
58
+ checkout?: string;
59
+ }
60
+
61
+ export interface CreateSessionInit {
62
+ id?: string;
63
+ createdAt?: number;
64
+ messages?: ModelMessage[];
65
+ meta?: Record<string, unknown>;
66
+ }
67
+
68
+ export function createSession(id: string, init: CreateSessionInit = {}, now = Date.now()): Session {
69
+ return {
70
+ id: init.id ?? id,
71
+ createdAt: init.createdAt ?? now,
72
+ updatedAt: init.createdAt ?? now,
73
+ messages: init.messages ?? [],
74
+ usage: {},
75
+ meta: init.meta ?? {},
76
+ };
77
+ }
78
+
79
+ export function summarize(session: Session): SessionSummary {
80
+ const summary: SessionSummary = {
81
+ id: session.id,
82
+ createdAt: session.createdAt,
83
+ updatedAt: session.updatedAt,
84
+ messageCount: session.messages.length,
85
+ };
86
+ const source = sourceOf(session.meta);
87
+ if (source !== undefined) summary.source = source;
88
+ const checkout = checkoutOf(session.meta);
89
+ if (checkout !== undefined) summary.checkout = checkout;
90
+ return summary;
91
+ }
92
+
93
+ /** Anything that is not a string is treated as absent rather than coerced. */
94
+ export function sourceOf(meta: Record<string, unknown>): string | undefined {
95
+ return typeof meta.source === "string" ? meta.source : undefined;
96
+ }
97
+
98
+ export function checkoutOf(meta: Record<string, unknown>): string | undefined {
99
+ return typeof meta.checkout === "string" ? meta.checkout : undefined;
100
+ }
101
+
102
+ export interface SessionModel {
103
+ /** The reference the run was asked for — a profile name, or `provider:model`. */
104
+ profile?: string;
105
+ /** `provider:model`, which still names the model once a profile is gone. */
106
+ model?: string;
107
+ reasoning?: ExplicitEffort;
108
+ }
109
+
110
+ /**
111
+ * What the session was last running, for a resume to carry on with.
112
+ *
113
+ * Read here rather than by each host: the loop writes these keys, and a second
114
+ * reader could read them differently. Both references are given: a profile
115
+ * renamed since would otherwise resolve as a bare model id and quietly pick the
116
+ * wrong model. Empty for a session that has not run a turn.
117
+ */
118
+ export function sessionModel(session: Session): SessionModel {
119
+ const { profile, provider, model } = session.meta;
120
+ const reasoning = explicitEffort(session.meta.reasoning);
121
+ return {
122
+ ...(typeof profile === "string" && profile !== "" ? { profile } : {}),
123
+ ...(typeof provider === "string" && typeof model === "string" ? { model: `${provider}:${model}` } : {}),
124
+ ...(reasoning === undefined ? {} : { reasoning }),
125
+ };
126
+ }
127
+
128
+ export interface ResumedModel {
129
+ /** A reference `resolve()` takes. */
130
+ model?: string;
131
+ /** `provider-default` when the session ran without one. */
132
+ reasoning?: ReasoningEffort;
133
+ }
134
+
135
+ /**
136
+ * The model and effort a resumed session carries on with, as a pair.
137
+ *
138
+ * A host that names a model itself should not call this: that model brings its
139
+ * own profile's effort, and laying the session's over it mixes two choices.
140
+ * The profile is used while the config still has it. Once it is gone, the
141
+ * `provider:model` it stood for is used, since a bare name would resolve as a
142
+ * model id on the only provider and quietly pick the wrong model.
143
+ */
144
+ export function resumeModel(config: Pick<Config, "models">, session: Session): ResumedModel {
145
+ const last = sessionModel(session);
146
+ const model =
147
+ last.profile !== undefined && (config.models[last.profile] !== undefined || last.profile.includes(":"))
148
+ ? last.profile
149
+ : last.model;
150
+ if (model === undefined) return {};
151
+ // No level in the log means it ran without one, so a default set since does not move it.
152
+ return { model, reasoning: last.reasoning ?? "provider-default" };
153
+ }
@@ -0,0 +1,219 @@
1
+ import { type SessionBackend, sessionExists, sessionNotFound } from "./backend";
2
+ import {
3
+ type LogStats,
4
+ type SessionRecord,
5
+ type SessionRecordInput,
6
+ emptyStats,
7
+ headerOf,
8
+ initialRecords,
9
+ migrate,
10
+ planAppend,
11
+ project,
12
+ statsFromCheckpoint,
13
+ statsOf,
14
+ summaryFrom,
15
+ } from "./format";
16
+ import {
17
+ type CreateSessionInit,
18
+ type Session,
19
+ type SessionSummary,
20
+ createSession,
21
+ } from "./session";
22
+
23
+ /**
24
+ * A port: the loop never knows which store it talks to.
25
+ *
26
+ * Writing is `append` only. A `save(session)` beside it would be a second write
27
+ * path, and the two would eventually disagree.
28
+ *
29
+ * `createSessionStore` is the implementation; what differs between a file, a
30
+ * database and memory is the `SessionBackend` under it.
31
+ */
32
+ export interface SessionStore {
33
+ create(init?: CreateSessionInit): Promise<Session>;
34
+ /** The session as the model should see it: compaction already applied. */
35
+ get(id: string): Promise<Session | null>;
36
+ /** The raw log, for tooling that shows what actually happened. */
37
+ records(id: string): Promise<SessionRecord[] | null>;
38
+ append(id: string, records: readonly SessionRecordInput[]): Promise<void>;
39
+ list(limit?: number): Promise<SessionSummary[]>;
40
+ delete(id: string): Promise<boolean>;
41
+ }
42
+
43
+ export interface SessionStoreOptions {
44
+ newId?: () => string;
45
+ now?: () => number;
46
+ /**
47
+ * Keep a session in this instance until its first message, so one nobody
48
+ * wrote in leaves nothing behind. Off, a session is kept from `create()`,
49
+ * which a server that hands out an id before the first message needs.
50
+ */
51
+ deferUntilFirstMessage?: boolean;
52
+ }
53
+
54
+ /** Where the next record goes, and the totals its checkpoint continues from. */
55
+ interface Cursor {
56
+ nextSeq: number;
57
+ stats: LogStats;
58
+ }
59
+
60
+ /** What a deferred session has so far, before any of it reached the backend. */
61
+ interface Unwritten {
62
+ records: SessionRecord[];
63
+ stats: LogStats;
64
+ }
65
+
66
+ /**
67
+ * Ids start with a UTC timestamp so a listing sorts chronologically and a
68
+ * human can tell what they are looking at without opening anything.
69
+ */
70
+ function timestampId(now: number, random: () => number): string {
71
+ const iso = new Date(now).toISOString();
72
+ const stamp = `${iso.slice(0, 10).replace(/-/g, "")}-${iso.slice(11, 19).replace(/:/g, "")}`;
73
+ const suffix = Math.floor(random() * 36 ** 6)
74
+ .toString(36)
75
+ .padStart(6, "0");
76
+ return `${stamp}-${suffix}`;
77
+ }
78
+
79
+ /**
80
+ * Everything about a session log that does not depend on where it is kept:
81
+ * the header, `seq`, the time of undated records, running totals, the closing
82
+ * checkpoint, migrations and the projection.
83
+ */
84
+ export function createSessionStore(
85
+ backend: SessionBackend,
86
+ options: SessionStoreOptions = {},
87
+ ): SessionStore {
88
+ const now = options.now ?? Date.now;
89
+ const newId = options.newId ?? (() => timestampId(now(), Math.random));
90
+ const defer = options.deferUntilFirstMessage === true;
91
+ const cursors = new Map<string, Cursor>();
92
+ // An id is here or in the backend, never both: the first message moves it across.
93
+ const unwritten = new Map<string, Unwritten>();
94
+ const queues = new Map<string, Promise<void>>();
95
+
96
+ const stored = async (id: string): Promise<SessionRecord[] | null> => {
97
+ const records = await backend.read(id);
98
+ return records === null ? null : migrate(records, headerOf(records).formatVersion);
99
+ };
100
+
101
+ // A log cut off before its checkpoint has totals nobody wrote down; replay it.
102
+ const statsAfter = async (id: string, last: SessionRecord): Promise<LogStats> =>
103
+ last.type === "checkpoint" ? statsFromCheckpoint(last) : statsOf((await stored(id)) ?? []);
104
+
105
+ const cursorFor = async (id: string): Promise<Cursor> => {
106
+ const cached = cursors.get(id);
107
+ if (cached !== undefined) return cached;
108
+
109
+ const ends = await backend.ends(id);
110
+ if (ends === null) throw sessionNotFound(id);
111
+ const cursor = { nextSeq: ends.last.seq + 1, stats: await statsAfter(id, ends.last) };
112
+ cursors.set(id, cursor);
113
+ return cursor;
114
+ };
115
+
116
+ // Two appends at once would read one cursor and take the same `seq`.
117
+ const inOrder = (id: string, task: () => Promise<void>): Promise<void> => {
118
+ const next = (queues.get(id) ?? Promise.resolve()).then(task);
119
+ // A failed write still frees the queue; its caller gets the error from `next`.
120
+ const settled = next.then(
121
+ () => undefined,
122
+ () => undefined,
123
+ );
124
+ queues.set(id, settled);
125
+ void settled.then(() => {
126
+ if (queues.get(id) === settled) queues.delete(id);
127
+ });
128
+ return next;
129
+ };
130
+
131
+ const persist = async (id: string, records: SessionRecord[], stats: LogStats): Promise<void> => {
132
+ await backend.create(id, records);
133
+ unwritten.delete(id);
134
+ cursors.set(id, { nextSeq: (records[records.length - 1]?.seq ?? -1) + 1, stats });
135
+ };
136
+
137
+ // Copied on the way out: a caller mutating what it was handed must not
138
+ // rewrite what is still to be written.
139
+ const pending = (id: string): SessionRecord[] | undefined => {
140
+ const found = unwritten.get(id);
141
+ return found === undefined ? undefined : (structuredClone(found.records) as SessionRecord[]);
142
+ };
143
+
144
+ return {
145
+ async create(init: CreateSessionInit = {}): Promise<Session> {
146
+ const session = createSession(newId(), init, now());
147
+ if (unwritten.has(session.id)) throw sessionExists(session.id);
148
+
149
+ const plan = planAppend(initialRecords(session), 0, session.createdAt, emptyStats);
150
+ // A history handed in is a conversation already, so it is kept now.
151
+ if (!defer || session.messages.length > 0) {
152
+ await persist(session.id, plan.records, plan.stats);
153
+ return project(plan.records);
154
+ }
155
+
156
+ // Checked now rather than at the first message, which would report a
157
+ // taken id far from the call that chose it.
158
+ if ((await backend.ends(session.id)) !== null) throw sessionExists(session.id);
159
+ unwritten.set(session.id, { records: plan.records, stats: plan.stats });
160
+ return project(plan.records);
161
+ },
162
+
163
+ async get(id: string): Promise<Session | null> {
164
+ const records = pending(id) ?? (await stored(id));
165
+ return records === null ? null : project(records);
166
+ },
167
+
168
+ async records(id: string): Promise<SessionRecord[] | null> {
169
+ return pending(id) ?? stored(id);
170
+ },
171
+
172
+ append(id: string, records: readonly SessionRecordInput[]): Promise<void> {
173
+ return inOrder(id, async () => {
174
+ const waiting = unwritten.get(id);
175
+ if (waiting !== undefined) {
176
+ const nextSeq = (waiting.records[waiting.records.length - 1]?.seq ?? -1) + 1;
177
+ const plan = planAppend(records, nextSeq, now(), waiting.stats);
178
+ const all = [...waiting.records, ...plan.records];
179
+ // A title or a model change is not a conversation; they wait with the
180
+ // header for the first message.
181
+ if (all.some((record) => record.type === "message")) {
182
+ await persist(id, all, plan.stats);
183
+ } else {
184
+ unwritten.set(id, { records: all, stats: plan.stats });
185
+ }
186
+ return;
187
+ }
188
+
189
+ const cursor = await cursorFor(id);
190
+ const plan = planAppend(records, cursor.nextSeq, now(), cursor.stats);
191
+ try {
192
+ await backend.append(id, plan.records);
193
+ } catch (error) {
194
+ // Whatever refused the write, the tail may not be what this cursor says.
195
+ cursors.delete(id);
196
+ throw error;
197
+ }
198
+ cursors.set(id, { nextSeq: cursor.nextSeq + plan.records.length, stats: plan.stats });
199
+ });
200
+ },
201
+
202
+ async list(limit?: number): Promise<SessionSummary[]> {
203
+ const summaries: SessionSummary[] = [];
204
+ for (const { first, last } of await backend.list(limit)) {
205
+ const header = headerOf([first]);
206
+ summaries.push(summaryFrom(header, last.ts, await statsAfter(header.id, last)));
207
+ }
208
+
209
+ summaries.sort((left, right) => right.updatedAt - left.updatedAt);
210
+ return limit === undefined ? summaries : summaries.slice(0, limit);
211
+ },
212
+
213
+ async delete(id: string): Promise<boolean> {
214
+ if (unwritten.delete(id)) return true;
215
+ cursors.delete(id);
216
+ return backend.delete(id);
217
+ },
218
+ };
219
+ }
@@ -0,0 +1,166 @@
1
+ import type { AgentError } from "../errors";
2
+ import { listenOnLoopback, type Loopback } from "./loopback";
3
+
4
+ /** Long enough for a password manager and a second factor, short enough that a forgotten one ends. */
5
+ export const SIGN_IN_TIMEOUT_MS = 10 * 60_000;
6
+
7
+ /**
8
+ * One browser sign-in under way, the same for every kind of server.
9
+ *
10
+ * The answer reaches it two ways: the browser comes back to a port on this
11
+ * machine, or the host passes on an address — one a person pasted, or one its
12
+ * own callback route received. Both go through the same checks.
13
+ */
14
+ export interface SignIn<T> {
15
+ /** The page to open in a browser. Opening it is the host's: only it knows where the person is. */
16
+ url: string;
17
+ /** The `state` the answer carries, for a host that routes several sign-ins through one address. */
18
+ state: string;
19
+ /** False when nothing listens for the browser: only `complete` can finish it. */
20
+ listening: boolean;
21
+ /** Settles once the sign-in is stored and usable; fails with why it was not. */
22
+ done: Promise<T>;
23
+ /**
24
+ * The address the browser ended up on, whole or as the path a route received.
25
+ * A wrong address fails this call and the sign-in keeps waiting; a refusal
26
+ * from the server ends the sign-in.
27
+ */
28
+ complete(address: string): Promise<void>;
29
+ cancel(): void;
30
+ }
31
+
32
+ export interface SignInOptions<T> {
33
+ /** A port to listen on (0 for any), and whether any port will do when it is taken; or the host's own address. */
34
+ redirect: { port: number; anyPortIfTaken: boolean; path: string } | { url: string };
35
+ /** Builds the authorization page for this redirect URI. */
36
+ prepare(redirectUrl: string): Promise<{ url: string; state: string }>;
37
+ /** Exchanges the code; a failure ends the sign-in. */
38
+ finish(code: string, iss: string | undefined): Promise<T>;
39
+ /** Every error this sign-in reports, so each kind of server keeps its own code. */
40
+ failure(message: string, cause?: unknown): AgentError;
41
+ timeoutMs: number;
42
+ /** What the page the browser lands on calls the application. */
43
+ appName: string;
44
+ /** Takes a pasted query string or a bare code too, for a server whose page shows only that. */
45
+ acceptsBareCode?: boolean;
46
+ }
47
+
48
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
49
+
50
+ /** A browser told `localhost` and a listener on 127.0.0.1 are the same place. */
51
+ function sameHost(a: string, b: string): boolean {
52
+ return a === b || (LOOPBACK.has(a) && LOOPBACK.has(b));
53
+ }
54
+
55
+ export async function openSignIn<T>(options: SignInOptions<T>): Promise<SignIn<T>> {
56
+ const { redirect, failure } = options;
57
+ let loopback: Loopback | undefined;
58
+ let redirectUrl: string;
59
+
60
+ if ("url" in redirect) {
61
+ redirectUrl = redirect.url;
62
+ } else {
63
+ loopback = await listenOnLoopback(redirect.port, redirect.path, options.appName);
64
+ if (loopback === undefined && redirect.anyPortIfTaken && redirect.port !== 0) {
65
+ loopback = await listenOnLoopback(0, redirect.path, options.appName);
66
+ }
67
+ if (loopback === undefined && redirect.port === 0) {
68
+ throw failure("Could not listen on 127.0.0.1 for the browser to come back.");
69
+ }
70
+ redirectUrl = loopback?.redirectUrl ?? `http://127.0.0.1:${String(redirect.port)}${redirect.path}`;
71
+ }
72
+
73
+ let prepared: { url: string; state: string };
74
+ try {
75
+ prepared = await options.prepare(redirectUrl);
76
+ } catch (error) {
77
+ loopback?.close();
78
+ throw error;
79
+ }
80
+
81
+ let resolveDone: (value: T) => void = () => undefined;
82
+ let rejectDone: (error: AgentError) => void = () => undefined;
83
+ const done = new Promise<T>((resolve, reject) => {
84
+ resolveDone = resolve;
85
+ rejectDone = reject;
86
+ });
87
+ // Whoever awaits `done` still sees the failure; this only keeps one nobody awaits from counting as unhandled.
88
+ done.catch(() => undefined);
89
+
90
+ let finished = false;
91
+ let exchanging = false;
92
+ const end = (): void => {
93
+ finished = true;
94
+ clearTimeout(timer);
95
+ loopback?.close();
96
+ };
97
+ const fail = (error: AgentError): AgentError => {
98
+ if (!finished) {
99
+ end();
100
+ rejectDone(error);
101
+ }
102
+ return error;
103
+ };
104
+ // The server held as long as the sign-in is open; the timer must not hold a process by itself.
105
+ const timer = setTimeout(() => fail(failure("Timed out waiting for the browser.")), options.timeoutMs);
106
+ timer.unref?.();
107
+
108
+ const expected = new URL(redirectUrl);
109
+ const answerIn = (text: string): URLSearchParams => {
110
+ if (text.startsWith("/") || URL.canParse(text)) {
111
+ const url = new URL(text, expected);
112
+ if (
113
+ url.protocol !== expected.protocol ||
114
+ url.port !== expected.port ||
115
+ url.pathname !== expected.pathname ||
116
+ !sameHost(url.hostname, expected.hostname)
117
+ ) {
118
+ throw failure(`This address is not where the sign-in returns to (${expected.origin}${expected.pathname}).`);
119
+ }
120
+ return url.searchParams;
121
+ }
122
+ if (options.acceptsBareCode === true && text.includes("=")) return new URLSearchParams(text.replace(/^\?/, ""));
123
+ if (options.acceptsBareCode === true && text !== "") return new URLSearchParams({ code: text });
124
+ throw failure("Paste the whole address from the browser's address bar.");
125
+ };
126
+
127
+ const complete = async (address: string): Promise<void> => {
128
+ if (finished) throw failure("This sign-in has already ended.");
129
+ const answer = answerIn(address.trim());
130
+ const refused = answer.get("error_description") ?? answer.get("error");
131
+ if (refused !== null) throw fail(failure(`The server refused the sign-in: ${refused}`));
132
+ const state = answer.get("state");
133
+ // A bare code carries no state; where one is taken, that is all somebody has.
134
+ if (state === null ? options.acceptsBareCode !== true : state !== prepared.state) {
135
+ throw failure("This address belongs to another sign-in.");
136
+ }
137
+ const code = answer.get("code");
138
+ if (code === null || code === "") throw failure("The address has no authorization code.");
139
+ if (exchanging) throw failure("The browser already came back.");
140
+
141
+ exchanging = true;
142
+ let value: T;
143
+ try {
144
+ value = await options.finish(code, answer.get("iss") ?? undefined);
145
+ } catch (error) {
146
+ throw fail(failure(error instanceof Error ? error.message : String(error), error));
147
+ }
148
+ if (!finished) {
149
+ end();
150
+ resolveDone(value);
151
+ }
152
+ };
153
+ loopback?.onRedirect(complete);
154
+
155
+ return {
156
+ url: prepared.url,
157
+ state: prepared.state,
158
+ listening: loopback !== undefined,
159
+ done,
160
+ complete,
161
+ cancel: () => {
162
+ // An exchange already sent finishes: a code the server spent cannot be asked for again.
163
+ if (!exchanging) fail(failure("Signing in was cancelled."));
164
+ },
165
+ };
166
+ }
@@ -0,0 +1,74 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+
3
+ /**
4
+ * Where a browser on this machine comes back to after a sign-in: a server on
5
+ * 127.0.0.1 that answers one path and hands every address it gets to `onRedirect`.
6
+ */
7
+
8
+ export interface Loopback {
9
+ /** The address to name as the redirect URI, port included. */
10
+ redirectUrl: string;
11
+ /** The answer to the next request on the path, or an error to show in the browser. */
12
+ onRedirect(handler: (address: string) => Promise<void>): void;
13
+ close(): void;
14
+ }
15
+
16
+ const escapeHtml = (text: string): string =>
17
+ text.replace(/[&<>"']/g, (char) => `&#${String(char.charCodeAt(0))};`);
18
+
19
+ function page(appName: string, title: string, body: string): string {
20
+ return `<!doctype html><meta charset="utf-8"><title>${escapeHtml(appName)}</title>
21
+ <body style="font-family:system-ui;margin:4rem auto;max-width:32rem">
22
+ <h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p></body>`;
23
+ }
24
+
25
+ /** Undefined when the port is taken: then only an address the host passes on can finish. */
26
+ export async function listenOnLoopback(port: number, path: string, appName: string): Promise<Loopback | undefined> {
27
+ // Imported here, so a host without `node:http` can load the core and sign in through its own route.
28
+ const { createServer } = await import("node:http");
29
+ let handler: ((address: string) => Promise<void>) | undefined;
30
+ let actualPort = port;
31
+
32
+ const server = createServer((request: IncomingMessage, response: ServerResponse) => {
33
+ const address = new URL(request.url ?? "/", `http://127.0.0.1:${String(actualPort)}`);
34
+ // Browsers also ask for icons, prefetch and reload: only an answer from the sign-in counts.
35
+ const answer = address.searchParams.has("code") || address.searchParams.has("error");
36
+ if (request.method !== "GET" || address.pathname !== path || !answer || handler === undefined) {
37
+ response.writeHead(404).end();
38
+ return;
39
+ }
40
+ // Answered after the exchange, so the page never says "signed in" for a code that was refused.
41
+ handler(address.href).then(
42
+ () => {
43
+ response
44
+ .writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
45
+ .end(page(appName, "Signed in", "You can close this tab and go back to where you started."));
46
+ },
47
+ (error: unknown) => {
48
+ response
49
+ .writeHead(400, { "Content-Type": "text/html; charset=utf-8" })
50
+ .end(page(appName, "Not signed in", error instanceof Error ? error.message : String(error)));
51
+ },
52
+ );
53
+ });
54
+
55
+ const listening = await new Promise<boolean>((resolve) => {
56
+ server.once("error", () => resolve(false));
57
+ // 127.0.0.1, not localhost: localhost may resolve to ::1 here and to 127.0.0.1 in the browser.
58
+ server.listen(port, "127.0.0.1", () => {
59
+ actualPort = (server.address() as { port: number }).port;
60
+ resolve(true);
61
+ });
62
+ });
63
+ if (!listening) return undefined;
64
+
65
+ return {
66
+ redirectUrl: `http://127.0.0.1:${String(actualPort)}${path}`,
67
+ onRedirect: (next) => {
68
+ handler = next;
69
+ },
70
+ close: () => {
71
+ server.close();
72
+ },
73
+ };
74
+ }