@theokit/sdk 4.19.0 → 4.19.2

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
@@ -6171,12 +6171,14 @@ __export(compact_session_exports, {
6171
6171
  shouldAutoCompact: () => shouldAutoCompact
6172
6172
  });
6173
6173
  function isCompactSummary(content) {
6174
- return content.startsWith(COMPACT_SUMMARY_MARKER);
6174
+ return content.startsWith(COMPACT_SUMMARY_MARKER) || content.startsWith("[[theokit:goal-continuation]]");
6175
6175
  }
6176
6176
  function plainText(content) {
6177
6177
  if (typeof content === "string") return content;
6178
6178
  if (!Array.isArray(content)) return void 0;
6179
- const texts = content.filter((p) => p !== null && typeof p === "object" && p.type === "text" && typeof p.text === "string").map((p) => p.text);
6179
+ const texts = content.filter(
6180
+ (p) => p !== null && typeof p === "object" && p.type === "text" && typeof p.text === "string"
6181
+ ).map((p) => p.text);
6180
6182
  return texts.length > 0 ? texts.join("\n") : void 0;
6181
6183
  }
6182
6184
  async function compactSessionTranscript(opts) {
@@ -6297,8 +6299,10 @@ async function autoCompactIfNeeded(opts) {
6297
6299
  return true;
6298
6300
  } catch (cause) {
6299
6301
  const msg = cause instanceof Error ? cause.message : String(cause);
6300
- process.stderr.write(`[theokit-sdk] auto-compaction failed (left transcript untouched): ${msg}
6301
- `);
6302
+ process.stderr.write(
6303
+ `[theokit-sdk] auto-compaction failed (left transcript untouched): ${msg}
6304
+ `
6305
+ );
6302
6306
  return false;
6303
6307
  }
6304
6308
  }
@@ -6308,11 +6312,11 @@ var init_compact_session = __esm({
6308
6312
  init_compaction();
6309
6313
  init_router();
6310
6314
  init_real_local_run_provider();
6315
+ init_session_transcript();
6311
6316
  init_providers();
6312
6317
  init_compression_model_registry();
6313
6318
  init_compression_summarizer();
6314
6319
  init_agent_session();
6315
- init_session_transcript();
6316
6320
  COMPACT_SUMMARY_MARKER = "[[theokit:compact-summary]]";
6317
6321
  COMPACT_USER_MESSAGE_MAX_TOKENS = 2e4;
6318
6322
  autoCompactAttempts = (() => {
@@ -6534,7 +6538,9 @@ async function loadDriver(filePath) {
6534
6538
  }
6535
6539
  try {
6536
6540
  const mod = await (driverLoaderOverrides?.nodeSqlite?.() ?? Promise.resolve(
6537
- process.getBuiltinModule?.("node:sqlite") ?? (() => {
6541
+ process.getBuiltinModule?.(
6542
+ "node:sqlite"
6543
+ ) ?? (() => {
6538
6544
  throw new Error("node:sqlite built-in unavailable (Node < 22.3)");
6539
6545
  })()
6540
6546
  ));
@@ -7501,6 +7507,133 @@ var init_context = __esm({
7501
7507
  }
7502
7508
  });
7503
7509
 
7510
+ // src/internal/judge/parse-verdict.ts
7511
+ function parseVerdict(text) {
7512
+ const trimmed = text.trim();
7513
+ if (trimmed.startsWith(DONE_PREFIX)) {
7514
+ return {
7515
+ verdict: "done",
7516
+ reason: trimmed.slice(DONE_PREFIX.length).trim(),
7517
+ parseFailed: false
7518
+ };
7519
+ }
7520
+ if (trimmed.startsWith(CONTINUE_PREFIX)) {
7521
+ return {
7522
+ verdict: "continue",
7523
+ reason: trimmed.slice(CONTINUE_PREFIX.length).trim(),
7524
+ parseFailed: false
7525
+ };
7526
+ }
7527
+ if (trimmed.startsWith(SKIPPED_PREFIX)) {
7528
+ return {
7529
+ verdict: "skipped",
7530
+ reason: trimmed.slice(SKIPPED_PREFIX.length).trim(),
7531
+ parseFailed: false
7532
+ };
7533
+ }
7534
+ return {
7535
+ verdict: "continue",
7536
+ reason: `judge response malformed: "${trimmed.slice(0, 100)}"`,
7537
+ parseFailed: true
7538
+ };
7539
+ }
7540
+ var DONE_PREFIX, CONTINUE_PREFIX, SKIPPED_PREFIX;
7541
+ var init_parse_verdict = __esm({
7542
+ "src/internal/judge/parse-verdict.ts"() {
7543
+ DONE_PREFIX = "DONE:";
7544
+ CONTINUE_PREFIX = "CONTINUE:";
7545
+ SKIPPED_PREFIX = "SKIPPED:";
7546
+ }
7547
+ });
7548
+
7549
+ // src/internal/judge/judge-call.ts
7550
+ var judge_call_exports = {};
7551
+ __export(judge_call_exports, {
7552
+ composeJudgePrompt: () => composeJudgePrompt,
7553
+ judgeCallImpl: () => judgeCallImpl
7554
+ });
7555
+ async function judgeCallImpl(ctx, options, deps) {
7556
+ const prompt = composeJudgePrompt(ctx);
7557
+ const apiKey = options?.apiKey ?? process.env.OPENROUTER_API_KEY;
7558
+ if (apiKey === void 0) {
7559
+ return {
7560
+ verdict: "continue",
7561
+ reason: "judge unavailable: OPENROUTER_API_KEY missing and no override passed via options.apiKey",
7562
+ parseFailed: true
7563
+ };
7564
+ }
7565
+ const judgeModel = options?.judgeModel ?? "openai/gpt-4o-mini";
7566
+ let auxAgent;
7567
+ try {
7568
+ auxAgent = await deps.create({
7569
+ apiKey,
7570
+ model: { id: judgeModel },
7571
+ tools: [],
7572
+ local: {},
7573
+ metadata: { forkOrigin: "judge" }
7574
+ });
7575
+ const run = await auxAgent.send(prompt);
7576
+ const result = await run.wait();
7577
+ return parseVerdict(result.result ?? "");
7578
+ } catch (err) {
7579
+ return {
7580
+ verdict: "continue",
7581
+ reason: `judge call failed: ${err instanceof Error ? err.message : String(err)}`,
7582
+ parseFailed: true
7583
+ };
7584
+ } finally {
7585
+ if (auxAgent !== void 0) {
7586
+ try {
7587
+ await auxAgent.dispose();
7588
+ } catch {
7589
+ }
7590
+ }
7591
+ }
7592
+ }
7593
+ function composeJudgePrompt(ctx) {
7594
+ const subgoals = ctx.subgoals !== void 0 && ctx.subgoals.length > 0 ? ctx.subgoals.join(", ") : "(none)";
7595
+ return `You are a goal judge. Determine if this goal is satisfied.
7596
+
7597
+ Goal: ${ctx.goal}
7598
+ Subgoals: ${subgoals}
7599
+ Last agent response: ${ctx.lastResponse}
7600
+
7601
+ Respond with EXACTLY one of:
7602
+ - DONE: <reason>
7603
+ - CONTINUE: <what's left>
7604
+ - SKIPPED: <why not applicable>
7605
+
7606
+ Be strict. If unclear, prefer CONTINUE.`;
7607
+ }
7608
+ var init_judge_call = __esm({
7609
+ "src/internal/judge/judge-call.ts"() {
7610
+ init_parse_verdict();
7611
+ }
7612
+ });
7613
+
7614
+ // src/goal-loop.ts
7615
+ function runGoalLoop(agent, goal, options, depsOverride) {
7616
+ async function* wrap() {
7617
+ const { runUntilImpl: runUntilImpl2 } = await Promise.resolve().then(() => (init_run_until(), run_until_exports));
7618
+ const deps = depsOverride ?? await (async () => {
7619
+ const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
7620
+ const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
7621
+ const create = getAgentFacade2().create;
7622
+ return {
7623
+ judge: (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
7624
+ };
7625
+ })();
7626
+ return yield* runUntilImpl2(agent, goal, options, deps);
7627
+ }
7628
+ return wrap();
7629
+ }
7630
+ var GOAL_CONTINUATION_MARKER;
7631
+ var init_goal_loop = __esm({
7632
+ "src/goal-loop.ts"() {
7633
+ GOAL_CONTINUATION_MARKER = "[[theokit:goal-continuation]]";
7634
+ }
7635
+ });
7636
+
7504
7637
  // src/internal/runtime/lifecycle/run-until.ts
7505
7638
  var run_until_exports = {};
7506
7639
  __export(run_until_exports, {
@@ -7644,6 +7777,7 @@ async function* runUntilImpl(agent, goal, options, deps) {
7644
7777
  }
7645
7778
  function composeContinuation(goal, lastResponse) {
7646
7779
  return [
7780
+ GOAL_CONTINUATION_MARKER,
7647
7781
  "Continue working toward the active goal.",
7648
7782
  "",
7649
7783
  `<objective>
@@ -7664,115 +7798,12 @@ ${goal}
7664
7798
  " current state, requirement by requirement. Treat uncertain or indirect evidence as not achieved.",
7665
7799
  "",
7666
7800
  `Your last response was:
7667
- ${lastResponse.slice(0, 1e3)}`
7801
+ ${lastResponse.slice(-1e3)}`
7668
7802
  ].join("\n");
7669
7803
  }
7670
7804
  var init_run_until = __esm({
7671
7805
  "src/internal/runtime/lifecycle/run-until.ts"() {
7672
- }
7673
- });
7674
-
7675
- // src/internal/judge/parse-verdict.ts
7676
- function parseVerdict(text) {
7677
- const trimmed = text.trim();
7678
- if (trimmed.startsWith(DONE_PREFIX)) {
7679
- return {
7680
- verdict: "done",
7681
- reason: trimmed.slice(DONE_PREFIX.length).trim(),
7682
- parseFailed: false
7683
- };
7684
- }
7685
- if (trimmed.startsWith(CONTINUE_PREFIX)) {
7686
- return {
7687
- verdict: "continue",
7688
- reason: trimmed.slice(CONTINUE_PREFIX.length).trim(),
7689
- parseFailed: false
7690
- };
7691
- }
7692
- if (trimmed.startsWith(SKIPPED_PREFIX)) {
7693
- return {
7694
- verdict: "skipped",
7695
- reason: trimmed.slice(SKIPPED_PREFIX.length).trim(),
7696
- parseFailed: false
7697
- };
7698
- }
7699
- return {
7700
- verdict: "continue",
7701
- reason: `judge response malformed: "${trimmed.slice(0, 100)}"`,
7702
- parseFailed: true
7703
- };
7704
- }
7705
- var DONE_PREFIX, CONTINUE_PREFIX, SKIPPED_PREFIX;
7706
- var init_parse_verdict = __esm({
7707
- "src/internal/judge/parse-verdict.ts"() {
7708
- DONE_PREFIX = "DONE:";
7709
- CONTINUE_PREFIX = "CONTINUE:";
7710
- SKIPPED_PREFIX = "SKIPPED:";
7711
- }
7712
- });
7713
-
7714
- // src/internal/judge/judge-call.ts
7715
- var judge_call_exports = {};
7716
- __export(judge_call_exports, {
7717
- composeJudgePrompt: () => composeJudgePrompt,
7718
- judgeCallImpl: () => judgeCallImpl
7719
- });
7720
- async function judgeCallImpl(ctx, options, deps) {
7721
- const prompt = composeJudgePrompt(ctx);
7722
- const apiKey = options?.apiKey ?? process.env.OPENROUTER_API_KEY;
7723
- if (apiKey === void 0) {
7724
- return {
7725
- verdict: "continue",
7726
- reason: "judge unavailable: OPENROUTER_API_KEY missing and no override passed via options.apiKey",
7727
- parseFailed: true
7728
- };
7729
- }
7730
- const judgeModel = options?.judgeModel ?? "openai/gpt-4o-mini";
7731
- let auxAgent;
7732
- try {
7733
- auxAgent = await deps.create({
7734
- apiKey,
7735
- model: { id: judgeModel },
7736
- tools: [],
7737
- local: {},
7738
- metadata: { forkOrigin: "judge" }
7739
- });
7740
- const run = await auxAgent.send(prompt);
7741
- const result = await run.wait();
7742
- return parseVerdict(result.result ?? "");
7743
- } catch (err) {
7744
- return {
7745
- verdict: "continue",
7746
- reason: `judge call failed: ${err instanceof Error ? err.message : String(err)}`,
7747
- parseFailed: true
7748
- };
7749
- } finally {
7750
- if (auxAgent !== void 0) {
7751
- try {
7752
- await auxAgent.dispose();
7753
- } catch {
7754
- }
7755
- }
7756
- }
7757
- }
7758
- function composeJudgePrompt(ctx) {
7759
- const subgoals = ctx.subgoals !== void 0 && ctx.subgoals.length > 0 ? ctx.subgoals.join(", ") : "(none)";
7760
- return `You are a goal judge. Determine if this goal is satisfied.
7761
-
7762
- Goal: ${ctx.goal}
7763
- Subgoals: ${subgoals}
7764
- Last agent response: ${ctx.lastResponse}
7765
-
7766
- Respond with EXACTLY one of:
7767
- - DONE: <reason>
7768
- - CONTINUE: <what's left>
7769
- - SKIPPED: <why not applicable>
7770
-
7771
- Be strict. If unclear, prefer CONTINUE.`;
7772
- }
7773
- var init_judge_call = __esm({
7774
- "src/internal/judge/judge-call.ts"() {
7775
- init_parse_verdict();
7806
+ init_goal_loop();
7776
7807
  }
7777
7808
  });
7778
7809
 
@@ -21312,8 +21343,8 @@ async function getRegisteredAgentOrThrow(agentId) {
21312
21343
  // src/agent.ts
21313
21344
  init_errors();
21314
21345
  init_discovery();
21315
- init_agent_session();
21316
21346
  init_agent_factory_registry();
21347
+ init_agent_session();
21317
21348
  var streamObjectImport;
21318
21349
  var Agent = class _Agent {
21319
21350
  constructor() {
@@ -21605,7 +21636,9 @@ var Agent = class _Agent {
21605
21636
  reg = getRegisteredAgent(agentId);
21606
21637
  }
21607
21638
  if (reg === void 0 || reg.runtime !== "local") {
21608
- throw new UnknownAgentError(`No local agent "${agentId}" registered \u2014 compact targets local sessions.`);
21639
+ throw new UnknownAgentError(
21640
+ `No local agent "${agentId}" registered \u2014 compact targets local sessions.`
21641
+ );
21609
21642
  }
21610
21643
  const cwd = reg.cwd ?? process.cwd();
21611
21644
  const optModel = reg.options.model;
@@ -21615,16 +21648,20 @@ var Agent = class _Agent {
21615
21648
  const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await Promise.resolve().then(() => (init_session_transcript(), session_transcript_exports));
21616
21649
  const baseDir = reg.options.local?.baseDir !== void 0 ? expandTilde2(reg.options.local.baseDir) : defaultBaseDir2();
21617
21650
  const store = new FsSessionStore2({ baseDir, cwd });
21618
- return enqueueSessionWrite(cwd, agentId, () => compactSessionTranscript2({
21619
- store,
21620
- loc: { cwd, agentId, model },
21621
- sessionId: agentId,
21622
- trigger: options.trigger ?? "manual",
21623
- summarize: options.summarize ?? buildDefaultSummarizer2({
21624
- agentModel: model,
21625
- ...reg.options.apiKey !== void 0 ? { apiKey: reg.options.apiKey } : {}
21651
+ return enqueueSessionWrite(
21652
+ cwd,
21653
+ agentId,
21654
+ () => compactSessionTranscript2({
21655
+ store,
21656
+ loc: { cwd, agentId, model },
21657
+ sessionId: agentId,
21658
+ trigger: options.trigger ?? "manual",
21659
+ summarize: options.summarize ?? buildDefaultSummarizer2({
21660
+ agentModel: model,
21661
+ ...reg.options.apiKey !== void 0 ? { apiKey: reg.options.apiKey } : {}
21662
+ })
21626
21663
  })
21627
- }));
21664
+ );
21628
21665
  }
21629
21666
  /**
21630
21667
  * M51 — inject a SYNTHETIC user+assistant pair into a LOCAL session's persisted transcript WITHOUT
@@ -21641,7 +21678,9 @@ var Agent = class _Agent {
21641
21678
  reg = getRegisteredAgent(agentId);
21642
21679
  }
21643
21680
  if (reg === void 0 || reg.runtime !== "local") {
21644
- throw new UnknownAgentError(`No local agent "${agentId}" registered \u2014 injectSessionTurn targets local sessions.`);
21681
+ throw new UnknownAgentError(
21682
+ `No local agent "${agentId}" registered \u2014 injectSessionTurn targets local sessions.`
21683
+ );
21645
21684
  }
21646
21685
  const cwd = reg.cwd ?? process.cwd();
21647
21686
  const optModel = reg.options.model;
@@ -22667,23 +22706,6 @@ async function updateJobStatus(jobId, enabled) {
22667
22706
  return updated;
22668
22707
  }
22669
22708
 
22670
- // src/goal-loop.ts
22671
- function runGoalLoop(agent, goal, options, depsOverride) {
22672
- async function* wrap() {
22673
- const { runUntilImpl: runUntilImpl2 } = await Promise.resolve().then(() => (init_run_until(), run_until_exports));
22674
- const deps = depsOverride ?? await (async () => {
22675
- const { judgeCallImpl: judgeCallImpl2 } = await Promise.resolve().then(() => (init_judge_call(), judge_call_exports));
22676
- const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
22677
- const create = getAgentFacade2().create;
22678
- return {
22679
- judge: (ctx, opts) => judgeCallImpl2(ctx, opts, { create })
22680
- };
22681
- })();
22682
- return yield* runUntilImpl2(agent, goal, options, deps);
22683
- }
22684
- return wrap();
22685
- }
22686
-
22687
22709
  // src/define-provider.ts
22688
22710
  init_builtin();
22689
22711
  init_registry();
@@ -22823,6 +22845,7 @@ var EventBus = class {
22823
22845
 
22824
22846
  // src/index.ts
22825
22847
  init_generate_object();
22848
+ init_goal_loop();
22826
22849
 
22827
22850
  // src/internal/budget/tracker/budget-tracker-counter.ts
22828
22851
  function createCounterBudgetTracker(options = {}) {
@@ -24519,6 +24542,6 @@ function safeStringify2(v) {
24519
24542
  // src/index.ts
24520
24543
  init_run_events();
24521
24544
 
24522
- export { Agent, AgentBuilder, AgentDisposedError, AgentFactory, AgentRunError, AuthenticationError, Budget, BudgetExceededError, ConfigurationError, Cron, EventBus, GenerateObjectError, IntegrationNotConnectedError, InvalidTaskIdError, JobQueue, Memory, MemoryAdapterError, NetworkError, NoopMemoryProvider, PermissionEngine, PermissionPlugin, Plugin, Provider, RateLimitError, Security, Skill, SkillReadTool, Squad, StreamObjectError, Task, TaskNotFoundError, Theokit, TheokitAgentError, TokenLimiter, Tool, ToolError, UnicodeNormalizer, UnknownAgentError, UnsupportedBudgetOperationError, UnsupportedRunOperationError, UnsupportedTaskOperationError, UsageAccumulator, applyMode, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, emitRunEvent, estimateTokens2 as estimateTokens, extractRawId, getPricingEntry, inferApiMode, isTransientError, migrateSqliteToLance2 as migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, preflightCheck, runGoalLoop, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, withCwdMutex };
24545
+ export { Agent, AgentBuilder, AgentDisposedError, AgentFactory, AgentRunError, AuthenticationError, Budget, BudgetExceededError, ConfigurationError, Cron, EventBus, GOAL_CONTINUATION_MARKER, GenerateObjectError, IntegrationNotConnectedError, InvalidTaskIdError, JobQueue, Memory, MemoryAdapterError, NetworkError, NoopMemoryProvider, PermissionEngine, PermissionPlugin, Plugin, Provider, RateLimitError, Security, Skill, SkillReadTool, Squad, StreamObjectError, Task, TaskNotFoundError, Theokit, TheokitAgentError, TokenLimiter, Tool, ToolError, UnicodeNormalizer, UnknownAgentError, UnsupportedBudgetOperationError, UnsupportedRunOperationError, UnsupportedTaskOperationError, UsageAccumulator, applyMode, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, emitRunEvent, estimateTokens2 as estimateTokens, extractRawId, getPricingEntry, inferApiMode, isTransientError, migrateSqliteToLance2 as migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, preflightCheck, runGoalLoop, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, withCwdMutex };
24523
24546
  //# sourceMappingURL=index.js.map
24524
24547
  //# sourceMappingURL=index.js.map