@cortexkit/anthropic-auth-core 2.5.6 → 2.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -14,6 +14,39 @@ function routingHandle(sessionId) {
14
14
  function isObject(value) {
15
15
  return typeof value === "object" && value !== null;
16
16
  }
17
+ function turnNotes(sessionId) {
18
+ try {
19
+ const handle = routingHandle(sessionId);
20
+ if (!handle)
21
+ return [];
22
+ const read = handle.turn_notes;
23
+ if (typeof read !== "function")
24
+ return [];
25
+ const answer = read.call(handle);
26
+ if (isObject(answer) && typeof answer.then === "function") {
27
+ Promise.resolve(answer).catch(() => {});
28
+ return [];
29
+ }
30
+ if (!Array.isArray(answer))
31
+ return [];
32
+ const notes = [];
33
+ const encoder = new TextEncoder;
34
+ for (const entry of answer) {
35
+ try {
36
+ if (!isObject(entry) || Array.isArray(entry))
37
+ continue;
38
+ const afterToolUseId = entry.after_tool_use_id;
39
+ const text = entry.text;
40
+ if (typeof afterToolUseId !== "string" || afterToolUseId.length === 0 || typeof text !== "string" || text.trim().length === 0 || encoder.encode(text).byteLength > 16384)
41
+ continue;
42
+ notes.push({ afterToolUseId, text });
43
+ } catch {}
44
+ }
45
+ return notes;
46
+ } catch {
47
+ return [];
48
+ }
49
+ }
17
50
  function selectionFor(answer, candidates) {
18
51
  if (!isObject(answer))
19
52
  return;
@@ -76,32 +109,61 @@ function reportRouting(input) {
76
109
  const report = handle.report;
77
110
  if (typeof report !== "function")
78
111
  return;
79
- const identity = {
80
- account_id: input.accountId,
81
- ...input.credentialId !== undefined ? { credential_id: input.credentialId } : {}
82
- };
83
112
  let payload;
84
- switch (input.outcome) {
85
- case "served":
86
- payload = { ...identity, outcome: "served", headers: input.headers };
87
- break;
88
- case "exhausted": {
89
- const { window, pool } = input;
90
- if (window !== "5h" && window !== "7d")
113
+ if ("kind" in input) {
114
+ switch (input.kind) {
115
+ case "turn_notes_supported": {
116
+ const { model, supported } = input;
117
+ if (typeof model !== "string" || model.length === 0 || typeof supported !== "boolean")
118
+ return;
119
+ payload = {
120
+ kind: "turn_notes_supported",
121
+ model,
122
+ supported
123
+ };
124
+ break;
125
+ }
126
+ case "turn_note_skipped": {
127
+ const { after_tool_use_id, reason } = input;
128
+ if (typeof after_tool_use_id !== "string" || after_tool_use_id.length === 0 || reason !== "anchor_missing" && reason !== "before_user_message" && reason !== "unsupported_model" && reason !== "not_oauth")
129
+ return;
130
+ payload = {
131
+ kind: "turn_note_skipped",
132
+ after_tool_use_id,
133
+ reason
134
+ };
135
+ break;
136
+ }
137
+ default:
91
138
  return;
92
- if (pool !== undefined && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
139
+ }
140
+ } else {
141
+ const identity = {
142
+ account_id: input.accountId,
143
+ ...input.credentialId !== undefined ? { credential_id: input.credentialId } : {}
144
+ };
145
+ switch (input.outcome) {
146
+ case "served":
147
+ payload = { ...identity, outcome: "served", headers: input.headers };
148
+ break;
149
+ case "exhausted": {
150
+ const { window, pool } = input;
151
+ if (window !== "5h" && window !== "7d")
152
+ return;
153
+ if (pool !== undefined && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
154
+ return;
155
+ payload = {
156
+ ...identity,
157
+ outcome: "exhausted",
158
+ window,
159
+ ...pool ? { pool } : {},
160
+ ...input.resetsAt !== undefined ? { resets_at: input.resetsAt } : {}
161
+ };
162
+ break;
163
+ }
164
+ default:
93
165
  return;
94
- payload = {
95
- ...identity,
96
- outcome: "exhausted",
97
- window,
98
- ...pool ? { pool } : {},
99
- ...input.resetsAt !== undefined ? { resets_at: input.resetsAt } : {}
100
- };
101
- break;
102
166
  }
103
- default:
104
- return;
105
167
  }
106
168
  const pending = report.call(handle, payload);
107
169
  if (isObject(pending) && typeof pending.then === "function") {
@@ -802,7 +864,7 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
802
864
  });
803
865
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
804
866
  import { randomUUID as randomUUID3 } from "node:crypto";
805
- import { lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
867
+ import { link, lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
806
868
  import { dirname as dirname3, join as join3 } from "node:path";
807
869
 
808
870
  // ../../node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
@@ -878,7 +940,35 @@ async function withLock(target, options, fn) {
878
940
  }
879
941
 
880
942
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
943
+ var leaseCreationTestHooks;
881
944
  async function createExclusiveText(path, text) {
945
+ const tempPath = `${path}.${randomUUID3()}.tmp`;
946
+ let handle;
947
+ try {
948
+ handle = await open2(tempPath, "wx", 384);
949
+ try {
950
+ if (leaseCreationTestHooks?.beforeWrite)
951
+ await leaseCreationTestHooks.beforeWrite(tempPath);
952
+ await handle.writeFile(text, "utf8");
953
+ } finally {
954
+ await handle.close();
955
+ }
956
+ try {
957
+ if (leaseCreationTestHooks?.beforeLink)
958
+ await leaseCreationTestHooks.beforeLink(tempPath, path);
959
+ await link(tempPath, path);
960
+ } catch (error) {
961
+ const code = error.code;
962
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EOPNOTSUPP" && code !== "EXDEV")
963
+ throw error;
964
+ await writeExclusiveText(path, text);
965
+ }
966
+ } finally {
967
+ if (handle)
968
+ await rm2(tempPath, { force: true }).catch(() => {});
969
+ }
970
+ }
971
+ async function writeExclusiveText(path, text) {
882
972
  const handle = await open2(path, "wx", 384);
883
973
  let createdStat;
884
974
  try {
@@ -887,6 +977,8 @@ async function createExclusiveText(path, text) {
887
977
  createdStat = undefined;
888
978
  }
889
979
  try {
980
+ if (leaseCreationTestHooks?.beforeWrite)
981
+ await leaseCreationTestHooks.beforeWrite(path);
890
982
  await handle.writeFile(text, "utf8");
891
983
  } catch (error) {
892
984
  try {
@@ -1257,7 +1349,7 @@ async function acquireRefreshFileLockWithClock(options) {
1257
1349
  if (windowsPrivateFiles)
1258
1350
  await createPrivateBytes(evictOwnerPath, bytes);
1259
1351
  else
1260
- await createExclusiveText(evictOwnerPath, bytes);
1352
+ await writeExclusiveText(evictOwnerPath, bytes);
1261
1353
  } catch (error) {
1262
1354
  const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
1263
1355
  if (isLostMarkerRaceError(error) && !stillOurs)
@@ -15770,7 +15862,7 @@ class CacheKeepManager {
15770
15862
  // src/cachekeep-registry.ts
15771
15863
  import { randomUUID as randomUUID15 } from "node:crypto";
15772
15864
  import {
15773
- link,
15865
+ link as link2,
15774
15866
  lstat as lstat13,
15775
15867
  mkdir as mkdir11,
15776
15868
  readdir as readdir3,
@@ -24019,7 +24111,7 @@ class CacheKeepSessionRegistry {
24019
24111
  }
24020
24112
  async restoreSweptRecord(recordPath, sweptPath, raw) {
24021
24113
  try {
24022
- await link(sweptPath, recordPath);
24114
+ await link2(sweptPath, recordPath);
24023
24115
  } catch (error) {
24024
24116
  const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
24025
24117
  if (code === "EEXIST") {
@@ -36757,10 +36849,10 @@ function isSignInLink(candidate) {
36757
36849
  }
36758
36850
  function showSignInLink(text6, scrub) {
36759
36851
  const links = new Set((text6.match(/https:\/\/\S+/g) ?? []).filter(isSignInLink));
36760
- const [link2] = links;
36761
- if (links.size !== 1 || link2 === undefined)
36852
+ const [link3] = links;
36853
+ if (links.size !== 1 || link3 === undefined)
36762
36854
  return { text: scrub(text6) };
36763
- return { text: text6.split(link2).map(scrub).join(link2), link: link2 };
36855
+ return { text: text6.split(link3).map(scrub).join(link3), link: link3 };
36764
36856
  }
36765
36857
  var DISCONNECT_OUTCOMES = {
36766
36858
  disconnected: {
@@ -41432,60 +41524,26 @@ function supportsTurnEndNote(model) {
41432
41524
  var runnerReports = new Map;
41433
41525
  var SKIP_REPORT_LIMIT = 512;
41434
41526
  var RUNNER_REPORT_SESSION_LIMIT = 1024;
41435
- function readRunnerNotes(handle) {
41436
- try {
41437
- const read = handle.turn_notes;
41438
- if (typeof read !== "function")
41439
- return [];
41440
- const answer = read.call(handle);
41441
- if (answer !== null && (typeof answer === "object" || typeof answer === "function") && typeof Reflect.get(answer, "then") === "function") {
41442
- Promise.resolve(answer).catch(() => {});
41443
- return [];
41444
- }
41445
- if (!Array.isArray(answer))
41446
- return [];
41447
- const notes = [];
41448
- for (let index = 0;index < answer.length; index++) {
41449
- try {
41450
- const entry2 = answer[index];
41451
- if (!isRecord20(entry2) || Array.isArray(entry2))
41452
- continue;
41453
- const { after_tool_use_id, text: text6 } = entry2;
41454
- if (typeof after_tool_use_id !== "string" || typeof text6 !== "string" || !text6.trim() || new TextEncoder().encode(text6).byteLength > 16384)
41455
- continue;
41456
- notes.push({ after_tool_use_id, text: text6 });
41457
- } catch {}
41458
- }
41459
- return notes;
41460
- } catch {
41461
- return [];
41462
- }
41463
- }
41464
- function runnerNotes(sessionId) {
41527
+ function hasRunnerTurnNotes(sessionId) {
41465
41528
  try {
41466
41529
  const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
41467
41530
  if (typeof routing !== "function")
41468
- return;
41531
+ return false;
41469
41532
  const handle = routing(sessionId);
41470
- if (isRecord20(handle) && typeof handle.turn_notes === "function")
41471
- return { handle, notes: readRunnerNotes(handle) };
41533
+ return isRecord20(handle) && typeof handle.turn_notes === "function";
41472
41534
  } catch {
41473
- return;
41535
+ return false;
41474
41536
  }
41475
41537
  }
41476
- function reportRunnerNote(handle, payload) {
41477
- Promise.resolve().then(() => {
41478
- const report = handle.report;
41479
- if (typeof report === "function")
41480
- return report.call(handle, payload);
41481
- }).catch(() => {});
41538
+ function reportRunnerNote(payload) {
41539
+ Promise.resolve().then(() => reportRouting(payload)).catch(() => {});
41482
41540
  }
41483
41541
  function applyRunnerTurnNotes(body, options) {
41484
41542
  if (!options.sessionId)
41485
41543
  return 0;
41486
- const runner = runnerNotes(options.sessionId);
41487
- if (!runner)
41544
+ if (!hasRunnerTurnNotes(options.sessionId))
41488
41545
  return 0;
41546
+ const notes = turnNotes(options.sessionId);
41489
41547
  let reported3 = runnerReports.get(options.sessionId);
41490
41548
  if (reported3) {
41491
41549
  runnerReports.delete(options.sessionId);
@@ -41502,7 +41560,8 @@ function applyRunnerTurnNotes(body, options) {
41502
41560
  const model = options.modelId;
41503
41561
  if (reported3.models.get(model) !== supported) {
41504
41562
  reported3.models.set(model, supported);
41505
- reportRunnerNote(runner.handle, {
41563
+ reportRunnerNote({
41564
+ sessionId: options.sessionId,
41506
41565
  kind: "turn_notes_supported",
41507
41566
  model,
41508
41567
  supported
@@ -41520,21 +41579,22 @@ function applyRunnerTurnNotes(body, options) {
41520
41579
  }
41521
41580
  const insertions = new Map;
41522
41581
  let inserted = 0;
41523
- for (const note of runner.notes) {
41524
- const index = anchors.get(note.after_tool_use_id);
41582
+ for (const note of notes) {
41583
+ const index = anchors.get(note.afterToolUseId);
41525
41584
  const next = index === undefined ? undefined : messages[index + 1];
41526
41585
  const reason = !options.isOAuth ? "not_oauth" : !supported ? "unsupported_model" : index === undefined ? "anchor_missing" : isRecord20(next) && next.role === "user" ? "before_user_message" : undefined;
41527
41586
  if (reason) {
41528
- if (!reported3.skipped.has(note.after_tool_use_id)) {
41587
+ if (!reported3.skipped.has(note.afterToolUseId)) {
41529
41588
  if (reported3.skipped.size >= SKIP_REPORT_LIMIT) {
41530
41589
  const oldest = reported3.skipped.values().next();
41531
41590
  if (!oldest.done)
41532
41591
  reported3.skipped.delete(oldest.value);
41533
41592
  }
41534
- reported3.skipped.add(note.after_tool_use_id);
41535
- reportRunnerNote(runner.handle, {
41593
+ reported3.skipped.add(note.afterToolUseId);
41594
+ reportRunnerNote({
41595
+ sessionId: options.sessionId,
41536
41596
  kind: "turn_note_skipped",
41537
- after_tool_use_id: note.after_tool_use_id,
41597
+ after_tool_use_id: note.afterToolUseId,
41538
41598
  reason
41539
41599
  });
41540
41600
  }
@@ -1,3 +1,9 @@
1
+ type LeaseCreationTestHooks = {
2
+ beforeWrite?: (path: string) => void | Promise<void>;
3
+ beforeLink?: (tempPath: string, lockPath: string) => void | Promise<void>;
4
+ };
5
+ /** Test-only creation faults; not re-exported from the public fs entry point. */
6
+ export declare function setLeaseCreationTestHooksForTest(hooks?: LeaseCreationTestHooks): void;
1
7
  export declare function isLostMarkerRaceError(error: unknown): boolean;
2
8
  /** Test-only fault injection between marker mkdir and owner.json write. */
3
9
  export interface EvictionMarkerTestHooks {
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Optional THALAMUS routing for vault mode and advisory turn notes for request
3
+ * shaping. Account ids are vault account ids, not local pool rows. Nothing is
4
+ * persisted here; plugins on routes the runner does not serve get no turn notes.
5
+ */
1
6
  /** An eligible vault route, not a local pool row. */
2
7
  export interface RoutingCandidate {
3
8
  /** Vault account id, not the plugin's route id. */
@@ -35,7 +40,7 @@ interface RoutingReportIdentity {
35
40
  accountId: string;
36
41
  credentialId?: string;
37
42
  }
38
- export type ReportRoutingInput = RoutingReportIdentity & ({
43
+ export type ReportRoutingInput = (RoutingReportIdentity & ({
39
44
  outcome: 'served';
40
45
  /**
41
46
  * Pass only rate-limit headers, never the whole response headers.
@@ -56,7 +61,26 @@ export type ReportRoutingInput = RoutingReportIdentity & ({
56
61
  pool?: string;
57
62
  /** Optional reset time in epoch milliseconds. */
58
63
  resetsAt?: number;
59
- });
64
+ })) | {
65
+ sessionId: string;
66
+ kind: 'turn_notes_supported';
67
+ model: string;
68
+ supported: boolean;
69
+ } | {
70
+ sessionId: string;
71
+ kind: 'turn_note_skipped';
72
+ after_tool_use_id: string;
73
+ reason: 'anchor_missing' | 'before_user_message' | 'unsupported_model' | 'not_oauth';
74
+ };
75
+ /**
76
+ * Read advisory input for request shaping, in landing order, without persisting
77
+ * it. If no routing handle is available or the runner does not serve the route,
78
+ * returns [].
79
+ */
80
+ export declare function turnNotes(sessionId: string): readonly {
81
+ afterToolUseId: string;
82
+ text: string;
83
+ }[];
60
84
  /**
61
85
  * Ask routing for an eligible vault route. Any failure or unfamiliar answer
62
86
  * yields undefined so the plugin can keep its own choice. This does not admit
@@ -64,9 +88,10 @@ export type ReportRoutingInput = RoutingReportIdentity & ({
64
88
  */
65
89
  export declare function askRouting<Candidate extends RoutingCandidate>(input: AskRoutingInput<Candidate>): Promise<RoutingSelection<Candidate> | undefined>;
66
90
  /**
67
- * Report a vault request without waiting for routing. Only contract fields are
68
- * sent, and all accessor failures are ignored. Headers must already be limited
69
- * to rate-limit headers by the caller; values are not filtered or redacted here.
91
+ * Report a vault request or turn-note event without waiting for routing. Only
92
+ * contract fields are sent, and all accessor failures are ignored. Headers must
93
+ * already be limited to rate-limit headers by the caller; values are not filtered
94
+ * or redacted here.
70
95
  */
71
96
  export declare function reportRouting(input: ReportRoutingInput): void;
72
97
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.5.6",
3
+ "version": "2.5.7",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,7 +30,7 @@
30
30
  "prepublishOnly": "bun run build"
31
31
  },
32
32
  "devDependencies": {
33
- "@cortexkit/common-auth": "0.38.0"
33
+ "@cortexkit/common-auth": "0.39.1"
34
34
  },
35
35
  "dependencies": {
36
36
  "@cortexkit/claustrum-client": "0.13.0",