@maximem/synap-js-sdk 0.6.4 → 0.6.6
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/anticipation-cache-Q7IYC3ID.cjs +26 -0
- package/dist/anticipation-cache-Q7IYC3ID.cjs.map +1 -0
- package/dist/{anticipation-cache-RWKF55J4.js → anticipation-cache-VL5WHTJB.js} +8 -2
- package/dist/chunk-7IZHVYO2.cjs.map +1 -1
- package/dist/{chunk-ICUFS3B5.cjs → chunk-BYUGILQI.cjs} +136 -142
- package/dist/chunk-BYUGILQI.cjs.map +1 -0
- package/dist/{chunk-R72YL6Q4.js → chunk-CSG3N5E3.js} +136 -142
- package/dist/chunk-CSG3N5E3.js.map +1 -0
- package/dist/{chunk-2VJV4HCF.cjs → chunk-PYJOWTI5.cjs} +72 -20
- package/dist/chunk-PYJOWTI5.cjs.map +1 -0
- package/dist/{chunk-N55UBGER.js → chunk-VCCZ33ZU.js} +59 -7
- package/dist/chunk-VCCZ33ZU.js.map +1 -0
- package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
- package/dist/env-55ULHNJZ.cjs.map +1 -1
- package/dist/{errors-DWjdpExq.d.cts → errors-x5bpgxmC.d.cts} +18 -3
- package/dist/{errors-DWjdpExq.d.ts → errors-x5bpgxmC.d.ts} +18 -3
- package/dist/grpc/index.cjs +4 -4
- package/dist/grpc/index.cjs.map +1 -1
- package/dist/grpc/index.d.cts +11 -3
- package/dist/grpc/index.d.ts +11 -3
- package/dist/grpc/index.js +3 -3
- package/dist/index.cjs +906 -185
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +242 -20
- package/dist/index.d.ts +242 -20
- package/dist/index.js +826 -105
- package/dist/index.js.map +1 -1
- package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
- package/dist/stream-client-BY5LNLVB.cjs +22 -0
- package/dist/stream-client-BY5LNLVB.cjs.map +1 -0
- package/dist/{stream-client-GRDVRBFA.js → stream-client-JKFBVZPN.js} +2 -2
- package/package.json +1 -1
- package/dist/anticipation-cache-LPNKMRBH.cjs +0 -20
- package/dist/anticipation-cache-LPNKMRBH.cjs.map +0 -1
- package/dist/chunk-2VJV4HCF.cjs.map +0 -1
- package/dist/chunk-ICUFS3B5.cjs.map +0 -1
- package/dist/chunk-N55UBGER.js.map +0 -1
- package/dist/chunk-R72YL6Q4.js.map +0 -1
- package/dist/stream-client-SZIYGVVJ.cjs +0 -22
- package/dist/stream-client-SZIYGVVJ.cjs.map +0 -1
- /package/dist/{anticipation-cache-RWKF55J4.js.map → anticipation-cache-VL5WHTJB.js.map} +0 -0
- /package/dist/{stream-client-GRDVRBFA.js.map → stream-client-JKFBVZPN.js.map} +0 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
var _chunkBYUGILQIcjs = require('./chunk-BYUGILQI.cjs');
|
|
13
|
+
require('./chunk-ZKOJDUN4.cjs');
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
exports.ANY_SCOPE = _chunkBYUGILQIcjs.ANY_SCOPE; exports.AnticipationCache = _chunkBYUGILQIcjs.AnticipationCache; exports.MATCHERS = _chunkBYUGILQIcjs.MATCHERS; exports.asServed = _chunkBYUGILQIcjs.asServed; exports.canonicalQuery = _chunkBYUGILQIcjs.canonicalQuery; exports.distinctQueries = _chunkBYUGILQIcjs.distinctQueries; exports.reservePerQuery = _chunkBYUGILQIcjs.reservePerQuery; exports.rungKey = _chunkBYUGILQIcjs.rungKey; exports.rungServes = _chunkBYUGILQIcjs.rungServes; exports.unownedElsewhere = _chunkBYUGILQIcjs.unownedElsewhere;
|
|
26
|
+
//# sourceMappingURL=anticipation-cache-Q7IYC3ID.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/anish/npm-publish-0.6.6/synap/sdk/js/dist/anticipation-cache-Q7IYC3ID.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,miBAAC","file":"/Users/anish/npm-publish-0.6.6/synap/sdk/js/dist/anticipation-cache-Q7IYC3ID.cjs"}
|
|
@@ -2,19 +2,25 @@ import {
|
|
|
2
2
|
ANY_SCOPE,
|
|
3
3
|
AnticipationCache,
|
|
4
4
|
MATCHERS,
|
|
5
|
+
asServed,
|
|
5
6
|
canonicalQuery,
|
|
7
|
+
distinctQueries,
|
|
8
|
+
reservePerQuery,
|
|
6
9
|
rungKey,
|
|
7
10
|
rungServes,
|
|
8
11
|
unownedElsewhere
|
|
9
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-CSG3N5E3.js";
|
|
10
13
|
import "./chunk-QBCVMPGK.js";
|
|
11
14
|
export {
|
|
12
15
|
ANY_SCOPE,
|
|
13
16
|
AnticipationCache,
|
|
14
17
|
MATCHERS,
|
|
18
|
+
asServed,
|
|
15
19
|
canonicalQuery,
|
|
20
|
+
distinctQueries,
|
|
21
|
+
reservePerQuery,
|
|
16
22
|
rungKey,
|
|
17
23
|
rungServes,
|
|
18
24
|
unownedElsewhere
|
|
19
25
|
};
|
|
20
|
-
//# sourceMappingURL=anticipation-cache-
|
|
26
|
+
//# sourceMappingURL=anticipation-cache-VL5WHTJB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/anish/maximemai/maximem_synap/synap/sdk/js/dist/chunk-7IZHVYO2.cjs","../src/errors.ts","../src/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;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAEA;AACM,EAAA;AACJ,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACA,EAAA;AACF;AAMa;AACA;AACA;AACA;AD7LN;AACA;AErNA;AACL,EAAA;AACI,EAAA;AAEA,EAAA;AACF,IAAA;AAGG,IAAA;AACA,IAAA;AACH,IAAA;AACA,IAAA;AACF,EAAA;AAIA,EAAA;AACE,IAAA;AACA,IAAA;AACD,EAAA;AACH;AFiNO;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/anish/maximemai/maximem_synap/synap/sdk/js/dist/chunk-7IZHVYO2.cjs","sourcesContent":[null,"/**\n * Synap SDK error taxonomy.\n *\n * Mirrors `maximem_synap/models/errors.py` 1:1, including the four\n * backward-compatibility aliases at the bottom. If you add an error to one\n * SDK, add it to the other in the same change.\n *\n * ## Why every error carries a `.code`\n *\n * This package ships dual ESM + CJS. A consumer whose dependency graph pulls\n * in both formats gets *two* copies of every class in this file, and then:\n *\n * try { ... } catch (e) { if (e instanceof SynapError) { ... } }\n *\n * silently evaluates to `false` against the copy from the other format. Error\n * handling stops working and nothing throws to tell you. `.code` is a plain\n * string, so it is immune. Prefer it at package boundaries:\n *\n * if (isSynapError(e) && e.code === 'rate_limit') { ... }\n *\n * `Symbol.hasInstance` is also wired up on the base class, so `instanceof`\n * works across realms too -- but `.code` is the documented contract.\n */\n\n/** Stable, format-independent discriminators. Never renumber or reuse. */\nexport type SynapErrorCode =\n | 'synap_error'\n | 'transient'\n | 'permanent'\n | 'network_timeout'\n | 'rate_limit'\n | 'insufficient_credits'\n | 'service_unavailable'\n | 'invalid_input'\n | 'invalid_instance_id'\n | 'invalid_conversation_id'\n | 'customer_id_not_accepted'\n | 'authentication'\n | 'context_not_found'\n | 'conflict'\n | 'transcript_conflict'\n | 'instance_not_ready'\n | 'instance_build_failed'\n | 'session_expired'\n | 'listening_already_active'\n | 'listening_not_active'\n | 'agent_unavailable';\n\nconst BRAND = Symbol.for('@maximem/synap-js-sdk.SynapError');\n\nexport interface SynapErrorOptions {\n correlationId?: string | null;\n cause?: unknown;\n}\n\nexport class SynapError extends Error {\n /**\n * The single declaration site for each subclass's code.\n *\n * It is `static` rather than a class field on purpose. Under\n * `useDefineForClassFields` (the default at our ES2022 target) a class field\n * is an *instance* property, so it is invisible from the constructor object.\n * `Symbol.hasInstance` below only has the constructor to work with, so a\n * field would leave it unable to tell `AuthenticationError` from\n * `RateLimitError` -- it would report every Synap error as an instance of\n * every other one.\n */\n static readonly errorCode: SynapErrorCode = 'synap_error';\n /** True for errors where a retry may succeed. Static for the same reason. */\n static readonly isTransient: boolean = false;\n\n /** Own, enumerable, so logs and JSON.stringify include it. */\n readonly code: SynapErrorCode;\n readonly correlationId: string | null;\n readonly transient: boolean;\n\n constructor(message: string, options: SynapErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n const ctor = new.target as typeof SynapError;\n this.name = new.target.name;\n this.code = ctor.errorCode;\n this.transient = ctor.isTransient;\n this.correlationId = options.correlationId ?? null;\n Object.defineProperty(this, BRAND, { value: true, enumerable: false });\n // Without this, subclassing a built-in under a downlevel target breaks the\n // prototype chain and `instanceof` fails even within a single copy.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static override [Symbol.hasInstance](instance: unknown): boolean {\n if (instance === null || typeof instance !== 'object') return false;\n // Cross-realm / dual-format tolerant: identify by brand, then narrow by the\n // subclass's own code so `e instanceof RateLimitError` stays meaningful.\n if (!(BRAND in instance)) return false;\n const expected = (this as unknown as { errorCode?: SynapErrorCode }).errorCode;\n // Called on something that is not one of our classes: fall back to the brand.\n if (expected === undefined) return true;\n // Everything branded descends from the root.\n if (expected === 'synap_error') return true;\n const actual = (instance as { code?: string }).code;\n return actual === expected || descendsFrom(actual, expected);\n }\n}\n\n/** Type guard that works across ESM/CJS copies and realms. */\nexport function isSynapError(e: unknown): e is SynapError {\n return typeof e === 'object' && e !== null && BRAND in e;\n}\n\nexport class SynapTransientError extends SynapError {\n static override readonly errorCode: SynapErrorCode = 'transient';\n static override readonly isTransient: boolean = true;\n}\n\nexport class SynapPermanentError extends SynapError {\n static override readonly errorCode: SynapErrorCode = 'permanent';\n static override readonly isTransient: boolean = false;\n}\n\n// ─── Transient ────────────────────────────────────────────────────────────────\n\nexport class NetworkTimeoutError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'network_timeout';\n}\n\n/**\n * Rate limit exceeded (HTTP 429, gRPC RESOURCE_EXHAUSTED).\n *\n * Also carries the two credit stops the server reports as 429, because both\n * recover with time or a plan change rather than with a retry of this request:\n * `reason: 'trial_limit_reached'` (the Trial cap is spent, see `upgradeUrl`)\n * and `reason: 'subscription_inactive'` (a paid plan whose subscription is past\n * due, unpaid or cancelled, see `manageUrl`). `reason` is null for an ordinary\n * rate limit and against a server too old to send one.\n */\nexport class RateLimitError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'rate_limit';\n readonly retryAfterSeconds: number | null;\n /** Machine-readable cause, when the stop was a credit stop. */\n readonly reason: string | null;\n /** Where a Trial customer upgrades. Python calls this `upgrade_url`. */\n readonly upgradeUrl: string | null;\n /** Where billing is managed. Python calls this `manage_url`. */\n readonly manageUrl: string | null;\n\n constructor(\n message: string,\n options: SynapErrorOptions & {\n retryAfterSeconds?: number | null;\n reason?: string | null;\n upgradeUrl?: string | null;\n manageUrl?: string | null;\n } = {},\n ) {\n super(message, options);\n this.retryAfterSeconds = options.retryAfterSeconds ?? null;\n this.reason = options.reason ?? null;\n this.upgradeUrl = options.upgradeUrl ?? null;\n this.manageUrl = options.manageUrl ?? null;\n }\n}\n\nexport class ServiceUnavailableError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'service_unavailable';\n}\n\nexport class AgentUnavailableError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'agent_unavailable';\n constructor(message = 'Agent unavailable', options: SynapErrorOptions = {}) {\n super(message, options);\n }\n}\n\n// ─── Permanent ────────────────────────────────────────────────────────────────\n\n/**\n * The caller's credit wallet cannot cover this request.\n *\n * HTTP 402, and gRPC RESOURCE_EXHAUSTED with credit-related trailing metadata.\n * Permanent by design: retrying without topping up burns quota and never\n * succeeds. This is the error behind \"the agent forgot\" reports where retrieval\n * silently returns nothing.\n */\nexport class InsufficientCreditsError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'insufficient_credits';\n readonly balanceCredits: number | null;\n readonly requiredCredits: number | null;\n /** Where the balance can be viewed. Python calls this `recovery_url`. */\n readonly recoveryUrl: string | null;\n /** Where a redeem code can be entered. Python calls this `redeem_url`. */\n readonly redeemUrl: string | null;\n /**\n * Machine-readable cause. `'overages_disabled'` means the plan is paid and\n * the balance is spent, but the account has not allowed usage past zero, so\n * the work stops until someone allows overages or adds credits. Null when an\n * older server did not send one.\n */\n readonly reason: string | null;\n /** Where that setting and billing are managed. Python calls this `manage_url`. */\n readonly manageUrl: string | null;\n\n constructor(\n message: string,\n options: SynapErrorOptions & {\n balanceCredits?: number | null;\n requiredCredits?: number | null;\n recoveryUrl?: string | null;\n redeemUrl?: string | null;\n reason?: string | null;\n manageUrl?: string | null;\n } = {},\n ) {\n super(message, options);\n this.balanceCredits = options.balanceCredits ?? null;\n this.requiredCredits = options.requiredCredits ?? null;\n this.recoveryUrl = options.recoveryUrl ?? null;\n this.redeemUrl = options.redeemUrl ?? null;\n this.reason = options.reason ?? null;\n this.manageUrl = options.manageUrl ?? null;\n }\n}\n\nexport class InvalidInputError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'invalid_input';\n}\n\n/**\n * Raised by `validateInstanceId` before any network call, matching Python's\n * `utils/validators.py`. The message text is identical in both SDKs.\n */\nexport class InvalidInstanceIdError extends InvalidInputError {\n static override readonly errorCode: SynapErrorCode = 'invalid_instance_id';\n}\n\n/** See the note on InvalidInstanceIdError. Raised by `validateConversationId`. */\nexport class InvalidConversationIdError extends InvalidInputError {\n static override readonly errorCode: SynapErrorCode = 'invalid_conversation_id';\n}\n\n/**\n * A customer_id passed on a B2C instance, refused before any request.\n * Python raises the same class (`maximem_synap.CustomerIdNotAcceptedError`),\n * also a subclass of InvalidInputError, with the same three fields.\n */\nexport class CustomerIdNotAcceptedError extends InvalidInputError {\n static override readonly errorCode: SynapErrorCode = 'customer_id_not_accepted';\n readonly where: string;\n readonly customerId: string;\n readonly instanceId: string | null;\n\n constructor(where: string, customerId: string, instanceId?: string | null) {\n super(\n `${where}: customer_id is not accepted on this instance` +\n `${instanceId ? ` (${instanceId})` : ''}, which is B2C ` +\n `(user_context_isolation='equals_customer'). Send user_id only; it is the ` +\n `whole identity, and the server files and reads your data under it. ` +\n `Received customer_id=${JSON.stringify(customerId)}.`,\n );\n this.where = where;\n this.customerId = customerId;\n this.instanceId = instanceId ?? null;\n }\n}\n\nexport class AuthenticationError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'authentication';\n}\n\nexport class ContextNotFoundError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'context_not_found';\n}\n\nexport class ConflictError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'conflict';\n}\n\nexport class TranscriptConflictError extends ConflictError {\n static override readonly errorCode: SynapErrorCode = 'transcript_conflict';\n}\n\n/**\n * The instance's memory architecture is still being built (HTTP 409).\n *\n * A new instance usually spends 15 to 20 minutes building. Until that finishes the\n * server refuses memory writes and reads with\n * `409 {\"error\": \"instance_not_ready\", ...}` plus a `Retry-After` header.\n * Nothing was recorded; the same call works once the build is done.\n *\n * Extends `ConflictError`, so existing `catch` code that handles\n * `ConflictError` keeps working. Thrown immediately and **never retried inside\n * the SDK**: a wait this long must not hide inside a call. Mirrors\n * `InstanceNotReadyError` in `maximem_synap/models/errors.py`.\n */\nexport class InstanceNotReadyError extends ConflictError {\n static override readonly errorCode: SynapErrorCode = 'instance_not_ready';\n /** The server's estimate of the wait. Python calls this `retry_after_seconds`. */\n readonly retryAfterSeconds: number | null;\n readonly instanceId: string | null;\n /** Build state reported by the server (`'building'`). */\n readonly state: string | null;\n /**\n * `true` when the SDK threw this itself, without a network call, because an\n * earlier call to the same instance was refused and the server's wait has not\n * elapsed. Then `retryAfterSeconds` is the REMAINING wait (rounded up, at\n * least 1). `false` when the server sent this refusal just now. Python:\n * `from_cooldown`.\n */\n readonly fromCooldown: boolean;\n\n constructor(\n message = \"This instance's memory architecture is still being built.\",\n options: SynapErrorOptions & {\n retryAfterSeconds?: number | null;\n instanceId?: string | null;\n state?: string | null;\n fromCooldown?: boolean;\n } = {},\n ) {\n super(message, options);\n this.retryAfterSeconds = options.retryAfterSeconds ?? null;\n this.instanceId = options.instanceId ?? null;\n this.state = options.state === undefined ? 'building' : options.state;\n this.fromCooldown = options.fromCooldown ?? false;\n }\n}\n\n/**\n * The instance's memory architecture build failed for good (HTTP 409\n * `{\"error\": \"instance_build_failed\", ...}`).\n *\n * The server tried the build several times and gave up. Waiting does not help:\n * a person has to start a rebuild (see `hint`, e.g.\n * `maximem-synap instances rebuild <instance_id>`). Extends `ConflictError`.\n * Thrown immediately, **never retried** and sets **no cooldown**: it is not time\n * based. Mirrors `InstanceBuildFailedError` in `maximem_synap/models/errors.py`.\n */\nexport class InstanceBuildFailedError extends ConflictError {\n static override readonly errorCode: SynapErrorCode = 'instance_build_failed';\n readonly instanceId: string | null;\n /** How many build attempts the server made. Python: `attempts`. */\n readonly attempts: number | null;\n /** The server's instruction for recovering. */\n readonly hint: string | null;\n\n constructor(\n message = \"This instance's memory architecture build failed.\",\n options: SynapErrorOptions & {\n instanceId?: string | null;\n attempts?: number | null;\n hint?: string | null;\n } = {},\n ) {\n super(message, options);\n this.instanceId = options.instanceId ?? null;\n this.attempts = options.attempts ?? null;\n this.hint = options.hint ?? null;\n }\n}\n\nexport class SessionExpiredError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'session_expired';\n}\n\nexport class ListeningAlreadyActiveError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'listening_already_active';\n}\n\nexport class ListeningNotActiveError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'listening_not_active';\n}\n\n// ─── Hierarchy metadata (drives the cross-copy instanceof above) ──────────────\n\nconst PARENT: Partial<Record<SynapErrorCode, SynapErrorCode>> = {\n transient: 'synap_error',\n permanent: 'synap_error',\n network_timeout: 'transient',\n rate_limit: 'transient',\n service_unavailable: 'transient',\n agent_unavailable: 'transient',\n insufficient_credits: 'permanent',\n invalid_input: 'permanent',\n invalid_instance_id: 'invalid_input',\n invalid_conversation_id: 'invalid_input',\n customer_id_not_accepted: 'invalid_input',\n authentication: 'permanent',\n context_not_found: 'permanent',\n conflict: 'permanent',\n transcript_conflict: 'conflict',\n instance_not_ready: 'conflict',\n instance_build_failed: 'conflict',\n session_expired: 'permanent',\n listening_already_active: 'permanent',\n listening_not_active: 'permanent',\n};\n\nfunction descendsFrom(actual: string | undefined, expected: string): boolean {\n let cur = actual as SynapErrorCode | undefined;\n const seen = new Set<string>();\n while (cur && !seen.has(cur)) {\n seen.add(cur);\n if (cur === expected) return true;\n cur = PARENT[cur];\n }\n return false;\n}\n\n// ─── Backward-compatibility aliases (mirrors the tail of errors.py) ──────────\n// `ConnectionError` deliberately shadows the global in a module scope. Python\n// does the same thing; keeping the name means ported code reads identically.\n\nexport const SDKError = SynapError;\nexport const TransientError = SynapTransientError;\nexport const PermanentError = SynapPermanentError;\nexport const ConnectionError = NetworkTimeoutError;\n","/**\n * Correlation ID generation.\n *\n * `globalThis.crypto` is unflagged from Node 19 onward and this package\n * declares `engines.node >= 20`, so `randomUUID` is normally present. It is\n * still feature-detected rather than assumed, because `engines` is advisory:\n * npm warns and installs anyway, and the SDK also runs on Workers, Edge and\n * Bun, where the available crypto surface varies.\n *\n * Deliberately does NOT import `node:crypto`. That import is what breaks Edge\n * and Workers builds at bundle time, and a correlation ID is not a security\n * value, so there is nothing to gain from it.\n */\nexport function newCorrelationId(): string {\n const c = globalThis.crypto;\n if (typeof c?.randomUUID === 'function') return c.randomUUID();\n\n if (typeof c?.getRandomValues === 'function') {\n const b = c.getRandomValues(new Uint8Array(16));\n // RFC 4122 version (4) and variant bits. The `?? 0` guards satisfy\n // `noUncheckedIndexedAccess`; a 16-byte array always has these slots.\n b[6] = ((b[6] ?? 0) & 0x0f) | 0x40;\n b[8] = ((b[8] ?? 0) & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n }\n\n // Last resort. Correlation IDs are for tracing only, never for security, so\n // Math.random is acceptable here and only here.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/anish/npm-publish-0.6.6/synap/sdk/js/dist/chunk-7IZHVYO2.cjs","../src/errors.ts","../src/util/correlation.ts"],"names":[],"mappings":"AAAA;ACgDA,IAAM,MAAA,kBAAQ,MAAA,CAAO,GAAA,CAAI,kCAAkC,CAAA;AAOpD,IAAM,WAAA,YAAN,MAAA,QAAyB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYpC,4BAAgB,UAAA,EAA4B,cAAA;AAAA;AAAA,EAE5C,6BAAgB,YAAA,EAAuB,MAAA;AAAA;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Ma;AACA;AACA;AACA;AD7LN;AACA;AErNA;AACL,EAAA;AACI,EAAA;AAEA,EAAA;AACF,IAAA;AAGG,IAAA;AACA,IAAA;AACH,IAAA;AACA,IAAA;AACF,EAAA;AAIA,EAAA;AACE,IAAA;AACA,IAAA;AACD,EAAA;AACH;AFiNO;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/anish/npm-publish-0.6.6/synap/sdk/js/dist/chunk-7IZHVYO2.cjs","sourcesContent":[null,"/**\n * Synap SDK error taxonomy.\n *\n * Mirrors `maximem_synap/models/errors.py` 1:1, including the four\n * backward-compatibility aliases at the bottom. If you add an error to one\n * SDK, add it to the other in the same change.\n *\n * ## Why every error carries a `.code`\n *\n * This package ships dual ESM + CJS. A consumer whose dependency graph pulls\n * in both formats gets *two* copies of every class in this file, and then:\n *\n * try { ... } catch (e) { if (e instanceof SynapError) { ... } }\n *\n * silently evaluates to `false` against the copy from the other format. Error\n * handling stops working and nothing throws to tell you. `.code` is a plain\n * string, so it is immune. Prefer it at package boundaries:\n *\n * if (isSynapError(e) && e.code === 'rate_limit') { ... }\n *\n * `Symbol.hasInstance` is also wired up on the base class, so `instanceof`\n * works across realms too -- but `.code` is the documented contract.\n */\n\n/** Stable, format-independent discriminators. Never renumber or reuse. */\nexport type SynapErrorCode =\n | 'synap_error'\n | 'transient'\n | 'permanent'\n | 'network_timeout'\n | 'rate_limit'\n | 'insufficient_credits'\n | 'service_unavailable'\n | 'invalid_input'\n | 'invalid_instance_id'\n | 'invalid_conversation_id'\n | 'customer_id_not_accepted'\n | 'authentication'\n | 'context_not_found'\n | 'conflict'\n | 'transcript_conflict'\n | 'instance_not_ready'\n | 'instance_build_failed'\n | 'session_expired'\n | 'listening_already_active'\n | 'listening_not_active'\n | 'agent_unavailable';\n\nconst BRAND = Symbol.for('@maximem/synap-js-sdk.SynapError');\n\nexport interface SynapErrorOptions {\n correlationId?: string | null;\n cause?: unknown;\n}\n\nexport class SynapError extends Error {\n /**\n * The single declaration site for each subclass's code.\n *\n * It is `static` rather than a class field on purpose. Under\n * `useDefineForClassFields` (the default at our ES2022 target) a class field\n * is an *instance* property, so it is invisible from the constructor object.\n * `Symbol.hasInstance` below only has the constructor to work with, so a\n * field would leave it unable to tell `AuthenticationError` from\n * `RateLimitError` -- it would report every Synap error as an instance of\n * every other one.\n */\n static readonly errorCode: SynapErrorCode = 'synap_error';\n /** True for errors where a retry may succeed. Static for the same reason. */\n static readonly isTransient: boolean = false;\n\n /** Own, enumerable, so logs and JSON.stringify include it. */\n readonly code: SynapErrorCode;\n readonly correlationId: string | null;\n readonly transient: boolean;\n\n constructor(message: string, options: SynapErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n const ctor = new.target as typeof SynapError;\n this.name = new.target.name;\n this.code = ctor.errorCode;\n this.transient = ctor.isTransient;\n this.correlationId = options.correlationId ?? null;\n Object.defineProperty(this, BRAND, { value: true, enumerable: false });\n // Without this, subclassing a built-in under a downlevel target breaks the\n // prototype chain and `instanceof` fails even within a single copy.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static override [Symbol.hasInstance](instance: unknown): boolean {\n if (instance === null || typeof instance !== 'object') return false;\n // Cross-realm / dual-format tolerant: identify by brand, then narrow by the\n // subclass's own code so `e instanceof RateLimitError` stays meaningful.\n if (!(BRAND in instance)) return false;\n const expected = (this as unknown as { errorCode?: SynapErrorCode }).errorCode;\n // Called on something that is not one of our classes: fall back to the brand.\n if (expected === undefined) return true;\n // Everything branded descends from the root.\n if (expected === 'synap_error') return true;\n const actual = (instance as { code?: string }).code;\n return actual === expected || descendsFrom(actual, expected);\n }\n}\n\n/** Type guard that works across ESM/CJS copies and realms. */\nexport function isSynapError(e: unknown): e is SynapError {\n return typeof e === 'object' && e !== null && BRAND in e;\n}\n\nexport class SynapTransientError extends SynapError {\n static override readonly errorCode: SynapErrorCode = 'transient';\n static override readonly isTransient: boolean = true;\n}\n\nexport class SynapPermanentError extends SynapError {\n static override readonly errorCode: SynapErrorCode = 'permanent';\n static override readonly isTransient: boolean = false;\n}\n\n// ─── Transient ────────────────────────────────────────────────────────────────\n\nexport class NetworkTimeoutError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'network_timeout';\n}\n\n/**\n * Rate limit exceeded (HTTP 429, gRPC RESOURCE_EXHAUSTED).\n *\n * Also carries the two credit stops the server reports as 429, because both\n * recover with time or a plan change rather than with a retry of this request:\n * `reason: 'trial_limit_reached'` (the Trial cap is spent, see `upgradeUrl`)\n * and `reason: 'subscription_inactive'` (a paid plan whose subscription is past\n * due, unpaid or cancelled, see `manageUrl`). `reason` is null for an ordinary\n * rate limit and against a server too old to send one.\n */\nexport class RateLimitError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'rate_limit';\n readonly retryAfterSeconds: number | null;\n /** Machine-readable cause, when the stop was a credit stop. */\n readonly reason: string | null;\n /** Where a Trial customer upgrades. Python calls this `upgrade_url`. */\n readonly upgradeUrl: string | null;\n /** Where billing is managed. Python calls this `manage_url`. */\n readonly manageUrl: string | null;\n\n constructor(\n message: string,\n options: SynapErrorOptions & {\n retryAfterSeconds?: number | null;\n reason?: string | null;\n upgradeUrl?: string | null;\n manageUrl?: string | null;\n } = {},\n ) {\n super(message, options);\n this.retryAfterSeconds = options.retryAfterSeconds ?? null;\n this.reason = options.reason ?? null;\n this.upgradeUrl = options.upgradeUrl ?? null;\n this.manageUrl = options.manageUrl ?? null;\n }\n}\n\nexport class ServiceUnavailableError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'service_unavailable';\n}\n\nexport class AgentUnavailableError extends SynapTransientError {\n static override readonly errorCode: SynapErrorCode = 'agent_unavailable';\n constructor(message = 'Agent unavailable', options: SynapErrorOptions = {}) {\n super(message, options);\n }\n}\n\n// ─── Permanent ────────────────────────────────────────────────────────────────\n\n/**\n * The caller's credit wallet cannot cover this request.\n *\n * HTTP 402, and gRPC RESOURCE_EXHAUSTED with credit-related trailing metadata.\n * Permanent by design: retrying without topping up burns quota and never\n * succeeds. This is the error behind \"the agent forgot\" reports where retrieval\n * silently returns nothing.\n */\nexport class InsufficientCreditsError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'insufficient_credits';\n readonly balanceCredits: number | null;\n readonly requiredCredits: number | null;\n /** Where the balance can be viewed. Python calls this `recovery_url`. */\n readonly recoveryUrl: string | null;\n /** Where a redeem code can be entered. Python calls this `redeem_url`. */\n readonly redeemUrl: string | null;\n /**\n * Machine-readable cause. `'overages_disabled'` means the plan is paid and\n * the balance is spent, but the account has not allowed usage past zero, so\n * the work stops until someone allows overages or adds credits. Null when an\n * older server did not send one.\n */\n readonly reason: string | null;\n /** Where that setting and billing are managed. Python calls this `manage_url`. */\n readonly manageUrl: string | null;\n\n constructor(\n message: string,\n options: SynapErrorOptions & {\n balanceCredits?: number | null;\n requiredCredits?: number | null;\n recoveryUrl?: string | null;\n redeemUrl?: string | null;\n reason?: string | null;\n manageUrl?: string | null;\n } = {},\n ) {\n super(message, options);\n this.balanceCredits = options.balanceCredits ?? null;\n this.requiredCredits = options.requiredCredits ?? null;\n this.recoveryUrl = options.recoveryUrl ?? null;\n this.redeemUrl = options.redeemUrl ?? null;\n this.reason = options.reason ?? null;\n this.manageUrl = options.manageUrl ?? null;\n }\n}\n\nexport class InvalidInputError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'invalid_input';\n}\n\n/**\n * Raised by `validateInstanceId` before any network call, matching Python's\n * `utils/validators.py`. The message text is identical in both SDKs.\n */\nexport class InvalidInstanceIdError extends InvalidInputError {\n static override readonly errorCode: SynapErrorCode = 'invalid_instance_id';\n}\n\n/** See the note on InvalidInstanceIdError. Raised by `validateConversationId`. */\nexport class InvalidConversationIdError extends InvalidInputError {\n static override readonly errorCode: SynapErrorCode = 'invalid_conversation_id';\n}\n\n/**\n * A customer_id passed on a B2C instance, refused before any request.\n * Python raises the same class (`maximem_synap.CustomerIdNotAcceptedError`),\n * also a subclass of InvalidInputError, with the same three fields.\n */\nexport class CustomerIdNotAcceptedError extends InvalidInputError {\n static override readonly errorCode: SynapErrorCode = 'customer_id_not_accepted';\n readonly where: string;\n readonly customerId: string;\n readonly instanceId: string | null;\n\n constructor(where: string, customerId: string, instanceId?: string | null) {\n super(\n `${where}: customer_id is not accepted on this instance` +\n `${instanceId ? ` (${instanceId})` : ''}, which is B2C ` +\n `(user_context_isolation='equals_customer'). Send user_id only; it is the ` +\n `whole identity, and the server files and reads your data under it. ` +\n `Received customer_id=${JSON.stringify(customerId)}.`,\n );\n this.where = where;\n this.customerId = customerId;\n this.instanceId = instanceId ?? null;\n }\n}\n\nexport class AuthenticationError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'authentication';\n}\n\nexport class ContextNotFoundError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'context_not_found';\n}\n\nexport class ConflictError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'conflict';\n}\n\nexport class TranscriptConflictError extends ConflictError {\n static override readonly errorCode: SynapErrorCode = 'transcript_conflict';\n}\n\n/**\n * The instance's memory architecture is still being built (HTTP 409).\n *\n * A new instance usually spends 15 to 20 minutes building. Until that finishes the\n * server refuses memory writes and reads with\n * `409 {\"error\": \"instance_not_ready\", ...}` plus a `Retry-After` header.\n * Nothing was recorded; the same call works once the build is done.\n *\n * Extends `ConflictError`, so existing `catch` code that handles\n * `ConflictError` keeps working. Thrown immediately and **never retried inside\n * the SDK**: a wait this long must not hide inside a call. Mirrors\n * `InstanceNotReadyError` in `maximem_synap/models/errors.py`.\n */\nexport class InstanceNotReadyError extends ConflictError {\n static override readonly errorCode: SynapErrorCode = 'instance_not_ready';\n /** The server's estimate of the wait. Python calls this `retry_after_seconds`. */\n readonly retryAfterSeconds: number | null;\n readonly instanceId: string | null;\n /** Build state reported by the server (`'building'`). */\n readonly state: string | null;\n /**\n * `true` when the SDK threw this itself, without a network call, because an\n * earlier call to the same instance was refused and the server's wait has not\n * elapsed. Then `retryAfterSeconds` is the REMAINING wait (rounded up, at\n * least 1). `false` when the server sent this refusal just now. Python:\n * `from_cooldown`.\n */\n readonly fromCooldown: boolean;\n\n constructor(\n message = \"This instance's memory architecture is still being built.\",\n options: SynapErrorOptions & {\n retryAfterSeconds?: number | null;\n instanceId?: string | null;\n state?: string | null;\n fromCooldown?: boolean;\n } = {},\n ) {\n super(message, options);\n this.retryAfterSeconds = options.retryAfterSeconds ?? null;\n this.instanceId = options.instanceId ?? null;\n this.state = options.state === undefined ? 'building' : options.state;\n this.fromCooldown = options.fromCooldown ?? false;\n }\n}\n\n/**\n * The instance's memory architecture build failed for good (HTTP 409\n * `{\"error\": \"instance_build_failed\", ...}`).\n *\n * The server tried the build several times and gave up. Waiting does not help:\n * a person has to start a rebuild (see `hint`, e.g.\n * `maximem-synap instances rebuild <instance_id>`). Extends `ConflictError`.\n * Thrown immediately, **never retried** and sets **no cooldown**: it is not time\n * based. Mirrors `InstanceBuildFailedError` in `maximem_synap/models/errors.py`.\n */\nexport class InstanceBuildFailedError extends ConflictError {\n static override readonly errorCode: SynapErrorCode = 'instance_build_failed';\n readonly instanceId: string | null;\n /** How many build attempts the server made. Python: `attempts`. */\n readonly attempts: number | null;\n /** The server's instruction for recovering. */\n readonly hint: string | null;\n\n constructor(\n message = \"This instance's memory architecture build failed.\",\n options: SynapErrorOptions & {\n instanceId?: string | null;\n attempts?: number | null;\n hint?: string | null;\n } = {},\n ) {\n super(message, options);\n this.instanceId = options.instanceId ?? null;\n this.attempts = options.attempts ?? null;\n this.hint = options.hint ?? null;\n }\n}\n\nexport class SessionExpiredError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'session_expired';\n}\n\nexport class ListeningAlreadyActiveError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'listening_already_active';\n}\n\nexport class ListeningNotActiveError extends SynapPermanentError {\n static override readonly errorCode: SynapErrorCode = 'listening_not_active';\n}\n\n// ─── Hierarchy metadata (drives the cross-copy instanceof above) ──────────────\n\nconst PARENT: Partial<Record<SynapErrorCode, SynapErrorCode>> = {\n transient: 'synap_error',\n permanent: 'synap_error',\n network_timeout: 'transient',\n rate_limit: 'transient',\n service_unavailable: 'transient',\n agent_unavailable: 'transient',\n insufficient_credits: 'permanent',\n invalid_input: 'permanent',\n invalid_instance_id: 'invalid_input',\n invalid_conversation_id: 'invalid_input',\n customer_id_not_accepted: 'invalid_input',\n authentication: 'permanent',\n context_not_found: 'permanent',\n conflict: 'permanent',\n transcript_conflict: 'conflict',\n instance_not_ready: 'conflict',\n instance_build_failed: 'conflict',\n session_expired: 'permanent',\n listening_already_active: 'permanent',\n listening_not_active: 'permanent',\n};\n\nfunction descendsFrom(actual: string | undefined, expected: string): boolean {\n let cur = actual as SynapErrorCode | undefined;\n const seen = new Set<string>();\n while (cur && !seen.has(cur)) {\n seen.add(cur);\n if (cur === expected) return true;\n cur = PARENT[cur];\n }\n return false;\n}\n\n// ─── Backward-compatibility aliases (mirrors the tail of errors.py) ──────────\n// `ConnectionError` deliberately shadows the global in a module scope. Python\n// does the same thing; keeping the name means ported code reads identically.\n\nexport const SDKError = SynapError;\nexport const TransientError = SynapTransientError;\nexport const PermanentError = SynapPermanentError;\nexport const ConnectionError = NetworkTimeoutError;\n","/**\n * Correlation ID generation.\n *\n * `globalThis.crypto` is unflagged from Node 19 onward and this package\n * declares `engines.node >= 20`, so `randomUUID` is normally present. It is\n * still feature-detected rather than assumed, because `engines` is advisory:\n * npm warns and installs anyway, and the SDK also runs on Workers, Edge and\n * Bun, where the available crypto surface varies.\n *\n * Deliberately does NOT import `node:crypto`. That import is what breaks Edge\n * and Workers builds at bundle time, and a correlation ID is not a security\n * value, so there is nothing to gain from it.\n */\nexport function newCorrelationId(): string {\n const c = globalThis.crypto;\n if (typeof c?.randomUUID === 'function') return c.randomUUID();\n\n if (typeof c?.getRandomValues === 'function') {\n const b = c.getRandomValues(new Uint8Array(16));\n // RFC 4122 version (4) and variant bits. The `?? 0` guards satisfy\n // `noUncheckedIndexedAccess`; a 16-byte array always has these slots.\n b[6] = ((b[6] ?? 0) & 0x0f) | 0x40;\n b[8] = ((b[8] ?? 0) & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n }\n\n // Last resort. Correlation IDs are for tracing only, never for security, so\n // Math.random is acceptable here and only here.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n"]}
|
|
@@ -8,98 +8,6 @@ var _chunkZKOJDUN4cjs = require('./chunk-ZKOJDUN4.cjs');
|
|
|
8
8
|
var anticipation_default = {
|
|
9
9
|
$comment: "SOURCE OF TRUTH for anticipation-cache behavior, shared by the Python and JS/TS SDKs. Do not duplicate these values into either SDK's source. See ../README.md. Regexes are restricted to the intersection of Python 're' and ECMAScript; both SDKs have a parity test.",
|
|
10
10
|
version: 1,
|
|
11
|
-
recall_bypass: {
|
|
12
|
-
note: "WS4 of the playground query-hygiene plan. A recall-shaped question never serves from the anticipation cache. Asymmetric cost is why: a stale false-hit makes the agent answer 'I don't see that' while the store holds the fact (the BZQR6J cross-session failure), whereas bypassing costs only cold-fetch latency on a turn where the user already expects a lookup. Stem coverage cannot gate this \u2014 false hits were measured at coverage=1.00. Ties break toward INCLUDING a pattern.",
|
|
13
|
-
env_flag: "SYNAP_SDK_CACHE_RECALL_BYPASS",
|
|
14
|
-
default: false,
|
|
15
|
-
patterns: [
|
|
16
|
-
{
|
|
17
|
-
pattern: "\\bremind me\\b",
|
|
18
|
-
flags: "i",
|
|
19
|
-
note: "Original set (WS4, playground query-hygiene plan)."
|
|
20
|
-
},
|
|
21
|
-
{
|
|
22
|
-
pattern: "\\bon file\\b",
|
|
23
|
-
flags: "i",
|
|
24
|
-
note: "Original set (WS4)."
|
|
25
|
-
},
|
|
26
|
-
{
|
|
27
|
-
pattern: "\\b(your|my|the) records\\b",
|
|
28
|
-
flags: "i",
|
|
29
|
-
note: "Original set (WS4)."
|
|
30
|
-
},
|
|
31
|
-
{
|
|
32
|
-
pattern: "\\bdo you (have|know|remember|recall|see)\\b",
|
|
33
|
-
flags: "i",
|
|
34
|
-
note: "Original set (WS4)."
|
|
35
|
-
},
|
|
36
|
-
{
|
|
37
|
-
pattern: "\\bwhat (do|did) (i|you) (say|tell|mention|have)\\b",
|
|
38
|
-
flags: "i",
|
|
39
|
-
note: "Original set (WS4)."
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
pattern: "\\bwhat('s| is) my\\b",
|
|
43
|
-
flags: "i",
|
|
44
|
-
note: "Original set (WS4)."
|
|
45
|
-
},
|
|
46
|
-
{
|
|
47
|
-
pattern: "\\bwhere (am i|do i live)\\b",
|
|
48
|
-
flags: "i",
|
|
49
|
-
note: "Original set (WS4)."
|
|
50
|
-
},
|
|
51
|
-
{
|
|
52
|
-
pattern: "\\bhow long have i\\b",
|
|
53
|
-
flags: "i",
|
|
54
|
-
note: "Original set (WS4)."
|
|
55
|
-
},
|
|
56
|
-
{
|
|
57
|
-
pattern: "\\bwhich of my\\b",
|
|
58
|
-
flags: "i",
|
|
59
|
-
note: "Original set (WS4)."
|
|
60
|
-
},
|
|
61
|
-
{
|
|
62
|
-
pattern: "\\bwhat .{0,40}\\b(again|earlier|last time|previously|yesterday)\\b",
|
|
63
|
-
flags: "i",
|
|
64
|
-
note: "Original set (WS4). 'again' alone is deliberately NOT a marker: 'book me a ride again' is a task query, not a recall query."
|
|
65
|
-
},
|
|
66
|
-
{
|
|
67
|
-
pattern: "\\bwill you use to (contact|reach|notify)\\b",
|
|
68
|
-
flags: "i",
|
|
69
|
-
note: "Original set (WS4)."
|
|
70
|
-
},
|
|
71
|
-
{
|
|
72
|
-
pattern: "\\b(confirm|verify|double.?check)\\b.{0,40}\\bmy\\b",
|
|
73
|
-
flags: "i",
|
|
74
|
-
note: "2026-07-16 eval register issue #11: 'can you confirm my email address?' served a stale bundle. Also catches 'confirm my booking' \u2014 an intentional over-match, costing one cloud fetch."
|
|
75
|
-
},
|
|
76
|
-
{
|
|
77
|
-
pattern: "\\b(linked to|associated with|registered (to|on|with)) my\\b",
|
|
78
|
-
flags: "i",
|
|
79
|
-
note: "2026-07-16 eval register issue #11: 'what name is linked to my Uber account?' served a stale bundle."
|
|
80
|
-
},
|
|
81
|
-
{
|
|
82
|
-
pattern: "\\b(best|preferred) way to (reach|contact|update|notify) me\\b",
|
|
83
|
-
flags: "i",
|
|
84
|
-
note: "2026-07-16 eval register issue #11: 'best way to contact me with updates' served a stale bundle."
|
|
85
|
-
},
|
|
86
|
-
{
|
|
87
|
-
pattern: "\\bhow (do|will|can|should) you (reach|contact|notify) me\\b",
|
|
88
|
-
flags: "i",
|
|
89
|
-
note: "2026-07-16 eval register issue #11, sibling phrasing of the above."
|
|
90
|
-
},
|
|
91
|
-
{
|
|
92
|
-
pattern: "\\bwhich .{0,40}\\b(are|will) you (going to )?(use|using)\\b",
|
|
93
|
-
flags: "i",
|
|
94
|
-
note: "2026-07-16 eval register issue #11: 'which email are you going to use?' served a stale bundle."
|
|
95
|
-
},
|
|
96
|
-
{
|
|
97
|
-
pattern: "\\bon (my|the) account\\b",
|
|
98
|
-
flags: "i",
|
|
99
|
-
note: "2026-07-16 eval register issue #11."
|
|
100
|
-
}
|
|
101
|
-
]
|
|
102
|
-
},
|
|
103
11
|
thresholds: {
|
|
104
12
|
bm25: {
|
|
105
13
|
value: 1.5,
|
|
@@ -224,14 +132,6 @@ var anticipation_default = {
|
|
|
224
132
|
},
|
|
225
133
|
env_flags: {
|
|
226
134
|
$comment: "Read at CALL time, never at module load. Python does os.environ.get inside the function bodies; JS must do the same or late process.env mutation stops working and the flag looks broken. See gotcha G-S.",
|
|
227
|
-
SYNAP_SDK_CACHE_RECALL_BYPASS: {
|
|
228
|
-
default: false,
|
|
229
|
-
truthy: [
|
|
230
|
-
"true",
|
|
231
|
-
"1",
|
|
232
|
-
"yes"
|
|
233
|
-
]
|
|
234
|
-
},
|
|
235
135
|
SYNAP_SDK_CACHE_HONOR_TTL_HINT: {
|
|
236
136
|
default: false,
|
|
237
137
|
truthy: [
|
|
@@ -543,20 +443,6 @@ var anticipation_default = {
|
|
|
543
443
|
|
|
544
444
|
// src/behavior/contract.ts
|
|
545
445
|
var CONTRACT = anticipation_default;
|
|
546
|
-
var ALLOWED_FLAGS = /* @__PURE__ */ new Set(["i", "m", "s"]);
|
|
547
|
-
function compile(pattern, flags) {
|
|
548
|
-
for (const ch of flags) {
|
|
549
|
-
if (!ALLOWED_FLAGS.has(ch)) {
|
|
550
|
-
throw new Error(
|
|
551
|
-
`Unsupported regex flag '${ch}' in behavior contract. Flags must be valid in both Python and ECMAScript.`
|
|
552
|
-
);
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
return new RegExp(pattern, flags);
|
|
556
|
-
}
|
|
557
|
-
var RECALL_PATTERNS = CONTRACT.recall_bypass.patterns.map(
|
|
558
|
-
(p) => compile(p.pattern, _nullishCoalesce(p.flags, () => ( "")))
|
|
559
|
-
);
|
|
560
446
|
var THRESHOLDS = {
|
|
561
447
|
bm25: CONTRACT.thresholds.bm25.value,
|
|
562
448
|
novelTerm: CONTRACT.thresholds.novel_term.value,
|
|
@@ -572,15 +458,6 @@ var SUFFIXES = CONTRACT.bm25.suffixes;
|
|
|
572
458
|
var ALIAS_TOKEN_SOURCE = CONTRACT.bm25.alias_token.pattern;
|
|
573
459
|
var HISTORY_SEARCH = CONTRACT.history_search;
|
|
574
460
|
var SEMANTIC_MATCH = CONTRACT.semantic_match;
|
|
575
|
-
function isRecallQuery(searchQuery) {
|
|
576
|
-
for (const q of _nullishCoalesce(searchQuery, () => ( []))) {
|
|
577
|
-
if (!q) continue;
|
|
578
|
-
for (const pattern of RECALL_PATTERNS) {
|
|
579
|
-
if (pattern.test(q)) return true;
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
return false;
|
|
583
|
-
}
|
|
584
461
|
|
|
585
462
|
// src/cache/bm25.ts
|
|
586
463
|
var MIN_STEM_LEN = BM25_PARAMS.min_stem_len;
|
|
@@ -709,6 +586,16 @@ function itemQuestions(item) {
|
|
|
709
586
|
const qs = item.questions;
|
|
710
587
|
return Array.isArray(qs) ? qs.filter((q) => typeof q === "string" && q.trim() !== "").map((q) => q.trim()) : [];
|
|
711
588
|
}
|
|
589
|
+
function asServed(item, matchedQueries = null) {
|
|
590
|
+
if (!("date_prefix" in item) && matchedQueries === null) return item;
|
|
591
|
+
const { date_prefix: raw, ...rest } = item;
|
|
592
|
+
const label = typeof raw === "string" ? raw : "";
|
|
593
|
+
const out = { ...rest };
|
|
594
|
+
if (matchedQueries !== null) out["matched_queries"] = [...matchedQueries];
|
|
595
|
+
const content = typeof out.content === "string" ? out.content : "";
|
|
596
|
+
if (label !== "" && !content.startsWith(label)) out.content = label + content;
|
|
597
|
+
return out;
|
|
598
|
+
}
|
|
712
599
|
var MATCHERS = ["bm25", "semantic"];
|
|
713
600
|
function matcherSetting() {
|
|
714
601
|
const raw = (_nullishCoalesce(_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_SDK_CACHE_MATCHER"), () => ( ""))).trim().toLowerCase();
|
|
@@ -727,6 +614,52 @@ function cosine(a, b) {
|
|
|
727
614
|
}
|
|
728
615
|
var DEFAULT_TTL_SECONDS = 1800;
|
|
729
616
|
var DEFAULT_MAX_BUNDLES = 50;
|
|
617
|
+
function distinctQueries(searchQuery) {
|
|
618
|
+
return [...new Set((_nullishCoalesce(searchQuery, () => ( []))).filter((q) => typeof q === "string" && q !== ""))];
|
|
619
|
+
}
|
|
620
|
+
function sharesOf(searchQuery, perQuery) {
|
|
621
|
+
if (!perQuery || perQuery <= 0) return null;
|
|
622
|
+
const queries = distinctQueries(searchQuery);
|
|
623
|
+
return queries.length > 1 ? queries : null;
|
|
624
|
+
}
|
|
625
|
+
function reservePerQuery(ranked, budget, perQuery, queries, matched) {
|
|
626
|
+
if (budget <= 0) return { kept: [], matched: [] };
|
|
627
|
+
const byQuery = new Map(queries.map((q) => [q, ranked.map((_, i) => i).filter((i) => matched[i].includes(q))]));
|
|
628
|
+
const cursor = new Map(queries.map((q) => [q, 0]));
|
|
629
|
+
const taken = new Map(queries.map((q) => [q, 0]));
|
|
630
|
+
const picked = [];
|
|
631
|
+
const pickedSet = /* @__PURE__ */ new Set();
|
|
632
|
+
let progressed = true;
|
|
633
|
+
while (picked.length < budget && progressed) {
|
|
634
|
+
progressed = false;
|
|
635
|
+
for (const q of queries) {
|
|
636
|
+
if (picked.length >= budget) break;
|
|
637
|
+
if (taken.get(q) >= perQuery) continue;
|
|
638
|
+
const candidates = byQuery.get(q);
|
|
639
|
+
let j = cursor.get(q);
|
|
640
|
+
while (j < candidates.length && pickedSet.has(candidates[j])) j++;
|
|
641
|
+
if (j >= candidates.length) {
|
|
642
|
+
cursor.set(q, j);
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
const i = candidates[j];
|
|
646
|
+
cursor.set(q, j + 1);
|
|
647
|
+
picked.push(i);
|
|
648
|
+
pickedSet.add(i);
|
|
649
|
+
for (const owner of matched[i]) if (taken.has(owner)) taken.set(owner, taken.get(owner) + 1);
|
|
650
|
+
progressed = true;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
for (let i = 0; i < ranked.length; i++) {
|
|
654
|
+
if (picked.length >= budget) break;
|
|
655
|
+
if (!pickedSet.has(i) && !matched[i].some((q) => queries.includes(q))) {
|
|
656
|
+
picked.push(i);
|
|
657
|
+
pickedSet.add(i);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const keep = [...picked].sort((a, b) => a - b);
|
|
661
|
+
return { kept: keep.map((i) => ranked[i]), matched: keep.map((i) => [...matched[i]]) };
|
|
662
|
+
}
|
|
730
663
|
var AnticipationCache = (_class2 = class {
|
|
731
664
|
|
|
732
665
|
|
|
@@ -873,14 +806,16 @@ var AnticipationCache = (_class2 = class {
|
|
|
873
806
|
async lookupAsync(params) {
|
|
874
807
|
const encoder = this.encoder;
|
|
875
808
|
let queries = (_nullishCoalesce(params.searchQuery, () => ( []))).filter((q) => typeof q === "string" && q.trim() !== "").map((q) => q.trim()).slice(0, SEMANTIC_MATCH.max_queries);
|
|
876
|
-
|
|
877
|
-
if (!this.semantic || encoder === null || queries.length === 0 || recall || this.items.length === 0) {
|
|
809
|
+
if (!this.semantic || encoder === null || queries.length === 0 || this.items.length === 0) {
|
|
878
810
|
return this.lookup(params);
|
|
879
811
|
}
|
|
812
|
+
const asked = [...queries];
|
|
813
|
+
let owners = [...asked];
|
|
880
814
|
if (this.canonical === "canon" || this.canonical === "both") {
|
|
881
815
|
const canon = queries.map(canonicalQuery);
|
|
882
816
|
const changed = canon.filter((c, i) => c !== queries[i]);
|
|
883
817
|
queries = this.canonical === "both" ? [...queries, ...changed] : canon;
|
|
818
|
+
if (this.canonical === "both") owners = [...asked, ...asked.filter((q, i) => canon[i] !== q)];
|
|
884
819
|
}
|
|
885
820
|
let queryVectors = null;
|
|
886
821
|
try {
|
|
@@ -888,7 +823,7 @@ var AnticipationCache = (_class2 = class {
|
|
|
888
823
|
} catch (e3) {
|
|
889
824
|
queryVectors = null;
|
|
890
825
|
}
|
|
891
|
-
return this.lookup({ ...params, queryVectors });
|
|
826
|
+
return this.lookup({ ...params, queryVectors, queryOwners: owners });
|
|
892
827
|
}
|
|
893
828
|
lookup(params) {
|
|
894
829
|
const {
|
|
@@ -899,8 +834,11 @@ var AnticipationCache = (_class2 = class {
|
|
|
899
834
|
conversationId = null,
|
|
900
835
|
scopeRung = null,
|
|
901
836
|
maxItems = 10,
|
|
902
|
-
queryVectors = null
|
|
837
|
+
queryVectors = null,
|
|
838
|
+
queryOwners = null,
|
|
839
|
+
maxResultsPerQuery = null
|
|
903
840
|
} = params;
|
|
841
|
+
const shares = sharesOf(searchQuery, maxResultsPerQuery);
|
|
904
842
|
this.evictExpired();
|
|
905
843
|
const accepted = this.buildAcceptedScope(entityId, customerId, clientId);
|
|
906
844
|
const telemetry = {
|
|
@@ -933,13 +871,21 @@ var AnticipationCache = (_class2 = class {
|
|
|
933
871
|
telemetry
|
|
934
872
|
);
|
|
935
873
|
}
|
|
936
|
-
if (_chunkZKOJDUN4cjs.getEnvFlag.call(void 0, CONTRACT.recall_bypass.env_flag) && isRecallQuery(searchQuery)) {
|
|
937
|
-
return this.miss(telemetry, "recall_bypass");
|
|
938
|
-
}
|
|
939
874
|
const queryTokens = (_nullishCoalesce(searchQuery, () => ( []))).flatMap((q) => tokenize(q));
|
|
940
875
|
telemetry.bm25QueryTokens = queryTokens;
|
|
941
876
|
if (this.semantic && queryVectors !== null && queryVectors.length > 0) {
|
|
942
|
-
return this.semanticLookup(
|
|
877
|
+
return this.semanticLookup(
|
|
878
|
+
queryTokens,
|
|
879
|
+
queryVectors,
|
|
880
|
+
accepted,
|
|
881
|
+
conversationId,
|
|
882
|
+
_nullishCoalesce(scopeRung, () => ( null)),
|
|
883
|
+
maxItems,
|
|
884
|
+
telemetry,
|
|
885
|
+
shares,
|
|
886
|
+
maxResultsPerQuery,
|
|
887
|
+
queryOwners
|
|
888
|
+
);
|
|
943
889
|
}
|
|
944
890
|
if (queryTokens.length === 0) {
|
|
945
891
|
return this.miss(telemetry, "no_query_tokens");
|
|
@@ -996,7 +942,14 @@ var AnticipationCache = (_class2 = class {
|
|
|
996
942
|
return this.miss(telemetry, "no_items_above_threshold");
|
|
997
943
|
}
|
|
998
944
|
picked.sort((a, b) => b.score - a.score);
|
|
999
|
-
|
|
945
|
+
let top = picked.slice(0, maxItems);
|
|
946
|
+
let matched = null;
|
|
947
|
+
if (shares !== null) {
|
|
948
|
+
const perQ = this.bm25PerQuery(shares);
|
|
949
|
+
const indexOf = new Map(this.items.map((it, i) => [it, i]));
|
|
950
|
+
const credit = picked.map(({ item }) => shares.filter((q) => perQ.get(q).scores[indexOf.get(item)] >= perQ.get(q).bar));
|
|
951
|
+
({ kept: top, matched } = reservePerQuery(picked, maxItems, maxResultsPerQuery, shares, credit));
|
|
952
|
+
}
|
|
1000
953
|
const pickedStems = /* @__PURE__ */ new Set();
|
|
1001
954
|
for (const { item } of top) for (const t of item.tokens) pickedStems.add(t);
|
|
1002
955
|
let overlap = 0;
|
|
@@ -1007,7 +960,7 @@ var AnticipationCache = (_class2 = class {
|
|
|
1007
960
|
if (coverageMin !== null && coverage < coverageMin) {
|
|
1008
961
|
return this.miss(telemetry, "coverage_gate");
|
|
1009
962
|
}
|
|
1010
|
-
return this.serve(top, telemetry, coverage, "bm25_score");
|
|
963
|
+
return this.serve(top, telemetry, coverage, "bm25_score", matched);
|
|
1011
964
|
}
|
|
1012
965
|
/**
|
|
1013
966
|
* Match by meaning: a lookup is a hit when an item's cosine to a query
|
|
@@ -1015,7 +968,7 @@ var AnticipationCache = (_class2 = class {
|
|
|
1015
968
|
* or above. An item with no vector yet is matched by BM25 with its novel-term
|
|
1016
969
|
* gate, as before. Python: `_semantic_lookup`, which explains the choices.
|
|
1017
970
|
*/
|
|
1018
|
-
semanticLookup(queryTokens, queryVectors, accepted, conversationId, scopeRung, maxItems, telemetry) {
|
|
971
|
+
semanticLookup(queryTokens, queryVectors, accepted, conversationId, scopeRung, maxItems, telemetry, shares = null, maxResultsPerQuery = null, queryOwners = null) {
|
|
1019
972
|
const model = _nullishCoalesce(_optionalChain([this, 'access', _2 => _2.encoder, 'optionalAccess', _3 => _3.model]), () => ( ""));
|
|
1020
973
|
if (queryTokens.length > 0 && (this.bm25Dirty || this.bm25 === null) && this.items.length > 0) {
|
|
1021
974
|
this.bm25 = new BM25(this.items.map((i) => i.tokens));
|
|
@@ -1080,25 +1033,64 @@ var AnticipationCache = (_class2 = class {
|
|
|
1080
1033
|
(c) => c.score >= this.serveMinCosine || hitBundles.has(c.item.bundleId) && c.score >= this.bundleServeMinCosine
|
|
1081
1034
|
);
|
|
1082
1035
|
served.sort((a, b) => b.score - a.score);
|
|
1083
|
-
const
|
|
1036
|
+
const candidates = [...picked, ...served];
|
|
1037
|
+
let top = candidates.slice(0, maxItems);
|
|
1038
|
+
let matched = null;
|
|
1039
|
+
if (shares !== null) {
|
|
1040
|
+
const owners = _nullishCoalesce(queryOwners, () => ( queryVectors.map((_, i) => _nullishCoalesce(telemetry.searchQuery[i], () => ( "")))));
|
|
1041
|
+
const bar = Math.min(this.minCosine, this.serveMinCosine, this.bundleServeMinCosine);
|
|
1042
|
+
const perQ = this.bm25PerQuery(shares);
|
|
1043
|
+
const indexOf = new Map(this.items.map((it, i) => [it, i]));
|
|
1044
|
+
const credit = candidates.map(({ item }) => {
|
|
1045
|
+
if (item.vec !== null && item.vecModel === model) {
|
|
1046
|
+
const vecs = [item.vec, ...item.qvecs];
|
|
1047
|
+
const best = /* @__PURE__ */ new Map();
|
|
1048
|
+
queryVectors.forEach((qv, j) => {
|
|
1049
|
+
const c = Math.max(...vecs.map((v) => cosine(qv, v)));
|
|
1050
|
+
const owner = _nullishCoalesce(owners[j], () => ( ""));
|
|
1051
|
+
best.set(owner, Math.max(_nullishCoalesce(best.get(owner), () => ( -1)), c));
|
|
1052
|
+
});
|
|
1053
|
+
return shares.filter((q) => (_nullishCoalesce(best.get(q.trim()), () => ( -1))) >= bar);
|
|
1054
|
+
}
|
|
1055
|
+
const idx = indexOf.get(item);
|
|
1056
|
+
return shares.filter((q) => perQ.get(q).scores[idx] >= perQ.get(q).bar);
|
|
1057
|
+
});
|
|
1058
|
+
({ kept: top, matched } = reservePerQuery(candidates, maxItems, maxResultsPerQuery, shares, credit));
|
|
1059
|
+
}
|
|
1084
1060
|
if (this.askedKind) {
|
|
1085
1061
|
const patterns = askedDetailPatterns(telemetry.searchQuery);
|
|
1086
1062
|
if (patterns.length > 0 && !top.some(({ item }) => patterns.some((p) => p.test(item.content)))) {
|
|
1087
1063
|
return this.miss(telemetry, "asked_kind_missing");
|
|
1088
1064
|
}
|
|
1089
1065
|
}
|
|
1090
|
-
const hit = this.serve(top, telemetry, null, "cosine");
|
|
1066
|
+
const hit = this.serve(top, telemetry, null, "cosine", matched);
|
|
1091
1067
|
hit.band = picked[0].score >= this.sureMinCosine ? "sure" : "borderline";
|
|
1092
1068
|
return hit;
|
|
1093
1069
|
}
|
|
1070
|
+
/** Each query's own BM25 scores over every cached item, and its bar. Python: `_bm25_per_query`. */
|
|
1071
|
+
bm25PerQuery(queries) {
|
|
1072
|
+
if ((this.bm25Dirty || this.bm25 === null) && this.items.length > 0) {
|
|
1073
|
+
this.bm25 = new BM25(this.items.map((i) => i.tokens));
|
|
1074
|
+
this.bm25Dirty = false;
|
|
1075
|
+
}
|
|
1076
|
+
const out = /* @__PURE__ */ new Map();
|
|
1077
|
+
for (const q of queries) {
|
|
1078
|
+
const toks = tokenize(q);
|
|
1079
|
+
const scores = toks.length > 0 && this.bm25 ? this.bm25.scores(toks) : this.items.map(() => 0);
|
|
1080
|
+
const bar = Math.max(EFFECTIVE_FLOOR, Math.min(THRESHOLDS.bm25, QUERY_TOKEN_SCALE * Math.max(toks.length, 1)));
|
|
1081
|
+
out.set(q, { scores, bar: toks.length > 0 ? bar : Infinity });
|
|
1082
|
+
}
|
|
1083
|
+
return out;
|
|
1084
|
+
}
|
|
1094
1085
|
/** A hit: renew the leases of the bundles used, report, merge the items. */
|
|
1095
|
-
serve(top, telemetry, coverage, scoreKey) {
|
|
1086
|
+
serve(top, telemetry, coverage, scoreKey, matched = null) {
|
|
1096
1087
|
const itemsByType = {};
|
|
1097
1088
|
const bundleIds = /* @__PURE__ */ new Set();
|
|
1098
|
-
|
|
1099
|
-
(
|
|
1089
|
+
top.forEach(({ item }, i) => {
|
|
1090
|
+
const dict = asServed(item.itemDict, matched === null ? null : matched[i]);
|
|
1091
|
+
(itemsByType[item.itemType] ??= []).push(dict);
|
|
1100
1092
|
bundleIds.add(item.bundleId);
|
|
1101
|
-
}
|
|
1093
|
+
});
|
|
1102
1094
|
const refreshOnHit = !_chunkZKOJDUN4cjs.getEnvFlag.call(void 0, "SYNAP_SDK_CACHE_HONOR_TTL_HINT");
|
|
1103
1095
|
if (refreshOnHit) {
|
|
1104
1096
|
const now = this.now();
|
|
@@ -1381,5 +1373,7 @@ function round4(n) {
|
|
|
1381
1373
|
|
|
1382
1374
|
|
|
1383
1375
|
|
|
1384
|
-
|
|
1385
|
-
|
|
1376
|
+
|
|
1377
|
+
|
|
1378
|
+
exports.CONTRACT = CONTRACT; exports.THRESHOLDS = THRESHOLDS; exports.HISTORY_SEARCH = HISTORY_SEARCH; exports.SEMANTIC_MATCH = SEMANTIC_MATCH; exports.stem = stem; exports.tokenize = tokenize; exports.BM25 = BM25; exports.ANY_SCOPE = ANY_SCOPE; exports.rungKey = rungKey; exports.rungServes = rungServes; exports.unownedElsewhere = unownedElsewhere; exports.canonicalQuery = canonicalQuery; exports.asServed = asServed; exports.MATCHERS = MATCHERS; exports.distinctQueries = distinctQueries; exports.reservePerQuery = reservePerQuery; exports.AnticipationCache = AnticipationCache;
|
|
1379
|
+
//# sourceMappingURL=chunk-BYUGILQI.cjs.map
|