@workit-dev/pi 2.27.8 → 2.27.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.js CHANGED
@@ -6947,11 +6947,6 @@ var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6947
6947
  var resolveStateDir = () => stateDir(process.env);
6948
6948
  var homePattern = new RegExp(`${escapeRegExp(os4.homedir())}(?=[/\\\\]|$)|\\$HOME(?=[/\\\\]|$)`, "g");
6949
6949
 
6950
- // packages/workit-core/src/store/paths.ts
6951
- import { spawnSync as spawnSync5 } from "node:child_process";
6952
- import fs5 from "node:fs";
6953
- import path8 from "node:path";
6954
-
6955
6950
  // packages/workit-core/src/store/folder-store.ts
6956
6951
  import fs4 from "node:fs";
6957
6952
  import os5 from "node:os";
@@ -7168,13 +7163,14 @@ var below = (parent, child) => {
7168
7163
  const rel = path7.relative(parent, child);
7169
7164
  return rel !== "" && !rel.startsWith("..") && !path7.isAbsolute(rel);
7170
7165
  };
7166
+ var insideTempDir = (dir, tempDir = os5.tmpdir()) => below(canonical3(tempDir), canonical3(dir));
7171
7167
  var TEST_RUN_REFUSALS = "folder-store-refusals.log";
7172
7168
  var testRunFolderRefusal = (folder, hasStray, env = process.env, tempDir = os5.tmpdir()) => {
7173
7169
  if (env.WORKIT_TEST_RUN === undefined || !hasStray)
7174
7170
  return null;
7175
7171
  const real = canonical3(folder);
7176
7172
  const tmp = canonical3(tempDir);
7177
- if (below(tmp, real))
7173
+ if (insideTempDir(folder, tempDir))
7178
7174
  return null;
7179
7175
  return `workit test run (WORKIT_TEST_RUN): refusing to move ${path7.join(real, ".workit")} into the run's throwaway state dir; a test must work in a fresh dir inside ${tmp}, never the temp dir itself, a parent of it or a folder outside it (#892)`;
7180
7176
  };
@@ -7260,6 +7256,9 @@ Merge them by hand (cp -Rn ${workit}/. ${target}/), then delete them here.
7260
7256
  }
7261
7257
 
7262
7258
  // packages/workit-core/src/store/paths.ts
7259
+ import { spawnSync as spawnSync5 } from "node:child_process";
7260
+ import fs5 from "node:fs";
7261
+ import path8 from "node:path";
7263
7262
  var NOT_A_REPO = /not a git repository \(or any (of the parent directories|parent up to)/u;
7264
7263
  var gitRun = (cwd, args) => {
7265
7264
  const run = spawnSync5("git", args, {
@@ -7423,6 +7422,7 @@ var STAMPING_HOSTS = new Set([
7423
7422
  "codex_cli",
7424
7423
  "codex_desktop"
7425
7424
  ]);
7425
+ var pinFiles = new Map;
7426
7426
  var OWN_CHILD_SHELL = new Set(["opencode", "pi"]);
7427
7427
  var SESSION_UNSAFE = /[^A-Za-z0-9_.:@/+-]/g;
7428
7428
  function childSessionId(lead, child) {
package/dist/workit.js CHANGED
@@ -10040,12 +10040,6 @@ var escapeRegExp2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10040
10040
  var resolveStateDir = () => stateDir(process.env);
10041
10041
  var homePattern = new RegExp(`${escapeRegExp2(os4.homedir())}(?=[/\\\\]|$)|\\$HOME(?=[/\\\\]|$)`, "g");
10042
10042
 
10043
- // packages/workit-core/src/store/paths.ts
10044
- import { spawnSync as spawnSync9 } from "node:child_process";
10045
- import { createHash as createHash7 } from "node:crypto";
10046
- import fs6 from "node:fs";
10047
- import path10 from "node:path";
10048
-
10049
10043
  // packages/workit-core/src/store/folder-store.ts
10050
10044
  import fs5 from "node:fs";
10051
10045
  import os5 from "node:os";
@@ -10262,13 +10256,14 @@ var below = (parent, child) => {
10262
10256
  const rel = path9.relative(parent, child);
10263
10257
  return rel !== "" && !rel.startsWith("..") && !path9.isAbsolute(rel);
10264
10258
  };
10259
+ var insideTempDir = (dir, tempDir = os5.tmpdir()) => below(canonical3(tempDir), canonical3(dir));
10265
10260
  var TEST_RUN_REFUSALS = "folder-store-refusals.log";
10266
10261
  var testRunFolderRefusal = (folder, hasStray, env = process.env, tempDir = os5.tmpdir()) => {
10267
10262
  if (env.WORKIT_TEST_RUN === undefined || !hasStray)
10268
10263
  return null;
10269
10264
  const real = canonical3(folder);
10270
10265
  const tmp = canonical3(tempDir);
10271
- if (below(tmp, real))
10266
+ if (insideTempDir(folder, tempDir))
10272
10267
  return null;
10273
10268
  return `workit test run (WORKIT_TEST_RUN): refusing to move ${path9.join(real, ".workit")} into the run's throwaway state dir; a test must work in a fresh dir inside ${tmp}, never the temp dir itself, a parent of it or a folder outside it (#892)`;
10274
10269
  };
@@ -10354,6 +10349,10 @@ Merge them by hand (cp -Rn ${workit}/. ${target}/), then delete them here.
10354
10349
  }
10355
10350
 
10356
10351
  // packages/workit-core/src/store/paths.ts
10352
+ import { spawnSync as spawnSync9 } from "node:child_process";
10353
+ import { createHash as createHash7 } from "node:crypto";
10354
+ import fs6 from "node:fs";
10355
+ import path10 from "node:path";
10357
10356
  var NOT_A_REPO = /not a git repository \(or any (of the parent directories|parent up to)/u;
10358
10357
  var gitRun = (cwd, args) => {
10359
10358
  const run = spawnSync9("git", args, {
@@ -10666,8 +10665,58 @@ function hostSessionFromEnv(env) {
10666
10665
  var ISSUED_PER_LEAD = 64;
10667
10666
  var ISSUED_SESSIONS_MARKER = "workit-issued-sessions/3";
10668
10667
  var hash = (value) => createHash8("sha256").update(value).digest("hex").slice(0, 32);
10669
- var userIssuedRoot = () => path11.join(resolveStateDir(), "issued");
10670
- var userTokenRoot = () => path11.join(resolveStateDir(), "issued-tokens");
10668
+ var PIN_FILE = "issued-registry";
10669
+ var pinFiles = new Map;
10670
+ var pinFile = (cwd) => {
10671
+ if (cwd === undefined)
10672
+ return null;
10673
+ const key = path11.resolve(cwd);
10674
+ const known = pinFiles.get(key);
10675
+ if (known !== undefined)
10676
+ return known;
10677
+ try {
10678
+ const location = resolveStore(key);
10679
+ if (location instanceof Error)
10680
+ return null;
10681
+ const file = location.shared ? path11.join(location.dir, "ledger", PIN_FILE) : null;
10682
+ pinFiles.set(key, file);
10683
+ return file;
10684
+ } catch {
10685
+ return null;
10686
+ }
10687
+ };
10688
+ var pinnedStateDir = (cwd) => {
10689
+ const file = pinFile(cwd);
10690
+ if (file === null)
10691
+ return null;
10692
+ try {
10693
+ const pinned = fs7.readFileSync(file, "utf8").trim();
10694
+ return path11.isAbsolute(pinned) ? pinned : null;
10695
+ } catch {
10696
+ return null;
10697
+ }
10698
+ };
10699
+ var registryDir = (cwd) => pinnedStateDir(cwd) ?? resolveStateDir();
10700
+ var testRunSkipsPin = (file) => process.env.WORKIT_TEST_RUN !== undefined && !insideTempDir(path11.dirname(path11.dirname(path11.dirname(file))));
10701
+ function pinIssuedRegistry(cwd) {
10702
+ const file = pinFile(cwd);
10703
+ if (file === null)
10704
+ return;
10705
+ const state = path11.resolve(resolveStateDir());
10706
+ if (pinnedStateDir(cwd) === state)
10707
+ return;
10708
+ if (testRunSkipsPin(file))
10709
+ return;
10710
+ try {
10711
+ fs7.mkdirSync(path11.dirname(file), { recursive: true });
10712
+ const temp = `${file}.${process.pid}.tmp`;
10713
+ fs7.writeFileSync(temp, `${state}
10714
+ `, { mode: 420 });
10715
+ fs7.renameSync(temp, file);
10716
+ } catch {}
10717
+ }
10718
+ var userIssuedRoot = (cwd) => path11.join(registryDir(cwd), "issued");
10719
+ var userTokenRoot = (cwd) => path11.join(registryDir(cwd), "issued-tokens");
10671
10720
  function migrateRepoIssued(cwd) {
10672
10721
  if (cwd === undefined)
10673
10722
  return;
@@ -10687,7 +10736,7 @@ function migrateRepoIssued(cwd) {
10687
10736
  const from = path11.join(old, lead);
10688
10737
  if (!fs7.statSync(from).isDirectory())
10689
10738
  continue;
10690
- const to = path11.join(userIssuedRoot(), lead);
10739
+ const to = path11.join(userIssuedRoot(cwd), lead);
10691
10740
  fs7.mkdirSync(to, { recursive: true, mode: 448 });
10692
10741
  for (const id of fs7.readdirSync(from)) {
10693
10742
  try {
@@ -10719,13 +10768,15 @@ var tokenHash = (token) => createHash8("sha256").update(token).digest("hex");
10719
10768
  function recordIssuedSession(cwd, lead, issued) {
10720
10769
  const token = randomBytes(18).toString("hex");
10721
10770
  try {
10771
+ pinIssuedRegistry(cwd);
10722
10772
  migrateRepoIssued(cwd);
10723
10773
  const own = hash(issued);
10724
- const tokens = path11.join(userTokenRoot(), hash(lead));
10774
+ const state = resolveStateDir();
10775
+ const tokens = path11.join(state, "issued-tokens", hash(lead));
10725
10776
  fs7.mkdirSync(tokens, { recursive: true, mode: 448 });
10726
10777
  fs7.writeFileSync(path11.join(tokens, own), `${tokenHash(token)}
10727
10778
  `, { mode: 384, flag: "wx" });
10728
- const dir = path11.join(userIssuedRoot(), hash(lead));
10779
+ const dir = path11.join(state, "issued", hash(lead));
10729
10780
  fs7.mkdirSync(dir, { recursive: true, mode: 448 });
10730
10781
  fs7.writeFileSync(path11.join(dir, own), `${ISSUED_SESSIONS_MARKER}
10731
10782
  `, { mode: 384 });
@@ -10770,17 +10821,17 @@ var issuedRecord = (cwd, claimed) => {
10770
10821
  return null;
10771
10822
  migrateRepoIssued(cwd);
10772
10823
  try {
10773
- return fs7.readFileSync(path11.join(userIssuedRoot(), hash(claimed.slice(0, cut)), hash(claimed)), "utf8");
10824
+ return fs7.readFileSync(path11.join(userIssuedRoot(cwd), hash(claimed.slice(0, cut)), hash(claimed)), "utf8");
10774
10825
  } catch {
10775
10826
  return null;
10776
10827
  }
10777
10828
  };
10778
10829
  var TOKEN_HASH = /^([0-9a-f]{64})$/mu;
10779
- var issuedToken = (claimed) => {
10830
+ var issuedToken = (cwd, claimed) => {
10780
10831
  const cut = claimed.lastIndexOf(":");
10781
10832
  if (cut <= 0)
10782
10833
  return { stored: null, leadBound: false };
10783
- const dir = path11.join(userTokenRoot(), hash(claimed.slice(0, cut)));
10834
+ const dir = path11.join(userTokenRoot(cwd), hash(claimed.slice(0, cut)));
10784
10835
  try {
10785
10836
  const text = fs7.readFileSync(path11.join(dir, hash(claimed)), "utf8");
10786
10837
  return { stored: TOKEN_HASH.exec(text)?.[1] ?? null, leadBound: true };
@@ -10790,7 +10841,7 @@ var issuedToken = (claimed) => {
10790
10841
  };
10791
10842
  function issuedBinding(cwd, claimed) {
10792
10843
  const record = issuedRecord(cwd, claimed);
10793
- const { stored, leadBound } = issuedToken(claimed);
10844
+ const { stored, leadBound } = issuedToken(cwd, claimed);
10794
10845
  if (stored)
10795
10846
  return "token";
10796
10847
  if (record === null)
@@ -33834,13 +33885,33 @@ Retry as: ${retry}`,
33834
33885
  }
33835
33886
 
33836
33887
  // packages/workit-core/src/agent-stamp.ts
33837
- import { createHash as createHash24, randomBytes as randomBytes5 } from "node:crypto";
33888
+ import { randomBytes as randomBytes5 } from "node:crypto";
33889
+ import fs36 from "node:fs";
33890
+ import path58 from "node:path";
33891
+
33892
+ // packages/workit-core/src/hooks/stamp-hint.ts
33893
+ import { createHash as createHash24 } from "node:crypto";
33838
33894
  import fs35 from "node:fs";
33839
33895
  import path57 from "node:path";
33896
+ var stampHash = (text) => createHash24("sha256").update(text).digest("hex").slice(0, 32);
33897
+ var stampDir = (env, session) => path57.join(stateDir(env), "agent-stamps", stampHash(session));
33898
+ var callTag = (toolUseId) => stampHash(toolUseId).slice(0, 8);
33899
+ var backgrounds = (command) => /(?:^|[^&<>])&(?![&>])/u.test(command);
33900
+ var dropCallStamps = (env, session, toolUseId) => {
33901
+ try {
33902
+ const dir = stampDir(env, session);
33903
+ const tag = `.${callTag(toolUseId)}-`;
33904
+ for (const name of fs35.readdirSync(dir))
33905
+ if (name.includes(tag))
33906
+ fs35.rmSync(path57.join(dir, name), { force: true });
33907
+ } catch {}
33908
+ };
33909
+ var STATE_NAME = "(?:WORKIT_(?:STATE_DIR|CONFIG)\\w*|XDG_(?:STATE|CONFIG|DATA)_HOME|HOME|USERPROFILE|(?:LOCAL)?APPDATA|OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)";
33910
+ var STATE_ENV = new RegExp(`${STATE_NAME}\\s*\\+?=|(?:unset|-u|--unset)[\\s=]+${STATE_NAME}|env:|EnvironmentVariable`, "iu");
33911
+
33912
+ // packages/workit-core/src/agent-stamp.ts
33840
33913
  var STAMP_TTL_MS = 120000;
33841
33914
  var AGENT_ID = /^[\w-]{1,64}$/u;
33842
- var hash2 = (text) => createHash24("sha256").update(text).digest("hex").slice(0, 32);
33843
- var stampDir = (env, session) => path57.join(stateDir(env), "agent-stamps", hash2(session));
33844
33915
  var workitCalls2 = (command, dialect = "posix") => {
33845
33916
  const calls = [];
33846
33917
  try {
@@ -33862,30 +33933,22 @@ var noteAgentStamps = (env, session, agentId, command, options = {}) => {
33862
33933
  const call = options.toolUseId ? callTag(options.toolUseId) : randomBytes5(4).toString("hex");
33863
33934
  try {
33864
33935
  const dir = stampDir(env, session);
33865
- fs35.mkdirSync(dir, { recursive: true, mode: 448 });
33936
+ fs36.mkdirSync(dir, { recursive: true, mode: 448 });
33866
33937
  const now = Date.now();
33867
- for (const name of fs35.readdirSync(dir))
33868
- if (now - fs35.statSync(path57.join(dir, name)).mtimeMs > STAMP_TTL_MS)
33869
- fs35.rmSync(path57.join(dir, name), { force: true });
33870
- calls.forEach((argv, index) => fs35.writeFileSync(path57.join(dir, `${hash2(argv.join("\x00"))}.${agentId ?? ""}.${call}-${index}`), ""));
33938
+ for (const name of fs36.readdirSync(dir))
33939
+ if (now - fs36.statSync(path58.join(dir, name)).mtimeMs > STAMP_TTL_MS)
33940
+ fs36.rmSync(path58.join(dir, name), { force: true });
33941
+ calls.forEach((argv, index) => fs36.writeFileSync(path58.join(dir, `${stampHash(argv.join("\x00"))}.${agentId ?? ""}.${call}-${index}`), ""));
33871
33942
  } catch {}
33872
33943
  };
33873
- var callTag = (toolUseId) => hash2(toolUseId).slice(0, 8);
33874
33944
  var dropAgentStamps = (env, session, toolUseId, command) => {
33875
- if (!session || !toolUseId || !command.includes("workit") || /(?:^|[^&<>])&(?![&>])/u.test(command))
33876
- return;
33877
- try {
33878
- const dir = stampDir(env, session);
33879
- const tag = `.${callTag(toolUseId)}-`;
33880
- for (const name of fs35.readdirSync(dir))
33881
- if (name.includes(tag))
33882
- fs35.rmSync(path57.join(dir, name), { force: true });
33883
- } catch {}
33945
+ if (session && toolUseId && command.includes("workit") && !backgrounds(command))
33946
+ dropCallStamps(env, session, toolUseId);
33884
33947
  };
33885
33948
 
33886
33949
  // packages/workit-core/src/hooks/hook-entry.ts
33887
33950
  import { existsSync as existsSync19, readFileSync as readFileSync16, realpathSync as realpathSync13 } from "node:fs";
33888
- import path58 from "node:path";
33951
+ import path59 from "node:path";
33889
33952
  var ENTRY_NAMES = /^(?:workit-hook(?:-[\w-]+)?\.(?:m?js|ts)|cursor-session-start\.js|workit-(?:codex|cursor)-hook|workit-cursor-session-start)(?:\.(?:cmd|ps1|exe))?$/iu;
33890
33953
  var PACKAGE_ENTRIES = {
33891
33954
  "claude-code": /^(?:bin\/workit-hook\.mjs|src\/(?:run|hook)\.ts|dist\/workit-hook\.js)$/u,
@@ -33926,7 +33989,7 @@ var MORE_WRAPPERS = new Set(["strace", "ltrace", "watch", "unshare", "firejail",
33926
33989
  var baseName3 = (word) => (word.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "").toLowerCase();
33927
33990
  var packageAt = (dir) => {
33928
33991
  try {
33929
- const name = JSON.parse(readFileSync16(path58.join(dir, "package.json"), "utf8")).name;
33992
+ const name = JSON.parse(readFileSync16(path59.join(dir, "package.json"), "utf8")).name;
33930
33993
  const short = /^@workit-dev\/(claude-code|codex|cursor|core)$/u.exec(String(name))?.[1];
33931
33994
  if (short)
33932
33995
  return short;
@@ -33937,7 +34000,7 @@ var packageAt = (dir) => {
33937
34000
  [".cursor-plugin", "cursor"]
33938
34001
  ]) {
33939
34002
  try {
33940
- const name = JSON.parse(readFileSync16(path58.join(dir, manifest, "plugin.json"), "utf8")).name;
34003
+ const name = JSON.parse(readFileSync16(path59.join(dir, manifest, "plugin.json"), "utf8")).name;
33941
34004
  if (name === "workit")
33942
34005
  return short;
33943
34006
  } catch {}
@@ -33945,12 +34008,12 @@ var packageAt = (dir) => {
33945
34008
  return null;
33946
34009
  };
33947
34010
  var entryByPath = (file) => {
33948
- let dir = path58.dirname(file);
33949
- for (let depth = 0;depth < 4; depth += 1, dir = path58.dirname(dir)) {
34011
+ let dir = path59.dirname(file);
34012
+ for (let depth = 0;depth < 4; depth += 1, dir = path59.dirname(dir)) {
33950
34013
  const short = packageAt(dir);
33951
34014
  if (short)
33952
- return PACKAGE_ENTRIES[short]?.test(path58.relative(dir, file).split(path58.sep).join("/")) ?? false;
33953
- if (existsSync19(path58.join(dir, "package.json")))
34015
+ return PACKAGE_ENTRIES[short]?.test(path59.relative(dir, file).split(path59.sep).join("/")) ?? false;
34016
+ if (existsSync19(path59.join(dir, "package.json")))
33954
34017
  return false;
33955
34018
  }
33956
34019
  return false;
@@ -33978,9 +34041,9 @@ var entryNamed = (word, scan) => {
33978
34041
  const fd = /^\/(?:dev|proc\/self)\/fd\/(\d+)$/u.exec(text)?.[1];
33979
34042
  if (fd !== undefined && scan.fds.has(fd))
33980
34043
  return text;
33981
- if (scan.dir === null && !path58.isAbsolute(text))
34044
+ if (scan.dir === null && !path59.isAbsolute(text))
33982
34045
  return null;
33983
- for (const file of expandGlob(path58.resolve(scan.dir ?? "/", text))) {
34046
+ for (const file of expandGlob(path59.resolve(scan.dir ?? "/", text))) {
33984
34047
  if (scan.links.has(file) || entryByPath(file))
33985
34048
  return text;
33986
34049
  let real;
@@ -34002,9 +34065,9 @@ var noteLink = (words, scan) => {
34002
34065
  if (dest === undefined || names.length < 2)
34003
34066
  return;
34004
34067
  for (const source of names.slice(0, -1).filter((name) => entryNamed(name, scan))) {
34005
- const to = path58.resolve(scan.dir, expand(dest, scan.vars));
34068
+ const to = path59.resolve(scan.dir, expand(dest, scan.vars));
34006
34069
  scan.links.add(to);
34007
- scan.links.add(path58.join(to, path58.basename(source)));
34070
+ scan.links.add(path59.join(to, path59.basename(source)));
34008
34071
  }
34009
34072
  };
34010
34073
  var runsEntry = (words, inputs, scan) => {
@@ -34097,7 +34160,7 @@ var ENTRY_SAMPLES = [
34097
34160
  "cursor-session-start.js"
34098
34161
  ];
34099
34162
  var tokenEntry = (token, scan) => {
34100
- if (!/[\\/]/u.test(token) && !existsSync19(path58.resolve(scan.dir ?? "/", token)))
34163
+ if (!/[\\/]/u.test(token) && !existsSync19(path59.resolve(scan.dir ?? "/", token)))
34101
34164
  return null;
34102
34165
  return entryNamed(token, scan);
34103
34166
  };
@@ -34135,7 +34198,7 @@ var opaqueEntry = (words, inputs, scan) => {
34135
34198
  if (/^(?:xargs|parallel)$/u.test(head) || tokens.includes("xargs"))
34136
34199
  for (const input of inputs) {
34137
34200
  try {
34138
- const file = path58.resolve(scan.dir ?? "/", expand(input, scan.vars));
34201
+ const file = path59.resolve(scan.dir ?? "/", expand(input, scan.vars));
34139
34202
  const text = readFileSync16(file, "utf8").slice(0, 65536);
34140
34203
  for (const token of text.split(/\s+/u).filter(Boolean)) {
34141
34204
  const hit = tokenEntry(token, scan);
@@ -34218,7 +34281,7 @@ var segmentEntry = (segment, words, dialect, scan, fed) => {
34218
34281
  if (["cd", "pushd", "chdir", "set-location", "sl"].includes(verb)) {
34219
34282
  const target = words.slice(1).find((word) => !word.startsWith("-") || word === "-");
34220
34283
  const moved = target === undefined ? userHome(process.env) : expand(target, scan.vars);
34221
- scan.dir = moved === "-" || /[$`]/u.test(moved) ? null : path58.isAbsolute(moved) ? moved : scan.dir && path58.resolve(scan.dir, moved);
34284
+ scan.dir = moved === "-" || /[$`]/u.test(moved) ? null : path59.isAbsolute(moved) ? moved : scan.dir && path59.resolve(scan.dir, moved);
34222
34285
  if (scan.dir === null)
34223
34286
  scan.vars.delete("PWD");
34224
34287
  else
@@ -34322,13 +34385,36 @@ var hookEntryRun = (cwd, command, dialect = "posix") => {
34322
34385
  var hookEntryDeny = (entry) => `workit hook guard: this command runs Workit's hook entry ${entry}. Only the host runs Workit's hooks, with the payload it builds; a payload written in a shell would act as a session, subagent or agent that never existed. Use the workit CLI for what you need (\`workit doctor\` probes the installed hooks).`;
34323
34386
 
34324
34387
  // packages/workit-core/src/hooks/identity-env.ts
34388
+ import fs37 from "node:fs";
34389
+ import path60 from "node:path";
34325
34390
  var NAMES = "WORKIT_(?:AGENT_ID|HOST|SESSION_ID|SESSION_TOKEN)";
34326
- var HOST_NAMES = "(?:OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)";
34327
34391
  var IDENTITY = new RegExp(`^${NAMES}$`, "u");
34392
+ var HOST_NAMES = "(?:OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)";
34328
34393
  var HOST_VARIABLE = new RegExp(`^${HOST_NAMES}$`, "u");
34329
- var powershell = (names) => new RegExp(`\\$env:${names}\\b|env:[\\\\/]?${names}\\b|EnvironmentVariable\\(\\s*['"]${names}\\b`, "iu");
34394
+ var IDENTITY_ANY = new RegExp(NAMES, "iu");
34395
+ var STATE_NAMES = "(?:WORKIT_(?:STATE_DIR|CONFIG(?:_DIR)?)|XDG_(?:STATE|CONFIG|DATA)_HOME|HOME|USERPROFILE|(?:LOCAL)?APPDATA)";
34396
+ var STATE2 = new RegExp(`^${STATE_NAMES}$`, "u");
34397
+ var STATE_ANY = new RegExp(STATE_NAMES, "iu");
34398
+ var powershell = (names) => new RegExp([
34399
+ `\\$\\{?env:${names}\\}?\\s*(?:[-+*/]|\\?\\?)?=(?!=)`,
34400
+ `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?${names}\\b`,
34401
+ `SetEnvironmentVariable\\(\\s*['"]${names}\\b`
34402
+ ].join("|"), "iu");
34403
+ var PS_ITEM = "\\b(?:(?:Set|New|Remove|Clear|Rename|Move|Copy)-Item(?:Property)?|(?:Set|Add|Clear)-Content|si|ni|ri|rm|del|erase|rd|rmdir|cli|sc|ac|clc|rni|mi|move|mv|cpi|copy|cp|ren)\\b";
34330
34404
  var POWERSHELL = powershell(NAMES);
34405
+ var POWERSHELL_STATE = powershell(STATE_NAMES);
34331
34406
  var POWERSHELL_HOST = powershell(HOST_NAMES);
34407
+ var POWERSHELL_OPAQUE = new RegExp([
34408
+ `SetEnvironmentVariable\\(\\s*(?:[^'"\\s]|"[^"]*\\$)`,
34409
+ `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?["']?[$(]`,
34410
+ `(?:^|[;&|{(\\n])\\s*\\.\\s+[^\\s.]`,
34411
+ `\\b(?:iex|Invoke-Expression)\\b`
34412
+ ].join("|"), "iu");
34413
+ var cmdSet = (names) => new RegExp(`(?:^|[&|(\\s"])set\\s+(?:/[ap]\\s+)?"?(${names})\\s*\\+?=`, "iu");
34414
+ var CMD_IDENTITY = cmdSet(NAMES);
34415
+ var CMD_STATE = cmdSet(STATE_NAMES);
34416
+ var CMD_HOST = cmdSet(HOST_NAMES);
34417
+ var RUNS_TEXT = /\bworkit(?:-cli)?\b|@workit-dev[\\/]cli/iu;
34332
34418
  var DECLARES = new Set(["export", "unset", "declare", "typeset", "local", "readonly"]);
34333
34419
  var OPAQUE = new Set([
34334
34420
  "watch",
@@ -34346,22 +34432,41 @@ var ENV_FLAGS = new Set(["i", "0", "v"]);
34346
34432
  var ENV_LONG_VALUED = new Set(["--unset", "--chdir", "--split-string", "--argv0"]);
34347
34433
  var ENV_LONG_FLAGS = /^--(?:ignore-environment|null|debug|(?:block|default|ignore)-signal(?:=.*)?)$/u;
34348
34434
  var base3 = (word) => (word?.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "");
34349
- var nameOf = (word) => word?.split("=")[0] ?? "";
34350
- var named = (word) => IDENTITY.test(nameOf(word)) || HOST_VARIABLE.test(nameOf(word));
34351
- var isWorkit = (word) => /^workit(?:-cli)?$/u.test(base3(word));
34435
+ var ASSIGN = /^[A-Za-z_]\w*\+?=/u;
34436
+ var nameOf = (word) => (word?.split("=")[0] ?? "").replace(/\+$/u, "");
34437
+ var named = (word) => IDENTITY.test(nameOf(word));
34438
+ var stateNamed = (word) => STATE2.test(nameOf(word));
34439
+ var isWorkit = (word) => /^workit(?:-cli)?(?:\.[cm]?js)?$/u.test(base3(word)) || /@workit-dev[\\/]cli\b|workit-cli[\\/](?:dist|src)[\\/]/u.test(word ?? "");
34440
+ var linksToWorkit = (word, cwd) => {
34441
+ const places = /[\\/]/u.test(word) ? [path60.resolve(cwd ?? process.cwd(), word)] : (process.env.PATH ?? "").split(path60.delimiter).map((dir) => path60.join(dir, word));
34442
+ for (const place of places) {
34443
+ try {
34444
+ const real = fs37.realpathSync(place);
34445
+ return isWorkit(real);
34446
+ } catch {}
34447
+ }
34448
+ return false;
34449
+ };
34450
+ var newSeg = () => ({ identity: null, scoped: null, runs: false, words: [] });
34352
34451
  var UNREADABLE = "env/unset arguments Workit cannot read";
34353
- var mark = (scan, word) => {
34354
- const name = nameOf(word);
34355
- if (IDENTITY.test(name))
34356
- scan.hit ??= name;
34357
- else if (HOST_VARIABLE.test(name))
34358
- scan.hostHit ??= name;
34359
- };
34360
- var scanEnv = (words, at, expands, scan, depth) => {
34452
+ var note = (scan, seg, word) => {
34453
+ if (scan.identity && named(word)) {
34454
+ if (seg)
34455
+ seg.identity ??= nameOf(word);
34456
+ else
34457
+ scan.hit ??= nameOf(word);
34458
+ }
34459
+ if (!stateNamed(word) && !(scan.identity && HOST_VARIABLE.test(nameOf(word))))
34460
+ return;
34461
+ if (seg)
34462
+ seg.scoped ??= nameOf(word);
34463
+ else
34464
+ scan.shell ??= nameOf(word);
34465
+ };
34466
+ var mayBeWorkit = (words, cwd) => words.some(({ word, built }) => built || linksToWorkit(word, cwd));
34467
+ var scanEnv = (words, at, expands, scan, seg, depth) => {
34361
34468
  const risky = (what) => void (scan.risky ??= what);
34362
- const unset = (name) => {
34363
- mark(scan, name);
34364
- };
34469
+ const unset = (name) => note(scan, seg, name);
34365
34470
  const split = (line, rest, built) => {
34366
34471
  if (line === undefined || depth >= 4)
34367
34472
  return risky(UNREADABLE);
@@ -34378,7 +34483,7 @@ var scanEnv = (words, at, expands, scan, depth) => {
34378
34483
  } catch {
34379
34484
  return risky(UNREADABLE);
34380
34485
  }
34381
- scanEnv([...tokens, ...words.slice(rest)], 0, expanded, scan, depth + 1);
34486
+ scanEnv([...tokens, ...words.slice(rest)], 0, expanded, scan, seg, depth + 1);
34382
34487
  };
34383
34488
  let options = true;
34384
34489
  for (let index = at;index < words.length; index += 1) {
@@ -34436,25 +34541,25 @@ var scanEnv = (words, at, expands, scan, depth) => {
34436
34541
  }
34437
34542
  continue;
34438
34543
  }
34439
- if (/^[A-Za-z_]\w*=/u.test(word)) {
34544
+ if (ASSIGN.test(word)) {
34440
34545
  unset(word);
34441
34546
  continue;
34442
34547
  }
34443
- return commandAt(words.slice(index), scan);
34548
+ return commandAt(words.slice(index), scan, seg, new Set([...expands].filter((at2) => at2 >= index).map((at2) => at2 - index)));
34444
34549
  }
34445
34550
  };
34446
- var commandAt = (words, scan, expands = new Set, from = 0) => {
34551
+ var commandAt = (words, scan, seg, expands = new Set, from = 0) => {
34447
34552
  let index = from;
34448
34553
  while (index < words.length) {
34449
- while (/^[A-Za-z_]\w*=/u.test(words[index] ?? "")) {
34450
- mark(scan, words[index]);
34554
+ while (ASSIGN.test(words[index] ?? "")) {
34555
+ note(scan, seg, words[index]);
34451
34556
  index += 1;
34452
34557
  }
34453
34558
  const name = base3(words[index]).toLowerCase();
34454
34559
  if (name === "env")
34455
- return scanEnv(words, index + 1, expands, scan, 0);
34560
+ return scanEnv(words, index + 1, expands, scan, seg, 0);
34456
34561
  if (OPAQUE.has(name))
34457
- return opaque(words.slice(index + 1), scan, true);
34562
+ return opaque(words.slice(index + 1), scan, seg, true);
34458
34563
  if (name === "busybox" || name === "toybox") {
34459
34564
  index += 1;
34460
34565
  continue;
@@ -34464,21 +34569,37 @@ var commandAt = (words, scan, expands = new Set, from = 0) => {
34464
34569
  break;
34465
34570
  index = pastOptions(words, index + 1, takes);
34466
34571
  }
34467
- if (isWorkit(words[index]))
34468
- scan.runs = true;
34469
- else if (words.slice(index + 1).some((word) => base3(word).toLowerCase() === "env"))
34470
- opaque(words.slice(index + 1), scan, false);
34471
- };
34472
- var opaque = (rest, scan, assigns) => {
34572
+ const word = words[index];
34573
+ if (word === undefined)
34574
+ return;
34575
+ seg.words.push({ word, built: expands.has(index) });
34576
+ const rest = words.slice(index + 1);
34577
+ if (isWorkit(word) || rest.some(isWorkit))
34578
+ seg.runs = true;
34579
+ if (!isWorkit(word) && rest.some((next) => base3(next).toLowerCase() === "env"))
34580
+ opaque(rest, scan, seg, false);
34581
+ const program = base3(word).toLowerCase();
34582
+ const shell = program === "pwsh" || program === "powershell";
34583
+ if (program === "cmd" || shell) {
34584
+ const at = rest.findIndex((next) => shell ? /^-(?:c|command)$/iu.test(next) : /^\/[ck]$/iu.test(next));
34585
+ if (at >= 0) {
34586
+ const script = rest.slice(at + 1).join(" ");
34587
+ const change = shell ? powershellChange(script, scan.identity) : cmdChange(script, scan);
34588
+ if (change)
34589
+ scan.hit ??= change;
34590
+ }
34591
+ }
34592
+ };
34593
+ var opaque = (rest, scan, seg, assigns) => {
34473
34594
  if (!rest.some(isWorkit))
34474
34595
  return;
34475
- scan.runs = true;
34476
- const changes = (word) => base3(word).toLowerCase() === "env" || DECLARES.has(word) || assigns && /^[A-Za-z_]\w*=/u.test(word);
34596
+ seg.runs = true;
34597
+ const changes = (word) => base3(word).toLowerCase() === "env" || DECLARES.has(word) || assigns && ASSIGN.test(word);
34477
34598
  if (rest.some(changes))
34478
34599
  scan.risky ??= UNREADABLE;
34479
- const hit = rest.find(named);
34480
- if (hit && rest.some((word) => base3(word).toLowerCase() === "env"))
34481
- mark(scan, hit);
34600
+ if (rest.some((word) => base3(word).toLowerCase() === "env"))
34601
+ for (const word of rest)
34602
+ note(scan, seg, word);
34482
34603
  };
34483
34604
  var LOGIN_VALUED = {
34484
34605
  su: /[sgGwc]/u,
@@ -34513,43 +34634,90 @@ var scanCommand2 = (command, dialect, depth, scan) => {
34513
34634
  }
34514
34635
  for (const { words, expands = [] } of segments) {
34515
34636
  const expanded = new Set(expands);
34637
+ const seg = newSeg();
34516
34638
  let at = 0;
34517
- while (/^[A-Za-z_]\w*=/u.test(words[at] ?? "")) {
34518
- mark(scan, words[at]);
34639
+ while (ASSIGN.test(words[at] ?? ""))
34519
34640
  at += 1;
34520
- }
34641
+ for (const word of words.slice(0, at))
34642
+ note(scan, at === words.length ? null : seg, word);
34521
34643
  let declare = at;
34522
34644
  if (["builtin", "command"].includes(words[declare] ?? ""))
34523
34645
  declare += 1;
34524
34646
  if (DECLARES.has(words[declare] ?? "")) {
34525
34647
  for (let index = declare + 1;index < words.length; index += 1) {
34526
- mark(scan, words[index]);
34648
+ note(scan, null, words[index]);
34527
34649
  if (expanded.has(index))
34528
34650
  scan.risky ??= UNREADABLE;
34529
34651
  }
34530
34652
  continue;
34531
34653
  }
34532
- commandAt(words, scan, expanded, at);
34654
+ commandAt(words, scan, seg, expanded, at);
34533
34655
  const script = depth < 4 ? shellScript2(words) ?? loginScript(words) : null;
34534
- if (script)
34656
+ if (script) {
34657
+ const before = scan.runs;
34658
+ scan.runs = false;
34535
34659
  scanCommand2(script, dialect, depth + 1, scan);
34536
- }
34537
- };
34538
- var identityEnvChange = (command, dialect = "posix") => {
34539
- if (!/WORKIT_|OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDE|\b(?:env|unset|export|declare|typeset|local|readonly)\b/u.test(command))
34660
+ seg.runs ||= scan.runs;
34661
+ scan.runs ||= before;
34662
+ }
34663
+ scan.words.push(...seg.words);
34664
+ const reaches = () => seg.runs || mayBeWorkit(seg.words, scan.cwd);
34665
+ if (seg.identity && reaches())
34666
+ scan.hit ??= seg.identity;
34667
+ if (seg.scoped && reaches())
34668
+ scan.state ??= seg.scoped;
34669
+ scan.runs ||= seg.runs;
34670
+ }
34671
+ };
34672
+ var cmdChange = (script, scan) => (scan.identity ? CMD_IDENTITY.exec(script)?.[1] : null) ?? (RUNS_TEXT.test(script) ? CMD_STATE.exec(script)?.[1] ?? (scan.identity ? CMD_HOST.exec(script)?.[1] : null) ?? null : null);
34673
+ var powershellChange = (command, identity) => {
34674
+ const hit = identity ? POWERSHELL.exec(command)?.[0] : null;
34675
+ if (hit)
34676
+ return hit;
34677
+ if (!RUNS_TEXT.test(command) && !/&\s*[$(]/u.test(command))
34540
34678
  return null;
34679
+ const state = POWERSHELL_STATE.exec(command)?.[0] ?? (identity ? POWERSHELL_HOST.exec(command)?.[0] : null) ?? cmdChange(command, { identity });
34680
+ if (state)
34681
+ return state;
34682
+ return POWERSHELL_OPAQUE.test(command) ? UNREADABLE : null;
34683
+ };
34684
+ var identityEnvChange = (command, dialect = "posix", options = {}) => {
34685
+ const identity = options.identity ?? true;
34541
34686
  if (dialect === "powershell")
34542
- return POWERSHELL.exec(command)?.[0] ?? (/\bworkit\b/iu.test(command) ? POWERSHELL_HOST.exec(command)?.[0] ?? null : null);
34543
- const scan = { hit: null, hostHit: null, risky: null, runs: false };
34687
+ return powershellChange(command, identity);
34688
+ if (!/WORKIT_|XDG_|HOME|USERPROFILE|APPDATA|OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDE|EnvironmentVariable|\b(?:env|unset|export|declare|typeset|local|readonly)\b/iu.test(command))
34689
+ return null;
34690
+ const scan = {
34691
+ identity,
34692
+ cwd: options.cwd,
34693
+ hit: null,
34694
+ state: null,
34695
+ shell: null,
34696
+ risky: null,
34697
+ runs: false,
34698
+ words: []
34699
+ };
34544
34700
  scanCommand2(command, dialect, 0, scan);
34545
- return scan.hit ?? (scan.runs ? scan.hostHit ?? scan.risky : null);
34701
+ if (scan.hit)
34702
+ return scan.hit;
34703
+ if (scan.state)
34704
+ return scan.state;
34705
+ if (scan.shell && (scan.runs || mayBeWorkit(scan.words, scan.cwd)))
34706
+ return scan.shell;
34707
+ return scan.runs ? scan.risky : null;
34708
+ };
34709
+ var identityEnvDeny = (change) => {
34710
+ if (change === UNREADABLE || IDENTITY_ANY.test(change) || !STATE_ANY.test(change))
34711
+ return `workit identity: ${change === UNREADABLE ? `this command runs workit with ${UNREADABLE}` : `this command changes ${change}`}. The host sets WORKIT_HOST, WORKIT_SESSION_ID, WORKIT_AGENT_ID and its own session variables, and Workit acts as who they name; run it without changing them (a verifier or reviewer passes the --session and --token its start text names).`;
34712
+ return `workit identity: this command runs workit with ${change} changed. Workit reads issued sessions, grants and its ledger trust from the state and config dirs the host's environment names, so a workit call may not move them (#980); run it without setting, unsetting or emptying ${change}.`;
34546
34713
  };
34547
- var identityEnvDeny = (change) => `workit identity: ${change === UNREADABLE ? `this command runs workit with ${UNREADABLE}` : `this command changes ${change}`}. The host sets WORKIT_HOST, WORKIT_SESSION_ID, WORKIT_AGENT_ID and its own session variables, and Workit acts as who they name; run it without changing them (a verifier or reviewer passes the --session and --token its start text names).`;
34548
34714
 
34549
34715
  // packages/workit-core/src/hooks/handle.ts
34550
34716
  var usable2 = (value) => value === "native" || value === "partial";
34551
34717
  var stampsAgents = (descriptor) => descriptor.transport === "hook-process" && usable2(descriptor.provenance.agentIdOnTool);
34552
34718
  var NONE6 = { kind: "none" };
34719
+ var subagentShellIsOwnSession = (descriptor) => descriptor.host === "codex_cli" || descriptor.host === "codex_desktop";
34720
+ var stampKey = (input, descriptor) => subagentShellIsOwnSession(descriptor) && input.session.agentId ? { session: input.session.agentId, agentId: null } : { session: input.session.id, agentId: input.session.agentId };
34553
34721
  var resendsOnChange = (descriptor) => descriptor.context.turnResend === "on-change" && usable2(descriptor.context.perTurn);
34554
34722
  var offered = new Set;
34555
34723
  var agentRole = (input, descriptor) => input.session.agentId && input.session.agentType !== null ? workitRole(descriptor, input.session.agentType) : null;
@@ -34595,7 +34763,7 @@ ${subagentStartText({ ...input, cwd: "" }, descriptor, event)}`;
34595
34763
  const at = currentBranch(cwd) === null ? null : worktreeTop(cwd) ?? null;
34596
34764
  const checks = judgeChecksLine(cwd);
34597
34765
  const checksText = checks ? ` ${checks}` : "";
34598
- if (descriptor.host === "codex_cli" || descriptor.host === "codex_desktop")
34766
+ if (subagentShellIsOwnSession(descriptor))
34599
34767
  return `${readOnly} Its shell already acts as its own Workit session, so the ledger tells its verdicts apart from the author's. Record the verdict with exactly this command (pick the result${pick}, name the candidate branch if it differs, say what you ran): \`${verdictCommand({ branch, judge, cwd: at })}\`. Add no session or token option to it, and never set WORKIT_SESSION_ID by hand.${checksText}`;
34600
34768
  const token = session ? recordIssuedSession(cwd, session, own) : null;
34601
34769
  if (session && !token)
@@ -34621,6 +34789,7 @@ function decide(input, deps) {
34621
34789
  switch (event.kind) {
34622
34790
  case "session.start": {
34623
34791
  reapAtStart(input.cwd);
34792
+ pinIssuedRegistry(input.cwd);
34624
34793
  if (!usable2(descriptor.context.sessionStart))
34625
34794
  return NONE6;
34626
34795
  const key = input.session.id ? `${input.host}\x00${input.session.id}` : null;
@@ -34744,7 +34913,10 @@ function decide(input, deps) {
34744
34913
  const gate = usable2(descriptor.events["write.pre"].support) ? shellGate(input.cwd, event.command, owner, event.dialect) : NONE6;
34745
34914
  if (gate.kind === "deny")
34746
34915
  return gate;
34747
- const identity = canDeny && stampsAgents(descriptor) ? identityEnvChange(event.command, event.dialect) : null;
34916
+ const identity = canDeny ? identityEnvChange(event.command, event.dialect, {
34917
+ identity: stampsAgents(descriptor),
34918
+ cwd: input.cwd
34919
+ }) : null;
34748
34920
  if (identity)
34749
34921
  return { kind: "deny", reason: identityEnvDeny(identity), unblock: null };
34750
34922
  const plan = heavyGate(input.cwd, event.command, {
@@ -34764,8 +34936,10 @@ function decide(input, deps) {
34764
34936
  const aside = plan.kind === "passthrough" ? plan.note : null;
34765
34937
  noteRawCommit(input, event.command, postTool ? callKey(event.toolUseId, event.command) : NEXT_COMMAND);
34766
34938
  const bypass = !lease && input.host === "claude_code" ? workitBypassFlag(event.command, event.dialect) : null;
34767
- if (stampsAgents(descriptor))
34768
- noteAgentStamps(process.env, input.session.id, input.session.agentId, lease?.command ?? cwdCommand ?? event.command, { dialect: event.dialect, toolUseId: event.toolUseId });
34939
+ if (stampsAgents(descriptor)) {
34940
+ const key = stampKey(input, descriptor);
34941
+ noteAgentStamps(process.env, key.session, key.agentId, lease?.command ?? cwdCommand ?? event.command, { dialect: event.dialect, toolUseId: event.toolUseId });
34942
+ }
34769
34943
  if (bypass)
34770
34944
  return { kind: "ask", reason: bypass };
34771
34945
  const rewrittenTo = lease?.command ?? cwdCommand;
@@ -34795,7 +34969,7 @@ function decide(input, deps) {
34795
34969
  if (usable2(descriptor.events["shell.post"].support))
34796
34970
  rawGitPost(input, event.command, callKey(event.toolUseId, event.command));
34797
34971
  if (stampsAgents(descriptor))
34798
- dropAgentStamps(process.env, input.session.id, event.toolUseId, event.command);
34972
+ dropAgentStamps(process.env, stampKey(input, descriptor).session, event.toolUseId, event.command);
34799
34973
  return NONE6;
34800
34974
  case "write.pre": {
34801
34975
  if (!usable2(descriptor.events["write.pre"].support))
@@ -34881,11 +35055,11 @@ var modelKey = (model) => {
34881
35055
 
34882
35056
  // packages/workit-core/src/hooks/budget-signal.ts
34883
35057
  import { createHash as createHash25 } from "node:crypto";
34884
- import fs36 from "node:fs";
34885
- import path59 from "node:path";
34886
- var hash3 = (text) => createHash25("sha256").update(text).digest("hex").slice(0, 32);
34887
- var budgetDir = (store) => path59.join(store, "budget");
34888
- var agentBase = (store, session, agentId) => path59.join(budgetDir(store), hash3(`${session}\x00${agentId ?? ""}`));
35058
+ import fs38 from "node:fs";
35059
+ import path61 from "node:path";
35060
+ var hash2 = (text) => createHash25("sha256").update(text).digest("hex").slice(0, 32);
35061
+ var budgetDir = (store) => path61.join(store, "budget");
35062
+ var agentBase = (store, session, agentId) => path61.join(budgetDir(store), hash2(`${session}\x00${agentId ?? ""}`));
34889
35063
  var spawnBudget = (prompt) => {
34890
35064
  const found = /^TIMEBOX:[^\n]*?\b(\d+)\s+tool calls\b/mu.exec(prompt);
34891
35065
  const n = found ? Number(found[1]) : NaN;
@@ -34893,7 +35067,7 @@ var spawnBudget = (prompt) => {
34893
35067
  };
34894
35068
  var readBudget = (file) => {
34895
35069
  try {
34896
- const { limit, told } = JSON.parse(fs36.readFileSync(file, "utf8"));
35070
+ const { limit, told } = JSON.parse(fs38.readFileSync(file, "utf8"));
34897
35071
  return typeof limit === "number" && limit > 0 ? { limit, told: Number(told) || 0 } : null;
34898
35072
  } catch {
34899
35073
  return null;
@@ -34901,16 +35075,16 @@ var readBudget = (file) => {
34901
35075
  };
34902
35076
  var startBudget = (store, session, agentId, n) => {
34903
35077
  const dir = budgetDir(store);
34904
- fs36.mkdirSync(dir, { recursive: true });
35078
+ fs38.mkdirSync(dir, { recursive: true });
34905
35079
  const cutoff = Date.now() - 604800000;
34906
- for (const name of fs36.readdirSync(dir))
35080
+ for (const name of fs38.readdirSync(dir))
34907
35081
  try {
34908
- if (fs36.statSync(path59.join(dir, name)).mtimeMs < cutoff)
34909
- fs36.rmSync(path59.join(dir, name));
35082
+ if (fs38.statSync(path61.join(dir, name)).mtimeMs < cutoff)
35083
+ fs38.rmSync(path61.join(dir, name));
34910
35084
  } catch {}
34911
35085
  const base = agentBase(store, session, agentId);
34912
- fs36.writeFileSync(`${base}.json`, JSON.stringify({ limit: n, told: 0 }));
34913
- fs36.rmSync(`${base}.calls`, { force: true });
35086
+ fs38.writeFileSync(`${base}.json`, JSON.stringify({ limit: n, told: 0 }));
35087
+ fs38.rmSync(`${base}.calls`, { force: true });
34914
35088
  };
34915
35089
  var bindBudget = (cwd, session, agentId, prompt) => {
34916
35090
  try {
@@ -34933,8 +35107,8 @@ var tickBudget = (cwd, session, agentId) => {
34933
35107
  const budget = readBudget(`${base}.json`);
34934
35108
  if (!budget)
34935
35109
  return false;
34936
- fs36.appendFileSync(`${base}.calls`, ".");
34937
- return fs36.statSync(`${base}.calls`).size >= budget.limit * (budget.told + 1);
35110
+ fs38.appendFileSync(`${base}.calls`, ".");
35111
+ return fs38.statSync(`${base}.calls`).size >= budget.limit * (budget.told + 1);
34938
35112
  } catch {
34939
35113
  return false;
34940
35114
  }
@@ -34946,14 +35120,14 @@ var reachedOf = (cwd, session, agentId) => {
34946
35120
  const budget = base && readBudget(`${base}.json`);
34947
35121
  if (!budget)
34948
35122
  return null;
34949
- return { base, budget, reached: Math.floor(fs36.statSync(`${base}.calls`).size / budget.limit) };
35123
+ return { base, budget, reached: Math.floor(fs38.statSync(`${base}.calls`).size / budget.limit) };
34950
35124
  };
34951
35125
  var budgetLine = (cwd, session, agentId) => {
34952
35126
  try {
34953
35127
  const at = reachedOf(cwd, session, agentId);
34954
35128
  if (!at || at.reached <= at.budget.told)
34955
35129
  return null;
34956
- fs36.writeFileSync(`${at.base}.json`, JSON.stringify({ ...at.budget, told: at.reached }));
35130
+ fs38.writeFileSync(`${at.base}.json`, JSON.stringify({ ...at.budget, told: at.reached }));
34957
35131
  return lineFor(at.budget.limit * at.reached);
34958
35132
  } catch {
34959
35133
  return null;
@@ -35361,12 +35535,12 @@ var skillPromptNudge = (prompt, ctx) => process.env.WORKIT_PI_WORKER_SESSION ? n
35361
35535
  // packages/workit-pi/src/launches.ts
35362
35536
  import { mkdirSync as mkdirSync8, readFileSync as readFileSync17, readdirSync as readdirSync9, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "node:fs";
35363
35537
  import os13 from "node:os";
35364
- import path60 from "node:path";
35538
+ import path62 from "node:path";
35365
35539
  var launchDir = (root) => {
35366
35540
  const location = resolveStore(root);
35367
- return location instanceof Error ? null : path60.join(location.dir, "pi-launches");
35541
+ return location instanceof Error ? null : path62.join(location.dir, "pi-launches");
35368
35542
  };
35369
- var fileFor = (dir, workerId) => path60.join(dir, `${workerId.replace(/[^A-Za-z0-9-]/g, "_")}.json`);
35543
+ var fileFor = (dir, workerId) => path62.join(dir, `${workerId.replace(/[^A-Za-z0-9-]/g, "_")}.json`);
35370
35544
  var recordLaunch = (root, attempt) => {
35371
35545
  const dir = launchDir(root);
35372
35546
  if (!dir)
@@ -35412,7 +35586,7 @@ var abandonedLaunches = (root) => {
35412
35586
  const found = [];
35413
35587
  for (const name of names) {
35414
35588
  try {
35415
- const attempt = JSON.parse(readFileSync17(path60.join(dir, name), "utf8"));
35589
+ const attempt = JSON.parse(readFileSync17(path62.join(dir, name), "utf8"));
35416
35590
  if (typeof attempt.workerId === "string" && typeof attempt.session === "string") {
35417
35591
  if (!alive(attempt))
35418
35592
  found.push(attempt);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workit-dev/pi",
3
- "version": "2.27.8",
3
+ "version": "2.27.10",
4
4
  "description": "Workit native extension for Pi — tools, method skills, and session continuity",
5
5
  "keywords": [
6
6
  "agentic-coding",