terminal-pilot 0.0.21 → 0.0.23

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 (61) hide show
  1. package/dist/cli.js +614 -250
  2. package/dist/cli.js.map +4 -4
  3. package/dist/commands/close-session.js +6 -4
  4. package/dist/commands/close-session.js.map +3 -3
  5. package/dist/commands/create-session.js +6 -4
  6. package/dist/commands/create-session.js.map +3 -3
  7. package/dist/commands/fill.js +6 -4
  8. package/dist/commands/fill.js.map +3 -3
  9. package/dist/commands/get-session.js +6 -4
  10. package/dist/commands/get-session.js.map +3 -3
  11. package/dist/commands/index.d.ts +35 -35
  12. package/dist/commands/index.js +97 -36
  13. package/dist/commands/index.js.map +4 -4
  14. package/dist/commands/install.js +74 -20
  15. package/dist/commands/install.js.map +4 -4
  16. package/dist/commands/installer.js +36 -2
  17. package/dist/commands/installer.js.map +4 -4
  18. package/dist/commands/list-sessions.js +6 -4
  19. package/dist/commands/list-sessions.js.map +3 -3
  20. package/dist/commands/press-key.js +6 -4
  21. package/dist/commands/press-key.js.map +3 -3
  22. package/dist/commands/read-history.js +6 -4
  23. package/dist/commands/read-history.js.map +3 -3
  24. package/dist/commands/read-screen.js +6 -4
  25. package/dist/commands/read-screen.js.map +3 -3
  26. package/dist/commands/resize.js +6 -4
  27. package/dist/commands/resize.js.map +3 -3
  28. package/dist/commands/runtime.js +6 -4
  29. package/dist/commands/runtime.js.map +3 -3
  30. package/dist/commands/screenshot.js +22 -8
  31. package/dist/commands/screenshot.js.map +4 -4
  32. package/dist/commands/send-signal.js +6 -4
  33. package/dist/commands/send-signal.js.map +3 -3
  34. package/dist/commands/type.js +6 -4
  35. package/dist/commands/type.js.map +3 -3
  36. package/dist/commands/uninstall.js +39 -5
  37. package/dist/commands/uninstall.js.map +4 -4
  38. package/dist/commands/wait-for-exit.js +6 -4
  39. package/dist/commands/wait-for-exit.js.map +3 -3
  40. package/dist/commands/wait-for.js +6 -4
  41. package/dist/commands/wait-for.js.map +3 -3
  42. package/dist/errors.d.ts +1 -0
  43. package/dist/errors.js +8 -0
  44. package/dist/errors.js.map +7 -0
  45. package/dist/index.js +8 -4
  46. package/dist/index.js.map +3 -3
  47. package/dist/terminal-pilot.js +6 -4
  48. package/dist/terminal-pilot.js.map +3 -3
  49. package/dist/terminal-session.js +6 -4
  50. package/dist/terminal-session.js.map +3 -3
  51. package/dist/testing/cli-repl.js +614 -250
  52. package/dist/testing/cli-repl.js.map +4 -4
  53. package/dist/testing/qa-cli.js +614 -250
  54. package/dist/testing/qa-cli.js.map +4 -4
  55. package/node_modules/@poe-code/agent-skill-config/dist/apply.js +2 -1
  56. package/node_modules/@poe-code/agent-skill-config/dist/bridge-active-skills.js +8 -9
  57. package/node_modules/@poe-code/agent-skill-config/dist/error-codes.d.ts +1 -0
  58. package/node_modules/@poe-code/agent-skill-config/dist/error-codes.js +5 -0
  59. package/node_modules/@poe-code/agent-skill-config/dist/git-exclude.js +18 -12
  60. package/node_modules/@poe-code/agent-skill-config/dist/templates.js +2 -1
  61. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import path23 from "node:path";
11
11
  import { fileURLToPath as fileURLToPath5 } from "node:url";
12
12
 
13
13
  // ../toolcraft/src/cli.ts
14
- import { access as access2, lstat as lstat3, readFile as readFile4, rename as rename3, unlink as unlink2, writeFile as writeFile5 } from "node:fs/promises";
14
+ import { access as access2, lstat as lstat3, readFile as readFile4, rename as rename3, unlink as unlink3, writeFile as writeFile5 } from "node:fs/promises";
15
15
  import path14 from "node:path";
16
16
  import {
17
17
  Command as CommanderCommand,
@@ -2707,6 +2707,11 @@ function getCommandSourcePath(command) {
2707
2707
  return command[commandSourcePathSymbol];
2708
2708
  }
2709
2709
 
2710
+ // ../toolcraft/src/error-codes.ts
2711
+ function hasOwnErrorCode(error3, code) {
2712
+ return typeof error3 === "object" && error3 !== null && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
2713
+ }
2714
+
2710
2715
  // ../task-list/src/open.ts
2711
2716
  import * as fsPromises from "node:fs/promises";
2712
2717
 
@@ -2727,27 +2732,27 @@ function validateMachine(machine) {
2727
2732
  if (!isRecord(machine)) {
2728
2733
  throw new TypeError("State machine must be an object.");
2729
2734
  }
2730
- if (!isStateList(machine.states)) {
2735
+ if (!hasOwnRecordField(machine, "states") || !isStateList(machine.states)) {
2731
2736
  throw new TypeError("State machine states must be a string array.");
2732
2737
  }
2733
2738
  const states = new Set(machine.states);
2734
- if (typeof machine.initial !== "string") {
2739
+ if (!hasOwnRecordField(machine, "initial") || typeof machine.initial !== "string") {
2735
2740
  throw new TypeError("State machine initial must be a string.");
2736
2741
  }
2737
2742
  if (!states.has(machine.initial)) {
2738
2743
  throw new Error(`Initial state "${machine.initial}" is not declared.`);
2739
2744
  }
2740
- if (!isRecord(machine.events)) {
2745
+ if (!hasOwnRecordField(machine, "events") || !isRecord(machine.events)) {
2741
2746
  throw new TypeError("State machine events must be an object.");
2742
2747
  }
2743
2748
  for (const [eventName, event] of Object.entries(machine.events)) {
2744
2749
  if (!isRecord(event)) {
2745
2750
  throw new TypeError(`Event "${eventName}" must be an object.`);
2746
2751
  }
2747
- if (event.from !== "*" && !isStateList(event.from)) {
2752
+ if (!hasOwnRecordField(event, "from") || event.from !== "*" && !isStateList(event.from)) {
2748
2753
  throw new TypeError(`Event "${eventName}" has an invalid "from" definition.`);
2749
2754
  }
2750
- if (typeof event.to !== "string") {
2755
+ if (!hasOwnRecordField(event, "to") || typeof event.to !== "string") {
2751
2756
  throw new TypeError(`Event "${eventName}" target state must be a string.`);
2752
2757
  }
2753
2758
  if (!states.has(event.to)) {
@@ -2762,6 +2767,9 @@ function validateMachine(machine) {
2762
2767
  }
2763
2768
  }
2764
2769
  }
2770
+ function hasOwnRecordField(record, key2) {
2771
+ return Object.prototype.hasOwnProperty.call(record, key2);
2772
+ }
2765
2773
  function eventsFromState(machine, fromState) {
2766
2774
  const events = [];
2767
2775
  for (const [eventName, event] of Object.entries(machine.events)) {
@@ -2872,10 +2880,12 @@ import path5 from "node:path";
2872
2880
  // ../process-runner/src/host/host-runner.ts
2873
2881
  import { spawn as spawnChildProcess } from "node:child_process";
2874
2882
  function createHostRunner(options = {}) {
2875
- const detachedByDefault = options.detached === true;
2883
+ const runnerOptions = normalizeHostRunnerOptions(options);
2884
+ const detachedByDefault = runnerOptions.detached === true;
2876
2885
  return {
2877
2886
  name: "host",
2878
- exec(spec) {
2887
+ exec(inputSpec) {
2888
+ const spec = normalizeRunSpec(inputSpec);
2879
2889
  if (spec.signal?.aborted === true) {
2880
2890
  return {
2881
2891
  pid: null,
@@ -2892,12 +2902,16 @@ function createHostRunner(options = {}) {
2892
2902
  const stderrMode = spec.stderr ?? "pipe";
2893
2903
  const killProcessGroup = detachedByDefault || spec.killProcessGroup === true;
2894
2904
  const stdio = stdinMode === "inherit" && stdoutMode === "inherit" && stderrMode === "inherit" ? "inherit" : [stdinMode, stdoutMode, stderrMode];
2895
- const child = spawnChildProcess(spec.command, spec.args ?? [], {
2896
- cwd: spec.cwd,
2897
- env: spec.env,
2898
- stdio,
2899
- ...killProcessGroup ? { detached: true } : {}
2900
- });
2905
+ const child = spawnChildProcess(
2906
+ spec.command,
2907
+ spec.args ?? [],
2908
+ createNullRecord({
2909
+ cwd: spec.cwd,
2910
+ env: spec.env,
2911
+ stdio,
2912
+ ...killProcessGroup ? { detached: true } : {}
2913
+ })
2914
+ );
2901
2915
  if (killProcessGroup) {
2902
2916
  child.unref();
2903
2917
  }
@@ -2943,6 +2957,38 @@ function createHostRunner(options = {}) {
2943
2957
  }
2944
2958
  };
2945
2959
  }
2960
+ function normalizeHostRunnerOptions(options) {
2961
+ return createNullRecord({
2962
+ ...optionalOwnProperty(options, "detached")
2963
+ });
2964
+ }
2965
+ function normalizeRunSpec(spec) {
2966
+ return createNullRecord({
2967
+ command: getOwnProperty(spec, "command"),
2968
+ ...optionalOwnProperty(spec, "args"),
2969
+ ...optionalOwnProperty(spec, "cwd"),
2970
+ ...optionalOwnProperty(spec, "env"),
2971
+ ...optionalOwnProperty(spec, "stdin"),
2972
+ ...optionalOwnProperty(spec, "stdout"),
2973
+ ...optionalOwnProperty(spec, "stderr"),
2974
+ ...optionalOwnProperty(spec, "tty"),
2975
+ ...optionalOwnProperty(spec, "signal"),
2976
+ ...optionalOwnProperty(spec, "killProcessGroup")
2977
+ });
2978
+ }
2979
+ function optionalOwnProperty(value, name) {
2980
+ const property = getOwnProperty(value, name);
2981
+ return property === void 0 ? {} : { [name]: property };
2982
+ }
2983
+ function getOwnProperty(value, name) {
2984
+ return hasOwnProperty(value, name) ? value[name] : void 0;
2985
+ }
2986
+ function hasOwnProperty(value, name) {
2987
+ return Object.prototype.hasOwnProperty.call(value, name);
2988
+ }
2989
+ function createNullRecord(value) {
2990
+ return Object.assign(/* @__PURE__ */ Object.create(null), value);
2991
+ }
2946
2992
  function bindAbortSignal(signal, onAbort) {
2947
2993
  if (signal === void 0) {
2948
2994
  return () => {
@@ -3033,6 +3079,7 @@ function resolveEndpoint(options = {}) {
3033
3079
  }
3034
3080
 
3035
3081
  // ../task-list/src/backends/utils.ts
3082
+ import { randomUUID as randomUUID2 } from "node:crypto";
3036
3083
  import path6 from "node:path";
3037
3084
  function compareCreated(left, right) {
3038
3085
  const leftCreated = typeof left.raw.created === "string" ? left.raw.created : "";
@@ -3053,9 +3100,8 @@ function applyOrder(entries, order) {
3053
3100
  }
3054
3101
  return entries.map((entry) => entry.task);
3055
3102
  }
3056
- var tmpFileCounter = 0;
3057
3103
  function hasErrorCode(error3, code) {
3058
- return !!error3 && typeof error3 === "object" && "code" in error3 && error3.code === code;
3104
+ return !!error3 && typeof error3 === "object" && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
3059
3105
  }
3060
3106
  function isRecord2(value) {
3061
3107
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -3102,18 +3148,22 @@ async function rejectSymbolicLinkComponents(fs4, filePath) {
3102
3148
  }
3103
3149
  }
3104
3150
  async function writeAtomically(fs4, filePath, content) {
3105
- const tempPath = `${filePath}.tmp-${process.pid}-${tmpFileCounter}`;
3106
- tmpFileCounter += 1;
3151
+ const tempPath = `${filePath}.${process.pid}.${randomUUID2()}.tmp`;
3152
+ let tempCreated = false;
3107
3153
  await fs4.mkdir(path6.dirname(filePath), { recursive: true });
3108
3154
  try {
3109
3155
  await fs4.writeFile(tempPath, content, { encoding: "utf8", flag: "wx" });
3156
+ tempCreated = true;
3110
3157
  await fs4.rename(tempPath, filePath);
3158
+ tempCreated = false;
3111
3159
  } catch (error3) {
3112
- try {
3113
- await fs4.unlink(tempPath);
3114
- } catch (unlinkError) {
3115
- if (!hasErrorCode(unlinkError, "ENOENT")) {
3116
- throw unlinkError;
3160
+ if (tempCreated || !hasErrorCode(error3, "EEXIST")) {
3161
+ try {
3162
+ await fs4.unlink(tempPath);
3163
+ } catch (unlinkError) {
3164
+ if (!hasErrorCode(unlinkError, "ENOENT")) {
3165
+ throw unlinkError;
3166
+ }
3117
3167
  }
3118
3168
  }
3119
3169
  throw error3;
@@ -3127,6 +3177,7 @@ async function withFileLock(fs4, lockPath, operation) {
3127
3177
  break;
3128
3178
  } catch (error3) {
3129
3179
  if (!hasErrorCode(error3, "EEXIST")) {
3180
+ await fs4.unlink(lockPath).catch(() => void 0);
3130
3181
  throw error3;
3131
3182
  }
3132
3183
  if (await removeAbandonedLock(fs4, lockPath)) {
@@ -4410,27 +4461,30 @@ function readFrontmatter(frontmatterContent, filePath) {
4410
4461
  return parsed;
4411
4462
  }
4412
4463
  function assertValidTaskRecord(frontmatter, filePath, validStates) {
4413
- if ("$schema" in frontmatter && frontmatter.$schema !== TASK_SCHEMA_ID) {
4464
+ if (hasOwnTaskField(frontmatter, "$schema") && frontmatter.$schema !== TASK_SCHEMA_ID) {
4414
4465
  throw malformedTask(filePath, "$schema");
4415
4466
  }
4416
- if ("kind" in frontmatter && frontmatter.kind !== TASK_KIND) {
4467
+ if (hasOwnTaskField(frontmatter, "kind") && frontmatter.kind !== TASK_KIND) {
4417
4468
  throw malformedTask(filePath, "kind");
4418
4469
  }
4419
- if ("version" in frontmatter) {
4470
+ if (hasOwnTaskField(frontmatter, "version")) {
4420
4471
  if (typeof frontmatter.version !== "number" || !Number.isInteger(frontmatter.version) || frontmatter.version !== TASK_VERSION) {
4421
4472
  throw malformedTask(filePath, "version");
4422
4473
  }
4423
4474
  }
4424
- if (typeof frontmatter.name !== "string" || frontmatter.name.length === 0) {
4475
+ if (!hasOwnTaskField(frontmatter, "name") || typeof frontmatter.name !== "string" || frontmatter.name.length === 0) {
4425
4476
  throw malformedTask(filePath, "name");
4426
4477
  }
4427
- if (typeof frontmatter.state !== "string" || !validStates.has(frontmatter.state)) {
4478
+ if (!hasOwnTaskField(frontmatter, "state") || typeof frontmatter.state !== "string" || !validStates.has(frontmatter.state)) {
4428
4479
  throw malformedTask(filePath, "state");
4429
4480
  }
4430
- if ("description" in frontmatter && typeof frontmatter.description !== "string") {
4481
+ if (hasOwnTaskField(frontmatter, "description") && typeof frontmatter.description !== "string") {
4431
4482
  throw malformedTask(filePath, "description");
4432
4483
  }
4433
4484
  }
4485
+ function hasOwnTaskField(frontmatter, key2) {
4486
+ return Object.prototype.hasOwnProperty.call(frontmatter, key2);
4487
+ }
4434
4488
  function reservedFrontmatterKeys(mode) {
4435
4489
  return mode === "passthrough" ? PASSTHROUGH_RESERVED_FRONTMATTER_KEYS : RESERVED_FRONTMATTER_KEYS;
4436
4490
  }
@@ -5279,7 +5333,8 @@ function parseQualifiedId3(qualifiedId) {
5279
5333
  };
5280
5334
  }
5281
5335
  function descriptionFromTaskRecord(taskRecord) {
5282
- return typeof taskRecord.description === "string" ? taskRecord.description : "";
5336
+ const description = getOwnEntry(taskRecord, "description");
5337
+ return typeof description === "string" ? description : "";
5283
5338
  }
5284
5339
  function metadataFromTaskRecord(taskRecord) {
5285
5340
  const metadata = /* @__PURE__ */ Object.create(null);
@@ -5295,8 +5350,8 @@ function createTask2(list, id, taskRecord, sourcePath) {
5295
5350
  list,
5296
5351
  id,
5297
5352
  qualifiedId: `${list}/${id}`,
5298
- name: taskRecord.name,
5299
- state: taskRecord.state,
5353
+ name: getOwnEntry(taskRecord, "name"),
5354
+ state: getOwnEntry(taskRecord, "state"),
5300
5355
  description: descriptionFromTaskRecord(taskRecord),
5301
5356
  metadata: metadataFromTaskRecord(taskRecord),
5302
5357
  ...sourcePath !== void 0 && { sourcePath: path8.resolve(sourcePath) }
@@ -5393,16 +5448,17 @@ function assertValidStoreRecord(store, filePath) {
5393
5448
  if (!isRecord2(store)) {
5394
5449
  throw malformedStore(filePath, "store");
5395
5450
  }
5396
- if (store.$schema !== STORE_SCHEMA_ID) {
5451
+ if (getOwnEntry(store, "$schema") !== STORE_SCHEMA_ID) {
5397
5452
  throw malformedStore(filePath, "$schema");
5398
5453
  }
5399
- if (store.kind !== STORE_KIND) {
5454
+ if (getOwnEntry(store, "kind") !== STORE_KIND) {
5400
5455
  throw malformedStore(filePath, "kind");
5401
5456
  }
5402
- if (typeof store.version !== "number" || !Number.isInteger(store.version) || store.version !== STORE_VERSION) {
5457
+ const version = getOwnEntry(store, "version");
5458
+ if (typeof version !== "number" || !Number.isInteger(version) || version !== STORE_VERSION) {
5403
5459
  throw malformedStore(filePath, "version");
5404
5460
  }
5405
- if (!isRecord2(store.lists)) {
5461
+ if (!isRecord2(getOwnEntry(store, "lists"))) {
5406
5462
  throw malformedStore(filePath, "lists");
5407
5463
  }
5408
5464
  }
@@ -5410,29 +5466,38 @@ function assertValidTaskRecord2(taskRecord, list, id, validStates) {
5410
5466
  if (!isRecord2(taskRecord)) {
5411
5467
  throw malformedTask2(list, id, "task");
5412
5468
  }
5413
- if ("$schema" in taskRecord && taskRecord.$schema !== TASK_SCHEMA_ID2) {
5469
+ if (hasOwnTaskField2(taskRecord, "$schema") && getOwnEntry(taskRecord, "$schema") !== TASK_SCHEMA_ID2) {
5414
5470
  throw malformedTask2(list, id, "$schema");
5415
5471
  }
5416
- if ("kind" in taskRecord && taskRecord.kind !== TASK_KIND2) {
5472
+ if (hasOwnTaskField2(taskRecord, "kind") && getOwnEntry(taskRecord, "kind") !== TASK_KIND2) {
5417
5473
  throw malformedTask2(list, id, "kind");
5418
5474
  }
5419
- if ("version" in taskRecord) {
5420
- if (typeof taskRecord.version !== "number" || !Number.isInteger(taskRecord.version) || taskRecord.version !== TASK_VERSION2) {
5475
+ if (hasOwnTaskField2(taskRecord, "version")) {
5476
+ const version = getOwnEntry(taskRecord, "version");
5477
+ if (typeof version !== "number" || !Number.isInteger(version) || version !== TASK_VERSION2) {
5421
5478
  throw malformedTask2(list, id, "version");
5422
5479
  }
5423
5480
  }
5424
- if (typeof taskRecord.name !== "string" || taskRecord.name.length === 0) {
5481
+ const name = getOwnEntry(taskRecord, "name");
5482
+ if (!hasOwnTaskField2(taskRecord, "name") || typeof name !== "string" || name.length === 0) {
5425
5483
  throw malformedTask2(list, id, "name");
5426
5484
  }
5427
- if (typeof taskRecord.state !== "string" || !validStates.has(taskRecord.state)) {
5485
+ const state = getOwnEntry(taskRecord, "state");
5486
+ if (!hasOwnTaskField2(taskRecord, "state") || typeof state !== "string" || !validStates.has(state)) {
5428
5487
  throw malformedTask2(list, id, "state");
5429
5488
  }
5430
- if ("description" in taskRecord && typeof taskRecord.description !== "string") {
5489
+ if (hasOwnTaskField2(taskRecord, "description") && typeof getOwnEntry(taskRecord, "description") !== "string") {
5431
5490
  throw malformedTask2(list, id, "description");
5432
5491
  }
5433
5492
  }
5493
+ function hasOwnTaskField2(taskRecord, key2) {
5494
+ return Object.prototype.hasOwnProperty.call(taskRecord, key2);
5495
+ }
5496
+ function getOwnEntry(record, key2) {
5497
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
5498
+ }
5434
5499
  function validateStoreEntries(store, filePath, validStates) {
5435
- const lists = store.lists;
5500
+ const lists = getOwnEntry(store, "lists");
5436
5501
  if (!isRecord2(lists)) {
5437
5502
  throw malformedStore(filePath, "lists");
5438
5503
  }
@@ -5472,10 +5537,11 @@ async function readStore(fs4, filePath, validStates) {
5472
5537
  };
5473
5538
  }
5474
5539
  function getListsRecord(store) {
5475
- return store.lists;
5540
+ const lists = getOwnEntry(store, "lists");
5541
+ return isRecord2(lists) ? lists : {};
5476
5542
  }
5477
5543
  function getListRecord(store, list) {
5478
- const listRecord = getListsRecord(store)[list];
5544
+ const listRecord = getOwnEntry(getListsRecord(store), list);
5479
5545
  return isRecord2(listRecord) ? listRecord : void 0;
5480
5546
  }
5481
5547
  function getTaskRecord(store, list, id) {
@@ -5768,7 +5834,7 @@ async function yamlFileBackend(deps) {
5768
5834
  const result = [];
5769
5835
  const listNames = sortStrings(Object.keys(getListsRecord(store)));
5770
5836
  for (const listName of listNames) {
5771
- const listRecord = getListsRecord(store)[listName];
5837
+ const listRecord = getOwnEntry(getListsRecord(store), listName);
5772
5838
  if (!isRecord2(listRecord)) continue;
5773
5839
  const entries = Object.entries(listRecord).map(([id, taskRecord]) => ({
5774
5840
  task: createTask2(listName, id, taskRecord, deps.path),
@@ -5816,51 +5882,74 @@ function createDefaultFs() {
5816
5882
  return fsPromises;
5817
5883
  }
5818
5884
  async function openTaskList(options) {
5819
- switch (options.type) {
5885
+ const type2 = getOwnProperty2(options, "type");
5886
+ switch (type2) {
5820
5887
  case "markdown-dir":
5821
5888
  case "yaml-file":
5822
5889
  return openFileBackend(options);
5823
5890
  case "gh-issues":
5824
5891
  return openGhIssuesBackend(options);
5825
5892
  default:
5826
- throw new Error(`Unknown task list backend type "${options.type}".`);
5893
+ throw new Error(`Unknown task list backend type "${String(type2)}".`);
5827
5894
  }
5828
5895
  }
5829
5896
  async function openFileBackend(options) {
5830
- const factory = backendFactories[options.type];
5831
- const stateMachine = resolveStateMachine(options.stateMachine);
5897
+ const type2 = getOwnProperty2(options, "type");
5898
+ const factory = backendFactories[type2];
5899
+ const stateMachine = resolveStateMachine(
5900
+ getOwnProperty2(options, "stateMachine")
5901
+ );
5832
5902
  validateMachine(stateMachine);
5833
- const markdownOptions = options.type === "markdown-dir" ? options : void 0;
5903
+ const markdownOptions = type2 === "markdown-dir" ? options : void 0;
5904
+ const defaults2 = getOwnProperty2(options, "defaults");
5834
5905
  const deps = {
5835
- path: options.path,
5906
+ path: getOwnProperty2(options, "path"),
5836
5907
  defaults: {
5837
- metadata: { ...options.defaults?.metadata ?? {} }
5908
+ metadata: readDefaultMetadata(defaults2)
5838
5909
  },
5839
- singleList: markdownOptions?.singleList,
5840
- frontmatterMode: markdownOptions?.frontmatterMode ?? "strict",
5841
- create: options.create ?? false,
5842
- fs: options.fs ?? createDefaultFs(),
5910
+ singleList: markdownOptions === void 0 ? void 0 : getOwnProperty2(markdownOptions, "singleList"),
5911
+ frontmatterMode: markdownOptions === void 0 ? "strict" : getOwnProperty2(
5912
+ markdownOptions,
5913
+ "frontmatterMode"
5914
+ ) ?? "strict",
5915
+ create: getOwnProperty2(options, "create") ?? false,
5916
+ fs: getOwnProperty2(options, "fs") ?? createDefaultFs(),
5843
5917
  stateMachine
5844
5918
  };
5845
5919
  return factory(deps);
5846
5920
  }
5847
5921
  async function openGhIssuesBackend(options) {
5848
- const token = await resolveAuth({ explicitToken: options.auth?.token });
5922
+ const auth = getOwnProperty2(options, "auth");
5923
+ const explicitToken = auth && hasOwnProperty2(auth, "token") ? auth.token : void 0;
5849
5924
  const endpoint = resolveEndpoint();
5925
+ const defaults2 = getOwnProperty2(options, "defaults");
5850
5926
  return ghIssuesBackend({
5851
- repo: options.repo,
5852
- project: options.project,
5853
- filter: options.filter,
5854
- state: options.state,
5855
- stateMachine: options.stateMachine,
5927
+ repo: getOwnProperty2(options, "repo"),
5928
+ project: getOwnProperty2(options, "project"),
5929
+ filter: getOwnProperty2(options, "filter"),
5930
+ state: getOwnProperty2(options, "state"),
5931
+ stateMachine: getOwnProperty2(options, "stateMachine"),
5856
5932
  defaults: {
5857
- metadata: { ...options.defaults?.metadata ?? {} }
5933
+ metadata: readDefaultMetadata(defaults2)
5858
5934
  },
5859
- token,
5935
+ token: await resolveAuth({ explicitToken }),
5860
5936
  endpoint,
5861
- fetch: options.fetch
5937
+ fetch: getOwnProperty2(options, "fetch")
5862
5938
  });
5863
5939
  }
5940
+ function readDefaultMetadata(defaults2) {
5941
+ const metadata = defaults2 === void 0 ? void 0 : getOwnProperty2(defaults2, "metadata");
5942
+ return isRecord4(metadata) ? { ...metadata } : {};
5943
+ }
5944
+ function getOwnProperty2(value, name) {
5945
+ return hasOwnProperty2(value, name) ? value[name] : void 0;
5946
+ }
5947
+ function hasOwnProperty2(value, name) {
5948
+ return Object.prototype.hasOwnProperty.call(value, name);
5949
+ }
5950
+ function isRecord4(value) {
5951
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5952
+ }
5864
5953
 
5865
5954
  // ../task-list/src/move.ts
5866
5955
  import * as fsPromises2 from "node:fs/promises";
@@ -6118,7 +6207,7 @@ function osascriptProvider(options = {}) {
6118
6207
  const { stdout } = await execFileAsync(binary, ["-e", script]);
6119
6208
  return parseStdout(stdout);
6120
6209
  } catch (error3) {
6121
- if (error3.code === "ENOENT") {
6210
+ if (hasOwnErrorCode2(error3, "ENOENT")) {
6122
6211
  throw new Error("osascript not found \u2014 provide a different provider on this platform");
6123
6212
  }
6124
6213
  if (isUserCanceled(error3)) {
@@ -6130,6 +6219,9 @@ function osascriptProvider(options = {}) {
6130
6219
  }
6131
6220
  };
6132
6221
  }
6222
+ function hasOwnErrorCode2(error3, code) {
6223
+ return typeof error3 === "object" && error3 !== null && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
6224
+ }
6133
6225
 
6134
6226
  // ../toolcraft/src/human-in-loop/default-provider.ts
6135
6227
  function noProviderConfigured() {
@@ -6402,8 +6494,8 @@ function createHandlerContext(command, params17) {
6402
6494
  function createFs() {
6403
6495
  return {
6404
6496
  readFile: async (path24, encoding = "utf8") => readFile2(path24, { encoding }),
6405
- writeFile: async (path24, contents) => {
6406
- await writeFile2(path24, contents);
6497
+ writeFile: async (path24, contents, options) => {
6498
+ await writeFile2(path24, contents, options);
6407
6499
  },
6408
6500
  exists: async (path24) => {
6409
6501
  try {
@@ -6687,21 +6779,21 @@ function escapeMarkdownCell(value) {
6687
6779
  return value.replaceAll("|", "\\|");
6688
6780
  }
6689
6781
  function isMissingStateError(error3) {
6690
- return typeof error3 === "object" && error3 !== null && "code" in error3 && error3.code === "ENOENT";
6782
+ return hasOwnErrorCode(error3, "ENOENT");
6691
6783
  }
6692
6784
 
6693
6785
  // ../toolcraft/src/error-report.ts
6694
6786
  import { mkdir as mkdir2, realpath as realpath2, writeFile as writeFile4 } from "node:fs/promises";
6695
- import { randomUUID as randomUUID3 } from "node:crypto";
6787
+ import { randomUUID as randomUUID5 } from "node:crypto";
6696
6788
  import os from "node:os";
6697
6789
  import path13 from "node:path";
6698
6790
  import { CommanderError } from "commander";
6699
6791
 
6700
6792
  // ../toolcraft/src/mcp-proxy.ts
6701
6793
  import { existsSync as existsSync2 } from "node:fs";
6702
- import { lstat as lstat2, mkdir, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
6794
+ import { lstat as lstat2, mkdir, readFile as readFile3, rename as rename2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
6703
6795
  import path12 from "node:path";
6704
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
6796
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
6705
6797
 
6706
6798
  // ../tiny-mcp-client/src/internal.ts
6707
6799
  import { spawn as spawn5 } from "node:child_process";
@@ -6712,10 +6804,17 @@ import crypto from "node:crypto";
6712
6804
  import path11 from "node:path";
6713
6805
 
6714
6806
  // ../auth-store/src/encrypted-file-store.ts
6715
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes4, scrypt } from "node:crypto";
6807
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes4, randomUUID as randomUUID3, scrypt } from "node:crypto";
6716
6808
  import { promises as fs } from "node:fs";
6717
6809
  import { homedir, hostname, userInfo } from "node:os";
6718
6810
  import path10 from "node:path";
6811
+
6812
+ // ../auth-store/src/error-codes.ts
6813
+ function hasOwnErrorCode3(error3, code) {
6814
+ return error3 instanceof Error && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
6815
+ }
6816
+
6817
+ // ../auth-store/src/encrypted-file-store.ts
6719
6818
  var derivedKeyCache = /* @__PURE__ */ new Map();
6720
6819
  var ENCRYPTION_ALGORITHM = "aes-256-gcm";
6721
6820
  var ENCRYPTION_VERSION = 1;
@@ -6723,7 +6822,6 @@ var ENCRYPTION_KEY_BYTES = 32;
6723
6822
  var ENCRYPTION_IV_BYTES = 12;
6724
6823
  var ENCRYPTION_AUTH_TAG_BYTES = 16;
6725
6824
  var ENCRYPTION_FILE_MODE = 384;
6726
- var temporaryFileSequence = 0;
6727
6825
  var EncryptedFileStore = class {
6728
6826
  fs;
6729
6827
  filePath;
@@ -6755,7 +6853,7 @@ var EncryptedFileStore = class {
6755
6853
  this.getRandomBytes = input.getRandomBytes ?? randomBytes4;
6756
6854
  }
6757
6855
  async get() {
6758
- await this.assertRegularCredentialPath();
6856
+ await this.assertCredentialPathHasNoSymbolicLinks(this.filePath);
6759
6857
  let rawDocument;
6760
6858
  try {
6761
6859
  rawDocument = await this.fs.readFile(this.filePath, "utf8");
@@ -6786,7 +6884,7 @@ var EncryptedFileStore = class {
6786
6884
  }
6787
6885
  }
6788
6886
  async set(value) {
6789
- await this.assertRegularCredentialPath();
6887
+ await this.assertCredentialPathHasNoSymbolicLinks(this.filePath);
6790
6888
  const key2 = await this.getEncryptionKey();
6791
6889
  const iv = this.getRandomBytes(ENCRYPTION_IV_BYTES);
6792
6890
  const cipher = createCipheriv(ENCRYPTION_ALGORITHM, key2, iv);
@@ -6802,25 +6900,28 @@ var EncryptedFileStore = class {
6802
6900
  ciphertext: ciphertext.toString("base64")
6803
6901
  };
6804
6902
  await this.fs.mkdir(path10.dirname(this.filePath), { recursive: true });
6805
- await this.assertRegularCredentialPath();
6806
- const temporaryPath = `${this.filePath}.${process.pid}.${temporaryFileSequence++}.tmp`;
6903
+ await this.assertCredentialPathHasNoSymbolicLinks(this.filePath);
6904
+ const temporaryPath = `${this.filePath}.${process.pid}.${randomUUID3()}.tmp`;
6905
+ let temporaryCreated = false;
6807
6906
  try {
6907
+ await this.assertCredentialPathHasNoSymbolicLinks(temporaryPath);
6808
6908
  await this.fs.writeFile(temporaryPath, JSON.stringify(document), {
6809
6909
  encoding: "utf8",
6810
6910
  flag: "wx",
6811
6911
  mode: ENCRYPTION_FILE_MODE
6812
6912
  });
6913
+ temporaryCreated = true;
6813
6914
  await this.fs.chmod(temporaryPath, ENCRYPTION_FILE_MODE);
6814
6915
  await this.fs.rename(temporaryPath, this.filePath);
6815
6916
  } catch (error3) {
6816
- if (!isAlreadyExistsError(error3)) {
6917
+ if (temporaryCreated || !isAlreadyExistsError(error3)) {
6817
6918
  await removeIfPresent(this.fs, temporaryPath).catch(() => void 0);
6818
6919
  }
6819
6920
  throw error3;
6820
6921
  }
6821
6922
  }
6822
6923
  async delete() {
6823
- await this.assertRegularCredentialPath();
6924
+ await this.assertCredentialPathHasNoSymbolicLinks(this.filePath);
6824
6925
  try {
6825
6926
  await this.fs.unlink(this.filePath);
6826
6927
  } catch (error3) {
@@ -6829,8 +6930,8 @@ var EncryptedFileStore = class {
6829
6930
  }
6830
6931
  }
6831
6932
  }
6832
- async assertRegularCredentialPath() {
6833
- const resolvedPath = path10.resolve(this.filePath);
6933
+ async assertCredentialPathHasNoSymbolicLinks(targetPath) {
6934
+ const resolvedPath = path10.resolve(targetPath);
6834
6935
  const protectedPaths = getProtectedCredentialPaths(
6835
6936
  resolvedPath,
6836
6937
  this.symbolicLinkCheckStartPath
@@ -6895,9 +6996,6 @@ async function removeIfPresent(fileSystem, filePath) {
6895
6996
  }
6896
6997
  }
6897
6998
  }
6898
- function isAlreadyExistsError(error3) {
6899
- return typeof error3 === "object" && error3 !== null && "code" in error3 && error3.code === "EEXIST";
6900
- }
6901
6999
  function defaultMachineIdentity() {
6902
7000
  return {
6903
7001
  hostname: hostname(),
@@ -6932,32 +7030,40 @@ async function deriveEncryptionKey(getMachineIdentity, salt) {
6932
7030
  function parseEncryptedDocument(raw) {
6933
7031
  try {
6934
7032
  const parsed = JSON.parse(raw);
6935
- if (!isRecord4(parsed)) {
7033
+ if (!isRecord5(parsed)) {
6936
7034
  return null;
6937
7035
  }
6938
- if (parsed.version !== ENCRYPTION_VERSION) {
7036
+ const version = getOwnEntry2(parsed, "version");
7037
+ const iv = getOwnEntry2(parsed, "iv");
7038
+ const authTag = getOwnEntry2(parsed, "authTag");
7039
+ const ciphertext = getOwnEntry2(parsed, "ciphertext");
7040
+ if (version !== ENCRYPTION_VERSION) {
6939
7041
  return null;
6940
7042
  }
6941
- if (typeof parsed.iv !== "string" || typeof parsed.authTag !== "string" || typeof parsed.ciphertext !== "string") {
7043
+ if (typeof iv !== "string" || typeof authTag !== "string" || typeof ciphertext !== "string") {
6942
7044
  return null;
6943
7045
  }
6944
7046
  return {
6945
- version: parsed.version,
6946
- iv: parsed.iv,
6947
- authTag: parsed.authTag,
6948
- ciphertext: parsed.ciphertext
7047
+ version,
7048
+ iv,
7049
+ authTag,
7050
+ ciphertext
6949
7051
  };
6950
7052
  } catch {
6951
7053
  return null;
6952
7054
  }
6953
7055
  }
6954
- function isRecord4(value) {
7056
+ function isRecord5(value) {
6955
7057
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
6956
7058
  }
7059
+ function getOwnEntry2(record, key2) {
7060
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
7061
+ }
6957
7062
  function isNotFoundError(error3) {
6958
- return Boolean(
6959
- error3 && typeof error3 === "object" && "code" in error3 && error3.code === "ENOENT"
6960
- );
7063
+ return hasOwnErrorCode3(error3, "ENOENT");
7064
+ }
7065
+ function isAlreadyExistsError(error3) {
7066
+ return hasOwnErrorCode3(error3, "EEXIST");
6961
7067
  }
6962
7068
 
6963
7069
  // ../auth-store/src/keychain-store.ts
@@ -6978,8 +7084,8 @@ var KeychainStore = class {
6978
7084
  ["find-generic-password", "-s", this.service, "-a", this.account, "-w"],
6979
7085
  "read secret from macOS Keychain"
6980
7086
  );
6981
- if (result.exitCode === 0) {
6982
- return stripTrailingLineBreak(result.stdout);
7087
+ if (getCommandExitCode(result) === 0) {
7088
+ return stripTrailingLineBreak(getCommandOutput(result, "stdout"));
6983
7089
  }
6984
7090
  if (isKeychainEntryNotFound(result)) {
6985
7091
  return null;
@@ -7003,7 +7109,7 @@ var KeychainStore = class {
7003
7109
  "store secret in macOS Keychain",
7004
7110
  { stdin: value }
7005
7111
  );
7006
- if (result.exitCode !== 0) {
7112
+ if (getCommandExitCode(result) !== 0) {
7007
7113
  throw createSecurityCliFailure("store secret in macOS Keychain", result);
7008
7114
  }
7009
7115
  }
@@ -7012,7 +7118,7 @@ var KeychainStore = class {
7012
7118
  ["delete-generic-password", "-s", this.service, "-a", this.account],
7013
7119
  "delete secret from macOS Keychain"
7014
7120
  );
7015
- if (result.exitCode === 0 || isKeychainEntryNotFound(result)) {
7121
+ if (getCommandExitCode(result) === 0 || isKeychainEntryNotFound(result)) {
7016
7122
  return;
7017
7123
  }
7018
7124
  throw createSecurityCliFailure("delete secret from macOS Keychain", result);
@@ -7091,16 +7197,28 @@ function stripTrailingLineBreak(value) {
7091
7197
  return value;
7092
7198
  }
7093
7199
  function isKeychainEntryNotFound(result) {
7094
- return result.exitCode === KEYCHAIN_ITEM_NOT_FOUND_EXIT_CODE;
7200
+ return getCommandExitCode(result) === KEYCHAIN_ITEM_NOT_FOUND_EXIT_CODE;
7095
7201
  }
7096
7202
  function createSecurityCliFailure(operation, result) {
7097
- const details = result.stderr.trim() || result.stdout.trim();
7203
+ const exitCode = getCommandExitCode(result);
7204
+ const details = getCommandOutput(result, "stderr").trim() || getCommandOutput(result, "stdout").trim();
7098
7205
  if (details) {
7099
7206
  return new Error(
7100
- `Failed to ${operation}: security exited with code ${result.exitCode}: ${details}`
7207
+ `Failed to ${operation}: security exited with code ${exitCode}: ${details}`
7101
7208
  );
7102
7209
  }
7103
- return new Error(`Failed to ${operation}: security exited with code ${result.exitCode}`);
7210
+ return new Error(`Failed to ${operation}: security exited with code ${exitCode}`);
7211
+ }
7212
+ function getCommandExitCode(result) {
7213
+ const value = getOwnEntry3(result, "exitCode");
7214
+ return typeof value === "number" && Number.isInteger(value) ? value : 1;
7215
+ }
7216
+ function getCommandOutput(result, key2) {
7217
+ const value = getOwnEntry3(result, key2);
7218
+ return typeof value === "string" ? value : "";
7219
+ }
7220
+ function getOwnEntry3(record, key2) {
7221
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
7104
7222
  }
7105
7223
 
7106
7224
  // ../auth-store/src/create-secret-store.ts
@@ -7133,7 +7251,7 @@ function createSecretStore(input) {
7133
7251
  }
7134
7252
  function resolveBackend(input) {
7135
7253
  const envVar = input.backendEnvVar ?? DEFAULT_BACKEND_ENV_VAR;
7136
- const configuredBackend = input.backend ?? input.env?.[envVar] ?? process.env[envVar];
7254
+ const configuredBackend = input.backend ?? getOwnEnvValue(input.env, envVar) ?? getOwnEnvValue(process.env, envVar);
7137
7255
  if (configuredBackend === "keychain") {
7138
7256
  return "keychain";
7139
7257
  }
@@ -7142,6 +7260,9 @@ function resolveBackend(input) {
7142
7260
  }
7143
7261
  throw new Error(`Unsupported auth store backend: ${configuredBackend}`);
7144
7262
  }
7263
+ function getOwnEnvValue(env, key2) {
7264
+ return env !== void 0 && Object.prototype.hasOwnProperty.call(env, key2) ? env[key2] : void 0;
7265
+ }
7145
7266
 
7146
7267
  // ../mcp-oauth/src/resource-indicator.ts
7147
7268
  function canonicalizeResourceIndicator(value) {
@@ -7195,8 +7316,13 @@ function createAuthStoreClientStore(options) {
7195
7316
  return null;
7196
7317
  }
7197
7318
  const parsed = JSON.parse(value);
7198
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && typeof parsed.clientId === "string") {
7199
- return parsed;
7319
+ const clientId = isObjectRecord(parsed) ? getOwnString(parsed, "clientId") : void 0;
7320
+ if (clientId !== void 0) {
7321
+ const client = { clientId };
7322
+ if (isObjectRecord(parsed) && Object.prototype.hasOwnProperty.call(parsed, "clientSecret")) {
7323
+ client.clientSecret = getOwnEntry4(parsed, "clientSecret");
7324
+ }
7325
+ return client;
7200
7326
  }
7201
7327
  throw new Error("Stored OAuth client must be a JSON object with clientId");
7202
7328
  },
@@ -7255,6 +7381,16 @@ function createIssuerSecretStore(issuer, options) {
7255
7381
  }
7256
7382
  );
7257
7383
  }
7384
+ function isObjectRecord(value) {
7385
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7386
+ }
7387
+ function getOwnEntry4(record, key2) {
7388
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
7389
+ }
7390
+ function getOwnString(record, key2) {
7391
+ const value = getOwnEntry4(record, key2);
7392
+ return typeof value === "string" ? value : void 0;
7393
+ }
7258
7394
 
7259
7395
  // ../mcp-oauth/src/client/default-oauth-client-provider.ts
7260
7396
  import { URL as URL2 } from "node:url";
@@ -7280,17 +7416,30 @@ function parseAuthorizationState(value) {
7280
7416
  try {
7281
7417
  const decoded = Buffer.from(value, "base64url").toString("utf8");
7282
7418
  const parsed = JSON.parse(decoded);
7283
- if (parsed.v !== 1 || typeof parsed.n !== "string" || parsed.n.length === 0 || typeof parsed.i !== "string" || parsed.i.length === 0 || typeof parsed.r !== "boolean") {
7419
+ if (!isObjectRecord2(parsed)) {
7420
+ return null;
7421
+ }
7422
+ const version = getOwnEntry5(parsed, "v");
7423
+ const nonce = getOwnEntry5(parsed, "n");
7424
+ const issuer = getOwnEntry5(parsed, "i");
7425
+ const requireIssuer = getOwnEntry5(parsed, "r");
7426
+ if (version !== 1 || typeof nonce !== "string" || nonce.length === 0 || typeof issuer !== "string" || issuer.length === 0 || typeof requireIssuer !== "boolean") {
7284
7427
  return null;
7285
7428
  }
7286
7429
  return {
7287
- issuer: parsed.i,
7288
- requireIssuer: parsed.r
7430
+ issuer,
7431
+ requireIssuer
7289
7432
  };
7290
7433
  } catch {
7291
7434
  return null;
7292
7435
  }
7293
7436
  }
7437
+ function isObjectRecord2(value) {
7438
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7439
+ }
7440
+ function getOwnEntry5(record, key2) {
7441
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
7442
+ }
7294
7443
 
7295
7444
  // ../mcp-oauth/src/client/loopback-authorization.ts
7296
7445
  async function createLoopbackAuthorizationSession(options = {}) {
@@ -7567,22 +7716,26 @@ async function requestTokens(input) {
7567
7716
  body: body.toString()
7568
7717
  });
7569
7718
  const payload = await readOAuthJsonObjectResponse(response);
7570
- if (typeof payload.access_token !== "string" || payload.access_token.trim().length === 0) {
7719
+ const accessToken = getOwnEntry6(payload, "access_token");
7720
+ if (typeof accessToken !== "string" || accessToken.trim().length === 0) {
7571
7721
  throw new Error("OAuth token response missing access_token");
7572
7722
  }
7573
- const tokenType = normalizeBearerTokenType(payload.token_type);
7723
+ const tokenType = normalizeBearerTokenType(getOwnEntry6(payload, "token_type"));
7574
7724
  if (tokenType === null) {
7575
7725
  throw new Error("OAuth token response missing token_type=Bearer");
7576
7726
  }
7577
- if (typeof payload.expires_in === "number" && Number.isFinite(payload.expires_in) && payload.expires_in < 0) {
7727
+ const expiresIn = getOwnEntry6(payload, "expires_in");
7728
+ if (typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn < 0) {
7578
7729
  throw new Error("OAuth token response has invalid expires_in");
7579
7730
  }
7731
+ const refreshToken = getOwnEntry6(payload, "refresh_token");
7732
+ const scope = getOwnEntry6(payload, "scope");
7580
7733
  return {
7581
- accessToken: payload.access_token,
7582
- refreshToken: typeof payload.refresh_token === "string" && payload.refresh_token.length > 0 ? payload.refresh_token : void 0,
7734
+ accessToken,
7735
+ refreshToken: typeof refreshToken === "string" && refreshToken.length > 0 ? refreshToken : void 0,
7583
7736
  tokenType,
7584
- expiresAt: typeof payload.expires_in === "number" && Number.isFinite(payload.expires_in) ? input.now() + payload.expires_in * 1e3 : null,
7585
- scope: typeof payload.scope === "string" && payload.scope.length > 0 ? payload.scope : void 0
7737
+ expiresAt: typeof expiresIn === "number" && Number.isFinite(expiresIn) ? input.now() + expiresIn * 1e3 : null,
7738
+ scope: typeof scope === "string" && scope.length > 0 ? scope : void 0
7586
7739
  };
7587
7740
  }
7588
7741
  async function readOAuthJsonObjectResponse(response) {
@@ -7609,12 +7762,18 @@ async function readOAuthJsonObjectResponse(response) {
7609
7762
  return record;
7610
7763
  }
7611
7764
  function readOAuthError(payload, fallbackError = "server_error") {
7765
+ const error3 = getOwnEntry6(payload, "error");
7766
+ const errorDescription = getOwnEntry6(payload, "error_description");
7767
+ const errorUri = getOwnEntry6(payload, "error_uri");
7612
7768
  return {
7613
- error: typeof payload.error === "string" ? payload.error : fallbackError,
7614
- error_description: typeof payload.error_description === "string" ? payload.error_description : void 0,
7615
- error_uri: typeof payload.error_uri === "string" ? payload.error_uri : void 0
7769
+ error: typeof error3 === "string" ? error3 : fallbackError,
7770
+ error_description: typeof errorDescription === "string" ? errorDescription : void 0,
7771
+ error_uri: typeof errorUri === "string" ? errorUri : void 0
7616
7772
  };
7617
7773
  }
7774
+ function getOwnEntry6(record, key2) {
7775
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
7776
+ }
7618
7777
  function createFallbackOAuthError(status) {
7619
7778
  const error3 = status === 503 ? "temporarily_unavailable" : "server_error";
7620
7779
  return new OAuthError({ error: error3 }, status);
@@ -7719,7 +7878,11 @@ function createDefaultOAuthClientProvider(options) {
7719
7878
  while (true) {
7720
7879
  try {
7721
7880
  refreshedTokens = await refreshAccessToken({
7722
- tokenEndpoint: discovery.authorizationServerMetadata.token_endpoint,
7881
+ tokenEndpoint: requireOwnString(
7882
+ discovery.authorizationServerMetadata,
7883
+ "token_endpoint",
7884
+ "Authorization server metadata"
7885
+ ),
7723
7886
  clientId: session.client.clientId,
7724
7887
  clientSecret: session.client.clientSecret,
7725
7888
  refreshToken: session.tokens.refreshToken,
@@ -7807,7 +7970,11 @@ function createDefaultOAuthClientProvider(options) {
7807
7970
  });
7808
7971
  const code = await loopback.waitForCode(authorizationUrl);
7809
7972
  const tokens = await exchangeAuthorizationCode({
7810
- tokenEndpoint: discovery.authorizationServerMetadata.token_endpoint,
7973
+ tokenEndpoint: requireOwnString(
7974
+ discovery.authorizationServerMetadata,
7975
+ "token_endpoint",
7976
+ "Authorization server metadata"
7977
+ ),
7811
7978
  clientId: resolvedClient.client.clientId,
7812
7979
  clientSecret: resolvedClient.client.clientSecret,
7813
7980
  code,
@@ -7860,7 +8027,10 @@ function createDefaultOAuthClientProvider(options) {
7860
8027
  }
7861
8028
  };
7862
8029
  }
7863
- const registrationEndpoint = discovery.authorizationServerMetadata.registration_endpoint;
8030
+ const registrationEndpoint = getOwnString2(
8031
+ discovery.authorizationServerMetadata,
8032
+ "registration_endpoint"
8033
+ );
7864
8034
  if (registrationEndpoint === void 0 && options.client.clientId !== void 0) {
7865
8035
  return {
7866
8036
  kind: "static",
@@ -7912,12 +8082,14 @@ function createDefaultOAuthClientProvider(options) {
7912
8082
  body: JSON.stringify(registrationBody)
7913
8083
  });
7914
8084
  const payload = await readOAuthJsonObjectResponse(response);
7915
- if (typeof payload.client_id !== "string" || payload.client_id.trim().length === 0) {
8085
+ const clientId = getOwnString2(payload, "client_id");
8086
+ if (clientId === void 0 || clientId.trim().length === 0) {
7916
8087
  throw new Error("OAuth client registration response missing client_id");
7917
8088
  }
8089
+ const clientSecret = getOwnString2(payload, "client_secret");
7918
8090
  const registeredClient = {
7919
- clientId: payload.client_id,
7920
- clientSecret: typeof payload.client_secret === "string" && payload.client_secret.length > 0 ? payload.client_secret : void 0
8091
+ clientId,
8092
+ clientSecret: clientSecret !== void 0 && clientSecret.length > 0 ? clientSecret : void 0
7921
8093
  };
7922
8094
  await saveRegisteredClient(discovery.authorizationServer, registeredClient);
7923
8095
  return {
@@ -7943,12 +8115,13 @@ function createDefaultOAuthClientProvider(options) {
7943
8115
  return null;
7944
8116
  }
7945
8117
  const client = await clientStore.load(issuer);
7946
- if (client !== null && !isUsableClient(client)) {
8118
+ const normalizedClient = client === null ? null : normalizeStoredClient(client);
8119
+ if (client !== null && normalizedClient === null) {
7947
8120
  await clientStore.clear(issuer);
7948
8121
  return null;
7949
8122
  }
7950
- registeredClients.set(issuer, client);
7951
- return client;
8123
+ registeredClients.set(issuer, normalizedClient);
8124
+ return normalizedClient;
7952
8125
  }
7953
8126
  async function saveRegisteredClient(issuer, client) {
7954
8127
  registeredClients.set(issuer, client);
@@ -7964,7 +8137,7 @@ function createDefaultOAuthClientProvider(options) {
7964
8137
  }
7965
8138
  }
7966
8139
  function isProviderOptions(options) {
7967
- return "provider" in options;
8140
+ return Object.prototype.hasOwnProperty.call(options, "provider");
7968
8141
  }
7969
8142
  function isExpired(tokens, now) {
7970
8143
  return tokens.expiresAt !== null && tokens.expiresAt <= now();
@@ -7980,7 +8153,14 @@ function resolveDiscovery(discovery, session) {
7980
8153
  return void 0;
7981
8154
  }
7982
8155
  const metadata = session.discovery.authorizationServerMetadata;
7983
- if (typeof metadata.issuer !== "string" || typeof metadata.authorization_endpoint !== "string" || typeof metadata.token_endpoint !== "string" || !Array.isArray(metadata.code_challenge_methods_supported) || !metadata.code_challenge_methods_supported.includes("S256")) {
8156
+ const issuer = getOwnString2(metadata, "issuer");
8157
+ const authorizationEndpoint = getOwnString2(metadata, "authorization_endpoint");
8158
+ const tokenEndpoint = getOwnString2(metadata, "token_endpoint");
8159
+ const codeChallengeMethodsSupported = getOwnStringArray(
8160
+ metadata,
8161
+ "code_challenge_methods_supported"
8162
+ );
8163
+ if (issuer === void 0 || authorizationEndpoint === void 0 || tokenEndpoint === void 0 || codeChallengeMethodsSupported === void 0 || !codeChallengeMethodsSupported.includes("S256")) {
7984
8164
  return void 0;
7985
8165
  }
7986
8166
  return {
@@ -8004,29 +8184,94 @@ function normalizeLoadedSession(session) {
8004
8184
  if (session === null) {
8005
8185
  return null;
8006
8186
  }
8007
- if (!isUsableClient(session.client)) {
8187
+ const client = normalizeStoredClient(getOwnEntry7(session, "client"));
8188
+ if (client === null) {
8008
8189
  return { ...session, client: { clientId: "" }, tokens: void 0 };
8009
8190
  }
8010
- return isUsableTokens(session.tokens) ? session : { ...session, tokens: void 0 };
8191
+ return {
8192
+ ...session,
8193
+ client,
8194
+ tokens: normalizeStoredTokens(getOwnEntry7(session, "tokens"))
8195
+ };
8011
8196
  }
8012
- function isUsableClient(client) {
8013
- return typeof client.clientId === "string" && client.clientId.trim().length > 0 && (client.clientSecret === void 0 || typeof client.clientSecret === "string" && client.clientSecret.trim().length > 0);
8197
+ function normalizeStoredClient(value) {
8198
+ if (!isObjectRecord3(value)) {
8199
+ return null;
8200
+ }
8201
+ const clientId = getOwnString2(value, "clientId");
8202
+ if (clientId === void 0 || clientId.trim().length === 0) {
8203
+ return null;
8204
+ }
8205
+ const clientSecret = getOwnEntry7(value, "clientSecret");
8206
+ if (clientSecret === void 0) {
8207
+ return { clientId };
8208
+ }
8209
+ if (typeof clientSecret !== "string" || clientSecret.trim().length === 0) {
8210
+ return null;
8211
+ }
8212
+ return { clientId, clientSecret };
8014
8213
  }
8015
- function isUsableTokens(tokens) {
8016
- if (tokens === void 0) {
8017
- return true;
8214
+ function normalizeStoredTokens(value) {
8215
+ if (value === void 0 || !isObjectRecord3(value)) {
8216
+ return void 0;
8217
+ }
8218
+ const accessToken = getOwnString2(value, "accessToken");
8219
+ const tokenType = getOwnString2(value, "tokenType");
8220
+ const expiresAt = getOwnEntry7(value, "expiresAt");
8221
+ const refreshToken = getOwnEntry7(value, "refreshToken");
8222
+ const scope = getOwnString2(value, "scope");
8223
+ const normalizedRefreshToken = typeof refreshToken === "string" ? refreshToken : void 0;
8224
+ if (accessToken === void 0 || accessToken.trim().length === 0 || tokenType !== "Bearer" || !(expiresAt === null || typeof expiresAt === "number" && Number.isFinite(expiresAt)) || refreshToken !== void 0 && (typeof refreshToken !== "string" || refreshToken.trim().length === 0)) {
8225
+ return void 0;
8018
8226
  }
8019
- return typeof tokens.accessToken === "string" && tokens.accessToken.trim().length > 0 && tokens.tokenType === "Bearer" && (tokens.expiresAt === null || typeof tokens.expiresAt === "number" && Number.isFinite(tokens.expiresAt)) && (tokens.refreshToken === void 0 || typeof tokens.refreshToken === "string" && tokens.refreshToken.trim().length > 0);
8227
+ return {
8228
+ accessToken,
8229
+ tokenType,
8230
+ expiresAt,
8231
+ ...normalizedRefreshToken === void 0 ? {} : { refreshToken: normalizedRefreshToken },
8232
+ ...scope === void 0 || scope.length === 0 ? {} : { scope }
8233
+ };
8020
8234
  }
8021
8235
  function getClientMetadata(client) {
8022
8236
  return client.metadata;
8023
8237
  }
8238
+ function getOwnEntry7(record, key2) {
8239
+ return Object.prototype.hasOwnProperty.call(record, key2) ? record[key2] : void 0;
8240
+ }
8241
+ function isObjectRecord3(value) {
8242
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8243
+ }
8244
+ function getOwnString2(record, key2) {
8245
+ const value = getOwnEntry7(record, key2);
8246
+ return typeof value === "string" ? value : void 0;
8247
+ }
8248
+ function requireOwnString(record, key2, label) {
8249
+ const value = getOwnString2(record, key2);
8250
+ if (value === void 0) {
8251
+ throw new Error(`${label} is missing ${key2}`);
8252
+ }
8253
+ return value;
8254
+ }
8255
+ function getOwnStringArray(record, key2) {
8256
+ const value = getOwnEntry7(record, key2);
8257
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : void 0;
8258
+ }
8024
8259
  function buildAuthorizationUrl(input) {
8025
- const url = new URL2(input.metadata.authorization_endpoint);
8260
+ const authorizationEndpoint = requireOwnString(
8261
+ input.metadata,
8262
+ "authorization_endpoint",
8263
+ "Authorization server metadata"
8264
+ );
8265
+ const issuer = requireOwnString(
8266
+ input.metadata,
8267
+ "issuer",
8268
+ "Authorization server metadata"
8269
+ );
8270
+ const url = new URL2(authorizationEndpoint);
8026
8271
  const resource = canonicalizeResourceIndicator(input.resource);
8027
8272
  const state = createAuthorizationState({
8028
- issuer: input.metadata.issuer,
8029
- requireIssuer: input.metadata.authorization_response_iss_parameter_supported === true
8273
+ issuer,
8274
+ requireIssuer: getOwnEntry7(input.metadata, "authorization_response_iss_parameter_supported") === true
8030
8275
  });
8031
8276
  url.searchParams.set("response_type", "code");
8032
8277
  url.searchParams.set("client_id", input.clientId);
@@ -8041,7 +8286,7 @@ function buildAuthorizationUrl(input) {
8041
8286
  return url.toString();
8042
8287
  }
8043
8288
  function assertS256PkceSupport(metadata) {
8044
- if (!metadata.code_challenge_methods_supported.includes("S256")) {
8289
+ if (!getOwnStringArray(metadata, "code_challenge_methods_supported")?.includes("S256")) {
8045
8290
  throw new Error(
8046
8291
  "Authorization server metadata must advertise code_challenge_methods_supported including S256"
8047
8292
  );
@@ -8065,13 +8310,24 @@ function assertSecureUrl(value, label) {
8065
8310
  throw new Error(`${label} must use https unless it targets a loopback host`);
8066
8311
  }
8067
8312
  function assertSecureOAuthFlowEndpoints(metadata) {
8068
- assertNoAccessTokenInUrl(metadata.authorization_endpoint, "Authorization endpoint");
8069
- assertNoAccessTokenInUrl(metadata.token_endpoint, "Token endpoint");
8070
- assertSecureUrl(metadata.authorization_endpoint, "Authorization endpoint");
8071
- assertSecureUrl(metadata.token_endpoint, "Token endpoint");
8072
- if (metadata.registration_endpoint !== void 0) {
8073
- assertNoAccessTokenInUrl(metadata.registration_endpoint, "Registration endpoint");
8074
- assertSecureUrl(metadata.registration_endpoint, "Registration endpoint");
8313
+ const authorizationEndpoint = requireOwnString(
8314
+ metadata,
8315
+ "authorization_endpoint",
8316
+ "Authorization server metadata"
8317
+ );
8318
+ const tokenEndpoint = requireOwnString(
8319
+ metadata,
8320
+ "token_endpoint",
8321
+ "Authorization server metadata"
8322
+ );
8323
+ const registrationEndpoint = getOwnString2(metadata, "registration_endpoint");
8324
+ assertNoAccessTokenInUrl(authorizationEndpoint, "Authorization endpoint");
8325
+ assertNoAccessTokenInUrl(tokenEndpoint, "Token endpoint");
8326
+ assertSecureUrl(authorizationEndpoint, "Authorization endpoint");
8327
+ assertSecureUrl(tokenEndpoint, "Token endpoint");
8328
+ if (registrationEndpoint !== void 0) {
8329
+ assertNoAccessTokenInUrl(registrationEndpoint, "Registration endpoint");
8330
+ assertSecureUrl(registrationEndpoint, "Registration endpoint");
8075
8331
  }
8076
8332
  }
8077
8333
  function assertNoAccessTokenInUrl(value, label) {
@@ -8094,17 +8350,21 @@ function buildClientRegistrationBody(metadata, redirectUri) {
8094
8350
  response_types: ["code"],
8095
8351
  token_endpoint_auth_method: "none"
8096
8352
  };
8097
- if (metadata?.clientName !== void 0 && metadata.clientName.length > 0) {
8098
- body.client_name = metadata.clientName;
8353
+ const clientName = metadata === void 0 ? void 0 : getOwnString2(metadata, "clientName");
8354
+ const scope = metadata === void 0 ? void 0 : getOwnString2(metadata, "scope");
8355
+ const softwareId = metadata === void 0 ? void 0 : getOwnString2(metadata, "softwareId");
8356
+ const softwareVersion = metadata === void 0 ? void 0 : getOwnString2(metadata, "softwareVersion");
8357
+ if (clientName !== void 0 && clientName.length > 0) {
8358
+ body.client_name = clientName;
8099
8359
  }
8100
- if (metadata?.scope !== void 0 && metadata.scope.length > 0) {
8101
- body.scope = metadata.scope;
8360
+ if (scope !== void 0 && scope.length > 0) {
8361
+ body.scope = scope;
8102
8362
  }
8103
- if (metadata?.softwareId !== void 0 && metadata.softwareId.length > 0) {
8104
- body.software_id = metadata.softwareId;
8363
+ if (softwareId !== void 0 && softwareId.length > 0) {
8364
+ body.software_id = softwareId;
8105
8365
  }
8106
- if (metadata?.softwareVersion !== void 0 && metadata.softwareVersion.length > 0) {
8107
- body.software_version = metadata.softwareVersion;
8366
+ if (softwareVersion !== void 0 && softwareVersion.length > 0) {
8367
+ body.software_version = softwareVersion;
8108
8368
  }
8109
8369
  return body;
8110
8370
  }
@@ -8140,7 +8400,7 @@ import {
8140
8400
  function defaultOAuthMetadataFetch(input, init) {
8141
8401
  return fetch(input, init);
8142
8402
  }
8143
- function isObjectRecord(value) {
8403
+ function isObjectRecord4(value) {
8144
8404
  return typeof value === "object" && value !== null && !Array.isArray(value);
8145
8405
  }
8146
8406
  function isStringArray(value) {
@@ -8163,7 +8423,7 @@ function assertSecureUrl2(url, label) {
8163
8423
  throw new Error(`${label} must use https unless it targets a loopback host`);
8164
8424
  }
8165
8425
  function validateProtectedResourceMetadata(value, resourceUrl) {
8166
- if (!isObjectRecord(value)) {
8426
+ if (!isObjectRecord4(value)) {
8167
8427
  throw new Error("Protected resource metadata must be a JSON object");
8168
8428
  }
8169
8429
  if (typeof value.resource !== "string" || value.resource.length === 0) {
@@ -8186,7 +8446,7 @@ function validateProtectedResourceMetadata(value, resourceUrl) {
8186
8446
  };
8187
8447
  }
8188
8448
  function validateAuthorizationServerMetadata(value, issuer) {
8189
- if (!isObjectRecord(value)) {
8449
+ if (!isObjectRecord4(value)) {
8190
8450
  throw new Error("Authorization server metadata must be a JSON object");
8191
8451
  }
8192
8452
  if (typeof value.issuer !== "string" || value.issuer.length === 0) {
@@ -8639,7 +8899,7 @@ var McpClient = class {
8639
8899
  await onPromptsChanged();
8640
8900
  });
8641
8901
  messageLayer.onNotification("notifications/message", async (params17) => {
8642
- if (onLog === void 0 || !isObjectRecord2(params17) || !isLogLevel(params17.level)) {
8902
+ if (onLog === void 0 || !isObjectRecord5(params17) || !isLogLevel(params17.level)) {
8643
8903
  return;
8644
8904
  }
8645
8905
  if (!hasOwn(params17, "data")) {
@@ -8658,7 +8918,7 @@ var McpClient = class {
8658
8918
  await onLog(message2);
8659
8919
  });
8660
8920
  messageLayer.onNotification("notifications/progress", async (params17) => {
8661
- if (onProgress === void 0 || !isObjectRecord2(params17)) {
8921
+ if (onProgress === void 0 || !isObjectRecord5(params17)) {
8662
8922
  return;
8663
8923
  }
8664
8924
  const { progressToken, progress } = params17;
@@ -9859,7 +10119,7 @@ var JsonRpcMessageLayer = class {
9859
10119
  })();
9860
10120
  }
9861
10121
  handleCancellationNotification(params17) {
9862
- if (!isObjectRecord2(params17)) {
10122
+ if (!isObjectRecord5(params17)) {
9863
10123
  return;
9864
10124
  }
9865
10125
  const requestId = params17.requestId;
@@ -9874,34 +10134,34 @@ var JsonRpcMessageLayer = class {
9874
10134
  this.activeIncomingRequests.delete(requestId);
9875
10135
  }
9876
10136
  };
9877
- function isObjectRecord2(value) {
10137
+ function isObjectRecord5(value) {
9878
10138
  return typeof value === "object" && value !== null && !Array.isArray(value);
9879
10139
  }
9880
10140
  function isInitializeResult(value) {
9881
- if (!isObjectRecord2(value) || typeof value.protocolVersion !== "string") {
10141
+ if (!isObjectRecord5(value) || typeof value.protocolVersion !== "string") {
9882
10142
  return false;
9883
10143
  }
9884
10144
  if (!isServerCapabilities(value.capabilities)) {
9885
10145
  return false;
9886
10146
  }
9887
- if (!isObjectRecord2(value.serverInfo) || typeof value.serverInfo.name !== "string" || value.serverInfo.name.length === 0 || typeof value.serverInfo.version !== "string" || value.serverInfo.version.length === 0) {
10147
+ if (!isObjectRecord5(value.serverInfo) || typeof value.serverInfo.name !== "string" || value.serverInfo.name.length === 0 || typeof value.serverInfo.version !== "string" || value.serverInfo.version.length === 0) {
9888
10148
  return false;
9889
10149
  }
9890
10150
  return value.instructions === void 0 || typeof value.instructions === "string";
9891
10151
  }
9892
10152
  function isServerCapabilities(value) {
9893
- if (!isObjectRecord2(value)) {
10153
+ if (!isObjectRecord5(value)) {
9894
10154
  return false;
9895
10155
  }
9896
10156
  for (const capability of ["prompts", "resources", "tools", "logging", "completions", "experimental"]) {
9897
- if (value[capability] !== void 0 && !isObjectRecord2(value[capability])) {
10157
+ if (value[capability] !== void 0 && !isObjectRecord5(value[capability])) {
9898
10158
  return false;
9899
10159
  }
9900
10160
  }
9901
10161
  return true;
9902
10162
  }
9903
10163
  function isCallToolResult(value) {
9904
- if (!isObjectRecord2(value) || !Array.isArray(value.content)) {
10164
+ if (!isObjectRecord5(value) || !Array.isArray(value.content)) {
9905
10165
  return false;
9906
10166
  }
9907
10167
  if (value.isError !== void 0 && typeof value.isError !== "boolean") {
@@ -9910,10 +10170,10 @@ function isCallToolResult(value) {
9910
10170
  return value.content.every(isContentItem);
9911
10171
  }
9912
10172
  function isToolsListResult(value) {
9913
- return isObjectRecord2(value) && Array.isArray(value.tools) && (value.nextCursor === void 0 || typeof value.nextCursor === "string");
10173
+ return isObjectRecord5(value) && Array.isArray(value.tools) && (value.nextCursor === void 0 || typeof value.nextCursor === "string");
9914
10174
  }
9915
10175
  function isContentItem(value) {
9916
- if (!isObjectRecord2(value)) {
10176
+ if (!isObjectRecord5(value)) {
9917
10177
  return false;
9918
10178
  }
9919
10179
  if (value.type === "text") {
@@ -9922,7 +10182,7 @@ function isContentItem(value) {
9922
10182
  if (value.type === "image" || value.type === "audio") {
9923
10183
  return typeof value.data === "string" && typeof value.mimeType === "string";
9924
10184
  }
9925
- if (value.type !== "resource" || !isObjectRecord2(value.resource)) {
10185
+ if (value.type !== "resource" || !isObjectRecord5(value.resource)) {
9926
10186
  return false;
9927
10187
  }
9928
10188
  return typeof value.resource.uri === "string" && (value.resource.mimeType === void 0 || typeof value.resource.mimeType === "string") && (typeof value.resource.text === "string" || typeof value.resource.blob === "string");
@@ -9946,7 +10206,7 @@ function invalidRequest() {
9946
10206
  return new McpError(ERROR_INVALID_REQUEST, "Invalid Request");
9947
10207
  }
9948
10208
  function isJsonRpcErrorObject(value) {
9949
- if (!isObjectRecord2(value)) {
10209
+ if (!isObjectRecord5(value)) {
9950
10210
  return false;
9951
10211
  }
9952
10212
  if (typeof value.code !== "number" || typeof value.message !== "string") {
@@ -9955,7 +10215,7 @@ function isJsonRpcErrorObject(value) {
9955
10215
  return value.data === void 0 || hasOwn(value, "data");
9956
10216
  }
9957
10217
  function parseJsonRpcPayload(parsed) {
9958
- if (!isObjectRecord2(parsed)) {
10218
+ if (!isObjectRecord5(parsed)) {
9959
10219
  return {
9960
10220
  type: "invalid",
9961
10221
  id: null,
@@ -10282,7 +10542,11 @@ function convertObjectSchema(schema, root, options) {
10282
10542
  "properties",
10283
10543
  key2
10284
10544
  ]);
10285
- shape[key2] = requiredKeys.has(key2) ? convertedProperty : S.Optional(convertedProperty);
10545
+ setOwnShapeProperty(
10546
+ shape,
10547
+ key2,
10548
+ requiredKeys.has(key2) ? convertedProperty : S.Optional(convertedProperty)
10549
+ );
10286
10550
  }
10287
10551
  return applyMetadata(
10288
10552
  S.Object(shape, {
@@ -10294,6 +10558,14 @@ function convertObjectSchema(schema, root, options) {
10294
10558
  }
10295
10559
  );
10296
10560
  }
10561
+ function setOwnShapeProperty(shape, key2, value) {
10562
+ Object.defineProperty(shape, key2, {
10563
+ configurable: true,
10564
+ enumerable: true,
10565
+ writable: true,
10566
+ value
10567
+ });
10568
+ }
10297
10569
  function createCommonOptions(schema, nullable, defaultValue) {
10298
10570
  return {
10299
10571
  ...schema.description === void 0 ? {} : { description: schema.description },
@@ -10544,6 +10816,9 @@ function resolveLocalRef(root, ref) {
10544
10816
  if (!isPlainObject(current)) {
10545
10817
  return void 0;
10546
10818
  }
10819
+ if (!Object.prototype.hasOwnProperty.call(current, segment)) {
10820
+ return void 0;
10821
+ }
10547
10822
  current = current[segment];
10548
10823
  }
10549
10824
  return isPlainObject(current) ? current : void 0;
@@ -10783,8 +11058,7 @@ async function readCache(cachePath) {
10783
11058
  version: parsed.version === 1 ? 1 : 1
10784
11059
  };
10785
11060
  } catch (error3) {
10786
- const code = error3.code;
10787
- if (code === "ENOENT" || error3 instanceof SyntaxError) {
11061
+ if (hasOwnErrorCode(error3, "ENOENT") || error3 instanceof SyntaxError) {
10788
11062
  return void 0;
10789
11063
  }
10790
11064
  return void 0;
@@ -10792,16 +11066,32 @@ async function readCache(cachePath) {
10792
11066
  }
10793
11067
  async function writeCache(cachePath, cache) {
10794
11068
  const directory = path12.dirname(cachePath);
10795
- const tempPath = `${cachePath}.tmp-${randomUUID2()}`;
11069
+ const tempPath = `${cachePath}.tmp-${randomUUID4()}`;
11070
+ let tempCreated = false;
10796
11071
  await assertCachePathHasNoSymlinks(cachePath);
10797
11072
  await assertCachePathHasNoSymlinks(tempPath);
10798
11073
  await mkdir(directory, { recursive: true });
10799
11074
  await assertCachePathHasNoSymlinks(directory);
10800
- await writeFile3(tempPath, `${JSON.stringify(cache, null, 2)}
10801
- `);
10802
- await assertCachePathHasNoSymlinks(tempPath);
10803
- await assertCachePathHasNoSymlinks(cachePath);
10804
- await rename2(tempPath, cachePath);
11075
+ try {
11076
+ await writeFile3(tempPath, `${JSON.stringify(cache, null, 2)}
11077
+ `, {
11078
+ encoding: "utf8",
11079
+ flag: "wx"
11080
+ });
11081
+ tempCreated = true;
11082
+ await assertCachePathHasNoSymlinks(tempPath);
11083
+ await assertCachePathHasNoSymlinks(cachePath);
11084
+ await rename2(tempPath, cachePath);
11085
+ tempCreated = false;
11086
+ } catch (error3) {
11087
+ if (tempCreated || !isAlreadyExistsError2(error3)) {
11088
+ await unlink2(tempPath).catch(() => void 0);
11089
+ }
11090
+ throw error3;
11091
+ }
11092
+ }
11093
+ function isAlreadyExistsError2(error3) {
11094
+ return hasOwnErrorCode(error3, "EEXIST");
10805
11095
  }
10806
11096
  async function fetchCache(name, config2) {
10807
11097
  const logger2 = createLogger((message2) => {
@@ -11005,7 +11295,7 @@ async function assertCachePathHasNoSymlinks(filePath) {
11005
11295
  throw new Error(`MCP cache path must not contain symbolic links: ${currentPath}.`);
11006
11296
  }
11007
11297
  } catch (error3) {
11008
- if (error3.code !== "ENOENT") {
11298
+ if (!hasOwnErrorCode(error3, "ENOENT")) {
11009
11299
  throw error3;
11010
11300
  }
11011
11301
  }
@@ -11541,7 +11831,7 @@ async function writeErrorReport(context) {
11541
11831
  }
11542
11832
  const projectRoot = resolveProjectRoot(context.projectRoot);
11543
11833
  const reportDir = resolveReportDir(context.errorReports, projectRoot);
11544
- const fileName = `${formatTimestamp(/* @__PURE__ */ new Date())}-${slugifyCommandPath(context.commandPath)}-${randomUUID3()}.log`;
11834
+ const fileName = `${formatTimestamp(/* @__PURE__ */ new Date())}-${slugifyCommandPath(context.commandPath)}-${randomUUID5()}.log`;
11545
11835
  const absolutePath = path13.join(reportDir, fileName);
11546
11836
  await mkdir2(reportDir, { recursive: true });
11547
11837
  if (reportDirMustStayWithinProject(context.errorReports)) {
@@ -12453,7 +12743,7 @@ function getJsonParseErrorLocation(error3, source) {
12453
12743
  return null;
12454
12744
  }
12455
12745
  function getJsonParseCauseLocation(error3) {
12456
- if (typeof error3 !== "object" || error3 === null || !("cause" in error3)) {
12746
+ if (typeof error3 !== "object" || error3 === null || !hasOwnProperty3(error3, "cause")) {
12457
12747
  return null;
12458
12748
  }
12459
12749
  const cause = error3.cause;
@@ -12465,7 +12755,7 @@ function getJsonParseCauseLocation(error3) {
12465
12755
  return { line, column };
12466
12756
  }
12467
12757
  function getNumericProperty(value, key2) {
12468
- if (typeof value !== "object" || value === null || !(key2 in value)) {
12758
+ if (typeof value !== "object" || value === null || !hasOwnProperty3(value, key2)) {
12469
12759
  return null;
12470
12760
  }
12471
12761
  const propertyValue = value[key2];
@@ -13020,10 +13310,10 @@ function renderHelpSections(sections) {
13020
13310
  return sections.filter((section) => section.length > 0).join("\n\n");
13021
13311
  }
13022
13312
  function formatHelpCommandList(rows) {
13023
- return process.stdout.isTTY === false ? help_formatter_plain_exports.formatCommandList(rows) : formatCommandList(rows);
13313
+ return process.stdout.isTTY !== true ? help_formatter_plain_exports.formatCommandList(rows) : formatCommandList(rows);
13024
13314
  }
13025
13315
  function formatHelpOptionList(rows) {
13026
- return process.stdout.isTTY === false ? help_formatter_plain_exports.formatOptionList(rows) : formatOptionList(rows);
13316
+ return process.stdout.isTTY !== true ? help_formatter_plain_exports.formatOptionList(rows) : formatOptionList(rows);
13027
13317
  }
13028
13318
  function buildUsageLine(breadcrumb, rootUsageName, suffix) {
13029
13319
  const visibleBreadcrumb = breadcrumb.filter((segment) => segment.length > 0);
@@ -13311,11 +13601,18 @@ function formatResolvedValue(value) {
13311
13601
  function fieldPromptLabel(field) {
13312
13602
  return field.positionalIndex === void 0 ? field.optionFlag : `<${field.displayPath}>`;
13313
13603
  }
13604
+ function enumOptionLabel(schema, value) {
13605
+ const key2 = String(value);
13606
+ if (schema.labels === void 0 || !Object.prototype.hasOwnProperty.call(schema.labels, key2)) {
13607
+ return key2;
13608
+ }
13609
+ return schema.labels[key2] ?? key2;
13610
+ }
13314
13611
  async function promptForField(field) {
13315
13612
  const schema = field.schema;
13316
13613
  if (schema.kind === "enum") {
13317
13614
  const options = schema.loadOptions ? await schema.loadOptions() : schema.values.map((value) => ({
13318
- label: schema.labels?.[String(value)] ?? String(value),
13615
+ label: enumOptionLabel(schema, value),
13319
13616
  value
13320
13617
  }));
13321
13618
  const selected = await select2({
@@ -13400,8 +13697,8 @@ async function withOutputFormat2(output, fn) {
13400
13697
  function createFs2() {
13401
13698
  return {
13402
13699
  readFile: async (path24, encoding = "utf8") => readFile4(path24, { encoding }),
13403
- writeFile: async (path24, contents) => {
13404
- await writeFile5(path24, contents);
13700
+ writeFile: async (path24, contents, options) => {
13701
+ await writeFile5(path24, contents, options);
13405
13702
  },
13406
13703
  exists: async (path24) => {
13407
13704
  try {
@@ -13413,7 +13710,7 @@ function createFs2() {
13413
13710
  },
13414
13711
  lstat: async (path24) => lstat3(path24),
13415
13712
  rename: async (fromPath, toPath) => rename3(fromPath, toPath),
13416
- unlink: async (path24) => unlink2(path24)
13713
+ unlink: async (path24) => unlink3(path24)
13417
13714
  };
13418
13715
  }
13419
13716
  function createEnv2(values = process.env) {
@@ -13515,7 +13812,7 @@ async function loadPresetValues(fields, presetPath) {
13515
13812
  encoding: "utf8"
13516
13813
  });
13517
13814
  } catch (error3) {
13518
- if (typeof error3 === "object" && error3 !== null && "code" in error3 && error3.code === "ENOENT") {
13815
+ if (hasOwnErrorCode(error3, "ENOENT")) {
13519
13816
  throw new UserError(`Preset file "${presetPath}" was not found.`);
13520
13817
  }
13521
13818
  const message2 = error3 instanceof Error && error3.message.length > 0 ? error3.message : "Unknown read error.";
@@ -14614,10 +14911,10 @@ function isHttpErrorLike(error3) {
14614
14911
  }
14615
14912
  const request = error3.request;
14616
14913
  const response = error3.response;
14617
- return isPlainObject4(request) && typeof request.method === "string" && typeof request.url === "string" && isStringRecord(request.headers) && isPlainObject4(response) && typeof response.status === "number" && typeof response.statusText === "string" && isStringRecord(response.headers) && "body" in response;
14914
+ return isPlainObject4(request) && typeof request.method === "string" && typeof request.url === "string" && isStringRecord(request.headers) && isPlainObject4(response) && typeof response.status === "number" && typeof response.statusText === "string" && isStringRecord(response.headers) && hasOwnProperty3(response, "body");
14618
14915
  }
14619
14916
  function hasTypedOptionalField(value, field, type2) {
14620
- return !(field in value) || typeof value[field] === type2;
14917
+ return !hasOwnProperty3(value, field) || typeof value[field] === type2;
14621
14918
  }
14622
14919
  function isNonEmptyString(value) {
14623
14920
  return typeof value === "string" && value.trim().length > 0;
@@ -14641,7 +14938,7 @@ function isProblemDetailsLike(body) {
14641
14938
  if (!hasTypedOptionalField(body, "instance", "string")) {
14642
14939
  return false;
14643
14940
  }
14644
- return isNonEmptyString(body.title) || isNonEmptyString(body.detail);
14941
+ return hasOwnNonEmptyString(body, "title") || hasOwnNonEmptyString(body, "detail");
14645
14942
  }
14646
14943
  function isGraphQLErrorEnvelopeLike(body) {
14647
14944
  if (!isPlainObject4(body) || !Array.isArray(body.errors) || body.errors.length === 0) {
@@ -14651,44 +14948,50 @@ function isGraphQLErrorEnvelopeLike(body) {
14651
14948
  if (!isPlainObject4(error3) || typeof error3.message !== "string") {
14652
14949
  return false;
14653
14950
  }
14654
- if ("path" in error3) {
14951
+ if (hasOwnProperty3(error3, "path")) {
14655
14952
  const pathValue = error3.path;
14656
14953
  if (!Array.isArray(pathValue) || !pathValue.every((entry) => typeof entry === "string" || typeof entry === "number")) {
14657
14954
  return false;
14658
14955
  }
14659
14956
  }
14660
- if ("extensions" in error3) {
14957
+ if (hasOwnProperty3(error3, "extensions")) {
14661
14958
  if (!isPlainObject4(error3.extensions)) {
14662
14959
  return false;
14663
14960
  }
14664
- if ("code" in error3.extensions && typeof error3.extensions.code !== "string") {
14961
+ if (hasOwnProperty3(error3.extensions, "code") && typeof error3.extensions.code !== "string") {
14665
14962
  return false;
14666
14963
  }
14667
14964
  }
14668
14965
  return true;
14669
14966
  });
14670
14967
  }
14968
+ function hasOwnProperty3(value, name) {
14969
+ return Object.prototype.hasOwnProperty.call(value, name);
14970
+ }
14971
+ function hasOwnNonEmptyString(value, name) {
14972
+ return hasOwnProperty3(value, name) && isNonEmptyString(value[name]);
14973
+ }
14671
14974
  function styleHttpErrorLine(value, style) {
14672
- return process.stdout.isTTY === false ? value : style(value);
14975
+ return process.stdout.isTTY !== true ? value : style(value);
14673
14976
  }
14674
14977
  function formatHttpErrorStatus(value) {
14675
14978
  return styleHttpErrorLine(value, text.error);
14676
14979
  }
14677
14980
  function formatProblemDetailsBody(body) {
14678
14981
  const lines = [];
14679
- if (isNonEmptyString(body.title)) {
14982
+ if (hasOwnNonEmptyString(body, "title")) {
14680
14983
  lines.push(`Problem: ${body.title}`);
14681
14984
  }
14682
- if (isNonEmptyString(body.detail)) {
14985
+ if (hasOwnNonEmptyString(body, "detail")) {
14683
14986
  lines.push(`Detail: ${body.detail}`);
14684
14987
  }
14685
- if (body.type !== void 0) {
14988
+ if (hasOwnProperty3(body, "type") && body.type !== void 0) {
14686
14989
  lines.push(`Type: ${body.type}`);
14687
14990
  }
14688
- if (body.instance !== void 0) {
14991
+ if (hasOwnProperty3(body, "instance") && body.instance !== void 0) {
14689
14992
  lines.push(`Instance: ${body.instance}`);
14690
14993
  }
14691
- if (body.status !== void 0) {
14994
+ if (hasOwnProperty3(body, "status") && body.status !== void 0) {
14692
14995
  lines.push(`Status: ${body.status}`);
14693
14996
  }
14694
14997
  return lines.join("\n");
@@ -14696,10 +14999,10 @@ function formatProblemDetailsBody(body) {
14696
14999
  function formatGraphQLErrorEnvelopeBody(body) {
14697
15000
  return body.errors.map((error3) => {
14698
15001
  const lines = [`GraphQL error: ${error3.message}`];
14699
- if (error3.path !== void 0) {
15002
+ if (hasOwnProperty3(error3, "path") && error3.path !== void 0) {
14700
15003
  lines.push(` at path: ${error3.path.join(".")}`);
14701
15004
  }
14702
- if (error3.extensions?.code !== void 0) {
15005
+ if (hasOwnProperty3(error3, "extensions") && error3.extensions !== void 0 && hasOwnProperty3(error3.extensions, "code") && error3.extensions.code !== void 0) {
14703
15006
  lines.push(` code: ${error3.extensions.code}`);
14704
15007
  }
14705
15008
  return lines.join("\n");
@@ -15151,7 +15454,7 @@ async function runCLI(roots, options = {}) {
15151
15454
  }
15152
15455
 
15153
15456
  // src/terminal-pilot.ts
15154
- import { randomUUID as randomUUID4 } from "node:crypto";
15457
+ import { randomUUID as randomUUID6 } from "node:crypto";
15155
15458
 
15156
15459
  // src/terminal-session.ts
15157
15460
  import { EventEmitter } from "node:events";
@@ -15233,6 +15536,11 @@ function consumeTerminatedString(input, index, allowBellTerminator) {
15233
15536
  return input.length;
15234
15537
  }
15235
15538
 
15539
+ // src/errors.ts
15540
+ function hasOwnErrorCode4(error3, code) {
15541
+ return error3 instanceof Error && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
15542
+ }
15543
+
15236
15544
  // src/terminal-buffer.ts
15237
15545
  var RESET_SGR = "\x1B[0m";
15238
15546
  var DEC_SPECIAL_GRAPHICS = {
@@ -16332,10 +16640,7 @@ function ensureSpawnHelperExecutable() {
16332
16640
  }
16333
16641
  }
16334
16642
  function isMissingFileError(error3) {
16335
- if (!(error3 instanceof Error)) {
16336
- return false;
16337
- }
16338
- return "code" in error3 && error3.code === "ENOENT";
16643
+ return hasOwnErrorCode4(error3, "ENOENT");
16339
16644
  }
16340
16645
  function matchPattern(buffer, pattern) {
16341
16646
  const clean = normalizeHistoryBuffer(stripAnsi4(buffer));
@@ -16426,7 +16731,7 @@ var TerminalPilot = class _TerminalPilot {
16426
16731
  }
16427
16732
  async newSession(opts) {
16428
16733
  const session = new TerminalSession({
16429
- id: randomUUID4(),
16734
+ id: randomUUID6(),
16430
16735
  command: opts.command,
16431
16736
  args: opts.args,
16432
16737
  cwd: opts.cwd,
@@ -16705,6 +17010,11 @@ var claudeCodeAgent = {
16705
17010
  aliases: ["claude"],
16706
17011
  binaryName: "claude",
16707
17012
  apiShapes: ["anthropic-messages"],
17013
+ otelCapture: {
17014
+ env: {
17015
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1"
17016
+ }
17017
+ },
16708
17018
  configPath: "~/.claude/settings.json",
16709
17019
  branding: {
16710
17020
  colors: {
@@ -16737,6 +17047,16 @@ var codexAgent = {
16737
17047
  summary: "Configure Codex to use Poe as the model provider.",
16738
17048
  binaryName: "codex",
16739
17049
  apiShapes: ["openai-responses"],
17050
+ otelCapture: {
17051
+ args: (endpoint, content) => [
17052
+ "-c",
17053
+ `otel.trace_exporter={"otlp-http"={endpoint=${JSON.stringify(`${endpoint}/v1/traces`)},protocol="json"}}`,
17054
+ "-c",
17055
+ `otel.exporter={"otlp-http"={endpoint=${JSON.stringify(`${endpoint}/v1/logs`)},protocol="json"}}`,
17056
+ "-c",
17057
+ `otel.log_user_prompt=${content}`
17058
+ ]
17059
+ },
16740
17060
  configPath: "~/.codex/config.toml",
16741
17061
  branding: {
16742
17062
  colors: {
@@ -16772,6 +17092,11 @@ var openCodeAgent = {
16772
17092
  summary: "Configure OpenCode CLI to use the Poe API.",
16773
17093
  binaryName: "opencode",
16774
17094
  apiShapes: ["openai-chat-completions"],
17095
+ otelCapture: {
17096
+ env: {
17097
+ OPENCODE_CONFIG_CONTENT: '{"experimental":{"openTelemetry":true}}'
17098
+ }
17099
+ },
16775
17100
  configPath: "~/.config/opencode/config.json",
16776
17101
  branding: {
16777
17102
  colors: {
@@ -16807,6 +17132,7 @@ var gooseAgent = {
16807
17132
  summary: "Block's open-source AI agent with ACP support.",
16808
17133
  binaryName: "goose",
16809
17134
  apiShapes: ["openai-chat-completions"],
17135
+ otelCapture: {},
16810
17136
  configPath: "~/.config/goose/config.yaml",
16811
17137
  branding: {
16812
17138
  colors: {
@@ -16840,6 +17166,12 @@ function freezeAgent(agent) {
16840
17166
  if (agent.apiShapes !== void 0) {
16841
17167
  Object.freeze(agent.apiShapes);
16842
17168
  }
17169
+ if (agent.otelCapture?.env !== void 0) {
17170
+ Object.freeze(agent.otelCapture.env);
17171
+ }
17172
+ if (agent.otelCapture !== void 0) {
17173
+ Object.freeze(agent.otelCapture);
17174
+ }
16843
17175
  Object.freeze(agent.branding.colors);
16844
17176
  Object.freeze(agent.branding);
16845
17177
  return Object.freeze(agent);
@@ -17003,6 +17335,7 @@ var templateMutation = {
17003
17335
  };
17004
17336
 
17005
17337
  // ../config-mutations/src/execution/apply-mutation.ts
17338
+ import { randomUUID as randomUUID7 } from "node:crypto";
17006
17339
  import path17 from "node:path";
17007
17340
 
17008
17341
  // ../config-mutations/src/formats/json.ts
@@ -17078,7 +17411,7 @@ function merge(base, patch) {
17078
17411
  if (value === void 0) {
17079
17412
  continue;
17080
17413
  }
17081
- const existing = result[key2];
17414
+ const existing = hasConfigEntry(result, key2) ? result[key2] : void 0;
17082
17415
  if (isConfigObject(existing) && isConfigObject(value)) {
17083
17416
  setConfigEntry(result, key2, merge(existing, value));
17084
17417
  continue;
@@ -17206,7 +17539,7 @@ function merge2(base, patch) {
17206
17539
  if (value === void 0) {
17207
17540
  continue;
17208
17541
  }
17209
- const existing = result[key2];
17542
+ const existing = hasConfigEntry(result, key2) ? result[key2] : void 0;
17210
17543
  if (isConfigObject2(existing) && isConfigObject2(value)) {
17211
17544
  setConfigEntry(result, key2, merge2(existing, value));
17212
17545
  continue;
@@ -17286,7 +17619,7 @@ function merge3(base, patch) {
17286
17619
  if (value === void 0) {
17287
17620
  continue;
17288
17621
  }
17289
- const existing = result[key2];
17622
+ const existing = hasConfigEntry(result, key2) ? result[key2] : void 0;
17290
17623
  if (isConfigObject3(existing) && isConfigObject3(value)) {
17291
17624
  setConfigEntry(result, key2, merge3(existing, value));
17292
17625
  continue;
@@ -17421,9 +17754,14 @@ function resolvePath(rawPath, homeDir, pathMapper) {
17421
17754
  return filename.length === 0 ? mappedDirectory : path16.join(mappedDirectory, filename);
17422
17755
  }
17423
17756
 
17757
+ // ../config-mutations/src/error-codes.ts
17758
+ function hasOwnErrorCode5(error3, code) {
17759
+ return typeof error3 === "object" && error3 !== null && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
17760
+ }
17761
+
17424
17762
  // ../config-mutations/src/fs-utils.ts
17425
17763
  function isNotFound(error3) {
17426
- return typeof error3 === "object" && error3 !== null && "code" in error3 && error3.code === "ENOENT";
17764
+ return hasOwnErrorCode5(error3, "ENOENT");
17427
17765
  }
17428
17766
  async function readFileIfExists(fs4, target) {
17429
17767
  try {
@@ -17472,6 +17810,7 @@ async function backupInvalidDocument(context, targetPath, content) {
17472
17810
  return;
17473
17811
  } catch (error3) {
17474
17812
  if (!isAlreadyExists(error3)) {
17813
+ await context.fs.unlink(backupPath).catch(() => void 0);
17475
17814
  throw error3;
17476
17815
  }
17477
17816
  attempt += 1;
@@ -17479,7 +17818,7 @@ async function backupInvalidDocument(context, targetPath, content) {
17479
17818
  }
17480
17819
  }
17481
17820
  function isAlreadyExists(error3) {
17482
- return Boolean(error3 && typeof error3 === "object" && "code" in error3 && error3.code === "EEXIST");
17821
+ return hasOwnErrorCode5(error3, "EEXIST");
17483
17822
  }
17484
17823
  async function assertRegularWriteTarget(context, targetPath) {
17485
17824
  const boundary = path17.dirname(path17.resolve(context.homeDir));
@@ -17503,28 +17842,34 @@ async function assertRegularWriteTarget(context, targetPath) {
17503
17842
  }
17504
17843
  async function writeAtomically2(context, targetPath, content) {
17505
17844
  await assertRegularWriteTarget(context, targetPath);
17506
- let attempt = 0;
17507
- while (true) {
17508
- const tempPath = `${targetPath}.mutation-tmp-${attempt}`;
17845
+ for (let attempt = 0; attempt < 10; attempt += 1) {
17846
+ const tempPath = `${targetPath}.mutation-tmp-${process.pid}-${randomUUID7()}`;
17847
+ let tempCreated = false;
17509
17848
  try {
17849
+ await assertRegularWriteTarget(context, tempPath);
17510
17850
  await context.fs.writeFile(tempPath, content, { encoding: "utf8", flag: "wx" });
17851
+ tempCreated = true;
17511
17852
  await context.fs.rename(tempPath, targetPath);
17853
+ tempCreated = false;
17512
17854
  return;
17513
17855
  } catch (error3) {
17514
- if (isAlreadyExists(error3)) {
17515
- attempt += 1;
17516
- continue;
17517
- }
17518
- try {
17519
- await context.fs.unlink(tempPath);
17520
- } catch (cleanupError) {
17521
- if (!isNotFound(cleanupError)) {
17522
- void cleanupError;
17856
+ const alreadyExists = isAlreadyExists(error3);
17857
+ if (tempCreated || !alreadyExists) {
17858
+ try {
17859
+ await context.fs.unlink(tempPath);
17860
+ } catch (cleanupError) {
17861
+ if (!isNotFound(cleanupError)) {
17862
+ void cleanupError;
17863
+ }
17523
17864
  }
17524
17865
  }
17866
+ if (alreadyExists) {
17867
+ continue;
17868
+ }
17525
17869
  throw error3;
17526
17870
  }
17527
17871
  }
17872
+ throw new Error(`Unable to create temporary mutation file for ${targetPath}.`);
17528
17873
  }
17529
17874
  function describeMutation(kind, targetPath) {
17530
17875
  const displayPath = targetPath ?? "target";
@@ -17816,6 +18161,7 @@ async function applyBackup(mutation, context, options) {
17816
18161
  break;
17817
18162
  } catch (error3) {
17818
18163
  if (!isAlreadyExists(error3)) {
18164
+ await context.fs.unlink(backupPath).catch(() => void 0);
17819
18165
  throw error3;
17820
18166
  }
17821
18167
  attempt += 1;
@@ -18199,6 +18545,11 @@ async function executeMutation(mutation, context, options) {
18199
18545
  }
18200
18546
  }
18201
18547
 
18548
+ // ../agent-skill-config/src/error-codes.ts
18549
+ function hasOwnErrorCode6(error3, code) {
18550
+ return error3 instanceof Error && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
18551
+ }
18552
+
18202
18553
  // ../agent-skill-config/src/templates.ts
18203
18554
  import { readFile as readFile5, stat } from "node:fs/promises";
18204
18555
  import path18 from "node:path";
@@ -18223,7 +18574,7 @@ async function pathExists2(fs4, targetPath) {
18223
18574
  await fs4.stat(targetPath);
18224
18575
  return true;
18225
18576
  } catch (error3) {
18226
- if (error3 && typeof error3 === "object" && "code" in error3 && error3.code === "ENOENT") {
18577
+ if (hasOwnErrorCode6(error3, "ENOENT")) {
18227
18578
  return false;
18228
18579
  }
18229
18580
  throw error3;
@@ -18282,12 +18633,13 @@ import path19 from "node:path";
18282
18633
 
18283
18634
  // ../agent-skill-config/src/git-exclude.ts
18284
18635
  import { execFileSync } from "node:child_process";
18636
+ import { randomUUID as randomUUID8 } from "node:crypto";
18285
18637
  import * as fs2 from "node:fs";
18286
18638
  import path20 from "node:path";
18287
18639
 
18288
18640
  // ../agent-skill-config/src/bridge-active-skills.ts
18289
18641
  import * as fs3 from "node:fs";
18290
- import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
18642
+ import { createHash as createHash4, randomUUID as randomUUID9 } from "node:crypto";
18291
18643
  import path21 from "node:path";
18292
18644
 
18293
18645
  // src/commands/installer.ts
@@ -18300,7 +18652,7 @@ var DEFAULT_INSTALL_SCOPE = "local";
18300
18652
  var TERMINAL_PILOT_SKILL_NAME = "terminal-pilot";
18301
18653
  var installableAgents = supportedAgents;
18302
18654
  function isNotFoundError2(error3) {
18303
- return typeof error3 === "object" && error3 !== null && "code" in error3 && error3.code === "ENOENT";
18655
+ return hasOwnErrorCode4(error3, "ENOENT");
18304
18656
  }
18305
18657
  function resolveInstallerServices(installer) {
18306
18658
  return {
@@ -18531,7 +18883,7 @@ var resize = defineCommand({
18531
18883
  });
18532
18884
 
18533
18885
  // ../terminal-png/src/index.ts
18534
- import { randomUUID as randomUUID6 } from "node:crypto";
18886
+ import { randomUUID as randomUUID10 } from "node:crypto";
18535
18887
  import { rename as rename4, rm, writeFile as writeFile6 } from "node:fs/promises";
18536
18888
 
18537
18889
  // ../terminal-png/src/ansi-parser.ts
@@ -18918,6 +19270,11 @@ function parseAnsi2(input) {
18918
19270
  return buildRuns(lines, lineBreakStyles);
18919
19271
  }
18920
19272
 
19273
+ // ../terminal-png/src/error-codes.ts
19274
+ function hasOwnErrorCode7(error3, code) {
19275
+ return typeof error3 === "object" && error3 !== null && Object.prototype.hasOwnProperty.call(error3, "code") && error3.code === code;
19276
+ }
19277
+
18921
19278
  // ../terminal-png/src/png-renderer.ts
18922
19279
  import { Resvg } from "@resvg/resvg-js";
18923
19280
 
@@ -19471,21 +19828,28 @@ async function renderTerminalPng(ansiText, options = {}) {
19471
19828
  });
19472
19829
  const png = renderPng(svg);
19473
19830
  if (options.output) {
19474
- const temporaryPath = `${options.output}.${randomUUID6()}.tmp`;
19831
+ const temporaryPath = `${options.output}.${randomUUID10()}.tmp`;
19832
+ let temporaryCreated = false;
19475
19833
  try {
19476
19834
  await writeFile6(temporaryPath, png, { flag: "wx" });
19835
+ temporaryCreated = true;
19477
19836
  await rename4(temporaryPath, options.output);
19478
19837
  } catch (error3) {
19479
- try {
19480
- await rm(temporaryPath, { force: true });
19481
- } catch (cleanupError) {
19482
- void cleanupError;
19838
+ if (temporaryCreated || !isAlreadyExistsError3(error3)) {
19839
+ try {
19840
+ await rm(temporaryPath, { force: true });
19841
+ } catch (cleanupError) {
19842
+ void cleanupError;
19843
+ }
19483
19844
  }
19484
19845
  throw error3;
19485
19846
  }
19486
19847
  }
19487
19848
  return png;
19488
19849
  }
19850
+ function isAlreadyExistsError3(error3) {
19851
+ return error3 instanceof Error && hasOwnErrorCode7(error3, "EEXIST");
19852
+ }
19489
19853
 
19490
19854
  // src/commands/screenshot.ts
19491
19855
  var params11 = S.Object({
@@ -19548,7 +19912,7 @@ var type = defineCommand({
19548
19912
  });
19549
19913
 
19550
19914
  // src/commands/uninstall.ts
19551
- import { randomUUID as randomUUID7 } from "node:crypto";
19915
+ import { randomUUID as randomUUID11 } from "node:crypto";
19552
19916
  var params14 = S.Object({
19553
19917
  agent: S.Enum(installableAgents, {
19554
19918
  description: "Agent to uninstall terminal-pilot from",
@@ -19584,7 +19948,7 @@ var uninstall = defineCommand({
19584
19948
  if (!await folderExists(services.fs, skill.fullPath)) {
19585
19949
  continue;
19586
19950
  }
19587
- const stagingPath = `${skill.fullPath}.removing-${randomUUID7()}`;
19951
+ const stagingPath = `${skill.fullPath}.removing-${randomUUID11()}`;
19588
19952
  await services.fs.rename(skill.fullPath, stagingPath);
19589
19953
  staged.push({ ...skill, stagingPath });
19590
19954
  }
@@ -19610,7 +19974,7 @@ async function folderExists(fs4, folderPath) {
19610
19974
  await fs4.stat(folderPath);
19611
19975
  return true;
19612
19976
  } catch (error3) {
19613
- if (typeof error3 === "object" && error3 !== null && "code" in error3 && error3.code === "ENOENT") {
19977
+ if (hasOwnErrorCode4(error3, "ENOENT")) {
19614
19978
  return false;
19615
19979
  }
19616
19980
  throw error3;
@@ -19664,8 +20028,6 @@ var waitForExit2 = defineCommand({
19664
20028
 
19665
20029
  // src/commands/index.ts
19666
20030
  var children = [
19667
- install,
19668
- uninstall,
19669
20031
  createSession,
19670
20032
  fill,
19671
20033
  type,
@@ -19679,7 +20041,9 @@ var children = [
19679
20041
  resize,
19680
20042
  closeSession,
19681
20043
  getSession,
19682
- listSessions
20044
+ listSessions,
20045
+ install,
20046
+ uninstall
19683
20047
  ];
19684
20048
  function createTerminalPilotGroup() {
19685
20049
  return defineGroup({
@@ -19702,7 +20066,7 @@ async function main(argv = process.argv) {
19702
20066
  const originalArgv = process.argv;
19703
20067
  process.argv = normalizeArgv(argv);
19704
20068
  try {
19705
- await runCLI(createTerminalPilotGroup());
20069
+ await runCLI(createTerminalPilotGroup(), { approvals: false });
19706
20070
  } finally {
19707
20071
  process.argv = originalArgv;
19708
20072
  }