agentpath 0.0.0-stage → 0.1.0-alpha.2

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 (127) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +101 -2
  3. package/THIRD_PARTY_NOTICES +12 -0
  4. package/apps/demo-site/dist/site.js +92 -0
  5. package/apps/studio/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  6. package/apps/studio/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  7. package/apps/studio/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  8. package/apps/studio/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  9. package/apps/studio/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  10. package/apps/studio/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  11. package/apps/studio/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  12. package/apps/studio/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  13. package/apps/studio/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  14. package/apps/studio/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  15. package/apps/studio/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  16. package/apps/studio/dist/assets/index-DH4wJPHm.js +67 -0
  17. package/apps/studio/dist/assets/index-DrnNh2ip.css +1 -0
  18. package/apps/studio/dist/index.html +14 -0
  19. package/audit.md +173 -0
  20. package/autonomous-mode.md +104 -0
  21. package/ci.md +118 -0
  22. package/coding-agents.md +143 -0
  23. package/concepts.md +145 -0
  24. package/contracts.md +356 -0
  25. package/examples/tasks/ambiguous.json +98 -0
  26. package/examples/tasks/assertion-failure.json +98 -0
  27. package/examples/tasks/broken.json +98 -0
  28. package/examples/tasks/fixed.json +98 -0
  29. package/examples/tasks/recovery.json +19 -0
  30. package/images/compare-recovery-desktop.jpg +0 -0
  31. package/images/compare-variants-desktop.jpg +0 -0
  32. package/images/overview-desktop.jpg +0 -0
  33. package/images/run-autonomous-passed-desktop.jpg +0 -0
  34. package/images/run-failed-desktop.jpg +0 -0
  35. package/images/run-failed-mobile.jpg +0 -0
  36. package/images/run-missing-artifact-desktop.jpg +0 -0
  37. package/images/task-editor-laptop.jpg +0 -0
  38. package/installation.md +102 -0
  39. package/ledger.md +62 -0
  40. package/licenses/-fontsource-variable-geist-mono.txt +93 -0
  41. package/licenses/-fontsource-variable-geist.txt +93 -0
  42. package/licenses/lucide-react.txt +43 -0
  43. package/licenses/react-dom.txt +21 -0
  44. package/licenses/react.txt +21 -0
  45. package/licenses/scheduler.txt +21 -0
  46. package/licenses/tailwindcss.txt +21 -0
  47. package/licenses/zod.txt +21 -0
  48. package/package.json +165 -4
  49. package/packages/cli/bin/agentpath.js +39 -0
  50. package/packages/cli/dist/audit-rerun.js +384 -0
  51. package/packages/cli/dist/audit.js +387 -0
  52. package/packages/cli/dist/change-summaries.js +87 -0
  53. package/packages/cli/dist/ci-report.js +88 -0
  54. package/packages/cli/dist/demo.js +88 -0
  55. package/packages/cli/dist/doctor.js +265 -0
  56. package/packages/cli/dist/explain.js +89 -0
  57. package/packages/cli/dist/git.js +7 -0
  58. package/packages/cli/dist/inspect.js +118 -0
  59. package/packages/cli/dist/ledger.js +509 -0
  60. package/packages/cli/dist/local.js +102 -0
  61. package/packages/cli/dist/main.js +708 -0
  62. package/packages/cli/dist/mcp.js +231 -0
  63. package/packages/cli/dist/paths.js +6 -0
  64. package/packages/cli/dist/playwright-fixture.js +185 -0
  65. package/packages/cli/dist/playwright-reporter.js +49 -0
  66. package/packages/cli/dist/tasks.js +37 -0
  67. package/packages/cli/dist/test-source.js +283 -0
  68. package/packages/cli/dist/watch.js +96 -0
  69. package/packages/contracts/dist/agent-settings.js +18 -0
  70. package/packages/contracts/dist/agent.js +175 -0
  71. package/packages/contracts/dist/audit.js +115 -0
  72. package/packages/contracts/dist/guidance.js +339 -0
  73. package/packages/contracts/dist/index.js +14 -0
  74. package/packages/contracts/dist/inspect.js +63 -0
  75. package/packages/contracts/dist/ledger.js +80 -0
  76. package/packages/contracts/dist/local.js +171 -0
  77. package/packages/contracts/dist/outcomes.js +94 -0
  78. package/packages/contracts/dist/platform.js +105 -0
  79. package/packages/contracts/dist/playwright-live.js +76 -0
  80. package/packages/contracts/dist/policy.js +93 -0
  81. package/packages/contracts/dist/run.js +178 -0
  82. package/packages/contracts/dist/task-issues.js +39 -0
  83. package/packages/contracts/dist/task.js +185 -0
  84. package/packages/contracts/dist/watch.js +57 -0
  85. package/packages/core/dist/action-feedback.js +103 -0
  86. package/packages/core/dist/actions.js +160 -0
  87. package/packages/core/dist/agent-loop.js +122 -0
  88. package/packages/core/dist/artifacts.js +156 -0
  89. package/packages/core/dist/assertions.js +120 -0
  90. package/packages/core/dist/autonomous.js +1 -0
  91. package/packages/core/dist/browser.js +196 -0
  92. package/packages/core/dist/compare.js +141 -0
  93. package/packages/core/dist/control-state.js +62 -0
  94. package/packages/core/dist/diagnostics.js +134 -0
  95. package/packages/core/dist/evidence-diff.js +93 -0
  96. package/packages/core/dist/evidence.js +203 -0
  97. package/packages/core/dist/index.js +22 -0
  98. package/packages/core/dist/inspect.js +257 -0
  99. package/packages/core/dist/integrity.js +176 -0
  100. package/packages/core/dist/liveness.js +114 -0
  101. package/packages/core/dist/local-files.js +61 -0
  102. package/packages/core/dist/locators.js +214 -0
  103. package/packages/core/dist/model-provider.js +88 -0
  104. package/packages/core/dist/observation.js +257 -0
  105. package/packages/core/dist/playwright-live.js +519 -0
  106. package/packages/core/dist/playwright-results.js +543 -0
  107. package/packages/core/dist/policy.js +182 -0
  108. package/packages/core/dist/privacy.js +93 -0
  109. package/packages/core/dist/recovery.js +54 -0
  110. package/packages/core/dist/retention.js +204 -0
  111. package/packages/core/dist/run-index.js +177 -0
  112. package/packages/core/dist/run-plan.js +28 -0
  113. package/packages/core/dist/run-repository.js +518 -0
  114. package/packages/core/dist/runner.js +913 -0
  115. package/packages/core/dist/storage.js +63 -0
  116. package/packages/core/dist/task-fingerprint.js +36 -0
  117. package/packages/core/dist/test-change-rerun.js +84 -0
  118. package/packages/core/dist/test-changes.js +896 -0
  119. package/packages/core/dist/timing.js +41 -0
  120. package/packages/core/dist/watch.js +165 -0
  121. package/packages/server/dist/index.js +265 -0
  122. package/packages/server/dist/task-store.js +103 -0
  123. package/quickstart.md +85 -0
  124. package/security.md +136 -0
  125. package/try-on-your-repo.md +54 -0
  126. package/understanding-results.md +159 -0
  127. package/writing-tasks.md +196 -0
@@ -0,0 +1,114 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { execFile } from "node:child_process";
3
+ import { hostname } from "node:os";
4
+ import { SCHEMA_VERSION, runLivenessRecordSchema } from "#agentpath/contracts";
5
+ import { writeLocalJson } from "./storage.js";
6
+ export const LIVENESS_FILE = "liveness.json";
7
+ export const HEARTBEAT_INTERVAL_MS = 2_000;
8
+ export const HEARTBEAT_TTL_MS = 15_000;
9
+ const processInstance = randomUUID();
10
+ // Wall-clock start of this process, recorded so readers can recognize PID reuse.
11
+ const processStartedAt = new Date(Date.now() - process.uptime() * 1000).toISOString();
12
+ export function hostDigest(name = hostname()) {
13
+ return createHash("sha256").update(name).digest("hex");
14
+ }
15
+ /** Periodically rewrites the run's owner lease until the run is released. */
16
+ export class RunHeartbeat {
17
+ path;
18
+ runId;
19
+ #timer;
20
+ #sequence = 0;
21
+ #writes = Promise.resolve();
22
+ #released = false;
23
+ intervalMs;
24
+ ttlMs;
25
+ constructor(path, runId, settings = {}) {
26
+ this.path = path;
27
+ this.runId = runId;
28
+ this.intervalMs = settings.intervalMs ?? HEARTBEAT_INTERVAL_MS;
29
+ this.ttlMs = settings.ttlMs ?? HEARTBEAT_TTL_MS;
30
+ }
31
+ async start() {
32
+ await this.#write("active");
33
+ this.#timer = setInterval(() => { void this.#write("active").catch(() => { }); }, this.intervalMs);
34
+ // A heartbeat never keeps a finished CLI process alive.
35
+ this.#timer.unref();
36
+ }
37
+ /** Marks the lease released. Readers then never treat the run as live. */
38
+ async release() {
39
+ if (this.#released)
40
+ return;
41
+ this.#released = true;
42
+ clearInterval(this.#timer);
43
+ await this.#write("released", true).catch(() => { });
44
+ }
45
+ #write(state, final = false) {
46
+ const next = this.#writes.then(async () => {
47
+ if (this.#released && !final)
48
+ return;
49
+ await writeLocalJson(this.path, runLivenessRecordSchema.parse({
50
+ schemaVersion: SCHEMA_VERSION, runId: this.runId, state,
51
+ owner: { pid: process.pid, hostDigest: hostDigest(), processStartedAt, instance: processInstance },
52
+ heartbeatAt: new Date().toISOString(), intervalMs: this.intervalMs, ttlMs: this.ttlMs, sequence: this.#sequence++,
53
+ }));
54
+ });
55
+ // Keep the chain usable after a failed write; the caller decides whether to observe the failure.
56
+ this.#writes = next.catch(() => { });
57
+ return next;
58
+ }
59
+ }
60
+ /** Probes a PID without signalling it. Signal 0 checks existence only. */
61
+ export const probeProcess = async (pid) => {
62
+ try {
63
+ process.kill(pid, 0);
64
+ }
65
+ catch (error) {
66
+ const code = error.code;
67
+ if (code === "ESRCH")
68
+ return { alive: false };
69
+ if (code !== "EPERM")
70
+ throw error;
71
+ }
72
+ return { alive: true, startedAt: await processStartTime(pid) };
73
+ };
74
+ async function processStartTime(pid) {
75
+ if (process.platform !== "darwin" && process.platform !== "linux")
76
+ return undefined;
77
+ return new Promise((resolve) => {
78
+ execFile("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 1_000, env: { ...process.env, LC_ALL: "C", TZ: process.env.TZ } }, (error, stdout) => {
79
+ const parsed = error ? Number.NaN : Date.parse(stdout.trim().replace(/\s+/g, " "));
80
+ resolve(Number.isFinite(parsed) ? parsed : undefined);
81
+ });
82
+ });
83
+ }
84
+ /**
85
+ * Interprets an owner lease for a run without a terminal event. An expired lease is only "abandoned" when the
86
+ * owner is on this host and its process is gone or its PID now belongs to a different process.
87
+ * Every other expired lease stays "stale": liveness is uncertain, not a crash.
88
+ */
89
+ export async function evaluateLiveness(record, options = {}) {
90
+ if (!record)
91
+ return { state: "unknown", reason: "no-liveness-record" };
92
+ const heartbeat = Date.parse(record.heartbeatAt);
93
+ const expires = heartbeat + record.ttlMs;
94
+ const times = { heartbeatAt: record.heartbeatAt, expiresAt: new Date(expires).toISOString() };
95
+ if (record.state === "released")
96
+ return { state: "abandoned", reason: "released-without-verdict", ...times };
97
+ if ((options.now ?? Date.now)() <= expires)
98
+ return { state: "active", reason: "heartbeat-fresh", ...times };
99
+ if (record.owner.hostDigest !== (options.host ?? hostDigest()))
100
+ return { state: "stale", reason: "owner-other-host", ...times };
101
+ try {
102
+ const owner = await (options.probe ?? probeProcess)(record.owner.pid);
103
+ if (!owner.alive)
104
+ return { state: "abandoned", reason: "owner-exited", ...times };
105
+ // `ps` reports whole seconds, so allow a small tolerance before declaring PID reuse.
106
+ if (owner.startedAt !== undefined && Math.abs(owner.startedAt - Date.parse(record.owner.processStartedAt)) > 3_000) {
107
+ return { state: "abandoned", reason: "owner-pid-reused", ...times };
108
+ }
109
+ return { state: "stale", reason: owner.startedAt === undefined ? "owner-unverifiable" : "heartbeat-expired", ...times };
110
+ }
111
+ catch {
112
+ return { state: "stale", reason: "owner-unverifiable", ...times };
113
+ }
114
+ }
@@ -0,0 +1,61 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ export class LocalFileUnavailable extends Error {
5
+ }
6
+ /** A stored record exists but is malformed, inconsistent, or uses an unsupported schema version. */
7
+ export class StoredRecordInvalid extends Error {
8
+ }
9
+ export function isInvalidRecord(error) {
10
+ return error instanceof StoredRecordInvalid;
11
+ }
12
+ // Parse failures of stored data become a typed error so callers can isolate one bad record.
13
+ export function parseRecord(parse) {
14
+ try {
15
+ return parse();
16
+ }
17
+ catch (error) {
18
+ if (error instanceof SyntaxError || (error instanceof Error && error.name === "ZodError")) {
19
+ throw new StoredRecordInvalid("The stored record is invalid.", { cause: error });
20
+ }
21
+ throw error;
22
+ }
23
+ }
24
+ export function isMissing(error) {
25
+ return error instanceof LocalFileUnavailable ||
26
+ (error instanceof Error && "code" in error && ["ENOENT", "ELOOP", "ENOTDIR"].includes(String(error.code)));
27
+ }
28
+ // Callers supply schema-validated segments underneath a trusted local workspace.
29
+ export async function readLocalFile(root, relative, limit) {
30
+ const segments = relative.split("/");
31
+ if (segments.some((segment) => !/^[a-z0-9_.-]+$/i.test(segment) || segment === "." || segment === "..")) {
32
+ throw new LocalFileUnavailable();
33
+ }
34
+ let directory = root;
35
+ for (const segment of ["", ...segments.slice(0, -1)]) {
36
+ directory = join(directory, segment);
37
+ if (!(await lstat(directory)).isDirectory())
38
+ throw new LocalFileUnavailable();
39
+ }
40
+ const path = join(root, relative);
41
+ if (!(await lstat(path)).isFile())
42
+ throw new LocalFileUnavailable();
43
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
44
+ try {
45
+ const info = await file.stat();
46
+ if (!info.isFile() || info.size > limit)
47
+ throw new LocalFileUnavailable();
48
+ const bytes = Buffer.alloc(info.size);
49
+ let offset = 0;
50
+ while (offset < bytes.length) {
51
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
52
+ if (bytesRead === 0)
53
+ break;
54
+ offset += bytesRead;
55
+ }
56
+ return bytes.subarray(0, offset);
57
+ }
58
+ finally {
59
+ await file.close();
60
+ }
61
+ }
@@ -0,0 +1,214 @@
1
+ import { NEAR_MATCH_LIMIT, semanticRoleSchema } from "#agentpath/contracts";
2
+ import { errors } from "playwright";
3
+ import { ambiguousTarget, missingTarget } from "./diagnostics.js";
4
+ import { visibleTextMatches } from "./evidence.js";
5
+ export function semanticLocator(page, target) {
6
+ if (target.by === "label")
7
+ return page.getByLabel(target.label, { exact: true });
8
+ // A role without a name means the only element with that role. Uniqueness is still enforced by callers.
9
+ return target.name === undefined ? page.getByRole(target.role) : page.getByRole(target.role, { name: target.name, exact: true });
10
+ }
11
+ export async function locateUnique(locator, deadline, describeMissing) {
12
+ let observedMissing = false;
13
+ try {
14
+ do {
15
+ const count = await deadline.observe(() => locator.count());
16
+ if (count === 1)
17
+ return;
18
+ if (count > 1)
19
+ throw ambiguousTarget(count);
20
+ observedMissing = true;
21
+ } while (await deadline.pause());
22
+ }
23
+ catch (error) {
24
+ if (!(error instanceof errors.TimeoutError) || !observedMissing)
25
+ throw error;
26
+ }
27
+ const observation = await describeMissing();
28
+ if (observation.matchCount !== undefined && observation.matchCount !== 0) {
29
+ if (observation.matchCount > 1)
30
+ throw ambiguousTarget(observation.matchCount);
31
+ throw new errors.TimeoutError("Target appeared after the operation deadline");
32
+ }
33
+ throw missingTarget({ ...observation, matchCount: 0 });
34
+ }
35
+ export async function observeTarget(page, target, deadline, editable = false, nearMatchDeadline) {
36
+ const locator = semanticLocator(page, target);
37
+ const observation = {};
38
+ try {
39
+ observation.matchCount = await deadline.observe(() => locator.count());
40
+ if (target.by === "role") {
41
+ observation.role = target.role;
42
+ if (observation.matchCount === 0 && target.name !== undefined) {
43
+ observation.roleCandidateCount = await deadline.observe(() => page.getByRole(target.role).count());
44
+ observation.unnamedRoleCandidateCount = await deadline.observe(() => page.getByRole(target.role, { name: "", exact: true }).count());
45
+ }
46
+ }
47
+ if (observation.matchCount === 1) {
48
+ observation.visible = await deadline.observe(() => locator.isVisible());
49
+ observation.enabled = await deadline.observe(() => locator.isEnabled({ timeout: deadline.remaining() }));
50
+ if (editable)
51
+ observation.editable = await deadline.observe(() => locator.isEditable({ timeout: deadline.remaining() }));
52
+ }
53
+ }
54
+ catch {
55
+ // Keep only the evidence that was actually observed.
56
+ }
57
+ const frames = embeddedFrameCount(page);
58
+ if (observation.matchCount === 0 && frames > 0)
59
+ observation.embeddedFrames = frames;
60
+ if (observation.matchCount === 0 && nearMatchDeadline) {
61
+ try {
62
+ const snapshot = await nearMatchDeadline.observe(() => page.locator("body").ariaSnapshot({ timeout: nearMatchDeadline.remaining() }));
63
+ let nearMatches = findNearMatches(target, snapshotTargets(snapshot));
64
+ if (target.by === "role" && target.name !== undefined && nearMatches.length < NEAR_MATCH_LIMIT) {
65
+ // visible text equal to the requested name, under a different accessible name.
66
+ const shown = await visibleTextMatches(page, target.role, target.name, nearMatchDeadline);
67
+ nearMatches = [...shown.map((entry) => ({ ...entry, relation: "visible-text-matches" })),
68
+ ...nearMatches.filter((match) => !shown.some((entry) => entry.role === match.role && entry.name === match.name))].slice(0, NEAR_MATCH_LIMIT);
69
+ }
70
+ if (nearMatches.length)
71
+ observation.nearMatches = nearMatches;
72
+ }
73
+ catch {
74
+ // Near matches are optional context. A slow or closing page simply records none.
75
+ }
76
+ }
77
+ return observation;
78
+ }
79
+ /** Child frames of the page, including nested ones. Targets inside them are never searched. */
80
+ export function embeddedFrameCount(page) {
81
+ try {
82
+ return page.isClosed() ? 0 : Math.min(Math.max(page.frames().length - 1, 0), 10_000);
83
+ }
84
+ catch {
85
+ return 0;
86
+ }
87
+ }
88
+ const roles = new Set(semanticRoleSchema.options);
89
+ export const NAME_LIMIT = 160;
90
+ /**
91
+ * Elements with a targetable role in a Playwright aria snapshot, in document order. `name` is page-controlled
92
+ * text with control and format characters removed; it is undefined when the accessible name is empty.
93
+ */
94
+ export function snapshotRoleEntries(snapshot) {
95
+ const entries = [];
96
+ for (const raw of snapshot.split("\n")) {
97
+ let line = raw.trim();
98
+ if (!line.startsWith("- "))
99
+ continue;
100
+ line = line.slice(2);
101
+ // YAML quotes an entry that contains a colon: 'link "The Internet: home"':
102
+ if (line.startsWith("'")) {
103
+ const end = line.lastIndexOf("'");
104
+ if (end <= 0)
105
+ continue;
106
+ line = line.slice(1, end).replaceAll("''", "'");
107
+ }
108
+ const match = /^([a-z]+)(?: ("(?:[^"\\]|\\.)*"))?(?=$|:| \[)/.exec(line);
109
+ if (!match || !roles.has(match[1]))
110
+ continue;
111
+ const role = match[1];
112
+ if (match[2] === undefined) {
113
+ entries.push({ role });
114
+ continue;
115
+ }
116
+ let name;
117
+ try {
118
+ name = JSON.parse(match[2]);
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ // Page-controlled text: strip control characters before it reaches any output.
124
+ name = name.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
125
+ entries.push(name ? { role, name } : { role });
126
+ }
127
+ return entries;
128
+ }
129
+ /** Role and name pairs from a Playwright aria snapshot, limited to the roles a task can target. */
130
+ export function snapshotTargets(snapshot) {
131
+ return snapshotRoleEntries(snapshot).flatMap(({ role, name }) => name && name.length <= NAME_LIMIT ? [{ role, name }] : []);
132
+ }
133
+ const spaced = (value) => value.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
134
+ const letters = (value) => spaced(value).replace(/[^\p{L}\p{N}]+/gu, "");
135
+ function distance(a, b, limit) {
136
+ if (Math.abs(a.length - b.length) > limit)
137
+ return limit + 1;
138
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
139
+ for (let i = 1; i <= a.length; i++) {
140
+ const current = [i];
141
+ for (let j = 1; j <= b.length; j++) {
142
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
143
+ }
144
+ previous = current;
145
+ }
146
+ return previous[b.length];
147
+ }
148
+ function similar(a, b) {
149
+ const [x, y] = [letters(a), letters(b)];
150
+ if (!x || !y)
151
+ return false;
152
+ const limit = Math.max(1, Math.floor(Math.max(x.length, y.length) * 0.25));
153
+ if (distance(x, y, limit) <= limit)
154
+ return true;
155
+ const [short, long] = x.length <= y.length ? [x, y] : [y, x];
156
+ return short.length >= 4 && short.length / long.length >= 0.4 && long.includes(short);
157
+ }
158
+ /**
159
+ * Values on the page (placeholders, test ids, titles, alt texts, short texts) that resemble a missing one, closest
160
+ * first: the same letters, then a similar spelling. Used by the Playwright fixture for locators that name a value
161
+ * rather than a role or label; the same similarity rule as for names.
162
+ */
163
+ export function similarValues(wanted, candidates, limit = NEAR_MATCH_LIMIT) {
164
+ const ranked = [];
165
+ for (const value of new Set(candidates)) {
166
+ if (value === wanted)
167
+ continue;
168
+ const relation = letters(value) === letters(wanted) ? "case-or-spacing" : similar(value, wanted) ? "similar-name" : undefined;
169
+ if (!relation)
170
+ continue;
171
+ const [x, y] = [letters(value), letters(wanted)];
172
+ ranked.push({ value, relation, rank: relation === "case-or-spacing" ? 0 : 1, gap: distance(x, y, Math.max(x.length, y.length)) });
173
+ }
174
+ return ranked.sort((a, b) => a.rank - b.rank || a.gap - b.gap).slice(0, limit).map(({ value, relation }) => ({ value, relation }));
175
+ }
176
+ /**
177
+ * Targets on the page that resemble a missing one. They explain a likely authoring mismatch and are never
178
+ * used to act: the step has already failed, and AgentPath still requires one exact match.
179
+ */
180
+ export function findNearMatches(target, candidates) {
181
+ const ranked = [];
182
+ const wanted = target.by === "role" ? target.name : target.label;
183
+ if (wanted === undefined)
184
+ return [];
185
+ for (const candidate of candidates) {
186
+ let relation;
187
+ let rank = 9;
188
+ if (target.by === "label") {
189
+ if (spaced(candidate.name) === spaced(wanted))
190
+ [relation, rank] = ["accessible-name-matches-label", 0];
191
+ else if (similar(candidate.name, wanted))
192
+ [relation, rank] = ["similar-name", 2];
193
+ }
194
+ else if (candidate.role !== target.role) {
195
+ if (candidate.name === wanted)
196
+ [relation, rank] = ["same-name-other-role", 0];
197
+ else if (letters(candidate.name) === letters(wanted))
198
+ [relation, rank] = ["same-name-other-role", 3];
199
+ }
200
+ else if (letters(candidate.name) === letters(wanted)) {
201
+ [relation, rank] = ["case-or-spacing", 1];
202
+ }
203
+ else if (similar(candidate.name, wanted)) {
204
+ [relation, rank] = ["similar-name", 2];
205
+ }
206
+ if (relation && !ranked.some((entry) => entry.role === candidate.role && entry.name === candidate.name)) {
207
+ // Within a rank, closer names come first, so on a page of many similar records the one nearest the
208
+ // requested name is recorded before the limit; page order breaks ties.
209
+ const [x, y] = [letters(candidate.name), letters(wanted)];
210
+ ranked.push({ ...candidate, relation, rank, gap: distance(x, y, Math.max(x.length, y.length)) });
211
+ }
212
+ }
213
+ return ranked.sort((a, b) => a.rank - b.rank || a.gap - b.gap).slice(0, NEAR_MATCH_LIMIT).map(({ role, name, relation }) => ({ role, name, relation }));
214
+ }
@@ -0,0 +1,88 @@
1
+ import { agentDecisionJsonSchema } from "#agentpath/contracts";
2
+ export class ProviderError extends Error {
3
+ kind;
4
+ constructor(kind) {
5
+ super(`Model provider ${kind}. Check the configured endpoint and model.`);
6
+ this.kind = kind;
7
+ }
8
+ }
9
+ /** Connect only to the configured endpoint. Model outputs never influence its URL or credentials. */
10
+ export function createModelProvider(settings) {
11
+ const endpoint = new URL(settings.endpoint);
12
+ if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
13
+ !["http:", "https:"].includes(endpoint.protocol))
14
+ throw new ProviderError("configuration");
15
+ const local = ["127.0.0.1", "[::1]"].includes(endpoint.hostname);
16
+ // External inference requires the local operator to explicitly configure this exact endpoint.
17
+ const approved = process.env.AGENTPATH_MODEL_ENDPOINT === endpoint.href;
18
+ if (!local && !approved)
19
+ throw new ProviderError("configuration");
20
+ const credential = approved ? process.env.AGENTPATH_MODEL_API_KEY : undefined;
21
+ const route = settings.provider === "ollama" ? "api/chat" : /\/v1\/?$/.test(endpoint.pathname) ? "chat/completions" : "v1/chat/completions";
22
+ const url = new URL(route, endpoint.href.endsWith("/") ? endpoint : endpoint.href + "/");
23
+ return {
24
+ async infer(messages, signal, decisionSchema) {
25
+ const timeout = AbortSignal.timeout(settings.requestTimeoutMs);
26
+ const combined = AbortSignal.any([signal, timeout]);
27
+ try {
28
+ const body = settings.provider === "ollama"
29
+ ? { model: settings.model, messages, stream: false,
30
+ format: settings.ollamaFormat === "schema" ? decisionSchema ?? agentDecisionJsonSchema : "json",
31
+ ...(settings.ollamaThink === undefined ? {} : { think: settings.ollamaThink }),
32
+ options: { num_predict: settings.maxOutputTokens,
33
+ ...(settings.temperature === undefined ? {} : { temperature: settings.temperature }) } }
34
+ : { model: settings.model, messages, stream: false, max_tokens: settings.maxOutputTokens,
35
+ ...(settings.temperature === undefined ? {} : { temperature: settings.temperature }),
36
+ response_format: { type: "json_object" } };
37
+ const response = await fetch(url, {
38
+ method: "POST", redirect: "error", signal: combined,
39
+ headers: { "content-type": "application/json", ...(credential ? { authorization: `Bearer ${credential}` } : {}) },
40
+ body: JSON.stringify(body),
41
+ });
42
+ if (!response.ok) {
43
+ await response.body?.cancel();
44
+ throw new ProviderError("http");
45
+ }
46
+ const reader = response.body?.getReader();
47
+ if (!reader)
48
+ throw new ProviderError("response");
49
+ const chunks = [];
50
+ let length = 0;
51
+ try {
52
+ while (true) {
53
+ const part = await reader.read();
54
+ if (part.done)
55
+ break;
56
+ length += part.value.length;
57
+ if (length > 131072)
58
+ throw new ProviderError("response");
59
+ chunks.push(part.value);
60
+ }
61
+ }
62
+ finally {
63
+ await reader.cancel().catch(() => { });
64
+ }
65
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
66
+ if (!data || typeof data !== "object")
67
+ throw new ProviderError("response");
68
+ const content = settings.provider === "ollama" ? data.message?.content : data.choices?.[0]?.message?.content;
69
+ if (typeof content !== "string" || content.length > 32768)
70
+ throw new ProviderError("response");
71
+ if (data.choices?.[0]?.finish_reason === "length" || data.done_reason === "length")
72
+ throw new ProviderError("response");
73
+ const tokens = settings.provider === "ollama" ? data.prompt_eval_count + data.eval_count : data.usage?.total_tokens;
74
+ return { content, tokens: Number.isSafeInteger(tokens) && tokens >= 0 ? tokens : undefined };
75
+ }
76
+ catch (error) {
77
+ signal.throwIfAborted();
78
+ if (timeout.aborted)
79
+ throw new ProviderError("timeout");
80
+ if (error instanceof ProviderError)
81
+ throw error;
82
+ if (error instanceof SyntaxError)
83
+ throw new ProviderError("response");
84
+ throw new ProviderError("unavailable");
85
+ }
86
+ },
87
+ };
88
+ }