reasonally 0.3.0 → 0.5.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.
@@ -3,9 +3,16 @@
3
3
  * `<config>/sessions/<project>/`. Owner-only, like everything else in the config folder.
4
4
  */
5
5
  import { createHash, randomBytes } from "node:crypto";
6
- import { appendFile, chmod, mkdir, readdir, readFile, stat } from "node:fs/promises";
6
+ import { access, appendFile, chmod, mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile, } from "node:fs/promises";
7
+ import { hostname } from "node:os";
7
8
  import { basename, join } from "node:path";
8
- import { CONTINUE_PROMPT, INTERRUPTED_NOTE } from "./loop-constants.js";
9
+ import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
10
+ import { PLAN_TOOL } from "./tools/plan.js";
11
+ /** A new session's id, which is also its file name: when it started, plus a few random characters. */
12
+ export function newSessionId(now = new Date()) {
13
+ const stamp = now.toISOString().replace(/[:.]/g, "-");
14
+ return `${stamp}-${randomBytes(3).toString("hex")}`;
15
+ }
9
16
  /** The folder for one project's sessions: readable name plus a hash of the full path. */
10
17
  export function sessionsDir(configDir, cwd) {
11
18
  const name = basename(cwd)
@@ -14,23 +21,105 @@ export function sessionsDir(configDir, cwd) {
14
21
  const hash = createHash("sha256").update(cwd).digest("hex").slice(0, 10);
15
22
  return join(configDir, "sessions", `${name}-${hash}`);
16
23
  }
24
+ /** A holder refreshes its lock this often… */
25
+ const LOCK_BEAT_MS = 30_000;
26
+ /** …so one untouched for this long was left behind by a program that died. */
27
+ export const LOCK_STALE_MS = 2 * 60_000;
28
+ const lockPath = (sessionPath) => `${sessionPath}.lock`;
29
+ function processIsAlive(pid) {
30
+ try {
31
+ process.kill(pid, 0);
32
+ return true;
33
+ }
34
+ catch (error) {
35
+ // EPERM: it exists but belongs to someone else.
36
+ return error.code === "EPERM";
37
+ }
38
+ }
39
+ const thisProcess = () => ({ pid: process.pid, host: hostname() });
40
+ /** The other running program that has this session open, or null when it's free to use. */
41
+ export async function sessionHolder(sessionPath, { self = thisProcess(), isAlive = processIsAlive, now = Date.now() } = {}) {
42
+ try {
43
+ const file = lockPath(sessionPath);
44
+ const [text, info] = await Promise.all([readFile(file, "utf8"), stat(file)]);
45
+ const lock = JSON.parse(text);
46
+ if (!lock || typeof lock.pid !== "number" || typeof lock.host !== "string")
47
+ return null;
48
+ if (lock.pid === self.pid && lock.host === self.host)
49
+ return null;
50
+ if (now - info.mtimeMs > LOCK_STALE_MS)
51
+ return null;
52
+ if (lock.host === self.host && !isAlive(lock.pid))
53
+ return null;
54
+ return { pid: lock.pid, host: lock.host, surface: lock.surface ?? "terminal" };
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ /**
61
+ * Takes the session for this program. Returns the holder when another running program has it
62
+ * (then don't write to it), or null once it's ours. If the lock can't be written at all (a
63
+ * read-only folder), that's null too: saving matters more than the lock.
64
+ */
65
+ export async function claimSession(sessionPath, surface, options = {}) {
66
+ const self = options.self ?? thisProcess();
67
+ const file = lockPath(sessionPath);
68
+ const body = JSON.stringify({ ...self, surface });
69
+ for (let attempt = 0; attempt < 2; attempt++) {
70
+ try {
71
+ await writeFile(file, body, { flag: "wx", mode: 0o600 });
72
+ return null;
73
+ }
74
+ catch (error) {
75
+ if (error.code !== "EEXIST")
76
+ return null;
77
+ }
78
+ const holder = await sessionHolder(sessionPath, options);
79
+ if (holder)
80
+ return holder;
81
+ // Ours already, or left behind: replace it.
82
+ await rm(file, { force: true }).catch(() => { });
83
+ }
84
+ return await sessionHolder(sessionPath, options);
85
+ }
86
+ /** Lets go of a session this program holds. Someone else's lock is left alone. */
87
+ export async function releaseSession(sessionPath, options = {}) {
88
+ const self = options.self ?? thisProcess();
89
+ const file = lockPath(sessionPath);
90
+ try {
91
+ const lock = JSON.parse(await readFile(file, "utf8"));
92
+ if (lock?.pid === self.pid && lock.host === self.host)
93
+ await rm(file, { force: true });
94
+ }
95
+ catch {
96
+ // no lock, or unreadable: nothing of ours to remove
97
+ }
98
+ }
17
99
  /** Appends records to a session file in order; the file is created with the first record. */
18
100
  export class SessionWriter {
19
101
  path;
20
102
  meta;
103
+ surface;
21
104
  chain = Promise.resolve();
22
105
  created;
23
106
  /** Set when a write failed (disk full, permissions); saving stops quietly after that. */
24
107
  failed = false;
25
- constructor(path, meta) {
108
+ beat;
109
+ constructor(path, meta,
110
+ /** Set for a new session that takes its lock when the file is created. */
111
+ surface = null) {
26
112
  this.path = path;
27
113
  this.meta = meta;
114
+ this.surface = surface;
28
115
  this.created = meta === null;
29
116
  }
30
- /** A new session; nothing is written until the first record. */
31
- static create(dir, cwd, model, now = new Date()) {
32
- const stamp = now.toISOString().replace(/[:.]/g, "-");
33
- const id = `${stamp}-${randomBytes(3).toString("hex")}`;
117
+ /**
118
+ * A new session; nothing is written until the first record. With `surface`, the file records
119
+ * where it was started and is locked to this program while it's open (see `release`).
120
+ */
121
+ static create(dir, cwd, model, now = new Date(), surface) {
122
+ const id = newSessionId(now);
34
123
  return new SessionWriter(join(dir, `${id}.jsonl`), {
35
124
  type: "meta",
36
125
  version: 1,
@@ -38,7 +127,8 @@ export class SessionWriter {
38
127
  cwd,
39
128
  model,
40
129
  createdAt: now.toISOString(),
41
- });
130
+ ...(surface ? { surface } : {}),
131
+ }, surface ?? null);
42
132
  }
43
133
  /** Continues an existing session file. */
44
134
  static resume(path) {
@@ -47,6 +137,32 @@ export class SessionWriter {
47
137
  get started() {
48
138
  return this.created;
49
139
  }
140
+ /**
141
+ * Takes an existing session for this program before continuing it. Returns the holder when
142
+ * another running program has it open: show it, but don't write to it.
143
+ */
144
+ async claim(surface) {
145
+ const holder = await claimSession(this.path, surface);
146
+ if (!holder)
147
+ this.keepLock();
148
+ return holder;
149
+ }
150
+ /** Lets go of the session (after the last write lands) so another program can continue it. */
151
+ async release() {
152
+ clearInterval(this.beat);
153
+ this.beat = undefined;
154
+ await this.chain;
155
+ await releaseSession(this.path);
156
+ }
157
+ keepLock() {
158
+ clearInterval(this.beat);
159
+ const touch = () => {
160
+ const now = new Date();
161
+ utimes(lockPath(this.path), now, now).catch(() => { });
162
+ };
163
+ this.beat = setInterval(touch, LOCK_BEAT_MS);
164
+ this.beat.unref();
165
+ }
50
166
  append(record) {
51
167
  if (this.failed)
52
168
  return;
@@ -59,6 +175,8 @@ export class SessionWriter {
59
175
  await appendFile(this.path, text, { mode: 0o600 });
60
176
  await chmod(this.path, 0o600);
61
177
  this.created = true;
178
+ if (this.surface && !(await claimSession(this.path, this.surface)))
179
+ this.keepLock();
62
180
  return;
63
181
  }
64
182
  await appendFile(this.path, text, { mode: 0o600 });
@@ -74,13 +192,96 @@ export class SessionWriter {
74
192
  }
75
193
  }
76
194
  const bigintSafe = (_key, value) => typeof value === "bigint" ? value.toString() : value;
195
+ /**
196
+ * Copies a saved conversation under a new id, to carry on separately. The original isn't touched.
197
+ * The copy starts with no cost of its own: usage records stay with the original, so nothing is
198
+ * counted twice. It appears whole or not at all (written aside, then moved into place). Returns
199
+ * the copy's id; throws if the source can't be read or isn't a conversation.
200
+ */
201
+ export async function copySession(sourcePath, dir, { now = new Date(), surface } = {}) {
202
+ const text = await readFile(sourcePath, "utf8");
203
+ let meta = null;
204
+ const kept = [];
205
+ for (const line of text.split("\n")) {
206
+ if (!line.trim())
207
+ continue;
208
+ let record;
209
+ try {
210
+ record = JSON.parse(line);
211
+ }
212
+ catch {
213
+ continue; // a torn line, as loadSession skips it
214
+ }
215
+ if (record.type === "meta")
216
+ meta ??= record;
217
+ else if (record.type !== "usage")
218
+ kept.push(line);
219
+ }
220
+ if (!meta)
221
+ throw new Error("That file isn't a conversation.");
222
+ await mkdir(dir, { recursive: true, mode: 0o700 });
223
+ let id = newSessionId(now);
224
+ // Two copies in the same millisecond: the random part differs, but never overwrite anything.
225
+ while (await access(join(dir, `${id}.jsonl`)).then(() => true, () => false)) {
226
+ id = newSessionId(now);
227
+ }
228
+ const copy = {
229
+ ...meta,
230
+ id,
231
+ createdAt: now.toISOString(),
232
+ ...(surface ? { surface } : {}),
233
+ };
234
+ const path = join(dir, `${id}.jsonl`);
235
+ // Not `.jsonl`, so a listing never picks up a half-written copy.
236
+ const temp = `${path}.${process.pid}.tmp`;
237
+ try {
238
+ await writeFile(temp, [JSON.stringify(copy), ...kept].join("\n") + "\n", {
239
+ mode: 0o600,
240
+ flag: "wx",
241
+ });
242
+ await rename(temp, path);
243
+ }
244
+ catch (error) {
245
+ await rm(temp, { force: true }).catch(() => { });
246
+ throw error;
247
+ }
248
+ return id;
249
+ }
250
+ /** The record a host saves when a step finishes (with a presented plan's outcome). */
251
+ export function stepRecord(id, title, result) {
252
+ return {
253
+ type: "step",
254
+ id,
255
+ title,
256
+ summary: result.summary,
257
+ isError: Boolean(result.isError),
258
+ ...(result.plan ? { plan: result.plan } : {}),
259
+ };
260
+ }
261
+ /** The plan in a `present_plan` call's arguments, or null when they don't parse. */
262
+ function planArgument(args) {
263
+ try {
264
+ const parsed = JSON.parse(args);
265
+ return typeof parsed?.plan === "string" && parsed.plan.trim() ? parsed.plan.trim() : null;
266
+ }
267
+ catch {
268
+ return null;
269
+ }
270
+ }
271
+ /** Notes the agent adds in front of a message, never shown as what the user wrote. */
272
+ const LEADING_NOTES = [INTERRUPTED_NOTE, PLAN_ON_NOTE, HELPER_PLAN_ON_NOTE, PLAN_OFF_NOTE];
77
273
  /** Strips our own markers from a user message, for showing it. */
78
274
  export function userText(content) {
79
275
  if (content === CONTINUE_PROMPT)
80
276
  return null;
81
- return content.startsWith(INTERRUPTED_NOTE)
82
- ? content.slice(INTERRUPTED_NOTE.length).trimStart()
83
- : content;
277
+ let text = content;
278
+ for (let found = true; found;) {
279
+ const note = LEADING_NOTES.find((n) => text.startsWith(n));
280
+ found = Boolean(note);
281
+ if (note)
282
+ text = text.slice(note.length).trimStart();
283
+ }
284
+ return text || null;
84
285
  }
85
286
  /** Reads a session. Lines that don't parse (a crash mid-write) are skipped. */
86
287
  export async function loadSession(path) {
@@ -142,6 +343,24 @@ export async function loadSession(path) {
142
343
  display.push({ kind: "text", text: m.content });
143
344
  for (const call of m.tool_calls ?? []) {
144
345
  const step = steps.get(call.id);
346
+ if (call.function.name === PLAN_TOOL) {
347
+ // Its outcome when it finished; with no step saved, it never got an answer.
348
+ const shown = step?.plan ?? (step ? null : planArgument(call.function.arguments));
349
+ if (typeof shown === "string") {
350
+ display.push({
351
+ kind: "plan",
352
+ text: shown,
353
+ edited: false,
354
+ outcome: "stopped",
355
+ feedback: null,
356
+ });
357
+ continue;
358
+ }
359
+ if (shown) {
360
+ display.push({ kind: "plan", ...shown });
361
+ continue;
362
+ }
363
+ }
145
364
  display.push({
146
365
  kind: "step",
147
366
  title: step?.title ?? call.function.name,
@@ -170,16 +389,19 @@ export async function listSessions(dir) {
170
389
  return [];
171
390
  }
172
391
  const loaded = await Promise.all(names.map((n) => loadSession(join(dir, n))));
392
+ // Ties (changed in the same millisecond) go to the newer conversation: ids start with its start.
173
393
  return loaded
174
394
  .filter((s) => s !== null && s.display.some((d) => d.kind === "user"))
175
395
  .map((s) => ({
396
+ id: s.meta.id,
176
397
  path: s.path,
398
+ surface: s.meta.surface ?? "terminal",
177
399
  firstMessage: s.display.find((d) => d.kind === "user").text,
178
400
  model: s.model,
179
401
  costMicros: s.costMicros,
180
402
  updatedAt: s.updatedAt,
181
403
  }))
182
- .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
404
+ .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.id.localeCompare(a.id));
183
405
  }
184
406
  /** "just now", "5m ago", "3h ago", "2d ago", or the date. */
185
407
  export function timeAgo(date, now = new Date()) {
@@ -1,5 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
- import { tildePath } from "./paths.js";
2
+ import { readOnlyWords } from "../readonly-command.js";
3
+ import { resolvePath, tildePath } from "./paths.js";
3
4
  import { optionalInt, stringArg, truncateMiddle } from "./types.js";
4
5
  const DEFAULT_TIMEOUT_MS = 120_000;
5
6
  const MAX_TIMEOUT_MS = 600_000;
@@ -66,13 +67,22 @@ export function runCommand(command, opts) {
66
67
  });
67
68
  // Keep a little more than the cap while running; truncate once at the end.
68
69
  const append = (chunk) => {
69
- output += chunk.toString("utf8");
70
+ const text = chunk.toString("utf8");
71
+ output += text;
70
72
  if (output.length > MAX_OUTPUT_CHARS * 4) {
71
73
  output = truncateMiddle(output, MAX_OUTPUT_CHARS * 2);
72
74
  }
75
+ if (opts.onOutput && !settled) {
76
+ const plain = stripAnsi(text);
77
+ if (plain)
78
+ opts.onOutput(plain);
79
+ }
73
80
  };
74
81
  child.stdout?.on("data", append);
75
82
  child.stderr?.on("data", append);
83
+ const pid = child.pid;
84
+ if (pid !== undefined)
85
+ opts.onProcess?.(pid, "start");
76
86
  let forceTimer;
77
87
  const stop = () => {
78
88
  killTree(child, "SIGTERM");
@@ -99,6 +109,8 @@ export function runCommand(command, opts) {
99
109
  // Something it started in the background may still hold the pipes open: stop listening.
100
110
  child.stdout?.destroy();
101
111
  child.stderr?.destroy();
112
+ if (pid !== undefined)
113
+ opts.onProcess?.(pid, "exit");
102
114
  resolve({
103
115
  output: truncateMiddle(stripAnsi(output), MAX_OUTPUT_CHARS),
104
116
  exitCode,
@@ -139,10 +151,16 @@ export const bashTool = {
139
151
  const timeoutMs = optionalInt(args, "timeout_ms", 1000, MAX_TIMEOUT_MS) ?? DEFAULT_TIMEOUT_MS;
140
152
  const firstLine = command.split("\n")[0];
141
153
  const short = firstLine.length > 80 ? `${firstLine.slice(0, 77)}…` : firstLine;
154
+ // Commands that only look can run without asking in Plan mode: their files, resolved.
155
+ const words = isWindows ? null : readOnlyWords(command, shellFor(ctx.env).name);
156
+ const readOnlyPaths = words
157
+ ? [ctx.cwd, ...(await Promise.all(words.map((w) => resolvePath(w, ctx.cwd, ctx.home))))]
158
+ : undefined;
142
159
  return {
143
160
  kind: "exec",
144
161
  paths: [ctx.cwd],
145
162
  command,
163
+ readOnlyPaths,
146
164
  title: `Run ${short}${command.includes("\n") ? " …" : ""}`,
147
165
  preview: `$ ${command}\n\nin ${tildePath(ctx.cwd, ctx.home)}`,
148
166
  async run() {
@@ -151,6 +169,8 @@ export const bashTool = {
151
169
  env: ctx.env,
152
170
  signal: ctx.signal,
153
171
  timeoutMs,
172
+ onOutput: ctx.output,
173
+ onProcess: ctx.process,
154
174
  });
155
175
  const status = result.aborted
156
176
  ? "stopped"
@@ -1,8 +1,11 @@
1
1
  import { bashTool } from "./bash.js";
2
2
  import { editTool, readTool, writeTool } from "./files.js";
3
+ import { planTool } from "./plan.js";
3
4
  import { findTool, grepTool } from "./search.js";
4
5
  import { taskTool } from "./task.js";
5
6
  import { todoTool } from "./todo.js";
7
+ import { webFetchTool } from "./web-fetch.js";
8
+ import { webSearchTool } from "./web-search.js";
6
9
  /** The built-in tools, in the order the model sees them. */
7
10
  export const BUILTIN_TOOLS = [
8
11
  readTool,
@@ -13,7 +16,15 @@ export const BUILTIN_TOOLS = [
13
16
  findTool,
14
17
  todoTool,
15
18
  taskTool,
19
+ planTool,
16
20
  ];
21
+ /** The web tools the user hasn't turned off, after the built-ins. */
22
+ export function webTools(policy) {
23
+ return [
24
+ ...(policy.search === "off" ? [] : [webSearchTool]),
25
+ ...(policy.fetch === "off" ? [] : [webFetchTool]),
26
+ ];
27
+ }
17
28
  /** The `tools` array for a chat request. */
18
29
  export const toolSchemas = (tools) => tools.map((t) => ({
19
30
  type: "function",
@@ -0,0 +1,101 @@
1
+ import { stringArg, ToolInputError } from "./types.js";
2
+ /** The tool the agent presents its plan with, in Plan mode. The loop answers it (see loop.ts). */
3
+ export const PLAN_TOOL = "present_plan";
4
+ export const MAX_PLAN_CHARS = 20_000;
5
+ /** One line for the transcript, the same in every app. */
6
+ export const PLAN_OUTCOME_LABELS = {
7
+ "approved-ask": "Plan approved · ask before edits",
8
+ "approved-auto": "Plan approved · auto-accept edits",
9
+ "sent-back": "Plan sent back",
10
+ "not-approved": "Plan not approved",
11
+ stopped: "Stopped",
12
+ };
13
+ /** The plan's title: its first heading, or else its first line, as plain text. */
14
+ export function planTitle(plan) {
15
+ const lines = plan.split("\n").map((l) => l.trim());
16
+ const line = lines.find((l) => /^#{1,6}\s/.test(l)) ?? lines.find(Boolean) ?? "";
17
+ const plain = line
18
+ .replace(/^#{1,6}\s+/, "")
19
+ .replace(/^(?:[-*+]|\d+[.)])\s+/, "")
20
+ .replace(/[*_`]/g, "")
21
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
22
+ .trim();
23
+ return plain.length > 80 ? `${plain.slice(0, 79)}…` : plain || "Plan";
24
+ }
25
+ export const planTool = {
26
+ name: PLAN_TOOL,
27
+ description: "Plan mode only: show the user your plan and ask them to approve it. Write it in Markdown: " +
28
+ "a short title (# …), the goal in a sentence or two, numbered steps naming the files each " +
29
+ "touches, and how you'll check the result. Keep it short enough to read in a minute. Call it " +
30
+ "once, when the plan is complete, as the last call in your reply. The user may approve it " +
31
+ "(you then carry it out), edit it, or send it back with what to change.",
32
+ parameters: {
33
+ type: "object",
34
+ properties: {
35
+ plan: { type: "string", description: "The plan, in Markdown." },
36
+ },
37
+ required: ["plan"],
38
+ additionalProperties: false,
39
+ },
40
+ async prepare(args) {
41
+ const plan = stringArg(args, "plan").trim();
42
+ if (!plan)
43
+ throw new ToolInputError("`plan` is empty. Write the plan in Markdown.");
44
+ if (plan.length > MAX_PLAN_CHARS) {
45
+ throw new ToolInputError(`The plan is ${plan.length.toLocaleString("en-US")} characters; keep it under ` +
46
+ `${MAX_PLAN_CHARS.toLocaleString("en-US")}. Summarize the steps instead of including code.`);
47
+ }
48
+ return {
49
+ kind: "meta",
50
+ paths: [],
51
+ title: "Plan",
52
+ preview: plan,
53
+ // The loop shows the plan and waits for the user's answer instead of running this.
54
+ run: async () => ({ output: plan, summary: "Plan" }),
55
+ };
56
+ },
57
+ };
58
+ /**
59
+ * The `plan` string so far from a tool call's streaming arguments (`{"plan": "# Add a…`), or null
60
+ * before it starts. Escapes are decoded; an escape cut off at the end is left out until it's whole.
61
+ */
62
+ export function partialPlan(args) {
63
+ const key = /"plan"\s*:\s*"/.exec(args);
64
+ if (!key)
65
+ return null;
66
+ let out = "";
67
+ for (let i = key.index + key[0].length; i < args.length; i++) {
68
+ const c = args[i];
69
+ if (c === '"')
70
+ return out;
71
+ if (c !== "\\") {
72
+ out += c;
73
+ continue;
74
+ }
75
+ const next = args[i + 1];
76
+ if (next === undefined)
77
+ return out;
78
+ if (next === "u") {
79
+ const hex = args.slice(i + 2, i + 6);
80
+ if (hex.length < 4)
81
+ return out;
82
+ if (/^[0-9a-fA-F]{4}$/.test(hex))
83
+ out += String.fromCharCode(parseInt(hex, 16));
84
+ i += 5;
85
+ continue;
86
+ }
87
+ const simple = {
88
+ n: "\n",
89
+ t: "\t",
90
+ r: "\r",
91
+ b: "\b",
92
+ f: "\f",
93
+ '"': '"',
94
+ "\\": "\\",
95
+ "/": "/",
96
+ };
97
+ out += simple[next] ?? next;
98
+ i++;
99
+ }
100
+ return out;
101
+ }
@@ -4,7 +4,7 @@ export const MAX_PARALLEL_HELPERS = 4;
4
4
  export const HELPER_NOTE = `# You are a helper
5
5
  Another agent handed you the task below and will act on your report; the user sees only a one-line
6
6
  status for you. Work on your own: you can't ask the user questions. You can read and search freely;
7
- edits and commands need the user's approval, so only make changes the task asks for.
7
+ edits, commands and some web pages need the user's approval, so only make changes the task asks for.
8
8
  Finish with a concise report: what you found (with path:line references), anything you changed,
9
9
  and anything you couldn't do. Don't paste whole files.`;
10
10
  export const taskTool = {
@@ -36,7 +36,7 @@ export const taskTool = {
36
36
  kind: "meta",
37
37
  paths: [],
38
38
  title: `Helper: ${description}`,
39
- run: () => helpers.run({ description, prompt }, ctx.signal, ctx.progress ?? (() => { })),
39
+ run: () => helpers.run({ description, prompt, callId: ctx.callId }, ctx.signal, ctx.progress ?? (() => { })),
40
40
  };
41
41
  },
42
42
  };
@@ -0,0 +1,131 @@
1
+ import { parseDocument } from "./dom.js";
2
+ const ENDPOINT = "https://html.duckduckgo.com/html/";
3
+ /** A search from this computer gets this long before the fallback takes over. */
4
+ export const DEVICE_TIMEOUT_MS = 5_000;
5
+ /** After a block (or a page we can't read), searches skip this computer for this long. */
6
+ export const BACKOFF_MS = 10 * 60_000;
7
+ /** At most one search a second from this computer. */
8
+ const MIN_INTERVAL_MS = 1_000;
9
+ const MAX_RESULTS = 10;
10
+ const RECENCY_PARAM = { day: "d", week: "w", month: "m", year: "y" };
11
+ /** Back-off and pacing, shared by every search in this process. */
12
+ export const deviceState = { blockedUntil: 0, lastAt: 0 };
13
+ /** DuckDuckGo's region for a locale ("en-US" → "us-en"); "wt-wt" means no region. */
14
+ export function regionFor(locale) {
15
+ const [language, country] = locale.toLowerCase().replace("_", "-").split("-");
16
+ if (!language || !country || !/^[a-z]{2}$/.test(country))
17
+ return "wt-wt";
18
+ return `${country === "gb" ? "uk" : country}-${language}`;
19
+ }
20
+ /** The result's real address: DuckDuckGo wraps links as `//duckduckgo.com/l/?uddg=<url>`. */
21
+ export function unwrapLink(href) {
22
+ try {
23
+ const url = new URL(href, "https://duckduckgo.com");
24
+ if (url.hostname.endsWith("duckduckgo.com")) {
25
+ if (url.pathname === "/y.js")
26
+ return null; // an ad
27
+ const target = url.searchParams.get("uddg");
28
+ return target && /^https?:\/\//i.test(target) ? target : null;
29
+ }
30
+ return /^https?:$/.test(url.protocol) ? url.href : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /** Reads a results page. `null`: not a results page we recognize (a block, or a changed layout). */
37
+ export async function parseResults(html) {
38
+ const document = await parseDocument(html);
39
+ const items = [...document.querySelectorAll(".result")];
40
+ if (!items.length)
41
+ return document.querySelector(".no-results") ? [] : null;
42
+ const seen = new Set();
43
+ const results = [];
44
+ for (const item of items) {
45
+ if (item.classList.contains("result--ad"))
46
+ continue;
47
+ const link = item.querySelector("a.result__a");
48
+ const url = link ? unwrapLink(link.getAttribute("href") ?? "") : null;
49
+ if (!link || !url || seen.has(url))
50
+ continue;
51
+ seen.add(url);
52
+ results.push({
53
+ title: (link.textContent ?? "").replace(/\s+/g, " ").trim() || url,
54
+ url,
55
+ snippet: (item.querySelector(".result__snippet")?.textContent ?? "")
56
+ .replace(/\s+/g, " ")
57
+ .trim(),
58
+ published: null,
59
+ });
60
+ if (results.length === MAX_RESULTS)
61
+ break;
62
+ }
63
+ // Results that are all ads, or none we could read, mean the layout isn't what we know.
64
+ return results.length ? results : null;
65
+ }
66
+ function wait(ms, signal) {
67
+ return new Promise((resolve, reject) => {
68
+ if (signal.aborted)
69
+ return reject(signal.reason);
70
+ const timer = setTimeout(done, ms);
71
+ function done() {
72
+ signal.removeEventListener("abort", onAbort);
73
+ resolve();
74
+ }
75
+ function onAbort() {
76
+ clearTimeout(timer);
77
+ reject(signal.reason);
78
+ }
79
+ signal.addEventListener("abort", onAbort, { once: true });
80
+ });
81
+ }
82
+ /** Searches from this computer. The user's `signal` aborting is thrown; anything else is a result. */
83
+ export async function searchFromDevice(query, options) {
84
+ const now = options.now ?? Date.now;
85
+ if (now() < deviceState.blockedUntil)
86
+ return { ok: false, why: "backoff" };
87
+ const gap = deviceState.lastAt + MIN_INTERVAL_MS - now();
88
+ if (gap > 0)
89
+ await wait(gap, options.signal);
90
+ deviceState.lastAt = now();
91
+ const locale = options.locale ?? Intl.DateTimeFormat().resolvedOptions().locale;
92
+ const form = new URLSearchParams({
93
+ q: query.site ? `${query.query} site:${query.site}` : query.query,
94
+ kl: regionFor(locale),
95
+ });
96
+ if (query.recency)
97
+ form.set("df", RECENCY_PARAM[query.recency]);
98
+ const timeout = AbortSignal.timeout(DEVICE_TIMEOUT_MS);
99
+ let html;
100
+ try {
101
+ const res = await options.fetch(ENDPOINT, {
102
+ method: "POST",
103
+ headers: {
104
+ "content-type": "application/x-www-form-urlencoded",
105
+ accept: "text/html",
106
+ "accept-language": `${locale}, en;q=0.8`,
107
+ "user-agent": options.userAgent,
108
+ },
109
+ body: form.toString(),
110
+ signal: AbortSignal.any([options.signal, timeout]),
111
+ });
112
+ // DuckDuckGo answers automated-looking traffic with 202 and a challenge instead of results.
113
+ if (res.status !== 200) {
114
+ res.body?.cancel().catch(() => { });
115
+ deviceState.blockedUntil = now() + BACKOFF_MS;
116
+ return { ok: false, why: "blocked" };
117
+ }
118
+ html = await res.text();
119
+ }
120
+ catch {
121
+ if (options.signal.aborted)
122
+ throw options.signal.reason;
123
+ return { ok: false, why: timeout.aborted ? "timeout" : "network" };
124
+ }
125
+ const results = await parseResults(html);
126
+ if (results === null) {
127
+ deviceState.blockedUntil = now() + BACKOFF_MS;
128
+ return { ok: false, why: "unreadable" };
129
+ }
130
+ return results.length ? { ok: true, results } : { ok: false, why: "empty" };
131
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The few DOM calls the web tools make, typed here so they compile the same with or without the
3
+ * DOM's own types (the CLI builds without them; the desktop's builds have them).
4
+ */
5
+ /** Parses HTML into a document (linkedom, loaded on first use). */
6
+ export async function parseDocument(html) {
7
+ const { parseHTML } = await import("linkedom");
8
+ return parseHTML(html).document;
9
+ }