@theokit/sdk 2.27.0 → 2.29.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/a2a/index.cjs +373 -17
  3. package/dist/a2a/index.cjs.map +1 -1
  4. package/dist/a2a/index.js +373 -17
  5. package/dist/a2a/index.js.map +1 -1
  6. package/dist/{cron-BR1NCSk1.d.cts → cron-COSAehOL.d.ts} +110 -3
  7. package/dist/{cron-DgEQCJ2i.d.ts → cron-yJoNUZxe.d.cts} +110 -3
  8. package/dist/cron.cjs +914 -508
  9. package/dist/cron.cjs.map +1 -1
  10. package/dist/cron.d.cts +2 -2
  11. package/dist/cron.d.ts +2 -2
  12. package/dist/cron.js +915 -509
  13. package/dist/cron.js.map +1 -1
  14. package/dist/{errors-CbY3pxY7.d.ts → errors-BxMIlgLP.d.ts} +1 -1
  15. package/dist/{errors-DLMNb4Ka.d.cts → errors-tP-8O-hR.d.cts} +1 -1
  16. package/dist/errors.d.cts +2 -2
  17. package/dist/eval.cjs +914 -508
  18. package/dist/eval.cjs.map +1 -1
  19. package/dist/eval.js +915 -509
  20. package/dist/eval.js.map +1 -1
  21. package/dist/filesystem/index.cjs +304 -0
  22. package/dist/filesystem/index.cjs.map +1 -0
  23. package/dist/filesystem/index.d.cts +12 -0
  24. package/dist/filesystem/index.d.ts +12 -0
  25. package/dist/filesystem/index.js +295 -0
  26. package/dist/filesystem/index.js.map +1 -0
  27. package/dist/filesystem/local-filesystem.d.cts +36 -0
  28. package/dist/filesystem/local-filesystem.d.ts +36 -0
  29. package/dist/filesystem/types.d.cts +118 -0
  30. package/dist/filesystem/types.d.ts +118 -0
  31. package/dist/index.cjs +973 -570
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +13 -7
  34. package/dist/index.d.ts +13 -7
  35. package/dist/index.js +972 -568
  36. package/dist/index.js.map +1 -1
  37. package/dist/internal/persistence/conversation-storage-fs.d.cts +4 -0
  38. package/dist/internal/persistence/conversation-storage-fs.d.ts +4 -0
  39. package/dist/internal/persistence/conversation-storage-memory.d.cts +4 -0
  40. package/dist/internal/persistence/conversation-storage-memory.d.ts +4 -0
  41. package/dist/internal/persistence/objective-coerce.d.cts +9 -0
  42. package/dist/internal/persistence/objective-coerce.d.ts +9 -0
  43. package/dist/internal/runtime/lifecycle/wrap-completion-check-run.d.ts +30 -0
  44. package/dist/internal/runtime/local-agent/local-agent-goal-extensions.d.ts +80 -0
  45. package/dist/internal/runtime/objective/objective-store.d.ts +33 -0
  46. package/dist/{run-CdWiihyU.d.cts → run-q_P0vHlY.d.cts} +71 -2
  47. package/dist/{run-CdWiihyU.d.ts → run-q_P0vHlY.d.ts} +71 -2
  48. package/dist/types/agent.d.ts +32 -1
  49. package/dist/types/conversation-storage.d.ts +23 -0
  50. package/dist/types/goal-events.d.ts +7 -0
  51. package/dist/types/index.d.ts +1 -0
  52. package/dist/types/objective.d.ts +45 -0
  53. package/dist/types/run-events.d.ts +12 -1
  54. package/dist/types/run.d.ts +58 -0
  55. package/package.json +11 -1
package/dist/cron.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { z, toJSONSchema } from 'zod';
2
2
  import { createRequire } from 'module';
3
- import { randomUUID, randomBytes, createHash } from 'crypto';
4
- import { readFile, unlink, mkdir, open, rename, statfs, stat, rm, readdir, writeFile, appendFile, access } from 'fs/promises';
5
- import { join, dirname, resolve, sep, relative, isAbsolute } from 'path';
3
+ import { randomUUID, createHash, randomBytes } from 'crypto';
6
4
  import { mkdirSync, readdirSync, existsSync, realpathSync, lstatSync, readlinkSync, readFileSync } from 'fs';
5
+ import { join, dirname, resolve, sep, relative, isAbsolute } from 'path';
6
+ import { rm, readdir, readFile, mkdir, unlink, open, rename, statfs, stat, access, appendFile, writeFile } from 'fs/promises';
7
7
  import { AsyncLocalStorage } from 'async_hooks';
8
8
  import { homedir } from 'os';
9
9
  import { spawn } from 'child_process';
@@ -780,6 +780,155 @@ var init_cwd_mutex = __esm({
780
780
  tails = /* @__PURE__ */ new Map();
781
781
  }
782
782
  });
783
+ function safePathJoin(base, ...parts) {
784
+ if (base === "") {
785
+ throw new Error("safePathJoin: base must be non-empty");
786
+ }
787
+ rejectNulAndControlChars(base, "base");
788
+ for (const part of parts) {
789
+ rejectNulAndControlChars(part, "path segment");
790
+ }
791
+ const baseResolved = resolve(base);
792
+ const target = resolve(base, ...parts);
793
+ if (target !== baseResolved && !target.startsWith(baseResolved + sep)) {
794
+ throw new PathTraversalError(parts.join("/"), target);
795
+ }
796
+ return target;
797
+ }
798
+ function rejectNulAndControlChars(input, role) {
799
+ for (let i = 0; i < input.length; i++) {
800
+ const code = input.charCodeAt(i);
801
+ if (code === 0 || code >= 1 && code <= 31 || code === 127) {
802
+ const label = code === 0 ? "<nul-byte>" : `<control-char-0x${code.toString(16)}>`;
803
+ throw new PathTraversalError(`${role}: ${input}`, label);
804
+ }
805
+ }
806
+ }
807
+ function assertNoSymlinkEscape(path, base) {
808
+ rejectNulAndControlChars(path, "path");
809
+ rejectNulAndControlChars(base, "base");
810
+ let baseResolved;
811
+ try {
812
+ baseResolved = realpathSync(base);
813
+ } catch {
814
+ baseResolved = resolve(base);
815
+ }
816
+ const resolved = realpathOfDeepestExisting(path);
817
+ if (resolved === void 0) return;
818
+ if (resolved !== baseResolved && !resolved.startsWith(baseResolved + sep)) {
819
+ throw new PathTraversalError(`symlink ${path}`, resolved);
820
+ }
821
+ }
822
+ function realpathOfDeepestExisting(path) {
823
+ try {
824
+ return realpathSync(path);
825
+ } catch {
826
+ }
827
+ try {
828
+ const stat6 = lstatSync(path);
829
+ if (stat6.isSymbolicLink()) {
830
+ const target = readlinkSync(path);
831
+ const parentReal = realpathOfDeepestExisting(dirname(path));
832
+ const parentBase = parentReal ?? dirname(path);
833
+ return resolve(parentBase, target);
834
+ }
835
+ } catch {
836
+ }
837
+ let cursor = dirname(path);
838
+ let suffix = path.slice(cursor.length);
839
+ while (cursor !== dirname(cursor)) {
840
+ try {
841
+ const real = realpathSync(cursor);
842
+ return resolve(real, `.${suffix}`);
843
+ } catch {
844
+ suffix = path.slice(dirname(cursor).length);
845
+ cursor = dirname(cursor);
846
+ }
847
+ }
848
+ return void 0;
849
+ }
850
+ function validateArtifactPath(input) {
851
+ rejectKnownPrefixVectors(input);
852
+ const normalized = decodeAndNormalize(input);
853
+ rejectParentTraversal(input, normalized);
854
+ }
855
+ function rejectKnownPrefixVectors(input) {
856
+ if (input.includes("\0")) {
857
+ throw new PathTraversalError(input, "<nul-byte>");
858
+ }
859
+ if (input.startsWith("/") || input.startsWith("~")) {
860
+ throw new PathTraversalError(input, input);
861
+ }
862
+ if (/^[A-Za-z]:[\\/]?/.test(input)) {
863
+ throw new PathTraversalError(input, input);
864
+ }
865
+ }
866
+ function decodeAndNormalize(input) {
867
+ let decoded = input;
868
+ for (let i = 0; i < 2; i += 1) {
869
+ try {
870
+ const next = decodeURIComponent(decoded);
871
+ if (next === decoded) break;
872
+ decoded = next;
873
+ } catch {
874
+ throw new PathTraversalError(input, "<malformed-url-encoding>");
875
+ }
876
+ }
877
+ return decoded.replace(/\\/g, "/");
878
+ }
879
+ function rejectParentTraversal(input, normalized) {
880
+ for (const segment of normalized.split("/")) {
881
+ if (segment === ".." || segment === "..%00") {
882
+ throw new PathTraversalError(input, normalized);
883
+ }
884
+ }
885
+ if (normalized.includes("..")) {
886
+ throw new PathTraversalError(input, normalized);
887
+ }
888
+ }
889
+ function sanitizeIdentifier(input, options) {
890
+ const maxLen = options?.maxLen ?? 64;
891
+ if (input.length === 0 || input.length > maxLen) {
892
+ throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): "${input}"`, {
893
+ code: "invalid_identifier"
894
+ });
895
+ }
896
+ rejectNulAndControlChars(input, "identifier");
897
+ if (!IDENTIFIER_PATTERN.test(input)) {
898
+ throw new ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
899
+ code: "invalid_identifier"
900
+ });
901
+ }
902
+ return input.toLowerCase();
903
+ }
904
+ function safeFilenameForId(id, options) {
905
+ if (id.length === 0) {
906
+ throw new ConfigurationError("Filename id must be a non-empty string", {
907
+ code: "invalid_filename_id"
908
+ });
909
+ }
910
+ const maxLen = options?.maxLen ?? 128;
911
+ const lower = id.toLowerCase();
912
+ if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {
913
+ return lower;
914
+ }
915
+ return `h-${createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
916
+ }
917
+ var PathTraversalError, IDENTIFIER_PATTERN;
918
+ var init_path_guard = __esm({
919
+ "src/internal/security/path-guard.ts"() {
920
+ init_errors();
921
+ PathTraversalError = class extends ConfigurationError {
922
+ name = "PathTraversalError";
923
+ constructor(input, resolvedPath) {
924
+ super(`Path traversal attempt: ${input} \u2192 ${resolvedPath}`, {
925
+ code: "path_traversal"
926
+ });
927
+ }
928
+ };
929
+ IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\-_]*$/i;
930
+ }
931
+ });
783
932
  function detectNetworkFsName(typeMagic) {
784
933
  return NETWORK_FS_MAGIC.get(typeMagic) ?? null;
785
934
  }
@@ -844,6 +993,80 @@ var init_atomic_write = __esm({
844
993
  }
845
994
  });
846
995
 
996
+ // src/internal/security/index.ts
997
+ var init_security = __esm({
998
+ "src/internal/security/index.ts"() {
999
+ init_path_guard();
1000
+ init_redact();
1001
+ }
1002
+ });
1003
+
1004
+ // src/internal/persistence/file-lock.ts
1005
+ async function getProperLockfile() {
1006
+ if (cached !== void 0) return cached;
1007
+ try {
1008
+ const mod = await import('proper-lockfile');
1009
+ if (!validateLockModule(mod)) {
1010
+ if (!warnedStructural) {
1011
+ warnedStructural = true;
1012
+ process.stderr.write(
1013
+ "[theokit-sdk] proper-lockfile: imported module does NOT expose the expected `lock`/`unlock` API surface. This may indicate a supply-chain compromise or an incompatible major version. Falling back to in-process mutex (no cross-process safety). Reinstall with: pnpm add proper-lockfile@^11\n"
1014
+ );
1015
+ }
1016
+ cached = null;
1017
+ return cached;
1018
+ }
1019
+ cached = mod;
1020
+ } catch {
1021
+ cached = null;
1022
+ }
1023
+ return cached;
1024
+ }
1025
+ function validateLockModule(mod) {
1026
+ if (mod === null || mod === void 0 || typeof mod !== "object") return false;
1027
+ const m = mod;
1028
+ return typeof m.lock === "function" && typeof m.unlock === "function";
1029
+ }
1030
+ async function withFileLock(path, fn, options) {
1031
+ const lib = await getProperLockfile();
1032
+ if (lib === null) {
1033
+ if (!warnedMissing) {
1034
+ warnedMissing = true;
1035
+ process.stderr.write(
1036
+ "[theokit-sdk] proper-lockfile not installed; cross-process file lock unavailable. Install with: pnpm add proper-lockfile\n"
1037
+ );
1038
+ }
1039
+ return withCwdMutex(`file-lock:${path}`, fn);
1040
+ }
1041
+ return withCwdMutex(`file-lock:${path}`, async () => {
1042
+ const release = await lib.lock(path, {
1043
+ // EC-1: companion lockfile, target path may not exist yet.
1044
+ lockfilePath: `${path}.lock`,
1045
+ realpath: false,
1046
+ stale: 3e4,
1047
+ retries: {
1048
+ retries: 5,
1049
+ factor: 1.5,
1050
+ minTimeout: 100,
1051
+ maxTimeout: 5e3
1052
+ }
1053
+ });
1054
+ try {
1055
+ return await fn();
1056
+ } finally {
1057
+ await release();
1058
+ }
1059
+ });
1060
+ }
1061
+ var cached, warnedMissing, warnedStructural;
1062
+ var init_file_lock = __esm({
1063
+ "src/internal/persistence/file-lock.ts"() {
1064
+ init_cwd_mutex();
1065
+ warnedMissing = false;
1066
+ warnedStructural = false;
1067
+ }
1068
+ });
1069
+
847
1070
  // src/internal/runtime/context/yaml-frontmatter.ts
848
1071
  function parseSimpleYaml(text) {
849
1072
  const fields = {};
@@ -1035,21 +1258,386 @@ function buildConfigFromMarkdown(entities) {
1035
1258
  command: entity.frontmatter.command,
1036
1259
  matcher: entity.frontmatter.matcher
1037
1260
  };
1038
- if (entity.frontmatter.timeoutMs !== void 0) {
1039
- command.timeoutMs = entity.frontmatter.timeoutMs;
1040
- }
1041
- list.push(command);
1042
- grouped[event] = list;
1043
- }
1044
- return { hooks: grouped };
1045
- }
1046
- var warned;
1047
- var init_hooks_source = __esm({
1048
- "src/internal/runtime/hooks/hooks-source.ts"() {
1049
- init_errors();
1050
- init_markdown_config_loader();
1051
- init_hooks_frontmatter();
1052
- warned = /* @__PURE__ */ new Set();
1261
+ if (entity.frontmatter.timeoutMs !== void 0) {
1262
+ command.timeoutMs = entity.frontmatter.timeoutMs;
1263
+ }
1264
+ list.push(command);
1265
+ grouped[event] = list;
1266
+ }
1267
+ return { hooks: grouped };
1268
+ }
1269
+ var warned;
1270
+ var init_hooks_source = __esm({
1271
+ "src/internal/runtime/hooks/hooks-source.ts"() {
1272
+ init_errors();
1273
+ init_markdown_config_loader();
1274
+ init_hooks_frontmatter();
1275
+ warned = /* @__PURE__ */ new Set();
1276
+ }
1277
+ });
1278
+ function sessionFilePath(cwd, agentId) {
1279
+ const safe2 = sanitizeIdentifier(agentId, { maxLen: 128 });
1280
+ return safePathJoin(cwd, ".theokit", "agents", safe2, "messages.jsonl");
1281
+ }
1282
+ async function readJsonlLines(cwd, agentId) {
1283
+ const path = sessionFilePath(cwd, agentId);
1284
+ try {
1285
+ const raw = await readFile(path, "utf8");
1286
+ return raw.split("\n").filter((line) => line.length > 0);
1287
+ } catch {
1288
+ return [];
1289
+ }
1290
+ }
1291
+ function warnMalformed(agentId, line) {
1292
+ process.stderr.write(
1293
+ `[theokit-sdk] skipping malformed line in messages.jsonl (${agentId}): ${line.slice(0, 80)}...
1294
+ `
1295
+ );
1296
+ }
1297
+ function hydrateSessionLine(parsed) {
1298
+ if (typeof parsed.text !== "string" || parsed.role === void 0) return void 0;
1299
+ if (parsed.role === "user" || parsed.role === "assistant") {
1300
+ return { role: parsed.role, text: parsed.text };
1301
+ }
1302
+ if (parsed.role === "tool_call" || parsed.role === "tool_result") {
1303
+ const label = parsed.role === "tool_call" ? "tool call" : "tool result";
1304
+ return { role: "assistant", text: `[${label}] ${parsed.text}` };
1305
+ }
1306
+ return void 0;
1307
+ }
1308
+ async function readSessionFile(cwd, agentId) {
1309
+ const lines = await readJsonlLines(cwd, agentId);
1310
+ const messages = [];
1311
+ for (const line of lines) {
1312
+ try {
1313
+ const msg = hydrateSessionLine(JSON.parse(line));
1314
+ if (msg !== void 0) messages.push(msg);
1315
+ } catch {
1316
+ warnMalformed(agentId, line);
1317
+ }
1318
+ }
1319
+ return messages;
1320
+ }
1321
+ async function readAllPersistedMessages(cwd, agentId) {
1322
+ const lines = await readJsonlLines(cwd, agentId);
1323
+ const messages = [];
1324
+ for (const line of lines) {
1325
+ try {
1326
+ const parsed = JSON.parse(line);
1327
+ if (parsed.role !== void 0 && VALID_ROLES.has(parsed.role) && typeof parsed.text === "string") {
1328
+ messages.push({
1329
+ role: parsed.role,
1330
+ text: parsed.text,
1331
+ at: typeof parsed.at === "number" ? parsed.at : Date.now()
1332
+ });
1333
+ }
1334
+ } catch {
1335
+ warnMalformed(agentId, line);
1336
+ }
1337
+ }
1338
+ return messages;
1339
+ }
1340
+ async function appendAnyPersistedMessage(cwd, agentId, record) {
1341
+ await appendPersistedMessages(cwd, agentId, [record]);
1342
+ }
1343
+ async function appendPersistedMessages(cwd, agentId, records) {
1344
+ if (records.length === 0) return;
1345
+ const path = sessionFilePath(cwd, agentId);
1346
+ const payload = records.map((r) => `${redactSecrets(JSON.stringify(r))}
1347
+ `).join("");
1348
+ const dir = dirname(path);
1349
+ let written = false;
1350
+ const attempt = async () => {
1351
+ await mkdir(dir, { recursive: true });
1352
+ await withFileLock(path, async () => {
1353
+ await appendFile(path, payload, "utf8");
1354
+ written = true;
1355
+ });
1356
+ };
1357
+ try {
1358
+ await attempt();
1359
+ } catch (cause) {
1360
+ if (written || cause.code !== "ENOENT") throw cause;
1361
+ await attempt();
1362
+ }
1363
+ }
1364
+ async function rewriteLockedSession(path, transform) {
1365
+ await withFileLock(path, async () => {
1366
+ let raw;
1367
+ try {
1368
+ raw = await readFile(path, "utf8");
1369
+ } catch {
1370
+ return;
1371
+ }
1372
+ const lines = raw.split("\n").filter((line) => line.length > 0);
1373
+ const next = transform(lines);
1374
+ if (next === void 0) return;
1375
+ await replaceFileAtomic(path, next);
1376
+ });
1377
+ }
1378
+ async function compactSessionFile(cwd, agentId, maxTurns) {
1379
+ const path = sessionFilePath(cwd, agentId);
1380
+ if (!existsSync(path)) return;
1381
+ await rewriteLockedSession(
1382
+ path,
1383
+ (lines) => lines.length <= maxTurns * 2 ? void 0 : `${lines.slice(-maxTurns).join("\n")}
1384
+ `
1385
+ );
1386
+ }
1387
+ async function truncateSessionTo(cwd, agentId, keepCount) {
1388
+ const path = sessionFilePath(cwd, agentId);
1389
+ if (!existsSync(path)) return 0;
1390
+ let kept = 0;
1391
+ await rewriteLockedSession(path, (lines) => {
1392
+ const keep = Math.max(0, Math.min(keepCount, lines.length));
1393
+ kept = keep;
1394
+ if (keep === lines.length) return void 0;
1395
+ return keep === 0 ? "" : `${lines.slice(0, keep).join("\n")}
1396
+ `;
1397
+ });
1398
+ return kept;
1399
+ }
1400
+ var VALID_ROLES;
1401
+ var init_agent_session_store = __esm({
1402
+ "src/internal/runtime/session/agent-session-store.ts"() {
1403
+ init_atomic_write();
1404
+ init_file_lock();
1405
+ init_security();
1406
+ VALID_ROLES = /* @__PURE__ */ new Set([
1407
+ "user",
1408
+ "assistant",
1409
+ "system",
1410
+ "tool_call",
1411
+ "tool_result"
1412
+ ]);
1413
+ }
1414
+ });
1415
+
1416
+ // src/internal/persistence/objective-coerce.ts
1417
+ function coerceOptions(raw) {
1418
+ if (typeof raw !== "object" || raw === null) return void 0;
1419
+ const o = raw;
1420
+ const out = {};
1421
+ if (typeof o.maxRuns === "number") out.maxRuns = o.maxRuns;
1422
+ if (typeof o.judgeModel === "string") out.judgeModel = o.judgeModel;
1423
+ if (typeof o.prompt === "string") out.prompt = o.prompt;
1424
+ return Object.keys(out).length > 0 ? out : void 0;
1425
+ }
1426
+ function coerceObjectiveRecord(raw) {
1427
+ if (typeof raw !== "object" || raw === null) return void 0;
1428
+ const o = raw;
1429
+ if (o._schemaVersion !== 1) return void 0;
1430
+ if (typeof o.objective !== "string") return void 0;
1431
+ if (typeof o.runsUsed !== "number") return void 0;
1432
+ if (typeof o.status !== "string" || !STATUSES.includes(o.status))
1433
+ return void 0;
1434
+ const options = coerceOptions(o.options);
1435
+ return {
1436
+ _schemaVersion: 1,
1437
+ objective: o.objective,
1438
+ ...options !== void 0 ? { options } : {},
1439
+ status: o.status,
1440
+ runsUsed: o.runsUsed
1441
+ };
1442
+ }
1443
+ var STATUSES;
1444
+ var init_objective_coerce = __esm({
1445
+ "src/internal/persistence/objective-coerce.ts"() {
1446
+ STATUSES = ["active", "done", "paused"];
1447
+ }
1448
+ });
1449
+
1450
+ // src/internal/persistence/pagination.ts
1451
+ function paginate(items, opts) {
1452
+ if (opts === void 0 || opts.offset === void 0 && opts.limit === void 0) return items;
1453
+ const start = Math.max(0, opts.offset ?? 0);
1454
+ const end = opts.limit === void 0 ? items.length : start + Math.max(0, opts.limit);
1455
+ return items.slice(start, end);
1456
+ }
1457
+ var init_pagination = __esm({
1458
+ "src/internal/persistence/pagination.ts"() {
1459
+ }
1460
+ });
1461
+
1462
+ // src/internal/persistence/session-meta.ts
1463
+ function applyMetaPatch(current, patch) {
1464
+ const next = {};
1465
+ if (current.title !== void 0) next.title = current.title;
1466
+ if (current.tag !== void 0) next.tag = current.tag;
1467
+ if (patch.title === null) delete next.title;
1468
+ else if (patch.title !== void 0) next.title = patch.title;
1469
+ if (patch.tag === null) delete next.tag;
1470
+ else if (patch.tag !== void 0) next.tag = patch.tag;
1471
+ return next;
1472
+ }
1473
+ function coerceSessionMeta(raw) {
1474
+ if (typeof raw !== "object" || raw === null) return void 0;
1475
+ const obj = raw;
1476
+ const meta = {};
1477
+ if (typeof obj.title === "string") meta.title = obj.title;
1478
+ if (typeof obj.tag === "string") meta.tag = obj.tag;
1479
+ return meta.title === void 0 && meta.tag === void 0 ? void 0 : meta;
1480
+ }
1481
+ var init_session_meta = __esm({
1482
+ "src/internal/persistence/session-meta.ts"() {
1483
+ }
1484
+ });
1485
+ function toStoredMessage(record) {
1486
+ return {
1487
+ role: record.role,
1488
+ content: record.text,
1489
+ at: record.at
1490
+ };
1491
+ }
1492
+ function toRecord(message) {
1493
+ return { role: message.role, text: message.content, at: message.at ?? Date.now() };
1494
+ }
1495
+ var FileSystemConversationStorage;
1496
+ var init_conversation_storage_fs = __esm({
1497
+ "src/internal/persistence/conversation-storage-fs.ts"() {
1498
+ init_agent_session_store();
1499
+ init_security();
1500
+ init_path_guard();
1501
+ init_file_lock();
1502
+ init_objective_coerce();
1503
+ init_pagination();
1504
+ init_session_meta();
1505
+ FileSystemConversationStorage = class {
1506
+ #root;
1507
+ constructor(opts = {}) {
1508
+ this.#root = opts.root ?? process.cwd();
1509
+ }
1510
+ /** Exposed for tests + diagnostics. The path is sanitized at use sites. */
1511
+ get root() {
1512
+ return this.#root;
1513
+ }
1514
+ async getMessages(conversationId, opts) {
1515
+ const records = await readAllPersistedMessages(this.#root, conversationId);
1516
+ const all = records.map(toStoredMessage);
1517
+ return paginate(all, opts);
1518
+ }
1519
+ async appendMessage(conversationId, message) {
1520
+ await appendAnyPersistedMessage(this.#root, conversationId, toRecord(message));
1521
+ }
1522
+ async appendMessages(conversationId, messages) {
1523
+ await appendPersistedMessages(this.#root, conversationId, messages.map(toRecord));
1524
+ }
1525
+ async truncateConversation(conversationId, keepCount) {
1526
+ return truncateSessionTo(this.#root, conversationId, keepCount);
1527
+ }
1528
+ async deleteConversation(conversationId) {
1529
+ const safe2 = sanitizeIdentifier(conversationId, { maxLen: 128 });
1530
+ const dirPath = safePathJoin(this.#root, ".theokit", "agents", safe2);
1531
+ await rm(dirPath, { recursive: true, force: true });
1532
+ }
1533
+ async deleteScope(prefix) {
1534
+ const ids = await this.listConversationIds();
1535
+ const matching = ids.filter((id) => id.startsWith(prefix));
1536
+ for (const id of matching) await this.deleteConversation(id);
1537
+ return matching.length;
1538
+ }
1539
+ async listConversationIds(opts = {}) {
1540
+ const agentsRoot = safePathJoin(this.#root, ".theokit", "agents");
1541
+ let entries;
1542
+ try {
1543
+ entries = await readdir(agentsRoot);
1544
+ } catch (cause) {
1545
+ if (cause.code === "ENOENT") return [];
1546
+ throw cause;
1547
+ }
1548
+ if (opts.limit !== void 0) return entries.slice(0, opts.limit);
1549
+ return entries;
1550
+ }
1551
+ async compact(conversationId, maxTurns) {
1552
+ await compactSessionFile(this.#root, conversationId, maxTurns);
1553
+ }
1554
+ // SE4 — session metadata persisted as a per-conversation sidecar
1555
+ // `<root>/.theokit/agents/<safeId>/session.json` (same sanitized perimeter as
1556
+ // the transcript). Kept separate from messages.jsonl so a title/tag write does
1557
+ // not rewrite the append-only log.
1558
+ #metaPath(conversationId) {
1559
+ const safe2 = sanitizeIdentifier(conversationId, { maxLen: 128 });
1560
+ return safePathJoin(this.#root, ".theokit", "agents", safe2, "session.json");
1561
+ }
1562
+ async getSessionMeta(conversationId) {
1563
+ try {
1564
+ const raw = await readFile(this.#metaPath(conversationId), "utf8");
1565
+ return coerceSessionMeta(JSON.parse(raw));
1566
+ } catch (cause) {
1567
+ if (cause.code === "ENOENT") return void 0;
1568
+ throw cause;
1569
+ }
1570
+ }
1571
+ async setSessionMeta(conversationId, patch) {
1572
+ const metaPath = this.#metaPath(conversationId);
1573
+ await mkdir(dirname(metaPath), { recursive: true });
1574
+ await withFileLock(metaPath, async () => {
1575
+ let current = {};
1576
+ try {
1577
+ current = coerceSessionMeta(JSON.parse(await readFile(metaPath, "utf8"))) ?? {};
1578
+ } catch (cause) {
1579
+ if (cause.code !== "ENOENT") throw cause;
1580
+ }
1581
+ const next = applyMetaPatch(current, patch);
1582
+ await writeFile(metaPath, redactSecrets(JSON.stringify(next)), "utf8");
1583
+ });
1584
+ }
1585
+ // SE33 — the durable objective is kept in `objective.json` beside the
1586
+ // transcript (separate from messages.jsonl + session.json). Uses the TOTAL
1587
+ // `safeFilenameForId` (not `sanitizeIdentifier`) so a caller-supplied
1588
+ // `threadId` with exotic characters (e.g. "user@example.com") hashes to a
1589
+ // deterministic dir instead of throwing — honoring the objective methods'
1590
+ // never-throw contract (ADR D6). Conforming ids pass through unchanged, so
1591
+ // the objective still sits beside the transcript for the normal case.
1592
+ #objectivePath(conversationId) {
1593
+ const safe2 = safeFilenameForId(conversationId, { maxLen: 128 });
1594
+ return safePathJoin(this.#root, ".theokit", "agents", safe2, "objective.json");
1595
+ }
1596
+ async getObjectiveRecord(conversationId) {
1597
+ try {
1598
+ const raw = await readFile(this.#objectivePath(conversationId), "utf8");
1599
+ return coerceObjectiveRecord(JSON.parse(raw));
1600
+ } catch (cause) {
1601
+ if (cause.code === "ENOENT") return void 0;
1602
+ throw cause;
1603
+ }
1604
+ }
1605
+ async setObjectiveRecord(conversationId, record) {
1606
+ const path = this.#objectivePath(conversationId);
1607
+ if (record === null) {
1608
+ await rm(path, { force: true });
1609
+ return;
1610
+ }
1611
+ await mkdir(dirname(path), { recursive: true });
1612
+ await withFileLock(path, async () => {
1613
+ await writeFile(path, redactSecrets(JSON.stringify(record)), "utf8");
1614
+ });
1615
+ }
1616
+ // SE33 (HIGH-1 fix) — atomic read-modify-write: the read that feeds `mutate`
1617
+ // happens INSIDE the same file lock as the write, so two concurrent progress
1618
+ // write-backs on one thread cannot both read a stale `runsUsed` and drop turns.
1619
+ async updateObjectiveRecord(conversationId, mutate) {
1620
+ const path = this.#objectivePath(conversationId);
1621
+ await mkdir(dirname(path), { recursive: true });
1622
+ await withFileLock(path, async () => {
1623
+ let current;
1624
+ try {
1625
+ current = coerceObjectiveRecord(JSON.parse(await readFile(path, "utf8")));
1626
+ } catch (cause) {
1627
+ if (cause.code !== "ENOENT") throw cause;
1628
+ }
1629
+ const next = mutate(current);
1630
+ if (next === void 0) return;
1631
+ if (next === null) {
1632
+ await rm(path, { force: true });
1633
+ return;
1634
+ }
1635
+ await writeFile(path, redactSecrets(JSON.stringify(next)), "utf8");
1636
+ });
1637
+ }
1638
+ async dispose() {
1639
+ }
1640
+ };
1053
1641
  }
1054
1642
  });
1055
1643
  async function withToolWhitelist(whitelist, fn) {
@@ -1425,6 +2013,151 @@ var init_credential_pool_context = __esm({
1425
2013
  }
1426
2014
  });
1427
2015
 
2016
+ // src/internal/runtime/objective/objective-store.ts
2017
+ function canPersist(a) {
2018
+ return typeof a.getObjectiveRecord === "function" && typeof a.setObjectiveRecord === "function";
2019
+ }
2020
+ async function mutateObjective(adapter, conversationId, mutate) {
2021
+ if (typeof adapter.updateObjectiveRecord === "function") {
2022
+ await adapter.updateObjectiveRecord(conversationId, mutate);
2023
+ return;
2024
+ }
2025
+ const current = await adapter.getObjectiveRecord(conversationId);
2026
+ const next = mutate(current);
2027
+ if (next === void 0) return;
2028
+ await adapter.setObjectiveRecord(conversationId, next);
2029
+ }
2030
+ async function getObjective(adapter, conversationId) {
2031
+ if (!canPersist(adapter)) return void 0;
2032
+ return adapter.getObjectiveRecord(conversationId);
2033
+ }
2034
+ async function setObjective(adapter, conversationId, objective, options) {
2035
+ if (!canPersist(adapter)) return;
2036
+ const record = {
2037
+ _schemaVersion: 1,
2038
+ objective,
2039
+ ...options !== void 0 ? { options } : {},
2040
+ status: "active",
2041
+ runsUsed: 0
2042
+ };
2043
+ await adapter.setObjectiveRecord(conversationId, record);
2044
+ }
2045
+ async function updateObjectiveOptions(adapter, conversationId, patch) {
2046
+ if (!canPersist(adapter)) return;
2047
+ await mutateObjective(
2048
+ adapter,
2049
+ conversationId,
2050
+ (current) => current === void 0 ? void 0 : { ...current, options: { ...current.options, ...patch } }
2051
+ );
2052
+ }
2053
+ async function writeObjectiveProgress(adapter, conversationId, progress) {
2054
+ if (!canPersist(adapter)) return;
2055
+ await mutateObjective(
2056
+ adapter,
2057
+ conversationId,
2058
+ (current) => current === void 0 ? void 0 : { ...current, runsUsed: progress.runsUsed, status: progress.status }
2059
+ );
2060
+ }
2061
+ async function clearObjective(adapter, conversationId) {
2062
+ if (!canPersist(adapter)) return;
2063
+ await adapter.setObjectiveRecord(conversationId, null);
2064
+ }
2065
+ var init_objective_store = __esm({
2066
+ "src/internal/runtime/objective/objective-store.ts"() {
2067
+ }
2068
+ });
2069
+
2070
+ // src/internal/runtime/local-agent/local-agent-goal-extensions.ts
2071
+ var local_agent_goal_extensions_exports = {};
2072
+ __export(local_agent_goal_extensions_exports, {
2073
+ formatObjectiveProjection: () => formatObjectiveProjection,
2074
+ localAgentClearObjective: () => localAgentClearObjective,
2075
+ localAgentGetObjective: () => localAgentGetObjective,
2076
+ localAgentSetObjective: () => localAgentSetObjective,
2077
+ localAgentUpdateObjectiveOptions: () => localAgentUpdateObjectiveOptions,
2078
+ persistDurableProgress: () => persistDurableProgress,
2079
+ resolveCurrentObjectiveText: () => resolveCurrentObjectiveText,
2080
+ resolveDurableRun: () => resolveDurableRun
2081
+ });
2082
+ function resolveAdapter(handle) {
2083
+ return typeof handle === "string" ? new FileSystemConversationStorage({ root: handle }) : handle;
2084
+ }
2085
+ function assertValidGoalOptions(options) {
2086
+ if (options.maxRuns !== void 0 && (!Number.isInteger(options.maxRuns) || options.maxRuns <= 0)) {
2087
+ throw new ConfigurationError(`maxRuns must be a positive integer, got ${options.maxRuns}`, {
2088
+ code: "invalid_objective_max_runs"
2089
+ });
2090
+ }
2091
+ }
2092
+ async function localAgentSetObjective(handle, objective, opts) {
2093
+ const { threadId, ...options } = opts;
2094
+ assertValidGoalOptions(options);
2095
+ await setObjective(
2096
+ resolveAdapter(handle),
2097
+ threadId,
2098
+ objective,
2099
+ Object.keys(options).length > 0 ? options : void 0
2100
+ );
2101
+ }
2102
+ async function localAgentGetObjective(handle, opts) {
2103
+ return getObjective(resolveAdapter(handle), opts.threadId);
2104
+ }
2105
+ async function localAgentUpdateObjectiveOptions(handle, opts) {
2106
+ const { threadId, ...patch } = opts;
2107
+ assertValidGoalOptions(patch);
2108
+ await updateObjectiveOptions(resolveAdapter(handle), threadId, patch);
2109
+ }
2110
+ async function localAgentClearObjective(handle, opts) {
2111
+ await clearObjective(resolveAdapter(handle), opts.threadId);
2112
+ }
2113
+ async function resolveCurrentObjectiveText(handle, threadId) {
2114
+ const record = await getObjective(resolveAdapter(handle), threadId);
2115
+ return record?.status === "active" ? record.objective : void 0;
2116
+ }
2117
+ function formatObjectiveProjection(objective, assembled) {
2118
+ const signal = `<current-objective>
2119
+ ${objective}
2120
+ </current-objective>`;
2121
+ return assembled === void 0 || assembled.length === 0 ? signal : `${signal}
2122
+
2123
+ ${assembled}`;
2124
+ }
2125
+ async function resolveDurableRun(handle, goalConfig, threadId, callerOptions) {
2126
+ const record = await getObjective(resolveAdapter(handle), threadId);
2127
+ if (record === void 0) return { kind: "none" };
2128
+ const judgeModel = callerOptions?.judgeModel ?? record.options?.judgeModel ?? goalConfig?.judgeModel;
2129
+ if (judgeModel === void 0) return { kind: "inert" };
2130
+ const totalBudget = record.options?.maxRuns ?? goalConfig?.maxRuns ?? DEFAULT_MAX_RUNS;
2131
+ const remaining = Math.max(0, totalBudget - record.runsUsed);
2132
+ if (remaining === 0) return { kind: "exhausted" };
2133
+ const perCall = callerOptions?.maxTurns;
2134
+ const maxTurns = perCall !== void 0 ? Math.min(perCall, remaining) : remaining;
2135
+ return {
2136
+ kind: "run",
2137
+ goal: record.objective,
2138
+ options: { ...callerOptions, maxTurns, judgeModel }
2139
+ };
2140
+ }
2141
+ async function persistDurableProgress(handle, threadId, result) {
2142
+ const adapter = resolveAdapter(handle);
2143
+ const record = await getObjective(adapter, threadId);
2144
+ if (record === void 0) return;
2145
+ const status = result.status === "completed" ? "done" : result.status === "paused" ? "paused" : "active";
2146
+ await writeObjectiveProgress(adapter, threadId, {
2147
+ runsUsed: record.runsUsed + result.turnsUsed,
2148
+ status
2149
+ });
2150
+ }
2151
+ var DEFAULT_MAX_RUNS;
2152
+ var init_local_agent_goal_extensions = __esm({
2153
+ "src/internal/runtime/local-agent/local-agent-goal-extensions.ts"() {
2154
+ init_errors();
2155
+ init_conversation_storage_fs();
2156
+ init_objective_store();
2157
+ DEFAULT_MAX_RUNS = 20;
2158
+ }
2159
+ });
2160
+
1428
2161
  // src/internal/personality/context.ts
1429
2162
  var context_exports = {};
1430
2163
  __export(context_exports, {
@@ -3215,152 +3948,7 @@ function structurableAnswerOrThrow(result, GenerateObjectError2) {
3215
3948
  // src/internal/runtime/cloud/cloud-agent.ts
3216
3949
  init_errors();
3217
3950
  init_cwd_mutex();
3218
-
3219
- // src/internal/security/path-guard.ts
3220
- init_errors();
3221
- var PathTraversalError = class extends ConfigurationError {
3222
- name = "PathTraversalError";
3223
- constructor(input, resolvedPath) {
3224
- super(`Path traversal attempt: ${input} \u2192 ${resolvedPath}`, {
3225
- code: "path_traversal"
3226
- });
3227
- }
3228
- };
3229
- function safePathJoin(base, ...parts) {
3230
- if (base === "") {
3231
- throw new Error("safePathJoin: base must be non-empty");
3232
- }
3233
- rejectNulAndControlChars(base, "base");
3234
- for (const part of parts) {
3235
- rejectNulAndControlChars(part, "path segment");
3236
- }
3237
- const baseResolved = resolve(base);
3238
- const target = resolve(base, ...parts);
3239
- if (target !== baseResolved && !target.startsWith(baseResolved + sep)) {
3240
- throw new PathTraversalError(parts.join("/"), target);
3241
- }
3242
- return target;
3243
- }
3244
- function rejectNulAndControlChars(input, role) {
3245
- for (let i = 0; i < input.length; i++) {
3246
- const code = input.charCodeAt(i);
3247
- if (code === 0 || code >= 1 && code <= 31 || code === 127) {
3248
- const label = code === 0 ? "<nul-byte>" : `<control-char-0x${code.toString(16)}>`;
3249
- throw new PathTraversalError(`${role}: ${input}`, label);
3250
- }
3251
- }
3252
- }
3253
- function assertNoSymlinkEscape(path, base) {
3254
- rejectNulAndControlChars(path, "path");
3255
- rejectNulAndControlChars(base, "base");
3256
- let baseResolved;
3257
- try {
3258
- baseResolved = realpathSync(base);
3259
- } catch {
3260
- baseResolved = resolve(base);
3261
- }
3262
- const resolved = realpathOfDeepestExisting(path);
3263
- if (resolved === void 0) return;
3264
- if (resolved !== baseResolved && !resolved.startsWith(baseResolved + sep)) {
3265
- throw new PathTraversalError(`symlink ${path}`, resolved);
3266
- }
3267
- }
3268
- function realpathOfDeepestExisting(path) {
3269
- try {
3270
- return realpathSync(path);
3271
- } catch {
3272
- }
3273
- try {
3274
- const stat6 = lstatSync(path);
3275
- if (stat6.isSymbolicLink()) {
3276
- const target = readlinkSync(path);
3277
- const parentReal = realpathOfDeepestExisting(dirname(path));
3278
- const parentBase = parentReal ?? dirname(path);
3279
- return resolve(parentBase, target);
3280
- }
3281
- } catch {
3282
- }
3283
- let cursor = dirname(path);
3284
- let suffix = path.slice(cursor.length);
3285
- while (cursor !== dirname(cursor)) {
3286
- try {
3287
- const real = realpathSync(cursor);
3288
- return resolve(real, `.${suffix}`);
3289
- } catch {
3290
- suffix = path.slice(dirname(cursor).length);
3291
- cursor = dirname(cursor);
3292
- }
3293
- }
3294
- return void 0;
3295
- }
3296
- var IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\-_]*$/i;
3297
- function validateArtifactPath(input) {
3298
- rejectKnownPrefixVectors(input);
3299
- const normalized = decodeAndNormalize(input);
3300
- rejectParentTraversal(input, normalized);
3301
- }
3302
- function rejectKnownPrefixVectors(input) {
3303
- if (input.includes("\0")) {
3304
- throw new PathTraversalError(input, "<nul-byte>");
3305
- }
3306
- if (input.startsWith("/") || input.startsWith("~")) {
3307
- throw new PathTraversalError(input, input);
3308
- }
3309
- if (/^[A-Za-z]:[\\/]?/.test(input)) {
3310
- throw new PathTraversalError(input, input);
3311
- }
3312
- }
3313
- function decodeAndNormalize(input) {
3314
- let decoded = input;
3315
- for (let i = 0; i < 2; i += 1) {
3316
- try {
3317
- const next = decodeURIComponent(decoded);
3318
- if (next === decoded) break;
3319
- decoded = next;
3320
- } catch {
3321
- throw new PathTraversalError(input, "<malformed-url-encoding>");
3322
- }
3323
- }
3324
- return decoded.replace(/\\/g, "/");
3325
- }
3326
- function rejectParentTraversal(input, normalized) {
3327
- for (const segment of normalized.split("/")) {
3328
- if (segment === ".." || segment === "..%00") {
3329
- throw new PathTraversalError(input, normalized);
3330
- }
3331
- }
3332
- if (normalized.includes("..")) {
3333
- throw new PathTraversalError(input, normalized);
3334
- }
3335
- }
3336
- function sanitizeIdentifier(input, options) {
3337
- const maxLen = options?.maxLen ?? 64;
3338
- if (input.length === 0 || input.length > maxLen) {
3339
- throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): "${input}"`, {
3340
- code: "invalid_identifier"
3341
- });
3342
- }
3343
- rejectNulAndControlChars(input, "identifier");
3344
- if (!IDENTIFIER_PATTERN.test(input)) {
3345
- throw new ConfigurationError(`Identifier contains invalid characters: "${input}"`, {
3346
- code: "invalid_identifier"
3347
- });
3348
- }
3349
- return input.toLowerCase();
3350
- }
3351
- function safeFilenameForId(id, options) {
3352
- if (id.length === 0) {
3353
- throw new ConfigurationError("Filename id must be a non-empty string", {
3354
- code: "invalid_filename_id"
3355
- });
3356
- }
3357
- const maxLen = options?.maxLen;
3358
- const lower = id.toLowerCase();
3359
- if (lower.length <= maxLen && IDENTIFIER_PATTERN.test(lower)) {
3360
- return lower;
3361
- }
3362
- return `h-${createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
3363
- }
3951
+ init_path_guard();
3364
3952
 
3365
3953
  // src/internal/runtime/model-selection.ts
3366
3954
  init_errors();
@@ -3850,8 +4438,8 @@ function serializeMemory2(memory) {
3850
4438
  return result;
3851
4439
  }
3852
4440
 
3853
- // src/internal/security/index.ts
3854
- init_redact();
4441
+ // src/internal/runtime/fixtures/fixture-responder.ts
4442
+ init_security();
3855
4443
 
3856
4444
  // src/internal/runtime/fixtures/fixture-events.ts
3857
4445
  function assistantOnlyConversation(text) {
@@ -3970,6 +4558,10 @@ function sanitizeMcpName(name) {
3970
4558
  // src/internal/memory/storage/markdown-store.ts
3971
4559
  init_atomic_write();
3972
4560
  init_cwd_mutex();
4561
+
4562
+ // src/internal/memory/types.ts
4563
+ init_path_guard();
4564
+ init_security();
3973
4565
  function legacyMemoryJsonPath(cwd, config) {
3974
4566
  if (config.storePath !== void 0) {
3975
4567
  return resolve(cwd, config.storePath);
@@ -5287,78 +5879,17 @@ function isStdioCommandConfig(config) {
5287
5879
  if (obj.type !== void 0 && obj.type !== "stdio") return false;
5288
5880
  return typeof obj.command === "string" && obj.command.length > 0;
5289
5881
  }
5290
- function isLocalPath(command) {
5291
- return command.startsWith("/") || command.startsWith("~/") || command.startsWith("./") || command.startsWith("../");
5292
- }
5293
-
5294
- // src/internal/runtime/local-agent/local-agent.ts
5295
- init_errors();
5296
- init_cwd_mutex();
5297
-
5298
- // src/internal/personality/store.ts
5299
- init_atomic_write();
5300
-
5301
- // src/internal/persistence/file-lock.ts
5302
- init_cwd_mutex();
5303
- var cached;
5304
- var warnedMissing = false;
5305
- var warnedStructural = false;
5306
- async function getProperLockfile() {
5307
- if (cached !== void 0) return cached;
5308
- try {
5309
- const mod = await import('proper-lockfile');
5310
- if (!validateLockModule(mod)) {
5311
- if (!warnedStructural) {
5312
- warnedStructural = true;
5313
- process.stderr.write(
5314
- "[theokit-sdk] proper-lockfile: imported module does NOT expose the expected `lock`/`unlock` API surface. This may indicate a supply-chain compromise or an incompatible major version. Falling back to in-process mutex (no cross-process safety). Reinstall with: pnpm add proper-lockfile@^11\n"
5315
- );
5316
- }
5317
- cached = null;
5318
- return cached;
5319
- }
5320
- cached = mod;
5321
- } catch {
5322
- cached = null;
5323
- }
5324
- return cached;
5325
- }
5326
- function validateLockModule(mod) {
5327
- if (mod === null || mod === void 0 || typeof mod !== "object") return false;
5328
- const m = mod;
5329
- return typeof m.lock === "function" && typeof m.unlock === "function";
5330
- }
5331
- async function withFileLock(path, fn, options) {
5332
- const lib = await getProperLockfile();
5333
- if (lib === null) {
5334
- if (!warnedMissing) {
5335
- warnedMissing = true;
5336
- process.stderr.write(
5337
- "[theokit-sdk] proper-lockfile not installed; cross-process file lock unavailable. Install with: pnpm add proper-lockfile\n"
5338
- );
5339
- }
5340
- return withCwdMutex(`file-lock:${path}`, fn);
5341
- }
5342
- return withCwdMutex(`file-lock:${path}`, async () => {
5343
- const release = await lib.lock(path, {
5344
- // EC-1: companion lockfile, target path may not exist yet.
5345
- lockfilePath: `${path}.lock`,
5346
- realpath: false,
5347
- stale: 3e4,
5348
- retries: {
5349
- retries: 5,
5350
- factor: 1.5,
5351
- minTimeout: 100,
5352
- maxTimeout: 5e3
5353
- }
5354
- });
5355
- try {
5356
- return await fn();
5357
- } finally {
5358
- await release();
5359
- }
5360
- });
5361
- }
5882
+ function isLocalPath(command) {
5883
+ return command.startsWith("/") || command.startsWith("~/") || command.startsWith("./") || command.startsWith("../");
5884
+ }
5885
+
5886
+ // src/internal/runtime/local-agent/local-agent.ts
5887
+ init_errors();
5888
+ init_cwd_mutex();
5889
+
5890
+ // src/internal/personality/store.ts
5891
+ init_atomic_write();
5892
+ init_file_lock();
5362
5893
  var THEOKIT_DIR_NAME = ".theokit";
5363
5894
  function getTheokitHome(cwd) {
5364
5895
  const override = process.env.THEOKIT_HOME?.trim();
@@ -5800,6 +6331,9 @@ var HISTOGRAM_NAMES = {
5800
6331
  /** M3 #66 — count of finishes where the provider omitted usage (silent undercount). */
5801
6332
  LLM_USAGE_MISSING: "theokit_llm_usage_missing"
5802
6333
  };
6334
+
6335
+ // src/internal/telemetry/tracer.ts
6336
+ init_security();
5803
6337
  function safeRequire(moduleName) {
5804
6338
  try {
5805
6339
  const r = createRequire(import.meta.url);
@@ -6372,6 +6906,7 @@ function parseDecisionFromStdout(stdout) {
6372
6906
 
6373
6907
  // src/internal/memory/storage/session-summary-writer.ts
6374
6908
  init_atomic_write();
6909
+ init_path_guard();
6375
6910
  var MAX_TURN_CHARS = 2e3;
6376
6911
  function sessionsDir(cwd) {
6377
6912
  return join(memoryDir(cwd), "sessions");
@@ -6432,262 +6967,9 @@ function resolveActiveMemorySummaryForSend(legacySummary, portPathEnabled) {
6432
6967
  return legacySummary;
6433
6968
  }
6434
6969
 
6435
- // src/internal/runtime/session/agent-session-store.ts
6436
- init_atomic_write();
6437
- var VALID_ROLES = /* @__PURE__ */ new Set([
6438
- "user",
6439
- "assistant",
6440
- "system",
6441
- "tool_call",
6442
- "tool_result"
6443
- ]);
6444
- function sessionFilePath(cwd, agentId) {
6445
- const safe2 = sanitizeIdentifier(agentId, { maxLen: 128 });
6446
- return safePathJoin(cwd, ".theokit", "agents", safe2, "messages.jsonl");
6447
- }
6448
- async function readJsonlLines(cwd, agentId) {
6449
- const path = sessionFilePath(cwd, agentId);
6450
- try {
6451
- const raw = await readFile(path, "utf8");
6452
- return raw.split("\n").filter((line) => line.length > 0);
6453
- } catch {
6454
- return [];
6455
- }
6456
- }
6457
- function warnMalformed(agentId, line) {
6458
- process.stderr.write(
6459
- `[theokit-sdk] skipping malformed line in messages.jsonl (${agentId}): ${line.slice(0, 80)}...
6460
- `
6461
- );
6462
- }
6463
- function hydrateSessionLine(parsed) {
6464
- if (typeof parsed.text !== "string" || parsed.role === void 0) return void 0;
6465
- if (parsed.role === "user" || parsed.role === "assistant") {
6466
- return { role: parsed.role, text: parsed.text };
6467
- }
6468
- if (parsed.role === "tool_call" || parsed.role === "tool_result") {
6469
- const label = parsed.role === "tool_call" ? "tool call" : "tool result";
6470
- return { role: "assistant", text: `[${label}] ${parsed.text}` };
6471
- }
6472
- return void 0;
6473
- }
6474
- async function readSessionFile(cwd, agentId) {
6475
- const lines = await readJsonlLines(cwd, agentId);
6476
- const messages = [];
6477
- for (const line of lines) {
6478
- try {
6479
- const msg = hydrateSessionLine(JSON.parse(line));
6480
- if (msg !== void 0) messages.push(msg);
6481
- } catch {
6482
- warnMalformed(agentId, line);
6483
- }
6484
- }
6485
- return messages;
6486
- }
6487
- async function readAllPersistedMessages(cwd, agentId) {
6488
- const lines = await readJsonlLines(cwd, agentId);
6489
- const messages = [];
6490
- for (const line of lines) {
6491
- try {
6492
- const parsed = JSON.parse(line);
6493
- if (parsed.role !== void 0 && VALID_ROLES.has(parsed.role) && typeof parsed.text === "string") {
6494
- messages.push({
6495
- role: parsed.role,
6496
- text: parsed.text,
6497
- at: typeof parsed.at === "number" ? parsed.at : Date.now()
6498
- });
6499
- }
6500
- } catch {
6501
- warnMalformed(agentId, line);
6502
- }
6503
- }
6504
- return messages;
6505
- }
6506
- async function appendAnyPersistedMessage(cwd, agentId, record) {
6507
- await appendPersistedMessages(cwd, agentId, [record]);
6508
- }
6509
- async function appendPersistedMessages(cwd, agentId, records) {
6510
- if (records.length === 0) return;
6511
- const path = sessionFilePath(cwd, agentId);
6512
- const payload = records.map((r) => `${redactSecrets(JSON.stringify(r))}
6513
- `).join("");
6514
- const dir = dirname(path);
6515
- let written = false;
6516
- const attempt = async () => {
6517
- await mkdir(dir, { recursive: true });
6518
- await withFileLock(path, async () => {
6519
- await appendFile(path, payload, "utf8");
6520
- written = true;
6521
- });
6522
- };
6523
- try {
6524
- await attempt();
6525
- } catch (cause) {
6526
- if (written || cause.code !== "ENOENT") throw cause;
6527
- await attempt();
6528
- }
6529
- }
6530
- async function rewriteLockedSession(path, transform) {
6531
- await withFileLock(path, async () => {
6532
- let raw;
6533
- try {
6534
- raw = await readFile(path, "utf8");
6535
- } catch {
6536
- return;
6537
- }
6538
- const lines = raw.split("\n").filter((line) => line.length > 0);
6539
- const next = transform(lines);
6540
- if (next === void 0) return;
6541
- await replaceFileAtomic(path, next);
6542
- });
6543
- }
6544
- async function compactSessionFile(cwd, agentId, maxTurns) {
6545
- const path = sessionFilePath(cwd, agentId);
6546
- if (!existsSync(path)) return;
6547
- await rewriteLockedSession(
6548
- path,
6549
- (lines) => lines.length <= maxTurns * 2 ? void 0 : `${lines.slice(-maxTurns).join("\n")}
6550
- `
6551
- );
6552
- }
6553
- async function truncateSessionTo(cwd, agentId, keepCount) {
6554
- const path = sessionFilePath(cwd, agentId);
6555
- if (!existsSync(path)) return 0;
6556
- let kept = 0;
6557
- await rewriteLockedSession(path, (lines) => {
6558
- const keep = Math.max(0, Math.min(keepCount, lines.length));
6559
- kept = keep;
6560
- if (keep === lines.length) return void 0;
6561
- return keep === 0 ? "" : `${lines.slice(0, keep).join("\n")}
6562
- `;
6563
- });
6564
- return kept;
6565
- }
6566
-
6567
- // src/internal/persistence/pagination.ts
6568
- function paginate(items, opts) {
6569
- if (opts === void 0 || opts.offset === void 0 && opts.limit === void 0) return items;
6570
- const start = Math.max(0, opts.offset ?? 0);
6571
- const end = opts.limit === void 0 ? items.length : start + Math.max(0, opts.limit);
6572
- return items.slice(start, end);
6573
- }
6574
-
6575
- // src/internal/persistence/session-meta.ts
6576
- function applyMetaPatch(current, patch) {
6577
- const next = {};
6578
- if (current.title !== void 0) next.title = current.title;
6579
- if (current.tag !== void 0) next.tag = current.tag;
6580
- if (patch.title === null) delete next.title;
6581
- else if (patch.title !== void 0) next.title = patch.title;
6582
- if (patch.tag === null) delete next.tag;
6583
- else if (patch.tag !== void 0) next.tag = patch.tag;
6584
- return next;
6585
- }
6586
- function coerceSessionMeta(raw) {
6587
- if (typeof raw !== "object" || raw === null) return void 0;
6588
- const obj = raw;
6589
- const meta = {};
6590
- if (typeof obj.title === "string") meta.title = obj.title;
6591
- if (typeof obj.tag === "string") meta.tag = obj.tag;
6592
- return meta.title === void 0 && meta.tag === void 0 ? void 0 : meta;
6593
- }
6594
-
6595
- // src/internal/persistence/conversation-storage-fs.ts
6596
- var FileSystemConversationStorage = class {
6597
- #root;
6598
- constructor(opts = {}) {
6599
- this.#root = opts.root ?? process.cwd();
6600
- }
6601
- /** Exposed for tests + diagnostics. The path is sanitized at use sites. */
6602
- get root() {
6603
- return this.#root;
6604
- }
6605
- async getMessages(conversationId, opts) {
6606
- const records = await readAllPersistedMessages(this.#root, conversationId);
6607
- const all = records.map(toStoredMessage);
6608
- return paginate(all, opts);
6609
- }
6610
- async appendMessage(conversationId, message) {
6611
- await appendAnyPersistedMessage(this.#root, conversationId, toRecord(message));
6612
- }
6613
- async appendMessages(conversationId, messages) {
6614
- await appendPersistedMessages(this.#root, conversationId, messages.map(toRecord));
6615
- }
6616
- async truncateConversation(conversationId, keepCount) {
6617
- return truncateSessionTo(this.#root, conversationId, keepCount);
6618
- }
6619
- async deleteConversation(conversationId) {
6620
- const safe2 = sanitizeIdentifier(conversationId, { maxLen: 128 });
6621
- const dirPath = safePathJoin(this.#root, ".theokit", "agents", safe2);
6622
- await rm(dirPath, { recursive: true, force: true });
6623
- }
6624
- async deleteScope(prefix) {
6625
- const ids = await this.listConversationIds();
6626
- const matching = ids.filter((id) => id.startsWith(prefix));
6627
- for (const id of matching) await this.deleteConversation(id);
6628
- return matching.length;
6629
- }
6630
- async listConversationIds(opts = {}) {
6631
- const agentsRoot = safePathJoin(this.#root, ".theokit", "agents");
6632
- let entries;
6633
- try {
6634
- entries = await readdir(agentsRoot);
6635
- } catch (cause) {
6636
- if (cause.code === "ENOENT") return [];
6637
- throw cause;
6638
- }
6639
- if (opts.limit !== void 0) return entries.slice(0, opts.limit);
6640
- return entries;
6641
- }
6642
- async compact(conversationId, maxTurns) {
6643
- await compactSessionFile(this.#root, conversationId, maxTurns);
6644
- }
6645
- // SE4 — session metadata persisted as a per-conversation sidecar
6646
- // `<root>/.theokit/agents/<safeId>/session.json` (same sanitized perimeter as
6647
- // the transcript). Kept separate from messages.jsonl so a title/tag write does
6648
- // not rewrite the append-only log.
6649
- #metaPath(conversationId) {
6650
- const safe2 = sanitizeIdentifier(conversationId, { maxLen: 128 });
6651
- return safePathJoin(this.#root, ".theokit", "agents", safe2, "session.json");
6652
- }
6653
- async getSessionMeta(conversationId) {
6654
- try {
6655
- const raw = await readFile(this.#metaPath(conversationId), "utf8");
6656
- return coerceSessionMeta(JSON.parse(raw));
6657
- } catch (cause) {
6658
- if (cause.code === "ENOENT") return void 0;
6659
- throw cause;
6660
- }
6661
- }
6662
- async setSessionMeta(conversationId, patch) {
6663
- const metaPath = this.#metaPath(conversationId);
6664
- await mkdir(dirname(metaPath), { recursive: true });
6665
- await withFileLock(metaPath, async () => {
6666
- let current = {};
6667
- try {
6668
- current = coerceSessionMeta(JSON.parse(await readFile(metaPath, "utf8"))) ?? {};
6669
- } catch (cause) {
6670
- if (cause.code !== "ENOENT") throw cause;
6671
- }
6672
- const next = applyMetaPatch(current, patch);
6673
- await writeFile(metaPath, redactSecrets(JSON.stringify(next)), "utf8");
6674
- });
6675
- }
6676
- async dispose() {
6677
- }
6678
- };
6679
- function toStoredMessage(record) {
6680
- return {
6681
- role: record.role,
6682
- content: record.text,
6683
- at: record.at
6684
- };
6685
- }
6686
- function toRecord(message) {
6687
- return { role: message.role, text: message.content, at: message.at ?? Date.now() };
6688
- }
6689
-
6690
6970
  // src/internal/runtime/session/agent-session.ts
6971
+ init_conversation_storage_fs();
6972
+ init_agent_session_store();
6691
6973
  var DEFAULT_MAX_TURNS = 200;
6692
6974
  var COMPACTION_CHECK_INTERVAL = 50;
6693
6975
  var sessions = /* @__PURE__ */ new Map();
@@ -7127,6 +7409,7 @@ function parseFrontmatterFields(frontmatter) {
7127
7409
 
7128
7410
  // src/internal/runtime/skills/discover-skills.ts
7129
7411
  init_errors();
7412
+ init_path_guard();
7130
7413
 
7131
7414
  // src/internal/runtime/skills/skill-frontmatter.ts
7132
7415
  init_errors();
@@ -8447,6 +8730,7 @@ function tokenizeContent(content) {
8447
8730
  // src/internal/runtime/plugins/plugins-manager.ts
8448
8731
  init_errors();
8449
8732
  init_markdown_config_loader();
8733
+ init_path_guard();
8450
8734
  init_hooks_source();
8451
8735
  var PluginFrontmatterSchema = z.object({
8452
8736
  /** Plugin identifier; defaults to folder name if omitted. */
@@ -10906,6 +11190,7 @@ function registerBuiltins() {
10906
11190
  init_errors();
10907
11191
 
10908
11192
  // src/internal/error-mappers/shared.ts
11193
+ init_security();
10909
11194
  var RAW_MAX_BYTES = 2048;
10910
11195
  function parseRetryAfter(headers) {
10911
11196
  if (headers === void 0) return void 0;
@@ -13037,6 +13322,7 @@ function selectTransport(profile, apiKey) {
13037
13322
 
13038
13323
  // src/internal/mcp/client.ts
13039
13324
  init_errors();
13325
+ init_path_guard();
13040
13326
  function createMcpClient(name, config, fetchImpl = fetch) {
13041
13327
  if (isStdio(config)) return new StdioMcpClient(name, config);
13042
13328
  return new HttpMcpClient(name, config, fetchImpl);
@@ -13746,6 +14032,9 @@ async function readProjectMcpServers(cwd) {
13746
14032
  }
13747
14033
  }
13748
14034
 
14035
+ // src/internal/runtime/local-agent/local-agent.ts
14036
+ init_local_agent_goal_extensions();
14037
+
13749
14038
  // src/internal/runtime/local-agent/local-agent-invalidate.ts
13750
14039
  async function applyDeferredInvalidation(agentId, pending, refresh) {
13751
14040
  process.stderr.write(
@@ -16076,16 +16365,49 @@ async function localAgentUsePersonality(args) {
16076
16365
  init_local_agent_plugins();
16077
16366
 
16078
16367
  // src/internal/runtime/local-agent/local-agent-runtime-extensions.ts
16079
- function localAgentRunUntil(agent, goal, options) {
16368
+ function pausedReason(kind, threadId) {
16369
+ switch (kind) {
16370
+ case "none":
16371
+ return `no durable objective set for thread "${threadId}" \u2014 call setObjective() first`;
16372
+ case "inert":
16373
+ return `durable objective for thread "${threadId}" is inert \u2014 no judge resolved (set a judge to activate)`;
16374
+ case "exhausted":
16375
+ return `durable objective for thread "${threadId}" exhausted its run budget \u2014 raise maxRuns to resume`;
16376
+ }
16377
+ }
16378
+ function localAgentRunUntil(agent, goal, options, durable) {
16080
16379
  async function* wrap() {
16081
16380
  const { runUntilImpl: runUntilImpl2 } = await Promise.resolve().then(() => (init_run_until(), run_until_exports));
16082
- const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
16083
- const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
16084
- const create = getAgentFacade2().create;
16085
- const deps = {
16086
- judge: async (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
16381
+ const buildDeps = async () => {
16382
+ const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
16383
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
16384
+ const create = getAgentFacade2().create;
16385
+ return {
16386
+ judge: (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
16387
+ };
16087
16388
  };
16088
- return yield* runUntilImpl2(agent, goal, options, deps);
16389
+ if (goal !== void 0) {
16390
+ return yield* runUntilImpl2(agent, goal, options, await buildDeps());
16391
+ }
16392
+ const threadId = options?.threadId;
16393
+ if (durable === void 0 || threadId === void 0) {
16394
+ const reason = "runUntil() called with no goal and no threadId \u2014 nothing to resolve a durable objective from";
16395
+ yield { type: "status_change", status: "paused", reason };
16396
+ return { status: "paused", turnsUsed: 0, finalResponse: void 0 };
16397
+ }
16398
+ const { resolveDurableRun: resolveDurableRun2, persistDurableProgress: persistDurableProgress2 } = await Promise.resolve().then(() => (init_local_agent_goal_extensions(), local_agent_goal_extensions_exports));
16399
+ const resolved = await resolveDurableRun2(durable.handle, durable.goalConfig, threadId, options);
16400
+ if (resolved.kind !== "run") {
16401
+ yield {
16402
+ type: "status_change",
16403
+ status: "paused",
16404
+ reason: pausedReason(resolved.kind, threadId)
16405
+ };
16406
+ return { status: "paused", turnsUsed: 0, finalResponse: void 0 };
16407
+ }
16408
+ const result = yield* runUntilImpl2(agent, resolved.goal, resolved.options, await buildDeps());
16409
+ await persistDurableProgress2(durable.handle, threadId, result);
16410
+ return result;
16089
16411
  }
16090
16412
  return wrap();
16091
16413
  }
@@ -16151,6 +16473,44 @@ function ponyfillAny(signals) {
16151
16473
  return ctrl.signal;
16152
16474
  }
16153
16475
 
16476
+ // src/internal/runtime/lifecycle/wrap-completion-check-run.ts
16477
+ function wrapRunWithCompletionCheck(args) {
16478
+ const check = args.completionCheck;
16479
+ if (check === void 0) return args.run;
16480
+ const compute = async () => {
16481
+ const result = await args.run.wait();
16482
+ if (result.status !== "finished" || result.result === void 0) return result;
16483
+ const judgeOpts = {};
16484
+ if (check.judgeModel !== void 0) judgeOpts.judgeModel = check.judgeModel;
16485
+ if (check.apiKey !== void 0) judgeOpts.apiKey = check.apiKey;
16486
+ const verdict = await args.deps.judge(
16487
+ { goal: check.criteria, lastResponse: result.result },
16488
+ judgeOpts
16489
+ );
16490
+ const complete = !verdict.parseFailed && verdict.verdict === "done";
16491
+ emitRunEvent(args.onRunEvent, {
16492
+ type: "completion_check",
16493
+ complete,
16494
+ reason: verdict.reason
16495
+ });
16496
+ return {
16497
+ ...result,
16498
+ completionCheck: { complete, reason: verdict.reason, parseFailed: verdict.parseFailed }
16499
+ };
16500
+ };
16501
+ let judged;
16502
+ const wrappedWait = () => {
16503
+ judged ??= compute();
16504
+ return judged;
16505
+ };
16506
+ return new Proxy(args.run, {
16507
+ get(target, prop, receiver) {
16508
+ if (prop === "wait") return wrappedWait;
16509
+ return Reflect.get(target, prop, receiver);
16510
+ }
16511
+ });
16512
+ }
16513
+
16154
16514
  // src/internal/runtime/processors/run-processors.ts
16155
16515
  var ProcessorAbort = class {
16156
16516
  constructor(processorId, reason) {
@@ -16290,6 +16650,9 @@ function wrapRunWithOutputProcessors(args) {
16290
16650
  });
16291
16651
  }
16292
16652
 
16653
+ // src/internal/runtime/local-agent/local-agent-send.ts
16654
+ init_local_agent_goal_extensions();
16655
+
16293
16656
  // src/internal/runtime/local-agent/local-agent-memory-hooks.ts
16294
16657
  var DEFAULT_MAX_RECALL_BYTES = 16e3;
16295
16658
  async function applyPreUserSendHook(args) {
@@ -16405,6 +16768,11 @@ async function executeSendLocked(inputs, message, options) {
16405
16768
  memoryFacts,
16406
16769
  activeMemorySummary
16407
16770
  );
16771
+ const projectedSystemPrompt = await projectCurrentObjective(
16772
+ inputs.storageHandle,
16773
+ options.objectiveThreadId,
16774
+ assembledSystemPrompt
16775
+ );
16408
16776
  const composedOptions = {
16409
16777
  ...options,
16410
16778
  signal: anySignal([options.signal, inputs.lifecycleAbortController.signal])
@@ -16412,7 +16780,7 @@ async function executeSendLocked(inputs, message, options) {
16412
16780
  const run = await inputs.dispatchRun(
16413
16781
  adaptedMessage,
16414
16782
  composedOptions,
16415
- assembledSystemPrompt,
16783
+ projectedSystemPrompt,
16416
16784
  memoryFacts,
16417
16785
  priorMessages,
16418
16786
  memoryTools,
@@ -16425,18 +16793,43 @@ async function executeSendLocked(inputs, message, options) {
16425
16793
  agentId: inputs.agentId,
16426
16794
  onRunEvent: options.onRunEvent
16427
16795
  }) : run;
16428
- return wrapRunWithPostReplyHook({
16796
+ const hookedRun = wrapRunWithPostReplyHook({
16429
16797
  pluginManager: inputs.pluginManagerCode,
16430
16798
  agentId: inputs.agentId,
16431
16799
  options: inputs.options,
16432
16800
  run: processedRun,
16433
16801
  userText
16434
16802
  });
16803
+ return wrapRunWithCompletionCheck({
16804
+ run: hookedRun,
16805
+ completionCheck: options.completionCheck,
16806
+ onRunEvent: options.onRunEvent,
16807
+ deps: buildCompletionCheckDeps()
16808
+ });
16809
+ }
16810
+ function buildCompletionCheckDeps() {
16811
+ return {
16812
+ judge: async (ctx, opts) => {
16813
+ const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
16814
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
16815
+ return judgeCallImpl2(ctx, opts, { create: getAgentFacade2().create });
16816
+ }
16817
+ };
16435
16818
  }
16436
16819
  function readMemoryForSend(workspaceCwd, memoryConfig) {
16437
16820
  if (memoryConfig?.enabled !== true) return Promise.resolve([]);
16438
16821
  return safeCall(() => readMemoryFacts(workspaceCwd, memoryConfig), [], "memory read");
16439
16822
  }
16823
+ async function projectCurrentObjective(storageHandle, objectiveThreadId, assembled) {
16824
+ if (objectiveThreadId === void 0) return assembled;
16825
+ const objective = await safeCall(
16826
+ () => resolveCurrentObjectiveText(storageHandle, objectiveThreadId),
16827
+ void 0,
16828
+ "objective projection"
16829
+ );
16830
+ if (objective === void 0) return assembled;
16831
+ return formatObjectiveProjection(objective, assembled);
16832
+ }
16440
16833
 
16441
16834
  // src/internal/runtime/local-agent/local-agent-task-wrap.ts
16442
16835
  init_registry();
@@ -16799,20 +17192,33 @@ var LocalAgent = class {
16799
17192
  ...opts !== void 0 ? { opts } : {}
16800
17193
  });
16801
17194
  }
17195
+ // biome-ignore format: G8 budget — artifact stubs (local agents have no artifacts); kept 1-line each.
16802
17196
  listArtifacts() {
16803
17197
  return Promise.resolve([]);
16804
17198
  }
17199
+ // biome-ignore format: G8 budget — see listArtifacts.
16805
17200
  downloadArtifact(_path) {
16806
- return Promise.reject(
16807
- new UnsupportedRunOperationError(
16808
- "Artifacts are not supported for local agents",
16809
- "downloadArtifact"
16810
- )
16811
- );
17201
+ return Promise.reject(new UnsupportedRunOperationError("Artifacts are not supported for local agents", "downloadArtifact"));
16812
17202
  }
16813
17203
  // biome-ignore format: G8 budget — both methods delegate to `local-agent-runtime-extensions.ts`; signatures kept as 1-line each.
16814
17204
  runUntil(goal, options) {
16815
- return localAgentRunUntil(this, goal, options);
17205
+ return localAgentRunUntil(this, goal, options, { handle: this.storageHandle(), goalConfig: this.options.goal });
17206
+ }
17207
+ // biome-ignore format: SE33 G8 budget — objective methods delegate to `local-agent-goal-extensions.ts`.
17208
+ setObjective(objective, opts) {
17209
+ return localAgentSetObjective(this.storageHandle(), objective, opts);
17210
+ }
17211
+ // biome-ignore format: SE33 G8 budget — see setObjective above.
17212
+ getObjective(opts) {
17213
+ return localAgentGetObjective(this.storageHandle(), opts);
17214
+ }
17215
+ // biome-ignore format: SE33 G8 budget — see setObjective above.
17216
+ updateObjectiveOptions(opts) {
17217
+ return localAgentUpdateObjectiveOptions(this.storageHandle(), opts);
17218
+ }
17219
+ // biome-ignore format: SE33 G8 budget — see setObjective above.
17220
+ clearObjective(opts) {
17221
+ return localAgentClearObjective(this.storageHandle(), opts);
16816
17222
  }
16817
17223
  // biome-ignore format: G8 budget — see runUntil comment above.
16818
17224
  fork(options) {