@theokit/sdk 4.27.0 → 4.28.0
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/{chunk-WBBYSW3Q.cjs → chunk-I53QDJVI.cjs} +5 -5
- package/dist/{chunk-WBBYSW3Q.cjs.map → chunk-I53QDJVI.cjs.map} +1 -1
- package/dist/{chunk-OX772BEW.js → chunk-PF5Y5BHG.js} +3 -3
- package/dist/{chunk-OX772BEW.js.map → chunk-PF5Y5BHG.js.map} +1 -1
- package/dist/{chunk-TMNS2LOS.cjs → chunk-PN53WGEI.cjs} +5 -5
- package/dist/{chunk-TMNS2LOS.cjs.map → chunk-PN53WGEI.cjs.map} +1 -1
- package/dist/{chunk-6M76Z3AI.js → chunk-XW6RXVGB.js} +3 -3
- package/dist/{chunk-6M76Z3AI.js.map → chunk-XW6RXVGB.js.map} +1 -1
- package/dist/{cron-DPUZzncH.d.ts → cron-BN6JJlDw.d.ts} +8 -0
- package/dist/{cron-DzZ9TMa2.d.cts → cron-CoQREV_k.d.cts} +8 -0
- package/dist/cron.cjs +3 -3
- package/dist/cron.d.cts +1 -1
- package/dist/cron.d.ts +1 -1
- package/dist/cron.js +2 -2
- package/dist/errors.d.ts +3 -424
- package/dist/eval.cjs +2 -2
- package/dist/eval.js +1 -1
- package/dist/index.cjs +21 -21
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -4
- package/dist/{run-until-K7IO7ZPQ.js → run-until-YZ2ODWOF.js} +3 -2
- package/dist/run-until-YZ2ODWOF.js.map +1 -0
- package/dist/{run-until-ZD4PRLNJ.cjs → run-until-ZZ2JLPJM.cjs} +3 -2
- package/dist/run-until-ZZ2JLPJM.cjs.map +1 -0
- package/dist/server/auth/index.d.cts +207 -11
- package/dist/server/auth/index.d.ts +207 -11
- package/dist/server/errors-envelope.d.cts +12 -6
- package/dist/server/errors-envelope.d.ts +12 -6
- package/dist/types/goal-events.d.ts +8 -0
- package/package.json +1 -1
- package/dist/run-until-K7IO7ZPQ.js.map +0 -1
- package/dist/run-until-ZD4PRLNJ.cjs.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot, E as ErrorMetadata } from './errors-BdL-buYn.cjs';
|
|
2
2
|
export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, m as ErrorCode, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-BdL-buYn.cjs';
|
|
3
|
-
import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as Plugin$1, m as ProviderProfile, I as InlineSkill, J as JudgeResult, n as GoalOptions, o as GoalEvent, p as GoalResult, B as BudgetTracker, q as MemoryProvider, r as MemoryId, s as PreToolCallDecision, t as StepResult, u as SDKProvider } from './cron-
|
|
4
|
-
export { v as ActiveMemoryPassArgs, w as ActiveMemoryPassResult, x as AgentMemory, y as BudgetCheck, z as BudgetTotal, D as BudgetUsageEvent, E as CloudEnv, F as CloudRepo, H as ContextBudget, K as ContextManagerKind, N as ContextSnapshot, O as ContextSource, Q as ContextSourceStatus, R as CreateSkillSpec, T as Cron, U as CronCreateOptions, V as CronGetOptions, W as CronJob, X as CronJobStatus, Y as CronListOptions, Z as CronOperationOptions, _ as CronRunOptions, $ as CronRuntime, a0 as CronSchedulerStatus, a1 as CronStartOptions, a2 as HookName, a3 as InvalidateCacheOptions, a4 as MemoryAdapter, a5 as MemoryAdapterCapabilities, a6 as MemoryContext, a7 as MemoryFact, a8 as MemoryProviderHandle, a9 as MemoryProviderInitOptions, aa as MemoryRevision, ab as MemoryToolSchema, ac as MemoryTurnMessage, ad as PersonalityPreset, ae as PluginContext, af as PostAssistantReplyContext, ag as PreToolCallContext, ah as PreUserSendContext, ai as PreUserSendResult, aj as ProviderCapability, ak as ProviderRoute, al as ProviderTransform, am as ProviderTransformContext, an as RecordSessionSummaryArgs, ao as ResolvedProviderRoute, ap as RunUntilIterator, aq as SDKAgentPlugins, ar as SDKAgentSkillDetail, as as SDKAgentSkills, at as SDKArtifact, au as SDKContextManager, av as SDKPluginMetadata, aw as SDKProvidersManager, ax as SessionRecord, ay as SessionStore, az as SettingSource, aA as Skill, aB as SkillsResolver, aC as SkillsResolverContext, aD as SystemPromptContext, aE as SystemPromptMemoryFact, aF as SystemPromptSkillRef, aG as TelemetrySettings, aH as Verdict } from './cron-
|
|
3
|
+
import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as Plugin$1, m as ProviderProfile, I as InlineSkill, J as JudgeResult, n as GoalOptions, o as GoalEvent, p as GoalResult, B as BudgetTracker, q as MemoryProvider, r as MemoryId, s as PreToolCallDecision, t as StepResult, u as SDKProvider } from './cron-CoQREV_k.cjs';
|
|
4
|
+
export { v as ActiveMemoryPassArgs, w as ActiveMemoryPassResult, x as AgentMemory, y as BudgetCheck, z as BudgetTotal, D as BudgetUsageEvent, E as CloudEnv, F as CloudRepo, H as ContextBudget, K as ContextManagerKind, N as ContextSnapshot, O as ContextSource, Q as ContextSourceStatus, R as CreateSkillSpec, T as Cron, U as CronCreateOptions, V as CronGetOptions, W as CronJob, X as CronJobStatus, Y as CronListOptions, Z as CronOperationOptions, _ as CronRunOptions, $ as CronRuntime, a0 as CronSchedulerStatus, a1 as CronStartOptions, a2 as HookName, a3 as InvalidateCacheOptions, a4 as MemoryAdapter, a5 as MemoryAdapterCapabilities, a6 as MemoryContext, a7 as MemoryFact, a8 as MemoryProviderHandle, a9 as MemoryProviderInitOptions, aa as MemoryRevision, ab as MemoryToolSchema, ac as MemoryTurnMessage, ad as PersonalityPreset, ae as PluginContext, af as PostAssistantReplyContext, ag as PreToolCallContext, ah as PreUserSendContext, ai as PreUserSendResult, aj as ProviderCapability, ak as ProviderRoute, al as ProviderTransform, am as ProviderTransformContext, an as RecordSessionSummaryArgs, ao as ResolvedProviderRoute, ap as RunUntilIterator, aq as SDKAgentPlugins, ar as SDKAgentSkillDetail, as as SDKAgentSkills, at as SDKArtifact, au as SDKContextManager, av as SDKPluginMetadata, aw as SDKProvidersManager, ax as SessionRecord, ay as SessionStore, az as SettingSource, aA as Skill, aB as SkillsResolver, aC as SkillsResolverContext, aD as SystemPromptContext, aE as SystemPromptMemoryFact, aF as SystemPromptSkillRef, aG as TelemetrySettings, aH as Verdict } from './cron-CoQREV_k.cjs';
|
|
5
5
|
import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, P as Processor, T as ToolResultContentBlock, c as PermissionMode, d as PermissionEngine, e as RunEventSink, S as SDKMessage } from './run-OJbGyweZ.cjs';
|
|
6
6
|
export { A as AgentConversationTurn, f as AssistantMessage, g as CompletionCheck, h as CompletionCheckResult, i as ConversationStep, j as ConversationTurn, k as CostBreakdown, l as CostSource, m as CostStatus, D as DoomLoopThresholds, G as GenerateOptions, n as GenerateRunResult, I as ImageBlock, o as InputProcessorContext, p as InteractionUpdate, q as McpAuthConfig, r as McpHttpServerConfig, s as McpOAuthConfig, t as McpStdioServerConfig, u as MessageOrigin, v as ModelParameterValue, O as OutputProcessorContext, w as PartialToolCallUpdate, x as PermissionAction, y as PermissionEngineOptions, z as PermissionRule, B as ProcessorControls, E as ProcessorTripwire, F as ProcessorViolation, H as RunCompactBoundaryEvent, J as RunCompletionCheckEvent, K as RunErrorDetail, L as RunEvent, N as RunGitInfo, Q as RunOperation, U as RunPermissionDeniedEvent, V as RunRateLimitEvent, W as RunStatus, X as RunTaskCompletedEvent, Y as RunTaskStartedEvent, Z as RunTaskUpdatedEvent, _ as RunToCompletionOptions, $ as RunToCompletionResult, a0 as RunToolProgressEvent, a1 as RunTripwireEvent, a2 as SDKAssistantMessage, a3 as SDKImage, a4 as SDKImageDimension, a5 as SDKObjectDelta, a6 as SDKRequestMessage, a7 as SDKStatusMessage, a8 as SDKSystemMessage, a9 as SDKTaskMessage, aa as SDKThinkingMessage, ab as SDKToolUseMessage, ac as SDKUserMessage, ad as SDKUserMessageEvent, ae as SendOptions, af as ShellCommand, ag as ShellConversationTurn, ah as ShellOutput, ai as ShellOutputDeltaUpdate, aj as StepCompletedUpdate, ak as StepStartedUpdate, al as StreamToCompletionResult, am as SummaryCompletedUpdate, an as SummaryStartedUpdate, ao as SummaryUpdate, ap as TextBlock, aq as TextDeltaUpdate, ar as ThinkingCompletedUpdate, as as ThinkingDeltaUpdate, at as ThinkingMessage, au as TokenDeltaUpdate, av as TokenUsage, aw as ToolCall, ax as ToolCallCompletedUpdate, ay as ToolCallStartedUpdate, az as ToolContextMessage, aA as ToolResult, aB as ToolResultGuardOptions, aC as ToolUseBlock, aD as TurnEndedUpdate, aE as UserMessage, aF as UserMessageAppendedUpdate, aG as applyMode, aH as emitRunEvent } from './run-OJbGyweZ.cjs';
|
|
7
7
|
import * as zod from 'zod';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot, E as ErrorMetadata } from './errors-DHZtSNnj.js';
|
|
2
2
|
export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, m as ErrorCode, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-DHZtSNnj.js';
|
|
3
|
-
import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as Plugin$1, m as ProviderProfile, I as InlineSkill, J as JudgeResult, n as GoalOptions, o as GoalEvent, p as GoalResult, B as BudgetTracker, q as MemoryProvider, r as MemoryId, s as PreToolCallDecision, t as StepResult, u as SDKProvider } from './cron-
|
|
4
|
-
export { v as ActiveMemoryPassArgs, w as ActiveMemoryPassResult, x as AgentMemory, y as BudgetCheck, z as BudgetTotal, D as BudgetUsageEvent, E as CloudEnv, F as CloudRepo, H as ContextBudget, K as ContextManagerKind, N as ContextSnapshot, O as ContextSource, Q as ContextSourceStatus, R as CreateSkillSpec, T as Cron, U as CronCreateOptions, V as CronGetOptions, W as CronJob, X as CronJobStatus, Y as CronListOptions, Z as CronOperationOptions, _ as CronRunOptions, $ as CronRuntime, a0 as CronSchedulerStatus, a1 as CronStartOptions, a2 as HookName, a3 as InvalidateCacheOptions, a4 as MemoryAdapter, a5 as MemoryAdapterCapabilities, a6 as MemoryContext, a7 as MemoryFact, a8 as MemoryProviderHandle, a9 as MemoryProviderInitOptions, aa as MemoryRevision, ab as MemoryToolSchema, ac as MemoryTurnMessage, ad as PersonalityPreset, ae as PluginContext, af as PostAssistantReplyContext, ag as PreToolCallContext, ah as PreUserSendContext, ai as PreUserSendResult, aj as ProviderCapability, ak as ProviderRoute, al as ProviderTransform, am as ProviderTransformContext, an as RecordSessionSummaryArgs, ao as ResolvedProviderRoute, ap as RunUntilIterator, aq as SDKAgentPlugins, ar as SDKAgentSkillDetail, as as SDKAgentSkills, at as SDKArtifact, au as SDKContextManager, av as SDKPluginMetadata, aw as SDKProvidersManager, ax as SessionRecord, ay as SessionStore, az as SettingSource, aA as Skill, aB as SkillsResolver, aC as SkillsResolverContext, aD as SystemPromptContext, aE as SystemPromptMemoryFact, aF as SystemPromptSkillRef, aG as TelemetrySettings, aH as Verdict } from './cron-
|
|
3
|
+
import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as Plugin$1, m as ProviderProfile, I as InlineSkill, J as JudgeResult, n as GoalOptions, o as GoalEvent, p as GoalResult, B as BudgetTracker, q as MemoryProvider, r as MemoryId, s as PreToolCallDecision, t as StepResult, u as SDKProvider } from './cron-BN6JJlDw.js';
|
|
4
|
+
export { v as ActiveMemoryPassArgs, w as ActiveMemoryPassResult, x as AgentMemory, y as BudgetCheck, z as BudgetTotal, D as BudgetUsageEvent, E as CloudEnv, F as CloudRepo, H as ContextBudget, K as ContextManagerKind, N as ContextSnapshot, O as ContextSource, Q as ContextSourceStatus, R as CreateSkillSpec, T as Cron, U as CronCreateOptions, V as CronGetOptions, W as CronJob, X as CronJobStatus, Y as CronListOptions, Z as CronOperationOptions, _ as CronRunOptions, $ as CronRuntime, a0 as CronSchedulerStatus, a1 as CronStartOptions, a2 as HookName, a3 as InvalidateCacheOptions, a4 as MemoryAdapter, a5 as MemoryAdapterCapabilities, a6 as MemoryContext, a7 as MemoryFact, a8 as MemoryProviderHandle, a9 as MemoryProviderInitOptions, aa as MemoryRevision, ab as MemoryToolSchema, ac as MemoryTurnMessage, ad as PersonalityPreset, ae as PluginContext, af as PostAssistantReplyContext, ag as PreToolCallContext, ah as PreUserSendContext, ai as PreUserSendResult, aj as ProviderCapability, ak as ProviderRoute, al as ProviderTransform, am as ProviderTransformContext, an as RecordSessionSummaryArgs, ao as ResolvedProviderRoute, ap as RunUntilIterator, aq as SDKAgentPlugins, ar as SDKAgentSkillDetail, as as SDKAgentSkills, at as SDKArtifact, au as SDKContextManager, av as SDKPluginMetadata, aw as SDKProvidersManager, ax as SessionRecord, ay as SessionStore, az as SettingSource, aA as Skill, aB as SkillsResolver, aC as SkillsResolverContext, aD as SystemPromptContext, aE as SystemPromptMemoryFact, aF as SystemPromptSkillRef, aG as TelemetrySettings, aH as Verdict } from './cron-BN6JJlDw.js';
|
|
5
5
|
import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, P as Processor, T as ToolResultContentBlock, c as PermissionMode, d as PermissionEngine, e as RunEventSink, S as SDKMessage } from './run-OJbGyweZ.js';
|
|
6
6
|
export { A as AgentConversationTurn, f as AssistantMessage, g as CompletionCheck, h as CompletionCheckResult, i as ConversationStep, j as ConversationTurn, k as CostBreakdown, l as CostSource, m as CostStatus, D as DoomLoopThresholds, G as GenerateOptions, n as GenerateRunResult, I as ImageBlock, o as InputProcessorContext, p as InteractionUpdate, q as McpAuthConfig, r as McpHttpServerConfig, s as McpOAuthConfig, t as McpStdioServerConfig, u as MessageOrigin, v as ModelParameterValue, O as OutputProcessorContext, w as PartialToolCallUpdate, x as PermissionAction, y as PermissionEngineOptions, z as PermissionRule, B as ProcessorControls, E as ProcessorTripwire, F as ProcessorViolation, H as RunCompactBoundaryEvent, J as RunCompletionCheckEvent, K as RunErrorDetail, L as RunEvent, N as RunGitInfo, Q as RunOperation, U as RunPermissionDeniedEvent, V as RunRateLimitEvent, W as RunStatus, X as RunTaskCompletedEvent, Y as RunTaskStartedEvent, Z as RunTaskUpdatedEvent, _ as RunToCompletionOptions, $ as RunToCompletionResult, a0 as RunToolProgressEvent, a1 as RunTripwireEvent, a2 as SDKAssistantMessage, a3 as SDKImage, a4 as SDKImageDimension, a5 as SDKObjectDelta, a6 as SDKRequestMessage, a7 as SDKStatusMessage, a8 as SDKSystemMessage, a9 as SDKTaskMessage, aa as SDKThinkingMessage, ab as SDKToolUseMessage, ac as SDKUserMessage, ad as SDKUserMessageEvent, ae as SendOptions, af as ShellCommand, ag as ShellConversationTurn, ah as ShellOutput, ai as ShellOutputDeltaUpdate, aj as StepCompletedUpdate, ak as StepStartedUpdate, al as StreamToCompletionResult, am as SummaryCompletedUpdate, an as SummaryStartedUpdate, ao as SummaryUpdate, ap as TextBlock, aq as TextDeltaUpdate, ar as ThinkingCompletedUpdate, as as ThinkingDeltaUpdate, at as ThinkingMessage, au as TokenDeltaUpdate, av as TokenUsage, aw as ToolCall, ax as ToolCallCompletedUpdate, ay as ToolCallStartedUpdate, az as ToolContextMessage, aA as ToolResult, aB as ToolResultGuardOptions, aC as ToolUseBlock, aD as TurnEndedUpdate, aE as UserMessage, aF as UserMessageAppendedUpdate, aG as applyMode, aH as emitRunEvent } from './run-OJbGyweZ.js';
|
|
7
7
|
import * as zod from 'zod';
|
package/dist/index.js
CHANGED
|
@@ -6,9 +6,9 @@ import './chunk-GJAGKFTR.js';
|
|
|
6
6
|
import { Workflow, agentStep } from './chunk-BFWPZMG7.js';
|
|
7
7
|
import './chunk-UVNG67DG.js';
|
|
8
8
|
import './chunk-CAH3G4IS.js';
|
|
9
|
-
export { Cron } from './chunk-
|
|
10
|
-
import { MEMORY_EMBEDDING_ADAPTERS, resolveApiKey, shouldUseFixtureMode, isFixtureApiKey, httpRequest, DEFAULT_AGENTIC_MODEL_ID, Agent } from './chunk-
|
|
11
|
-
export { Agent, AgentBuilder, Tool, ToolError, UsageAccumulator, computeCost, getPricingEntry } from './chunk-
|
|
9
|
+
export { Cron } from './chunk-PF5Y5BHG.js';
|
|
10
|
+
import { MEMORY_EMBEDDING_ADAPTERS, resolveApiKey, shouldUseFixtureMode, isFixtureApiKey, httpRequest, DEFAULT_AGENTIC_MODEL_ID, Agent } from './chunk-XW6RXVGB.js';
|
|
11
|
+
export { Agent, AgentBuilder, Tool, ToolError, UsageAccumulator, computeCost, getPricingEntry } from './chunk-XW6RXVGB.js';
|
|
12
12
|
import { configure, submit, list, get, cancel, subscribe } from './chunk-HRA3CPGG.js';
|
|
13
13
|
export { emitRunEvent } from './chunk-HRA3CPGG.js';
|
|
14
14
|
import './chunk-SQLZ7ONU.js';
|
|
@@ -695,7 +695,7 @@ var EventBus = class {
|
|
|
695
695
|
// src/goal-loop.ts
|
|
696
696
|
function runGoalLoop(agent, goal, options, depsOverride) {
|
|
697
697
|
async function* wrap() {
|
|
698
|
-
const { runUntilImpl } = await import('./run-until-
|
|
698
|
+
const { runUntilImpl } = await import('./run-until-YZ2ODWOF.js');
|
|
699
699
|
const deps = depsOverride ?? await (async () => {
|
|
700
700
|
const { judgeCallImpl } = await import('./judge-call-D7R3ZTZS.js');
|
|
701
701
|
const { getAgentFacade } = await import('./agent-factory-registry-ZVTABLEY.js');
|
|
@@ -59,6 +59,7 @@ async function* runUntilImpl(agent, goal, options, deps) {
|
|
|
59
59
|
const judgeOpts = {};
|
|
60
60
|
if (options?.judgeModel !== void 0) judgeOpts.judgeModel = options.judgeModel;
|
|
61
61
|
if (options?.judgeApiKey !== void 0) judgeOpts.apiKey = options.judgeApiKey;
|
|
62
|
+
if (options?.agentModel !== void 0) judgeOpts.agentModel = options.agentModel;
|
|
62
63
|
const judgeCtx = { goal, lastResponse };
|
|
63
64
|
if (options?.subgoals !== void 0) judgeCtx.subgoals = options.subgoals;
|
|
64
65
|
const judgment = await deps.judge(judgeCtx, judgeOpts);
|
|
@@ -173,5 +174,5 @@ ${lastResponse.slice(-1e3)}`
|
|
|
173
174
|
}
|
|
174
175
|
|
|
175
176
|
export { composeContinuation, runUntilImpl };
|
|
176
|
-
//# sourceMappingURL=run-until-
|
|
177
|
-
//# sourceMappingURL=run-until-
|
|
177
|
+
//# sourceMappingURL=run-until-YZ2ODWOF.js.map
|
|
178
|
+
//# sourceMappingURL=run-until-YZ2ODWOF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/lifecycle/run-until.ts"],"names":[],"mappings":";;;AA+BA,gBAAuB,YAAA,CACrB,KAAA,EACA,IAAA,EACA,OAAA,EACA,IAAA,EAC6C;AAC7C,EAAA,MAAM,QAAA,GAAW,SAAS,QAAA,IAAY,EAAA;AACtC,EAAA,MAAM,QAAA,GAAW,SAAS,2BAAA,IAA+B,CAAA;AACzD,EAAA,MAAM,cAAc,OAAA,EAAS,WAAA;AAC7B,EAAA,MAAM,SAAS,OAAA,EAAS,MAAA;AAKxB,EAAA,MAAM,SAAA,GAAY,MAAe,MAAA,KAAW,MAAA,IAAa,MAAA,CAAO,OAAA;AAChE,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI,mBAAA,GAAsB,CAAA;AAC1B,EAAA,IAAI,UAAA,GAAa,CAAA;AACjB,EAAA,IAAI,YAAA,GAAe,EAAA;AAGnB,EAAA,IAAI,WAAU,EAAG;AACf,IAAA,MAAM;AAAA,MACJ,IAAA,EAAM,eAAA;AAAA,MACN,MAAA,EAAQ,QAAA;AAAA,MACR,MAAA,EAAQ;AAAA,KACV;AACA,IAAA,OAAO,EAAE,MAAA,EAAQ,QAAA,EAAU,WAAW,CAAA,EAAG,UAAA,EAAY,eAAe,MAAA,EAAU;AAAA,EAChF;AAEA,EAAA,MAAM,EAAE,IAAA,EAAM,eAAA,EAAiB,MAAA,EA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C,CAAA;AAAA,GACvD,CAAE,KAAK,IAAI,CAAA;AACb","file":"run-until-YZ2ODWOF.js","sourcesContent":["/**\n * Goal-driven Ralph loop (T3.2, ADRs D115-D121).\n *\n * `runUntilImpl` is an `AsyncGenerator<GoalEvent, GoalResult, void>`:\n * yields events as the loop progresses, returns the final result when\n * the goal completes, fails, or is paused. The auxiliary judge model is\n * injected via `deps.judge` so the generator stays free of the `Agent`\n * façade import.\n *\n * EC-C fix: pre-aborted signals emit only `[paused]`, not `[active, paused]`.\n * EC-D: `maxTurns: 0` is supported (vacuous yield active → failed).\n *\n * @internal\n */\n\nimport type { SDKAgent } from \"../../../types/agent.js\";\nimport type {\n GoalEvent,\n GoalOptions,\n GoalResult,\n JudgeResult,\n} from \"../../../types/goal-events.js\";\nimport type { JudgeContext, JudgeOptions } from \"../../judge/judge-call.js\";\nimport { GOAL_CONTINUATION_MARKER } from \"./goal-marker.js\";\n\n/** DI contract: the judge is the only external touchpoint. */\nexport interface RunUntilDeps {\n judge: (ctx: JudgeContext, opts?: JudgeOptions) => Promise<JudgeResult>;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: the goal-loop interleaves turn-start, send, judge, continuation, abort-check, and failure-bail — extracting helpers harms the linear narrative.\nexport async function* runUntilImpl(\n agent: SDKAgent,\n goal: string,\n options: GoalOptions | undefined,\n deps: RunUntilDeps,\n): AsyncGenerator<GoalEvent, GoalResult, void> {\n const maxTurns = options?.maxTurns ?? 20;\n const maxFails = options?.maxConsecutiveJudgeFailures ?? 3;\n const tokenBudget = options?.tokenBudget; // M55 — undefined ⇒ ilimitado\n const signal = options?.signal;\n // Use a function (not direct property access) so TS does not narrow\n // `signal.aborted` to `false | undefined` after the initial check.\n // AbortSignal.aborted is a getter that can flip true between calls.\n // biome-ignore lint/complexity/useOptionalChain: optional-chain would re-narrow signal?.aborted to `false | undefined` after the first check, defeating the purpose of this helper.\n const isAborted = (): boolean => signal !== undefined && signal.aborted;\n let turn = 0;\n let consecutiveFailures = 0;\n let tokensUsed = 0; // M55 — soma observada (0 se usage ausente — fail-open)\n let lastResponse = \"\";\n\n // EC-C: signal already aborted BEFORE first event → emit only [paused].\n if (isAborted()) {\n yield {\n type: \"status_change\",\n status: \"paused\",\n reason: \"aborted via AbortSignal before first turn\",\n };\n return { status: \"paused\", turnsUsed: 0, tokensUsed, finalResponse: undefined };\n }\n\n yield { type: \"status_change\", status: \"active\", reason: \"Goal started\" };\n\n while (turn < maxTurns) {\n if (isAborted()) {\n yield { type: \"status_change\", status: \"paused\", reason: \"aborted via AbortSignal\" };\n return {\n status: \"paused\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n\n turn += 1;\n yield { type: \"turn_start\", turn, goal };\n\n const continuationPrompt = turn === 1 ? goal : composeContinuation(goal, lastResponse);\n\n const run = await agent.send(continuationPrompt);\n // M55 review HIGH — thread the abort INTO the in-flight run: without this, Esc mid-turn is\n // cosmetic (the turn keeps mutating the workspace until it finishes on its own). `run.cancel()`\n // aborts the stream + in-flight tool calls (types/run.ts contract).\n const cancelOnAbort = (): void => {\n void (run as { cancel?: () => Promise<void> }).cancel?.();\n };\n if (signal !== undefined) {\n if (signal.aborted) cancelOnAbort();\n else signal.addEventListener(\"abort\", cancelOnAbort, { once: true });\n }\n const result = await run.wait();\n if (signal !== undefined) signal.removeEventListener(\"abort\", cancelOnAbort);\n lastResponse = result.result ?? \"\";\n // M55 — token accounting fail-open: só soma quando o run reporta usage.\n const turnTokens = (result as { usage?: { totalTokens?: number } }).usage?.totalTokens;\n if (typeof turnTokens === \"number\") tokensUsed += turnTokens;\n // Re-check aborted right after the turn lands: a cancelled turn must NOT spend a judge call.\n if (isAborted()) {\n yield { type: \"status_change\", status: \"paused\", reason: \"aborted via AbortSignal\" };\n return {\n status: \"paused\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n yield { type: \"agent_response\", turn, content: lastResponse };\n\n const judgeOpts: JudgeOptions = {};\n if (options?.judgeModel !== undefined) judgeOpts.judgeModel = options.judgeModel;\n if (options?.judgeApiKey !== undefined) judgeOpts.apiKey = options.judgeApiKey;\n // M80 — encaminha o modelo do agente conduzido para o judge derivar quando `judgeModel` é omitido.\n if (options?.agentModel !== undefined) judgeOpts.agentModel = options.agentModel;\n const judgeCtx: JudgeContext = { goal, lastResponse };\n if (options?.subgoals !== undefined) judgeCtx.subgoals = options.subgoals;\n const judgment = await deps.judge(judgeCtx, judgeOpts);\n yield {\n type: \"judge_verdict\",\n turn,\n verdict: judgment.verdict,\n reason: judgment.reason,\n parseFailed: judgment.parseFailed,\n };\n\n if (judgment.parseFailed) {\n consecutiveFailures += 1;\n if (consecutiveFailures >= maxFails) {\n yield {\n type: \"status_change\",\n status: \"failed\",\n reason: `judge model too unreliable (${consecutiveFailures} parse failures in a row)`,\n };\n return {\n status: \"failed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n } else {\n consecutiveFailures = 0;\n }\n\n if (judgment.verdict === \"done\") {\n yield { type: \"status_change\", status: \"completed\", reason: judgment.reason };\n return {\n status: \"completed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n // M80 — o braço que faltava. Sem ele, um judge que reconhecesse impossibilidade só podia dizer\n // \"continue\", e o loop repetia o mesmo turno até estourar o orçamento — reportando `failed` por\n // limite em vez de `blocked` por impossibilidade. Duas causas distintas com o mesmo desfecho\n // visível, e o consumidor precisava reconciliar depois do loop para distingui-las.\n if (judgment.verdict === \"blocked\") {\n yield { type: \"status_change\", status: \"blocked\", reason: judgment.reason };\n return {\n status: \"blocked\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n if (judgment.verdict === \"skipped\") {\n yield {\n type: \"status_change\",\n status: \"completed\",\n reason: `skipped: ${judgment.reason}`,\n };\n return {\n status: \"completed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n\n // M55 — checagem de token budget APÓS o turno (Codex: wind-down suave, para o loop).\n if (tokenBudget !== undefined && tokensUsed >= tokenBudget) {\n yield {\n type: \"status_change\",\n status: \"budget_limited\",\n reason: `token budget (${tokenBudget}) reached: ${tokensUsed} used`,\n };\n return {\n status: \"budget_limited\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n\n yield { type: \"continuation\", turn, prompt: continuationPrompt };\n }\n\n yield {\n type: \"status_change\",\n status: \"failed\",\n reason: `max turns (${maxTurns}) exhausted`,\n };\n return {\n status: \"failed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n}\n\n/**\n * Build the continuation user message for turns 2+. Keeps last response\n * preview short so we don't bloat the prompt cache.\n *\n * @internal\n */\n\nexport function composeContinuation(goal: string, lastResponse: string): string {\n // M55 — Codex-faithful continuation (ext/goal templates/goals/continuation.md): keep the FULL\n // objective intact, work from current-state evidence, and audit completion requirement-by-requirement\n // before declaring done. Improves the quality of what the judge then evaluates.\n return [\n GOAL_CONTINUATION_MARKER,\n \"Continue working toward the active goal.\",\n \"\",\n `<objective>\\n${goal}\\n</objective>`,\n \"\",\n \"Continuation behavior:\",\n \"- This goal persists across turns. Keep the full objective intact; if it cannot be finished now,\",\n \" make concrete progress toward the real requested end state and do not redefine success around a\",\n \" smaller or easier task.\",\n \"\",\n \"Work from evidence:\",\n \"- Use the current worktree and external state as authoritative. Inspect the current state before\",\n \" relying on it. Improve, replace, or remove existing work as needed to satisfy the actual objective.\",\n \"\",\n \"Completion audit:\",\n \"- Before deciding the goal is achieved, treat completion as unproven and verify it against the actual\",\n \" current state, requirement by requirement. Treat uncertain or indirect evidence as not achieved.\",\n \"\",\n `Your last response was:\\n${lastResponse.slice(-1000)}`,\n ].join(\"\\n\");\n}\n"]}
|
|
@@ -61,6 +61,7 @@ async function* runUntilImpl(agent, goal, options, deps) {
|
|
|
61
61
|
const judgeOpts = {};
|
|
62
62
|
if (options?.judgeModel !== void 0) judgeOpts.judgeModel = options.judgeModel;
|
|
63
63
|
if (options?.judgeApiKey !== void 0) judgeOpts.apiKey = options.judgeApiKey;
|
|
64
|
+
if (options?.agentModel !== void 0) judgeOpts.agentModel = options.agentModel;
|
|
64
65
|
const judgeCtx = { goal, lastResponse };
|
|
65
66
|
if (options?.subgoals !== void 0) judgeCtx.subgoals = options.subgoals;
|
|
66
67
|
const judgment = await deps.judge(judgeCtx, judgeOpts);
|
|
@@ -176,5 +177,5 @@ ${lastResponse.slice(-1e3)}`
|
|
|
176
177
|
|
|
177
178
|
exports.composeContinuation = composeContinuation;
|
|
178
179
|
exports.runUntilImpl = runUntilImpl;
|
|
179
|
-
//# sourceMappingURL=run-until-
|
|
180
|
-
//# sourceMappingURL=run-until-
|
|
180
|
+
//# sourceMappingURL=run-until-ZZ2JLPJM.cjs.map
|
|
181
|
+
//# sourceMappingURL=run-until-ZZ2JLPJM.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/lifecycle/run-until.ts"],"names":["GOAL_CONTINUATION_MARKER"],"mappings":";;;;;AA+BA,gBAAuB,YAAA,CACrB,KAAA,EACA,IAAA,EACA,OAAA,EACA,IAAA,EAC6C;AAC7C,EAAA,MAAM,QAAA,GAAW,SAAS,QAAA,IAAY,EAAA;AACtC,EAAA,MAAM,QAAA,GAAW,SAAS,2BAAA,IAA+B,CAAA;AACzD,EAAA,MAAM,cAAc,OAAA,EAAS,WAAA;AAC7B,EAAA,MAAM,SAAS,OAAA,EAAS,MAAA;AAKxB,EAAA,MAAM,SAAA,GAAY,MAAe,MAAA,KAAW,MAAA,IAAa,MAAA,CAAO,OAAA;AAChE,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI,mBAAA,GAAsB,CAAA;AAC1B,EAAA,IAAI,UAAA,GAAa,CAAA;AACjB,EAAA,IAAI,YAAA,GAAe,EAAA;AAGnB,EAAA,IAAI,WAAU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A,wBAAA;AAAA,IACA,kGAAA;AAAA,IACA,mGAAA;AAAA,IACA,2BAAA;AAAA,IACA,EAAA;AAAA,IACA,qBAAA;AAAA,IACA,kGAAA;AAAA,IACA,uGAAA;AAAA,IACA,EAAA;AAAA,IACA,mBAAA;AAAA,IACA,uGAAA;AAAA,IACA,oGAAA;AAAA,IACA,EAAA;AAAA,IACA,CAAA;AAAA,EAA4B,YAAA,CAAa,KAAA,CAAM,IAAK,CAAC,CAAA;AAAA,GACvD,CAAE,KAAK,IAAI,CAAA;AACb","file":"run-until-ZZ2JLPJM.cjs","sourcesContent":["/**\n * Goal-driven Ralph loop (T3.2, ADRs D115-D121).\n *\n * `runUntilImpl` is an `AsyncGenerator<GoalEvent, GoalResult, void>`:\n * yields events as the loop progresses, returns the final result when\n * the goal completes, fails, or is paused. The auxiliary judge model is\n * injected via `deps.judge` so the generator stays free of the `Agent`\n * façade import.\n *\n * EC-C fix: pre-aborted signals emit only `[paused]`, not `[active, paused]`.\n * EC-D: `maxTurns: 0` is supported (vacuous yield active → failed).\n *\n * @internal\n */\n\nimport type { SDKAgent } from \"../../../types/agent.js\";\nimport type {\n GoalEvent,\n GoalOptions,\n GoalResult,\n JudgeResult,\n} from \"../../../types/goal-events.js\";\nimport type { JudgeContext, JudgeOptions } from \"../../judge/judge-call.js\";\nimport { GOAL_CONTINUATION_MARKER } from \"./goal-marker.js\";\n\n/** DI contract: the judge is the only external touchpoint. */\nexport interface RunUntilDeps {\n judge: (ctx: JudgeContext, opts?: JudgeOptions) => Promise<JudgeResult>;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: the goal-loop interleaves turn-start, send, judge, continuation, abort-check, and failure-bail — extracting helpers harms the linear narrative.\nexport async function* runUntilImpl(\n agent: SDKAgent,\n goal: string,\n options: GoalOptions | undefined,\n deps: RunUntilDeps,\n): AsyncGenerator<GoalEvent, GoalResult, void> {\n const maxTurns = options?.maxTurns ?? 20;\n const maxFails = options?.maxConsecutiveJudgeFailures ?? 3;\n const tokenBudget = options?.tokenBudget; // M55 — undefined ⇒ ilimitado\n const signal = options?.signal;\n // Use a function (not direct property access) so TS does not narrow\n // `signal.aborted` to `false | undefined` after the initial check.\n // AbortSignal.aborted is a getter that can flip true between calls.\n // biome-ignore lint/complexity/useOptionalChain: optional-chain would re-narrow signal?.aborted to `false | undefined` after the first check, defeating the purpose of this helper.\n const isAborted = (): boolean => signal !== undefined && signal.aborted;\n let turn = 0;\n let consecutiveFailures = 0;\n let tokensUsed = 0; // M55 — soma observada (0 se usage ausente — fail-open)\n let lastResponse = \"\";\n\n // EC-C: signal already aborted BEFORE first event → emit only [paused].\n if (isAborted()) {\n yield {\n type: \"status_change\",\n status: \"paused\",\n reason: \"aborted via AbortSignal before first turn\",\n };\n return { status: \"paused\", turnsUsed: 0, tokensUsed, finalResponse: undefined };\n }\n\n yield { type: \"status_change\", status: \"active\", reason: \"Goal started\" };\n\n while (turn < maxTurns) {\n if (isAborted()) {\n yield { type: \"status_change\", status: \"paused\", reason: \"aborted via AbortSignal\" };\n return {\n status: \"paused\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n\n turn += 1;\n yield { type: \"turn_start\", turn, goal };\n\n const continuationPrompt = turn === 1 ? goal : composeContinuation(goal, lastResponse);\n\n const run = await agent.send(continuationPrompt);\n // M55 review HIGH — thread the abort INTO the in-flight run: without this, Esc mid-turn is\n // cosmetic (the turn keeps mutating the workspace until it finishes on its own). `run.cancel()`\n // aborts the stream + in-flight tool calls (types/run.ts contract).\n const cancelOnAbort = (): void => {\n void (run as { cancel?: () => Promise<void> }).cancel?.();\n };\n if (signal !== undefined) {\n if (signal.aborted) cancelOnAbort();\n else signal.addEventListener(\"abort\", cancelOnAbort, { once: true });\n }\n const result = await run.wait();\n if (signal !== undefined) signal.removeEventListener(\"abort\", cancelOnAbort);\n lastResponse = result.result ?? \"\";\n // M55 — token accounting fail-open: só soma quando o run reporta usage.\n const turnTokens = (result as { usage?: { totalTokens?: number } }).usage?.totalTokens;\n if (typeof turnTokens === \"number\") tokensUsed += turnTokens;\n // Re-check aborted right after the turn lands: a cancelled turn must NOT spend a judge call.\n if (isAborted()) {\n yield { type: \"status_change\", status: \"paused\", reason: \"aborted via AbortSignal\" };\n return {\n status: \"paused\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n yield { type: \"agent_response\", turn, content: lastResponse };\n\n const judgeOpts: JudgeOptions = {};\n if (options?.judgeModel !== undefined) judgeOpts.judgeModel = options.judgeModel;\n if (options?.judgeApiKey !== undefined) judgeOpts.apiKey = options.judgeApiKey;\n // M80 — encaminha o modelo do agente conduzido para o judge derivar quando `judgeModel` é omitido.\n if (options?.agentModel !== undefined) judgeOpts.agentModel = options.agentModel;\n const judgeCtx: JudgeContext = { goal, lastResponse };\n if (options?.subgoals !== undefined) judgeCtx.subgoals = options.subgoals;\n const judgment = await deps.judge(judgeCtx, judgeOpts);\n yield {\n type: \"judge_verdict\",\n turn,\n verdict: judgment.verdict,\n reason: judgment.reason,\n parseFailed: judgment.parseFailed,\n };\n\n if (judgment.parseFailed) {\n consecutiveFailures += 1;\n if (consecutiveFailures >= maxFails) {\n yield {\n type: \"status_change\",\n status: \"failed\",\n reason: `judge model too unreliable (${consecutiveFailures} parse failures in a row)`,\n };\n return {\n status: \"failed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n } else {\n consecutiveFailures = 0;\n }\n\n if (judgment.verdict === \"done\") {\n yield { type: \"status_change\", status: \"completed\", reason: judgment.reason };\n return {\n status: \"completed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n // M80 — o braço que faltava. Sem ele, um judge que reconhecesse impossibilidade só podia dizer\n // \"continue\", e o loop repetia o mesmo turno até estourar o orçamento — reportando `failed` por\n // limite em vez de `blocked` por impossibilidade. Duas causas distintas com o mesmo desfecho\n // visível, e o consumidor precisava reconciliar depois do loop para distingui-las.\n if (judgment.verdict === \"blocked\") {\n yield { type: \"status_change\", status: \"blocked\", reason: judgment.reason };\n return {\n status: \"blocked\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n if (judgment.verdict === \"skipped\") {\n yield {\n type: \"status_change\",\n status: \"completed\",\n reason: `skipped: ${judgment.reason}`,\n };\n return {\n status: \"completed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n\n // M55 — checagem de token budget APÓS o turno (Codex: wind-down suave, para o loop).\n if (tokenBudget !== undefined && tokensUsed >= tokenBudget) {\n yield {\n type: \"status_change\",\n status: \"budget_limited\",\n reason: `token budget (${tokenBudget}) reached: ${tokensUsed} used`,\n };\n return {\n status: \"budget_limited\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n }\n\n yield { type: \"continuation\", turn, prompt: continuationPrompt };\n }\n\n yield {\n type: \"status_change\",\n status: \"failed\",\n reason: `max turns (${maxTurns}) exhausted`,\n };\n return {\n status: \"failed\",\n turnsUsed: turn,\n tokensUsed,\n finalResponse: lastResponse || undefined,\n };\n}\n\n/**\n * Build the continuation user message for turns 2+. Keeps last response\n * preview short so we don't bloat the prompt cache.\n *\n * @internal\n */\n\nexport function composeContinuation(goal: string, lastResponse: string): string {\n // M55 — Codex-faithful continuation (ext/goal templates/goals/continuation.md): keep the FULL\n // objective intact, work from current-state evidence, and audit completion requirement-by-requirement\n // before declaring done. Improves the quality of what the judge then evaluates.\n return [\n GOAL_CONTINUATION_MARKER,\n \"Continue working toward the active goal.\",\n \"\",\n `<objective>\\n${goal}\\n</objective>`,\n \"\",\n \"Continuation behavior:\",\n \"- This goal persists across turns. Keep the full objective intact; if it cannot be finished now,\",\n \" make concrete progress toward the real requested end state and do not redefine success around a\",\n \" smaller or easier task.\",\n \"\",\n \"Work from evidence:\",\n \"- Use the current worktree and external state as authoritative. Inspect the current state before\",\n \" relying on it. Improve, replace, or remove existing work as needed to satisfy the actual objective.\",\n \"\",\n \"Completion audit:\",\n \"- Before deciding the goal is achieved, treat completion as unproven and verify it against the actual\",\n \" current state, requirement by requirement. Treat uncertain or indirect evidence as not achieved.\",\n \"\",\n `Your last response was:\\n${lastResponse.slice(-1000)}`,\n ].join(\"\\n\");\n}\n"]}
|
|
@@ -1,15 +1,211 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
|
-
* @theokit/sdk/server/auth —
|
|
4
|
+
* @theokit/sdk/server/auth — typed error classes
|
|
3
5
|
*
|
|
4
|
-
*
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
* Plan T1.2 + v1.1 EC-1 (AuthCancelledError for OAuth provider error response RFC 6749 §4.1.2.1).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Thrown at `defineAuth()` time when configuration is invalid
|
|
10
|
+
* (e.g., duplicate provider name, invalid email shape per EC-V1-12).
|
|
11
|
+
*/
|
|
12
|
+
declare class AuthConfigError extends Error {
|
|
13
|
+
readonly name = "AuthConfigError";
|
|
14
|
+
readonly code: string;
|
|
15
|
+
constructor(code: string, message: string);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Thrown at `startSignIn(providerName, ...)` or `finishSignIn(providerName, ...)`
|
|
19
|
+
* when the named provider is not registered in `providers[]`.
|
|
20
|
+
*/
|
|
21
|
+
declare class AuthProviderNotFoundError extends Error {
|
|
22
|
+
readonly name = "AuthProviderNotFoundError";
|
|
23
|
+
readonly providerName: string;
|
|
24
|
+
constructor(providerName: string);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Thrown during OAuth callback handling for state mismatches, expired
|
|
28
|
+
* transactions, missing query params, or provider 4xx/5xx errors.
|
|
29
|
+
*
|
|
30
|
+
* Typed `code` field lets consumers branch on cause:
|
|
31
|
+
* - 'oauth_transaction_expired' — cookie tx > 10min old (per ADR D5)
|
|
32
|
+
* - 'oauth_state_mismatch' — query state ≠ cookie state (CSRF defense per RFC 6749 §10.12)
|
|
33
|
+
* - 'oauth_provider_error' — non-access_denied error in callback URL
|
|
34
|
+
* - 'oauth_token_exchange_failed' — provider rejected code-for-tokens swap
|
|
35
|
+
* - 'oauth_userinfo_failed' — userinfo endpoint returned error
|
|
36
|
+
* - 'oauth_missing_code_or_state' — required query params absent
|
|
37
|
+
*/
|
|
38
|
+
declare class AuthCallbackError extends Error {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly code: string;
|
|
41
|
+
constructor(code: string, message?: string);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Per v1.1 EC-1 MUST FIX — typed subclass of AuthCallbackError for the
|
|
45
|
+
* specific case where user declined consent at provider screen.
|
|
46
|
+
*
|
|
47
|
+
* OAuth 2.0 RFC 6749 §4.1.2.1: provider redirects with `?error=access_denied`.
|
|
48
|
+
* Apps can catch this distinctly from network/server errors to render
|
|
49
|
+
* "Login cancelled — try again" UX instead of opaque "callback failed".
|
|
50
|
+
*/
|
|
51
|
+
declare class AuthCancelledError extends AuthCallbackError {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
readonly errorDescription?: string;
|
|
54
|
+
constructor(errorDescription?: string);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @theokit/sdk/server/auth — orchestrator types (Caminho C Hybrid per G11)
|
|
59
|
+
*
|
|
60
|
+
* Plan: g11-auth-architecture-implementation v1.4 (sha256 4d381020...)
|
|
61
|
+
* Blueprint: g11-auth-architecture-decision v1.1 (SHIPPABLE 97.9)
|
|
62
|
+
* AUTH-DELEGATION lock (theokit/CLAUDE.md:217-225) — these types are the
|
|
63
|
+
* orchestrator contract; concrete OAuth/email providers ship in opt-in
|
|
64
|
+
* @theokit/auth-* packages (adapters layer per ADR D11).
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* SessionManager contract (matches theokit/packages/theo/src/server/auth/session.ts:49).
|
|
69
|
+
* Imported as type-only — runtime depends via peerDep `theokit@>=0.2.4`.
|
|
70
|
+
*/
|
|
71
|
+
interface SessionManager<TSession> {
|
|
72
|
+
getSession(req: IncomingMessage): Promise<TSession | null>;
|
|
73
|
+
createSession(res: ServerResponse, data: TSession): Promise<void>;
|
|
74
|
+
destroySession(res: ServerResponse): void;
|
|
75
|
+
rotateSession(req: IncomingMessage, res: ServerResponse): Promise<TSession | null>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Per ADR D5 — OAuth transaction state stored in encrypted HttpOnly cookie
|
|
79
|
+
* (cookie-state pattern). Expires within 10 minutes per invariant.
|
|
80
|
+
*/
|
|
81
|
+
interface OAuthTransaction {
|
|
82
|
+
state: string;
|
|
83
|
+
pkceVerifier?: string;
|
|
84
|
+
returnTo?: string;
|
|
85
|
+
createdAt: number;
|
|
86
|
+
expiresAt: number;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Per ADR D9 — provider profile types are provider-specific (not unified).
|
|
90
|
+
* Each @theokit/auth-* package exports its own profile shape.
|
|
91
|
+
* Generic param TProfile lets consumers narrow via discriminated unions on providerName.
|
|
92
|
+
*/
|
|
93
|
+
interface AuthResult<TProfile, TName extends string = string> {
|
|
94
|
+
profile: TProfile;
|
|
95
|
+
providerName: TName;
|
|
96
|
+
rawTokens?: {
|
|
97
|
+
accessToken: string;
|
|
98
|
+
refreshToken?: string;
|
|
99
|
+
idToken?: string;
|
|
100
|
+
expiresAt?: number;
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Provider contract — each @theokit/auth-* package implements this.
|
|
105
|
+
* Per blueprint Q5 + ADR D11 (adapters layer).
|
|
106
|
+
*/
|
|
107
|
+
interface AuthProvider<TProfile, TName extends string = string> {
|
|
108
|
+
name: TName;
|
|
109
|
+
createAuthorizationURL(tx: OAuthTransaction): URL | Promise<URL>;
|
|
110
|
+
handleCallback(req: IncomingMessage, tx: OAuthTransaction): Promise<AuthResult<TProfile, TName>>;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* `defineAuth(opts)` configuration shape — Caminho C (Hybrid).
|
|
114
|
+
* `providers` optional: empty = Caminho A escape hatch (manual signIn only).
|
|
115
|
+
* `onSignIn` invoked after provider callback success; returns TSession to persist.
|
|
116
|
+
*/
|
|
117
|
+
interface DefineAuthOptions<TSession> {
|
|
118
|
+
session: SessionManager<TSession>;
|
|
119
|
+
providers?: AuthProvider<unknown, string>[];
|
|
120
|
+
onSignIn?: <TProfile>(args: {
|
|
121
|
+
profile: TProfile;
|
|
122
|
+
provider: string;
|
|
123
|
+
}) => Promise<TSession>;
|
|
124
|
+
onSignOut?: (session: TSession | null) => Promise<void> | void;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Returned by `defineAuth<TSession>(opts)` — 5-method orchestrator surface.
|
|
128
|
+
*
|
|
129
|
+
* - startSignIn: returns Response.redirect to provider authorization URL with state cookie
|
|
130
|
+
* - finishSignIn: handles provider callback; verifies state; calls onSignIn; rotates session ID
|
|
131
|
+
* (OWASP A07:2021 per EC-10); creates session cookie; clears transaction cookie
|
|
132
|
+
* - signIn: Caminho A escape hatch — skip OAuth flow; directly persist session from external profile
|
|
133
|
+
* - signOut: destroys session cookie + invokes onSignOut callback
|
|
134
|
+
* - getSession: read-only passthrough to session.getSession
|
|
135
|
+
*/
|
|
136
|
+
interface AuthOrchestrator<TSession> {
|
|
137
|
+
startSignIn(providerName: string, req: IncomingMessage, opts?: {
|
|
138
|
+
returnTo?: string;
|
|
139
|
+
}): Promise<Response>;
|
|
140
|
+
finishSignIn(providerName: string, req: IncomingMessage, res: ServerResponse): Promise<{
|
|
141
|
+
session: TSession;
|
|
142
|
+
returnTo?: string;
|
|
143
|
+
}>;
|
|
144
|
+
signIn<TProfile>(profile: TProfile, providerName: string, req: IncomingMessage, res: ServerResponse): Promise<TSession>;
|
|
145
|
+
signOut(res: ServerResponse): void | Promise<void>;
|
|
146
|
+
getSession(req: IncomingMessage): Promise<TSession | null>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @theokit/sdk/server/auth — encrypted OAuth transaction cookie store
|
|
151
|
+
*
|
|
152
|
+
* Per ADR D5 — cookie-state pattern (no Redis/db dependency in core).
|
|
153
|
+
*
|
|
154
|
+
* Stores OAuthTransaction (state + pkceVerifier + returnTo + expiry) in a
|
|
155
|
+
* single signed+encrypted HttpOnly cookie. Stateless, works in edge/serverless.
|
|
156
|
+
*
|
|
157
|
+
* Cookie name: `__Host-theo_oauth_tx` (T5.3 — RFC 6265bis prefix)
|
|
158
|
+
* Lifetime: 10 minutes (per D5 invariant)
|
|
159
|
+
* Encryption: AES-256-GCM via Node's webcrypto subtle API
|
|
160
|
+
*
|
|
161
|
+
* Note: this is a minimal in-package implementation. Production deployments
|
|
162
|
+
* may prefer using `theokit/server/auth/crypto`'s encrypt/decrypt helpers
|
|
163
|
+
* via the SessionManager's existing secret rotation chain. For T1.2 we keep
|
|
164
|
+
* it self-contained to avoid cross-package peer-dep complexity; T2+ may
|
|
165
|
+
* refactor to share SessionManager's encrypt path.
|
|
166
|
+
*/
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* T5.1 — Typed error thrown when an OAuth tx-cookie secret has < 32
|
|
170
|
+
* bytes of entropy. Surfaces the actual byte length so operators can
|
|
171
|
+
* diagnose mis-configured env vars without leaking the secret itself.
|
|
172
|
+
*
|
|
173
|
+
* @public
|
|
174
|
+
*/
|
|
175
|
+
declare class AuthSecretTooShortError extends Error {
|
|
176
|
+
readonly name = "AuthSecretTooShortError";
|
|
177
|
+
constructor(actualBytes: number);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* @theokit/sdk/server/auth — defineAuth orchestrator runtime (Caminho C Hybrid)
|
|
182
|
+
*
|
|
183
|
+
* Plan T1.2 implementation per blueprint Q5 § Caminho C signatures.
|
|
184
|
+
* Composes existing primitives + the v1.1 EC-1/EC-2/EC-10 fixes.
|
|
185
|
+
*/
|
|
186
|
+
|
|
187
|
+
/** SE36 — `Auth.create` replaces `defineAuth` (ADR 0015). @public */
|
|
188
|
+
declare class Auth {
|
|
189
|
+
private constructor();
|
|
190
|
+
static create<TSession>(opts: DefineAuthOptions<TSession>): AuthOrchestrator<TSession>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* @theokit/sdk/server/auth — same-origin returnTo validator
|
|
195
|
+
*
|
|
196
|
+
* Per v1.1 EC-2 MUST FIX — OWASP A01:2021 open-redirect mitigation.
|
|
197
|
+
*
|
|
198
|
+
* Without this check, attacker craft `/login?returnTo=https://evil.com` would
|
|
199
|
+
* cause post-login redirect to attacker domain with authenticated session cookie.
|
|
7
200
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
201
|
+
* Rules:
|
|
202
|
+
* - undefined/empty returnTo → default '/'
|
|
203
|
+
* - protocol-relative `//evil.com` → default '/' (URL parser would resolve to baseUrl protocol)
|
|
204
|
+
* - absolute URL with origin ≠ baseUrl.origin → default '/' (cross-origin redirect)
|
|
205
|
+
* - absolute URL with origin === baseUrl.origin → keep (same-origin allowed)
|
|
206
|
+
* - relative path starting with '/' → keep (same-app navigation)
|
|
207
|
+
* - relative path not starting with '/' → default '/' (defensive)
|
|
10
208
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export { Auth
|
|
14
|
-
export type { AuthOrchestrator, AuthProvider, AuthResult, DefineAuthOptions, OAuthTransaction, SessionManager, } from "./types.js";
|
|
15
|
-
export { validateReturnTo } from "./validate-return-to.js";
|
|
209
|
+
declare function validateReturnTo(returnTo: string | undefined, baseUrl: URL): string;
|
|
210
|
+
|
|
211
|
+
export { Auth, AuthCallbackError, AuthCancelledError, AuthConfigError, type AuthOrchestrator, type AuthProvider, AuthProviderNotFoundError, type AuthResult, AuthSecretTooShortError, type DefineAuthOptions, type OAuthTransaction, type SessionManager, validateReturnTo };
|
|
@@ -1,15 +1,211 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
|
-
* @theokit/sdk/server/auth —
|
|
4
|
+
* @theokit/sdk/server/auth — typed error classes
|
|
3
5
|
*
|
|
4
|
-
*
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
* Plan T1.2 + v1.1 EC-1 (AuthCancelledError for OAuth provider error response RFC 6749 §4.1.2.1).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Thrown at `defineAuth()` time when configuration is invalid
|
|
10
|
+
* (e.g., duplicate provider name, invalid email shape per EC-V1-12).
|
|
11
|
+
*/
|
|
12
|
+
declare class AuthConfigError extends Error {
|
|
13
|
+
readonly name = "AuthConfigError";
|
|
14
|
+
readonly code: string;
|
|
15
|
+
constructor(code: string, message: string);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Thrown at `startSignIn(providerName, ...)` or `finishSignIn(providerName, ...)`
|
|
19
|
+
* when the named provider is not registered in `providers[]`.
|
|
20
|
+
*/
|
|
21
|
+
declare class AuthProviderNotFoundError extends Error {
|
|
22
|
+
readonly name = "AuthProviderNotFoundError";
|
|
23
|
+
readonly providerName: string;
|
|
24
|
+
constructor(providerName: string);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Thrown during OAuth callback handling for state mismatches, expired
|
|
28
|
+
* transactions, missing query params, or provider 4xx/5xx errors.
|
|
29
|
+
*
|
|
30
|
+
* Typed `code` field lets consumers branch on cause:
|
|
31
|
+
* - 'oauth_transaction_expired' — cookie tx > 10min old (per ADR D5)
|
|
32
|
+
* - 'oauth_state_mismatch' — query state ≠ cookie state (CSRF defense per RFC 6749 §10.12)
|
|
33
|
+
* - 'oauth_provider_error' — non-access_denied error in callback URL
|
|
34
|
+
* - 'oauth_token_exchange_failed' — provider rejected code-for-tokens swap
|
|
35
|
+
* - 'oauth_userinfo_failed' — userinfo endpoint returned error
|
|
36
|
+
* - 'oauth_missing_code_or_state' — required query params absent
|
|
37
|
+
*/
|
|
38
|
+
declare class AuthCallbackError extends Error {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly code: string;
|
|
41
|
+
constructor(code: string, message?: string);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Per v1.1 EC-1 MUST FIX — typed subclass of AuthCallbackError for the
|
|
45
|
+
* specific case where user declined consent at provider screen.
|
|
46
|
+
*
|
|
47
|
+
* OAuth 2.0 RFC 6749 §4.1.2.1: provider redirects with `?error=access_denied`.
|
|
48
|
+
* Apps can catch this distinctly from network/server errors to render
|
|
49
|
+
* "Login cancelled — try again" UX instead of opaque "callback failed".
|
|
50
|
+
*/
|
|
51
|
+
declare class AuthCancelledError extends AuthCallbackError {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
readonly errorDescription?: string;
|
|
54
|
+
constructor(errorDescription?: string);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @theokit/sdk/server/auth — orchestrator types (Caminho C Hybrid per G11)
|
|
59
|
+
*
|
|
60
|
+
* Plan: g11-auth-architecture-implementation v1.4 (sha256 4d381020...)
|
|
61
|
+
* Blueprint: g11-auth-architecture-decision v1.1 (SHIPPABLE 97.9)
|
|
62
|
+
* AUTH-DELEGATION lock (theokit/CLAUDE.md:217-225) — these types are the
|
|
63
|
+
* orchestrator contract; concrete OAuth/email providers ship in opt-in
|
|
64
|
+
* @theokit/auth-* packages (adapters layer per ADR D11).
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* SessionManager contract (matches theokit/packages/theo/src/server/auth/session.ts:49).
|
|
69
|
+
* Imported as type-only — runtime depends via peerDep `theokit@>=0.2.4`.
|
|
70
|
+
*/
|
|
71
|
+
interface SessionManager<TSession> {
|
|
72
|
+
getSession(req: IncomingMessage): Promise<TSession | null>;
|
|
73
|
+
createSession(res: ServerResponse, data: TSession): Promise<void>;
|
|
74
|
+
destroySession(res: ServerResponse): void;
|
|
75
|
+
rotateSession(req: IncomingMessage, res: ServerResponse): Promise<TSession | null>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Per ADR D5 — OAuth transaction state stored in encrypted HttpOnly cookie
|
|
79
|
+
* (cookie-state pattern). Expires within 10 minutes per invariant.
|
|
80
|
+
*/
|
|
81
|
+
interface OAuthTransaction {
|
|
82
|
+
state: string;
|
|
83
|
+
pkceVerifier?: string;
|
|
84
|
+
returnTo?: string;
|
|
85
|
+
createdAt: number;
|
|
86
|
+
expiresAt: number;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Per ADR D9 — provider profile types are provider-specific (not unified).
|
|
90
|
+
* Each @theokit/auth-* package exports its own profile shape.
|
|
91
|
+
* Generic param TProfile lets consumers narrow via discriminated unions on providerName.
|
|
92
|
+
*/
|
|
93
|
+
interface AuthResult<TProfile, TName extends string = string> {
|
|
94
|
+
profile: TProfile;
|
|
95
|
+
providerName: TName;
|
|
96
|
+
rawTokens?: {
|
|
97
|
+
accessToken: string;
|
|
98
|
+
refreshToken?: string;
|
|
99
|
+
idToken?: string;
|
|
100
|
+
expiresAt?: number;
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Provider contract — each @theokit/auth-* package implements this.
|
|
105
|
+
* Per blueprint Q5 + ADR D11 (adapters layer).
|
|
106
|
+
*/
|
|
107
|
+
interface AuthProvider<TProfile, TName extends string = string> {
|
|
108
|
+
name: TName;
|
|
109
|
+
createAuthorizationURL(tx: OAuthTransaction): URL | Promise<URL>;
|
|
110
|
+
handleCallback(req: IncomingMessage, tx: OAuthTransaction): Promise<AuthResult<TProfile, TName>>;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* `defineAuth(opts)` configuration shape — Caminho C (Hybrid).
|
|
114
|
+
* `providers` optional: empty = Caminho A escape hatch (manual signIn only).
|
|
115
|
+
* `onSignIn` invoked after provider callback success; returns TSession to persist.
|
|
116
|
+
*/
|
|
117
|
+
interface DefineAuthOptions<TSession> {
|
|
118
|
+
session: SessionManager<TSession>;
|
|
119
|
+
providers?: AuthProvider<unknown, string>[];
|
|
120
|
+
onSignIn?: <TProfile>(args: {
|
|
121
|
+
profile: TProfile;
|
|
122
|
+
provider: string;
|
|
123
|
+
}) => Promise<TSession>;
|
|
124
|
+
onSignOut?: (session: TSession | null) => Promise<void> | void;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Returned by `defineAuth<TSession>(opts)` — 5-method orchestrator surface.
|
|
128
|
+
*
|
|
129
|
+
* - startSignIn: returns Response.redirect to provider authorization URL with state cookie
|
|
130
|
+
* - finishSignIn: handles provider callback; verifies state; calls onSignIn; rotates session ID
|
|
131
|
+
* (OWASP A07:2021 per EC-10); creates session cookie; clears transaction cookie
|
|
132
|
+
* - signIn: Caminho A escape hatch — skip OAuth flow; directly persist session from external profile
|
|
133
|
+
* - signOut: destroys session cookie + invokes onSignOut callback
|
|
134
|
+
* - getSession: read-only passthrough to session.getSession
|
|
135
|
+
*/
|
|
136
|
+
interface AuthOrchestrator<TSession> {
|
|
137
|
+
startSignIn(providerName: string, req: IncomingMessage, opts?: {
|
|
138
|
+
returnTo?: string;
|
|
139
|
+
}): Promise<Response>;
|
|
140
|
+
finishSignIn(providerName: string, req: IncomingMessage, res: ServerResponse): Promise<{
|
|
141
|
+
session: TSession;
|
|
142
|
+
returnTo?: string;
|
|
143
|
+
}>;
|
|
144
|
+
signIn<TProfile>(profile: TProfile, providerName: string, req: IncomingMessage, res: ServerResponse): Promise<TSession>;
|
|
145
|
+
signOut(res: ServerResponse): void | Promise<void>;
|
|
146
|
+
getSession(req: IncomingMessage): Promise<TSession | null>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @theokit/sdk/server/auth — encrypted OAuth transaction cookie store
|
|
151
|
+
*
|
|
152
|
+
* Per ADR D5 — cookie-state pattern (no Redis/db dependency in core).
|
|
153
|
+
*
|
|
154
|
+
* Stores OAuthTransaction (state + pkceVerifier + returnTo + expiry) in a
|
|
155
|
+
* single signed+encrypted HttpOnly cookie. Stateless, works in edge/serverless.
|
|
156
|
+
*
|
|
157
|
+
* Cookie name: `__Host-theo_oauth_tx` (T5.3 — RFC 6265bis prefix)
|
|
158
|
+
* Lifetime: 10 minutes (per D5 invariant)
|
|
159
|
+
* Encryption: AES-256-GCM via Node's webcrypto subtle API
|
|
160
|
+
*
|
|
161
|
+
* Note: this is a minimal in-package implementation. Production deployments
|
|
162
|
+
* may prefer using `theokit/server/auth/crypto`'s encrypt/decrypt helpers
|
|
163
|
+
* via the SessionManager's existing secret rotation chain. For T1.2 we keep
|
|
164
|
+
* it self-contained to avoid cross-package peer-dep complexity; T2+ may
|
|
165
|
+
* refactor to share SessionManager's encrypt path.
|
|
166
|
+
*/
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* T5.1 — Typed error thrown when an OAuth tx-cookie secret has < 32
|
|
170
|
+
* bytes of entropy. Surfaces the actual byte length so operators can
|
|
171
|
+
* diagnose mis-configured env vars without leaking the secret itself.
|
|
172
|
+
*
|
|
173
|
+
* @public
|
|
174
|
+
*/
|
|
175
|
+
declare class AuthSecretTooShortError extends Error {
|
|
176
|
+
readonly name = "AuthSecretTooShortError";
|
|
177
|
+
constructor(actualBytes: number);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* @theokit/sdk/server/auth — defineAuth orchestrator runtime (Caminho C Hybrid)
|
|
182
|
+
*
|
|
183
|
+
* Plan T1.2 implementation per blueprint Q5 § Caminho C signatures.
|
|
184
|
+
* Composes existing primitives + the v1.1 EC-1/EC-2/EC-10 fixes.
|
|
185
|
+
*/
|
|
186
|
+
|
|
187
|
+
/** SE36 — `Auth.create` replaces `defineAuth` (ADR 0015). @public */
|
|
188
|
+
declare class Auth {
|
|
189
|
+
private constructor();
|
|
190
|
+
static create<TSession>(opts: DefineAuthOptions<TSession>): AuthOrchestrator<TSession>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* @theokit/sdk/server/auth — same-origin returnTo validator
|
|
195
|
+
*
|
|
196
|
+
* Per v1.1 EC-2 MUST FIX — OWASP A01:2021 open-redirect mitigation.
|
|
197
|
+
*
|
|
198
|
+
* Without this check, attacker craft `/login?returnTo=https://evil.com` would
|
|
199
|
+
* cause post-login redirect to attacker domain with authenticated session cookie.
|
|
7
200
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
201
|
+
* Rules:
|
|
202
|
+
* - undefined/empty returnTo → default '/'
|
|
203
|
+
* - protocol-relative `//evil.com` → default '/' (URL parser would resolve to baseUrl protocol)
|
|
204
|
+
* - absolute URL with origin ≠ baseUrl.origin → default '/' (cross-origin redirect)
|
|
205
|
+
* - absolute URL with origin === baseUrl.origin → keep (same-origin allowed)
|
|
206
|
+
* - relative path starting with '/' → keep (same-app navigation)
|
|
207
|
+
* - relative path not starting with '/' → default '/' (defensive)
|
|
10
208
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export { Auth
|
|
14
|
-
export type { AuthOrchestrator, AuthProvider, AuthResult, DefineAuthOptions, OAuthTransaction, SessionManager, } from "./types.js";
|
|
15
|
-
export { validateReturnTo } from "./validate-return-to.js";
|
|
209
|
+
declare function validateReturnTo(returnTo: string | undefined, baseUrl: URL): string;
|
|
210
|
+
|
|
211
|
+
export { Auth, AuthCallbackError, AuthCancelledError, AuthConfigError, type AuthOrchestrator, type AuthProvider, AuthProviderNotFoundError, type AuthResult, AuthSecretTooShortError, type DefineAuthOptions, type OAuthTransaction, type SessionManager, validateReturnTo };
|