@theokit/sdk 3.2.0 → 3.2.3

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/cron.cjs CHANGED
@@ -4747,7 +4747,14 @@ var init_env_policy = __esm({
4747
4747
  /[_-]PWD/i,
4748
4748
  /CREDENTIAL/i,
4749
4749
  /PRIVATE/i,
4750
- /_AUTH/i
4750
+ /_AUTH/i,
4751
+ // #54-a — value-embedded-secret conventions (no generic `*_URL` — see keep-list test).
4752
+ /DSN/i,
4753
+ /WEBHOOK/i,
4754
+ /COOKIE/i,
4755
+ /CONNECTION[_-]?STRING/i,
4756
+ // Known DB / message-broker connection-string vars (carry `user:pass@`).
4757
+ /(?:^|[_-])(?:DATABASE|DB|REDIS|MONGO(?:DB)?|POSTGRES(?:QL)?|MYSQL|MARIADB|AMQP|RABBITMQ|CLICKHOUSE|ELASTIC(?:SEARCH)?|CASSANDRA|COUCHDB|MEMCACHED|NATS|KAFKA)[_-]?(?:URL|URI|DSN|CONNECTION)/i
4751
4758
  ];
4752
4759
  CORE_VARS = [
4753
4760
  "PATH",
@@ -5156,12 +5163,23 @@ var init_objective_coerce = __esm({
5156
5163
  // src/internal/persistence/pagination.ts
5157
5164
  function paginate(items, opts) {
5158
5165
  if (opts === void 0 || opts.offset === void 0 && opts.limit === void 0) return items;
5159
- const start = Math.max(0, opts.offset ?? 0);
5160
- const end = opts.limit === void 0 ? items.length : start + Math.max(0, opts.limit);
5166
+ const start = opts.offset === void 0 ? 0 : requireNonNegativeInt(opts.offset, "offset");
5167
+ const limit = opts.limit === void 0 ? void 0 : requireNonNegativeInt(opts.limit, "limit");
5168
+ const end = limit === void 0 ? items.length : start + limit;
5161
5169
  return items.slice(start, end);
5162
5170
  }
5171
+ function requireNonNegativeInt(value, field) {
5172
+ if (!Number.isInteger(value) || value < 0) {
5173
+ throw new ConfigurationError(
5174
+ `Invalid pagination ${field}: expected a non-negative integer, got ${value}`,
5175
+ { code: "pagination_invalid" }
5176
+ );
5177
+ }
5178
+ return value;
5179
+ }
5163
5180
  var init_pagination = __esm({
5164
5181
  "src/internal/persistence/pagination.ts"() {
5182
+ init_errors();
5165
5183
  }
5166
5184
  });
5167
5185
 
@@ -7744,15 +7762,19 @@ async function collectChildToolResults(run) {
7744
7762
  ${lines.join("\n")}
7745
7763
  </subagent-tool-results>`;
7746
7764
  }
7747
- async function runChildAgent(spec, input, signal, maxSteps, inherited) {
7748
- const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
7765
+ function buildChildCreateOptions(spec, inherited) {
7749
7766
  const model = spec.model ? { id: spec.model } : inherited?.model;
7750
- const agent = await Agent2.create({
7767
+ return {
7751
7768
  ...inherited?.apiKey !== void 0 ? { apiKey: inherited.apiKey } : {},
7752
7769
  ...model !== void 0 ? { model } : {},
7770
+ ...inherited?.plugins !== void 0 ? { plugins: inherited.plugins } : {},
7753
7771
  systemPrompt: spec.instructions,
7754
7772
  tools: spec.tools ?? []
7755
- });
7773
+ };
7774
+ }
7775
+ async function runChildAgent(spec, input, signal, maxSteps, inherited) {
7776
+ const { Agent: Agent2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
7777
+ const agent = await Agent2.create(buildChildCreateOptions(spec, inherited));
7756
7778
  try {
7757
7779
  const sendOptions = {
7758
7780
  ...signal !== void 0 ? { signal } : {},
@@ -9655,7 +9677,10 @@ async function runAgentLoop(inputs) {
9655
9677
  }
9656
9678
  budget.consume();
9657
9679
  inputs.budgetTracker?.nextIteration?.();
9658
- if (inputs.signal?.aborted === true) break;
9680
+ if (inputs.signal?.aborted === true) {
9681
+ ctx.finalStatus = "cancelled";
9682
+ break;
9683
+ }
9659
9684
  }
9660
9685
  if (lastTurnDecision === "continue" && budget.shouldContinue() === false) {
9661
9686
  ctx.stoppedAtIterationLimit = true;
@@ -9840,15 +9865,15 @@ async function guardAndTransformToolResults(inputs, raw, ctx) {
9840
9865
  }
9841
9866
  async function continueOrTerminate(inputs, ctx, llmOutput) {
9842
9867
  if (llmOutput.errored) return "error";
9843
- if (llmOutput.text.length > 0) {
9844
- await emitAssistantTextStep(inputs, ctx, llmOutput.text);
9868
+ const tCtx = { agentId: inputs.agentId, runId: inputs.runId };
9869
+ const text = llmOutput.text.length > 0 ? await transformLlmOutputText(inputs, llmOutput.text, tCtx) : llmOutput.text;
9870
+ if (text.length > 0) {
9871
+ await emitAssistantTextStep(inputs, ctx, text);
9845
9872
  }
9846
9873
  if (llmOutput.stopReason !== "tool_use" || llmOutput.toolCalls.length === 0) {
9847
9874
  return finishOrReflect(inputs, ctx, llmOutput);
9848
9875
  }
9849
- const tCtx = { agentId: inputs.agentId, runId: inputs.runId };
9850
- const outText = await transformLlmOutputText(inputs, llmOutput.text, tCtx);
9851
- ctx.messages.push(buildAssistantTurn(outText, llmOutput.toolCalls));
9876
+ ctx.messages.push(buildAssistantTurn(text, llmOutput.toolCalls));
9852
9877
  const rawResults = await dispatchTools(
9853
9878
  // SE12 — forward a read-only text projection of the transcript-so-far to tool
9854
9879
  // handlers via `ctx.messages` (consumed by defineSubAgent's messageFilter).
@@ -10312,6 +10337,8 @@ function parseRetryAfter(headers) {
10312
10337
  if (raw === null) return void 0;
10313
10338
  const n = Number(raw);
10314
10339
  if (Number.isFinite(n) && n >= 0) return Math.ceil(n);
10340
+ const dateMs = Date.parse(raw);
10341
+ if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1e3));
10315
10342
  return void 0;
10316
10343
  }
10317
10344
  function truncateRaw(body) {
@@ -10632,6 +10659,7 @@ function buildAnthropicBody(request) {
10632
10659
  var AnthropicClient, AnthropicStreamAccumulator;
10633
10660
  var init_anthropic3 = __esm({
10634
10661
  "src/internal/llm/anthropic.ts"() {
10662
+ init_errors();
10635
10663
  init_anthropic2();
10636
10664
  init_anthropic_shared();
10637
10665
  init_finish();
@@ -10685,12 +10713,23 @@ var init_anthropic3 = __esm({
10685
10713
  const events = accumulator.consume(parsed);
10686
10714
  for (const event of events) yield event;
10687
10715
  }
10716
+ if (!accumulator.finishReasonSeen) {
10717
+ throw new NetworkError("Anthropic SSE stream truncated (no stop_reason)", {
10718
+ code: "stream_truncated"
10719
+ });
10720
+ }
10688
10721
  return accumulator.finish();
10689
10722
  }
10690
10723
  };
10691
10724
  AnthropicStreamAccumulator = class {
10692
10725
  text = "";
10693
10726
  stopReason = "end_turn";
10727
+ /**
10728
+ * M2 #61 — whether a `message_delta` carrying a real `stop_reason` was seen.
10729
+ * A stream that closes before it is a truncation (server FIN / proxy hiccup),
10730
+ * not a clean `end_turn` — the caller throws `stream_truncated` on `false`.
10731
+ */
10732
+ sawStopReason = false;
10694
10733
  inputTokens;
10695
10734
  outputTokens;
10696
10735
  cacheReadTokens;
@@ -10737,6 +10776,9 @@ var init_anthropic3 = __esm({
10737
10776
  * spinning the SSE parser.
10738
10777
  */
10739
10778
  handleMessageDelta(md) {
10779
+ if (md.delta.stop_reason !== void 0 && md.delta.stop_reason !== null) {
10780
+ this.sawStopReason = true;
10781
+ }
10740
10782
  this.stopReason = mapAnthropicStopReason(md.delta.stop_reason);
10741
10783
  if (md.usage?.input_tokens !== void 0) this.inputTokens = md.usage.input_tokens;
10742
10784
  if (md.usage?.output_tokens !== void 0) this.outputTokens = md.usage.output_tokens;
@@ -10747,6 +10789,10 @@ var init_anthropic3 = __esm({
10747
10789
  this.cacheReadTokens = md.usage.cache_read_input_tokens;
10748
10790
  }
10749
10791
  }
10792
+ /** M2 #61 — whether the terminal `message_delta` (stop_reason) was seen. */
10793
+ get finishReasonSeen() {
10794
+ return this.sawStopReason;
10795
+ }
10750
10796
  finish() {
10751
10797
  const toolCalls = [];
10752
10798
  for (const [index, tool] of this.toolCalls.entries()) {
@@ -12980,7 +13026,6 @@ var init_client = __esm({
12980
13026
  // concurrent request so parallel tool dispatch after a drop awaits one handshake
12981
13027
  // instead of racing (or spuriously failing with mcp_not_init).
12982
13028
  dropped = false;
12983
- reconnectAttempts = 0;
12984
13029
  reconnectPromise;
12985
13030
  get timeoutMs() {
12986
13031
  return this.config.requestTimeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;
@@ -13033,15 +13078,22 @@ var init_client = __esm({
13033
13078
  return this.reconnectPromise;
13034
13079
  }
13035
13080
  async reconnect() {
13036
- if (this.reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
13037
- throw new NetworkError(`MCP ${this.name} reconnect exhausted`, { code: "mcp_disconnected" });
13081
+ let lastErr;
13082
+ for (let attempt = 0; attempt < MAX_RECONNECT_ATTEMPTS; attempt += 1) {
13083
+ await reconnectDelay(attempt);
13084
+ this.spawnChild();
13085
+ try {
13086
+ await super.initialize();
13087
+ this.dropped = false;
13088
+ return;
13089
+ } catch (err) {
13090
+ lastErr = err;
13091
+ }
13038
13092
  }
13039
- await reconnectDelay(this.reconnectAttempts);
13040
- this.reconnectAttempts += 1;
13041
- this.spawnChild();
13042
- await super.initialize();
13043
- this.dropped = false;
13044
- this.reconnectAttempts = 0;
13093
+ throw new NetworkError(`MCP ${this.name} reconnect exhausted`, {
13094
+ code: "mcp_disconnected",
13095
+ ...lastErr instanceof Error ? { cause: lastErr } : {}
13096
+ });
13045
13097
  }
13046
13098
  async close() {
13047
13099
  this.rejectAllPending(new NetworkError(`MCP ${this.name} closed`, { code: "mcp_closed" }));
@@ -13172,7 +13224,12 @@ var init_client = __esm({
13172
13224
  code: "mcp_http_error"
13173
13225
  });
13174
13226
  }
13175
- return await response.json();
13227
+ try {
13228
+ return await response.json();
13229
+ } catch (cause) {
13230
+ if (isAbortLike(cause)) throw mcpTimeoutError(this.name, timeoutMs);
13231
+ throw cause;
13232
+ }
13176
13233
  }
13177
13234
  };
13178
13235
  }
@@ -13412,9 +13469,11 @@ function declarativeSubagentTools(agentOptions, parentTools) {
13412
13469
  return subAgentToolsFromDefinitions(agents2, parentTools);
13413
13470
  }
13414
13471
  function bindParentCredentials(tools, agentOptions) {
13472
+ const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : void 0;
13415
13473
  const credentials = {
13416
13474
  ...agentOptions.apiKey !== void 0 ? { apiKey: agentOptions.apiKey } : {},
13417
- ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {}
13475
+ ...typeof agentOptions.model === "object" ? { model: agentOptions.model } : {},
13476
+ ...parentPlugins !== void 0 ? { plugins: parentPlugins } : {}
13418
13477
  };
13419
13478
  for (const tool of tools) inheritSubAgentCredentials(tool, credentials);
13420
13479
  }
@@ -15939,10 +15998,11 @@ var init_local_agent_memory = __esm({
15939
15998
  }
15940
15999
  buildTelemetryRecallArgs(telemetry) {
15941
16000
  const userId = typeof this.options.memoryContext?.userId === "string" ? this.options.memoryContext.userId : void 0;
16001
+ const tenantId = typeof this.options.memoryContext?.tenantId === "string" ? this.options.memoryContext.tenantId : void 0;
15942
16002
  return {
15943
16003
  ...telemetry !== void 0 ? { telemetry } : {},
15944
16004
  ...userId !== void 0 ? { userId } : {},
15945
- namespace: "default",
16005
+ namespace: tenantId ?? "default",
15946
16006
  scope: "session"
15947
16007
  };
15948
16008
  }