@ekairos/events 1.22.83-beta.development.0 → 1.22.85-beta.development.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.
@@ -5,13 +5,22 @@ import { ContextEngine, type ContextModelInit, type ContextOptions, type ShouldC
5
5
  import type { ContextTool } from "./context.action.js";
6
6
  import type { ContextRuntime, ContextRuntimeHandleForDomain } from "./context.runtime.js";
7
7
  import type { ContextReactor } from "./context.reactor.js";
8
- import type { ContextItem, StoredContext } from "./context.store.js";
8
+ import type { ContextItem, ContextResource, StoredContext, StoredContextResource } from "./context.store.js";
9
9
  import { type ContextKey } from "./context.registry.js";
10
10
  import { eventsDomain } from "./schema.js";
11
+ export type ContextResourcesParams<Context, Env extends ContextEnvironment = ContextEnvironment, RequiredDomain extends DomainLike = typeof eventsDomain> = {
12
+ content: Context;
13
+ context: StoredContext<Context>;
14
+ env: Env;
15
+ runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>;
16
+ };
11
17
  export interface ContextConfig<Context, Env extends ContextEnvironment = ContextEnvironment, RequiredDomain extends DomainLike = typeof eventsDomain> {
12
18
  context: (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<Context> | Context;
13
19
  expandEvents?: (events: ContextItem[], context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<ContextItem[]> | ContextItem[];
14
- narrative: (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<string> | string;
20
+ narrative?: (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<string> | string;
21
+ description?: (content: Context, context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<string> | string;
22
+ goal?: (content: Context, context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<string> | string;
23
+ resources?: (params: ContextResourcesParams<Context, Env, RequiredDomain>) => Promise<ContextResource[] | StoredContextResource[]> | ContextResource[] | StoredContextResource[];
15
24
  skills?: (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<ContextSkillPackage[]> | ContextSkillPackage[];
16
25
  actions: (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<Record<string, ContextTool<Context, Env, RequiredDomain>>> | Record<string, ContextTool<Context, Env, RequiredDomain>>;
17
26
  /**
@@ -32,6 +41,10 @@ export declare function context<Context, Env extends ContextEnvironment = Contex
32
41
  type AnyContextInitializer<Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (context: StoredContext<any>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<any> | any;
33
42
  type InferContextFromInitializer<I extends AnyContextInitializer<any, any>> = Awaited<ReturnType<I>>;
34
43
  type BuilderSystemPrompt<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<string> | string;
44
+ type BuilderDescription<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (content: Context, context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<string> | string;
45
+ type BuilderGoal<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = BuilderDescription<Context, Env, RequiredDomain>;
46
+ type BuilderResources<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (params: ContextResourcesParams<Context, Env, RequiredDomain>) => Promise<ContextResource[] | StoredContextResource[] | null> | ContextResource[] | StoredContextResource[] | null;
47
+ type BuilderResource<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = ContextResource | StoredContextResource | ((params: ContextResourcesParams<Context, Env, RequiredDomain>) => Promise<ContextResource | StoredContextResource | null | undefined> | ContextResource | StoredContextResource | null | undefined);
35
48
  type BuilderSkills<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<ContextSkillPackage[]> | ContextSkillPackage[];
36
49
  type BuilderTools<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<Record<string, ContextTool<Context, Env, RequiredDomain>>> | Record<string, ContextTool<Context, Env, RequiredDomain>>;
37
50
  type BuilderExpandEvents<Context, Env extends ContextEnvironment, RequiredDomain extends DomainLike> = (events: ContextItem[], context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>) => Promise<ContextItem[]> | ContextItem[];
@@ -46,6 +59,10 @@ type FluentContextBuilder<Context, Env extends ContextEnvironment, RequiredDomai
46
59
  expandEvents(fn: BuilderExpandEvents<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
47
60
  narrative(fn: BuilderSystemPrompt<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
48
61
  system(fn: BuilderSystemPrompt<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
62
+ description(fn: BuilderDescription<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
63
+ goal(fn: BuilderGoal<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
64
+ resources(fn: BuilderResources<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
65
+ resource(resource: BuilderResource<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
49
66
  skills(fn: BuilderSkills<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
50
67
  actions(fn: BuilderTools<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
51
68
  tools(fn: BuilderTools<Context, Env, RequiredDomain>): FluentContextBuilder<Context, Env, RequiredDomain>;
@@ -64,6 +81,7 @@ type FluentContextBuilder<Context, Env extends ContextEnvironment, RequiredDomai
64
81
  build(): ContextInstance<Context, Env, RequiredDomain>;
65
82
  };
66
83
  type CreateContextEntry<Env extends ContextEnvironment, RequiredDomain extends DomainLike> = {
84
+ content<Initializer extends AnyContextInitializer<Env, RequiredDomain>>(initializer: Initializer): FluentContextBuilder<InferContextFromInitializer<Initializer>, Env, RequiredDomain>;
67
85
  context<Initializer extends AnyContextInitializer<Env, RequiredDomain>>(initializer: Initializer): FluentContextBuilder<InferContextFromInitializer<Initializer>, Env, RequiredDomain>;
68
86
  initialize<Initializer extends AnyContextInitializer<Env, RequiredDomain>>(initializer: Initializer): FluentContextBuilder<InferContextFromInitializer<Initializer>, Env, RequiredDomain>;
69
87
  };
@@ -4,6 +4,28 @@ import { eventsDomain } from "./schema.js";
4
4
  function isDynamicModelSelector(model) {
5
5
  return typeof model === "function" && model.length >= 1;
6
6
  }
7
+ function stringifyContextContent(content) {
8
+ try {
9
+ return JSON.stringify(content ?? null, null, 2);
10
+ }
11
+ catch {
12
+ return String(content);
13
+ }
14
+ }
15
+ function buildDefaultContextPrompt(params) {
16
+ const sections = [];
17
+ sections.push(`Content:\n${stringifyContextContent(params.content)}`);
18
+ if (params.resources?.length) {
19
+ sections.push(`Resources:\n${stringifyContextContent(params.resources)}`);
20
+ }
21
+ if (params.description) {
22
+ sections.push(`Description:\n${params.description}`);
23
+ }
24
+ if (params.goal) {
25
+ sections.push(`Goal:\n${params.goal}`);
26
+ }
27
+ return sections.join("\n\n");
28
+ }
7
29
  export function context(config) {
8
30
  class FunctionalContext extends ContextEngine {
9
31
  constructor() {
@@ -21,7 +43,36 @@ export function context(config) {
21
43
  async buildSystemPrompt(contextValue, env, runtime) {
22
44
  if (config.narrative)
23
45
  return config.narrative(contextValue, env, runtime);
24
- throw new Error("Context config is missing narrative()");
46
+ const content = contextValue.content;
47
+ const description = contextValue.description ??
48
+ (config.description
49
+ ? await config.description(content, contextValue, env, runtime)
50
+ : null);
51
+ const goal = contextValue.goal ??
52
+ (config.goal
53
+ ? await config.goal(content, contextValue, env, runtime)
54
+ : null);
55
+ return buildDefaultContextPrompt({
56
+ content,
57
+ resources: contextValue.resources ?? [],
58
+ description,
59
+ goal,
60
+ });
61
+ }
62
+ async describeContext(content, contextValue, env, runtime) {
63
+ if (!config.description)
64
+ return null;
65
+ return config.description(content, contextValue, env, runtime);
66
+ }
67
+ async defineGoal(content, contextValue, env, runtime) {
68
+ if (!config.goal)
69
+ return null;
70
+ return config.goal(content, contextValue, env, runtime);
71
+ }
72
+ async defineResources(content, contextValue, env, runtime) {
73
+ if (!config.resources)
74
+ return [];
75
+ return config.resources({ content, context: contextValue, env, runtime });
25
76
  }
26
77
  async buildSkills(contextValue, env, runtime) {
27
78
  if (config.skills)
@@ -51,10 +102,10 @@ export function context(config) {
51
102
  }
52
103
  function assertConfigComplete(config) {
53
104
  if (!config.context) {
54
- throw new Error("createContext: you must define context() before building the Context.");
105
+ throw new Error("createContext: you must define content() before building the Context.");
55
106
  }
56
- if (!config.narrative) {
57
- throw new Error("createContext: you must define narrative() before building the Context.");
107
+ if (!config.narrative && (!config.description || !config.goal)) {
108
+ throw new Error("createContext: you must define description() and goal() before building the Context.");
58
109
  }
59
110
  if (!config.actions && !config.tools) {
60
111
  throw new Error("createContext: you must define actions() before building the Context.");
@@ -71,6 +122,20 @@ export function createContext(keyOrDomain, maybeKey) {
71
122
  const fluentState = {
72
123
  context: typedInitializer,
73
124
  };
125
+ const resourceFactories = [];
126
+ const refreshResourcesConfig = () => {
127
+ fluentState.resources = async (params) => {
128
+ const resources = [];
129
+ for (const factory of resourceFactories) {
130
+ const result = await factory(params);
131
+ if (!result)
132
+ continue;
133
+ const list = Array.isArray(result) ? result : [result];
134
+ resources.push(...list);
135
+ }
136
+ return resources;
137
+ };
138
+ };
74
139
  let cached = null;
75
140
  const getOrBuild = () => {
76
141
  assertConfigComplete(fluentState);
@@ -98,6 +163,30 @@ export function createContext(keyOrDomain, maybeKey) {
98
163
  fluentState.narrative = system;
99
164
  return builder;
100
165
  },
166
+ description(description) {
167
+ fluentState.description = description;
168
+ return builder;
169
+ },
170
+ goal(goal) {
171
+ fluentState.goal = goal;
172
+ return builder;
173
+ },
174
+ resources(resources) {
175
+ resourceFactories.push(resources);
176
+ refreshResourcesConfig();
177
+ return builder;
178
+ },
179
+ resource(resource) {
180
+ resourceFactories.push(async (params) => {
181
+ if (typeof resource === "function") {
182
+ const resolved = await resource(params);
183
+ return resolved ? [resolved] : [];
184
+ }
185
+ return [resource];
186
+ });
187
+ refreshResourcesConfig();
188
+ return builder;
189
+ },
101
190
  skills(skillsFactory) {
102
191
  fluentState.skills = skillsFactory;
103
192
  return builder;
@@ -142,6 +231,7 @@ export function createContext(keyOrDomain, maybeKey) {
142
231
  return builder;
143
232
  };
144
233
  return {
234
+ content: initializeBuilder,
145
235
  context: initializeBuilder,
146
236
  initialize: initializeBuilder,
147
237
  };
package/dist/context.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { ContextEngine, type ContextOptions, type ContextStreamOptions, type ShouldContinue, type ContextShouldContinueArgs, type ContextReactParams, type ContextDirectReactParams, type ContextDurableReactParams, type ContextReactResult, type ContextReactBase, type ContextReactFinalResult, type ContextDirectRun, type ContextReactRun, type ContextWorkflowRun, type ContextDurableWorkflowPayload, type ContextDurableWorkflowFunction, type ContextModelInit, type ContextToolExecuteContext, runContextReactionDirect, } from "./context.engine.js";
2
- export { context, createContext, type ContextConfig, type ContextInstance, type RegistrableContextBuilder, } from "./context.builder.js";
2
+ export { context, createContext, type ContextConfig, type ContextInstance, type ContextResourcesParams, type RegistrableContextBuilder, } from "./context.builder.js";
3
3
  export { defineAction, action, type ContextAction, type ContextActionBase, type ContextActionExecuteParams, type AnyContextAction, type ContextActionDefinition, type ContextActionExecute, type DefineContextActionDefinition, type DefineContextActionExecute, type LegacyContextActionDefinition, type LegacyContextActionExecute, type ContextActionInput, type ContextActionOutput, type ContextProviderDefinedAction, type ContextActionSchema, type ContextTool, } from "./context.action.js";
4
4
  export { createAiSdkReactor, createScriptedReactor, type CreateAiSdkReactorOptions, type CreateScriptedReactorOptions, type ScriptedReactorStep, type ContextReactor, type ContextReactorParams, type ContextReactionResult, type ContextActionRequest, type ContextReactionLLM, } from "./context.reactor.js";
5
5
  export type { ContextSkillPackage, ContextSkillPackageFile, } from "./context.skill.js";
@@ -4,7 +4,7 @@ import type { ContextEnvironment } from "./context.config.js";
4
4
  import type { ContextTool } from "./context.action.js";
5
5
  import type { ContextRuntime, ContextRuntimeHandleForDomain, ContextRuntimeForDomain } from "./context.runtime.js";
6
6
  import { eventsDomain } from "./schema.js";
7
- import type { ContextExecution, ContextItem, ContextIdentifier, StoredContext } from "./context.store.js";
7
+ import type { ContextExecution, ContextItem, ContextIdentifier, ContextResource, StoredContext } from "./context.store.js";
8
8
  import type { ContextSkillPackage } from "./context.skill.js";
9
9
  import { type ContextReactor } from "./context.reactor.js";
10
10
  import { getClientResumeHookUrl, toolApprovalHookToken, toolApprovalWebhookToken } from "./context.hooks.js";
@@ -50,14 +50,6 @@ export interface ContextStreamOptions {
50
50
  * Default: true.
51
51
  */
52
52
  sendFinish?: boolean;
53
- /**
54
- * If true, the story loop runs silently (no UI streaming output).
55
- *
56
- * Persistence (contexts/events/executions) still happens normally.
57
- *
58
- * Default: false.
59
- */
60
- silent?: boolean;
61
53
  /**
62
54
  * Optional writable stream used by direct/non-durable execution.
63
55
  *
@@ -205,6 +197,9 @@ export declare abstract class ContextEngine<Context, Env extends ContextEnvironm
205
197
  constructor(opts?: ContextOptions<Context, Env, RequiredDomain>, reactor?: ContextReactor<Context, Env, RequiredDomain>);
206
198
  protected abstract initialize(context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<Context> | Context;
207
199
  protected abstract buildSystemPrompt(context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<string> | string;
200
+ protected describeContext(_content: Context, _context: StoredContext<Context>, _env: Env, _runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<string | null>;
201
+ protected defineGoal(_content: Context, _context: StoredContext<Context>, _env: Env, _runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<string | null>;
202
+ protected defineResources(_content: Context, _context: StoredContext<Context>, _env: Env, _runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<ContextResource[]>;
208
203
  protected abstract buildTools(context: StoredContext<Context>, env: Env, runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<Record<string, ContextTool<Context, Env, RequiredDomain>>> | Record<string, ContextTool<Context, Env, RequiredDomain>>;
209
204
  protected buildSkills(_context: StoredContext<Context>, _env: Env, _runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>): Promise<ContextSkillPackage[]>;
210
205
  /**
@@ -4,7 +4,7 @@ import { applyActionExecutionResultToParts } from "./context.action-calls.js";
4
4
  import { isContextPartEnvelope, normalizePartsForPersistence, } from "./context.parts.js";
5
5
  import { createAiSdkReactor, } from "./context.reactor.js";
6
6
  import { abortPersistedContextStepStream, closeContextStream, createPersistedContextStepStreamForRuntime, finalizePersistedContextStepStreamForRuntime, writeActionResultPartChunksToSession, } from "./steps/stream.steps.js";
7
- import { completeExecution, completeExecutionStep, createContextStep, getContextItems, initializeContext, openExecutionStep, openExecution, saveExecutionStepOutput, updateContextContent, updateContextReactor, updateContextStatus, updateItem, updateContextStep, updateExecutionWorkflowRun, } from "./steps/store.steps.js";
7
+ import { completeExecution, completeExecutionStep, createContextStep, getContextItems, initializeContext, openExecutionStep, openExecution, saveExecutionStepOutput, updateContextContent, updateContextDefinition, updateContextReactor, updateContextStatus, updateItem, updateContextStep, updateExecutionWorkflowRun, upsertContextResources, } from "./steps/store.steps.js";
8
8
  import { readContextDurableWorkflowReturnValue, readContextDurableWorkflowStatus, resumeContextReturnValueHook, startContextDurableWorkflow, } from "./steps/durable.steps.js";
9
9
  import { getClientResumeHookUrl, toolApprovalHookToken, toolApprovalWebhookToken, } from "./context.hooks.js";
10
10
  import { getContextDurableWorkflow } from "./context.durable.js";
@@ -188,6 +188,8 @@ async function createRuntimeOps(runtimeHandle, benchmark) {
188
188
  return { context, isNew: true };
189
189
  },
190
190
  updateContextContent: async (contextIdentifier, content) => await store.updateContextContent(contextIdentifier, content),
191
+ updateContextDefinition: async (contextIdentifier, definition) => await store.updateContextDefinition(contextIdentifier, definition),
192
+ upsertContextResources: async (contextIdentifier, resources) => await store.upsertContextResources(contextIdentifier, resources),
191
193
  updateContextReactor: async (contextIdentifier, reactor) => await store.updateContextReactor(contextIdentifier, reactor),
192
194
  updateContextStatus: async (contextIdentifier, status) => await instrumentedDb.transact([
193
195
  instrumentedDb.tx.event_contexts[requireContextId(contextIdentifier)].update({
@@ -390,8 +392,10 @@ async function createRuntimeOps(runtimeHandle, benchmark) {
390
392
  async function createWorkflowOps(runtime) {
391
393
  const env = runtime.env;
392
394
  return {
393
- initializeContext: async (contextIdentifier, opts) => await initializeContext({ runtime, contextIdentifier, opts }),
395
+ initializeContext: async (contextIdentifier) => await initializeContext({ runtime, contextIdentifier }),
394
396
  updateContextContent: async (contextIdentifier, content) => await updateContextContent({ runtime, contextIdentifier, content }),
397
+ updateContextDefinition: async (contextIdentifier, definition) => await updateContextDefinition({ runtime, contextIdentifier, definition }),
398
+ upsertContextResources: async (contextIdentifier, resources) => await upsertContextResources({ runtime, contextIdentifier, resources }),
395
399
  updateContextReactor: async (contextIdentifier, reactor) => await updateContextReactor({ runtime, contextIdentifier, reactor }),
396
400
  updateContextStatus: async (contextIdentifier, status) => await updateContextStatus({ runtime, contextIdentifier, status }),
397
401
  openExecution: async ({ contextIdentifier, triggerEvent }) => await openExecution({ runtime, contextIdentifier, triggerEvent }),
@@ -420,6 +424,15 @@ export class ContextEngine {
420
424
  reactor ??
421
425
  createAiSdkReactor();
422
426
  }
427
+ async describeContext(_content, _context, _env, _runtime) {
428
+ return null;
429
+ }
430
+ async defineGoal(_content, _context, _env, _runtime) {
431
+ return null;
432
+ }
433
+ async defineResources(_content, _context, _env, _runtime) {
434
+ return [];
435
+ }
423
436
  async buildSkills(_context, _env, _runtime) {
424
437
  return [];
425
438
  }
@@ -470,8 +483,7 @@ export class ContextEngine {
470
483
  const runtimeHandle = await resolveReactRuntime(params);
471
484
  const env = runtimeHandle.env;
472
485
  const ops = await measureBenchmark(params.__benchmark, "react.resolveOpsMs", async () => await getContextEngineOps(runtimeHandle, params.__benchmark));
473
- const silent = params.options?.silent ?? false;
474
- const ctxResult = await measureBenchmark(params.__benchmark, "react.initializeContextMs", async () => await ops.initializeContext(params.context ?? null, { silent }));
486
+ const ctxResult = await measureBenchmark(params.__benchmark, "react.initializeContextMs", async () => await ops.initializeContext(params.context ?? null));
475
487
  let currentContext = ctxResult.context;
476
488
  const contextSelector = { id: String(currentContext.id) };
477
489
  if (ctxResult.isNew) {
@@ -566,7 +578,6 @@ export class ContextEngine {
566
578
  maxModelSteps: params.options?.maxModelSteps,
567
579
  preventClose: params.options?.preventClose,
568
580
  sendFinish: params.options?.sendFinish,
569
- silent: params.options?.silent,
570
581
  },
571
582
  bootstrap: {
572
583
  contextId: shell.currentContext.id,
@@ -634,7 +645,6 @@ export class ContextEngine {
634
645
  const maxModelSteps = params.options?.maxModelSteps ?? 1;
635
646
  const preventClose = params.options?.preventClose ?? false;
636
647
  const sendFinish = params.options?.sendFinish ?? true;
637
- const silent = params.options?.silent ?? false;
638
648
  const writable = params.options?.writable;
639
649
  const bootstrapped = params.__bootstrap;
640
650
  const returnValueHookToken = bootstrapped?.returnValueHookToken ?? null;
@@ -649,7 +659,7 @@ export class ContextEngine {
649
659
  const shell = bootstrapped
650
660
  ? {
651
661
  contextSelector: { id: String(bootstrapped.contextId) },
652
- currentContext: (await measureBenchmark(params.__benchmark, "react.bootstrapContextLookupMs", async () => await ops.initializeContext({ id: String(bootstrapped.contextId) }, { silent }))).context,
662
+ currentContext: (await measureBenchmark(params.__benchmark, "react.bootstrapContextLookupMs", async () => await ops.initializeContext({ id: String(bootstrapped.contextId) }))).context,
653
663
  trigger: bootstrapped.trigger,
654
664
  reaction: bootstrapped.reaction,
655
665
  execution: bootstrapped.execution,
@@ -672,7 +682,6 @@ export class ContextEngine {
672
682
  execution = { ...execution, status: "failed" };
673
683
  updatedContext = { ...updatedContext, status: "closed" };
674
684
  await emitContextEvents({
675
- silent,
676
685
  writable,
677
686
  events: [
678
687
  {
@@ -695,9 +704,7 @@ export class ContextEngine {
695
704
  // noop
696
705
  }
697
706
  try {
698
- if (!silent) {
699
- await closeContextStream({ preventClose, sendFinish, writable });
700
- }
707
+ await closeContextStream({ preventClose, sendFinish, writable });
701
708
  }
702
709
  catch {
703
710
  // noop
@@ -725,8 +732,36 @@ export class ContextEngine {
725
732
  currentStepStream = openedStep.stream;
726
733
  updatedContext = openedStep.context;
727
734
  const rawEvents = openedStep.events;
735
+ const previousResources = updatedContext.resources ?? [];
736
+ const resources = await measureBenchmark(params.__benchmark, `${stagePrefix}.resourcesMs`, async () => await story.defineResources(nextContent, updatedContext, env, runtimeHandle));
737
+ const shouldPersistResources = resources.length > 0 || previousResources.length > 0;
738
+ let contextResources = previousResources;
739
+ if (shouldPersistResources) {
740
+ contextResources = await measureBenchmark(params.__benchmark, `${stagePrefix}.contextResourcesMs`, async () => await ops.upsertContextResources(activeContextSelector, resources));
741
+ updatedContext = {
742
+ ...updatedContext,
743
+ resources: contextResources,
744
+ };
745
+ }
746
+ else {
747
+ updatedContext = {
748
+ ...updatedContext,
749
+ resources: [],
750
+ };
751
+ }
752
+ const description = await measureBenchmark(params.__benchmark, `${stagePrefix}.descriptionMs`, async () => await story.describeContext(nextContent, updatedContext, env, runtimeHandle));
753
+ const goal = await measureBenchmark(params.__benchmark, `${stagePrefix}.goalMs`, async () => await story.defineGoal(nextContent, updatedContext, env, runtimeHandle));
754
+ if (description !== null || goal !== null) {
755
+ updatedContext = await measureBenchmark(params.__benchmark, `${stagePrefix}.contextDefinitionMs`, async () => await ops.updateContextDefinition(activeContextSelector, {
756
+ ...(description !== null ? { description } : {}),
757
+ ...(goal !== null ? { goal } : {}),
758
+ }));
759
+ updatedContext = {
760
+ ...updatedContext,
761
+ resources: contextResources,
762
+ };
763
+ }
728
764
  await emitContextEvents({
729
- silent,
730
765
  writable,
731
766
  events: [
732
767
  {
@@ -742,6 +777,24 @@ export class ContextEngine {
742
777
  at: nowIso(),
743
778
  contextId: String(updatedContext.id),
744
779
  },
780
+ ...(description !== null || goal !== null
781
+ ? [
782
+ {
783
+ type: "context.definition_updated",
784
+ at: nowIso(),
785
+ contextId: String(updatedContext.id),
786
+ },
787
+ ]
788
+ : []),
789
+ ...(shouldPersistResources
790
+ ? [
791
+ {
792
+ type: "context.resources_updated",
793
+ at: nowIso(),
794
+ contextId: String(updatedContext.id),
795
+ },
796
+ ]
797
+ : []),
745
798
  ],
746
799
  });
747
800
  await story.opts.onContextUpdated?.({
@@ -795,6 +848,7 @@ export class ContextEngine {
795
848
  runtime: runtimeHandle,
796
849
  context: updatedContext,
797
850
  contextIdentifier: activeContextSelector,
851
+ resources: contextResources,
798
852
  events: expandedEvents,
799
853
  triggerEvent,
800
854
  model: story.getModel(updatedContext, env, runtimeHandle),
@@ -808,8 +862,7 @@ export class ContextEngine {
808
862
  iteration: iter,
809
863
  maxModelSteps,
810
864
  // Only emit a `start` chunk once per story turn.
811
- sendStart: !silent && iter === 0,
812
- silent,
865
+ sendStart: iter === 0,
813
866
  contextStepStream: currentStepStream?.stream,
814
867
  writable,
815
868
  persistReactionParts,
@@ -865,7 +918,6 @@ export class ContextEngine {
865
918
  }));
866
919
  reactionEvent = appendedReactorOutput.reactionEvent;
867
920
  await emitContextEvents({
868
- silent,
869
921
  writable,
870
922
  events: stepParts.map((part, idx) => ({
871
923
  type: "part.created",
@@ -890,7 +942,6 @@ export class ContextEngine {
890
942
  }
891
943
  story.opts.onEventCreated?.(assistantEventEffective);
892
944
  await emitContextEvents({
893
- silent,
894
945
  writable,
895
946
  events: [
896
947
  {
@@ -925,7 +976,6 @@ export class ContextEngine {
925
976
  currentStepId = null;
926
977
  reactionEvent = finalized.reactionEvent ?? completedReactionEvent;
927
978
  await emitContextEvents({
928
- silent,
929
979
  writable,
930
980
  events: [
931
981
  {
@@ -947,7 +997,6 @@ export class ContextEngine {
947
997
  ],
948
998
  });
949
999
  await emitContextEvents({
950
- silent,
951
1000
  writable,
952
1001
  events: [
953
1002
  {
@@ -964,7 +1013,6 @@ export class ContextEngine {
964
1013
  execution = { ...execution, status: "completed" };
965
1014
  updatedContext = { ...updatedContext, status: "closed" };
966
1015
  await emitContextEvents({
967
- silent,
968
1016
  writable,
969
1017
  events: [
970
1018
  {
@@ -982,9 +1030,7 @@ export class ContextEngine {
982
1030
  },
983
1031
  ],
984
1032
  });
985
- if (!silent) {
986
- await closeContextStream({ preventClose, sendFinish, writable });
987
- }
1033
+ await closeContextStream({ preventClose, sendFinish, writable });
988
1034
  const result = {
989
1035
  context: updatedContext,
990
1036
  trigger,
@@ -1099,12 +1145,10 @@ export class ContextEngine {
1099
1145
  currentStepId = null;
1100
1146
  reactionEvent = completedStep.reactionEvent ?? pendingReactionEvent;
1101
1147
  await emitContextEvents({
1102
- silent,
1103
1148
  writable,
1104
1149
  events: completedStep.actionResultChunkEvents,
1105
1150
  });
1106
1151
  await emitContextEvents({
1107
- silent,
1108
1152
  writable,
1109
1153
  events: [
1110
1154
  {
@@ -1149,7 +1193,6 @@ export class ContextEngine {
1149
1193
  }));
1150
1194
  if (continueLoop !== false) {
1151
1195
  await emitContextEvents({
1152
- silent,
1153
1196
  writable,
1154
1197
  events: [
1155
1198
  {
@@ -1169,7 +1212,6 @@ export class ContextEngine {
1169
1212
  status: "completed",
1170
1213
  };
1171
1214
  await emitContextEvents({
1172
- silent,
1173
1215
  writable,
1174
1216
  events: [
1175
1217
  {
@@ -1190,7 +1232,6 @@ export class ContextEngine {
1190
1232
  execution = { ...execution, status: "completed" };
1191
1233
  updatedContext = { ...updatedContext, status: "closed" };
1192
1234
  await emitContextEvents({
1193
- silent,
1194
1235
  writable,
1195
1236
  events: [
1196
1237
  {
@@ -1208,9 +1249,7 @@ export class ContextEngine {
1208
1249
  },
1209
1250
  ],
1210
1251
  });
1211
- if (!silent) {
1212
- await closeContextStream({ preventClose, sendFinish, writable });
1213
- }
1252
+ await closeContextStream({ preventClose, sendFinish, writable });
1214
1253
  const result = {
1215
1254
  context: updatedContext,
1216
1255
  trigger,
@@ -1253,7 +1292,6 @@ export class ContextEngine {
1253
1292
  contextId: String(currentContext.id),
1254
1293
  }));
1255
1294
  await emitContextEvents({
1256
- silent,
1257
1295
  writable,
1258
1296
  events: [
1259
1297
  {
@@ -8,6 +8,50 @@ export type ContextIdentifier = {
8
8
  id?: never;
9
9
  };
10
10
  export type { ContextStatus } from "./context.contract.js";
11
+ export type ContextResourceBase = {
12
+ key: string;
13
+ type: string;
14
+ name: string;
15
+ description: string;
16
+ role?: string | null;
17
+ metadata?: Record<string, unknown> | null;
18
+ };
19
+ export type ContextFileResource = ContextResourceBase & {
20
+ type: "file";
21
+ fileId?: string;
22
+ documentId?: string;
23
+ url?: string;
24
+ filename?: string;
25
+ mediaType?: string;
26
+ size?: number;
27
+ };
28
+ export type ContextLinkResource = ContextResourceBase & {
29
+ type: "link";
30
+ url: string;
31
+ };
32
+ export type ContextRepositoryResource = ContextResourceBase & {
33
+ type: "repository";
34
+ provider?: string;
35
+ repository: string;
36
+ ref?: string;
37
+ paths?: string[];
38
+ commitSha?: string;
39
+ };
40
+ export type ContextDatasetResource = ContextResourceBase & {
41
+ type: "dataset";
42
+ datasetId: string;
43
+ };
44
+ export type ContextExternalResource = ContextResourceBase & {
45
+ type: "external";
46
+ uri?: string;
47
+ };
48
+ export type ContextResource = ContextFileResource | ContextLinkResource | ContextRepositoryResource | ContextDatasetResource | ContextExternalResource | (ContextResourceBase & Record<string, unknown>);
49
+ export type StoredContextResource = ContextResource & {
50
+ id?: string;
51
+ storageKey?: string;
52
+ createdAt?: Date;
53
+ updatedAt?: Date;
54
+ };
11
55
  export type StoredContext<Context> = {
12
56
  id: string;
13
57
  key: string | null;
@@ -16,6 +60,9 @@ export type StoredContext<Context> = {
16
60
  createdAt: Date;
17
61
  updatedAt?: Date;
18
62
  content: Context | null;
63
+ description?: string | null;
64
+ goal?: string | null;
65
+ resources?: StoredContextResource[] | null;
19
66
  reactor?: {
20
67
  kind: string;
21
68
  state?: Record<string, unknown> | null;
@@ -53,6 +100,12 @@ export interface ContextStore {
53
100
  getOrCreateContext<C>(contextIdentifier: ContextIdentifier | null): Promise<StoredContext<C>>;
54
101
  getContext<C>(contextIdentifier: ContextIdentifier): Promise<StoredContext<C> | null>;
55
102
  updateContextContent<C>(contextIdentifier: ContextIdentifier, content: C): Promise<StoredContext<C>>;
103
+ updateContextDefinition<C>(contextIdentifier: ContextIdentifier, definition: {
104
+ description?: string | null;
105
+ goal?: string | null;
106
+ }): Promise<StoredContext<C>>;
107
+ upsertContextResources(contextIdentifier: ContextIdentifier, resources: ContextResource[]): Promise<StoredContextResource[]>;
108
+ getContextResources(contextIdentifier: ContextIdentifier): Promise<StoredContextResource[]>;
56
109
  updateContextReactor<C>(contextIdentifier: ContextIdentifier, reactor: {
57
110
  kind: string;
58
111
  state?: Record<string, unknown> | null;
@@ -23,6 +23,14 @@ export type ContextContentUpdatedEvent = ContextStreamEventBase & {
23
23
  type: "context.content_updated";
24
24
  contextId: string;
25
25
  };
26
+ export type ContextDefinitionUpdatedEvent = ContextStreamEventBase & {
27
+ type: "context.definition_updated";
28
+ contextId: string;
29
+ };
30
+ export type ContextResourcesUpdatedEvent = ContextStreamEventBase & {
31
+ type: "context.resources_updated";
32
+ contextId: string;
33
+ };
26
34
  export type ExecutionCreatedEvent = ContextStreamEventBase & {
27
35
  type: "execution.created";
28
36
  executionId: string;
@@ -138,7 +146,7 @@ export type ChunkEmittedEvent = ContextStreamEventBase & {
138
146
  data?: unknown;
139
147
  raw?: unknown;
140
148
  };
141
- export type ContextLifecycleEvent = ContextCreatedEvent | ContextResolvedEvent | ContextStatusChangedEvent | ContextContentUpdatedEvent;
149
+ export type ContextLifecycleEvent = ContextCreatedEvent | ContextResolvedEvent | ContextStatusChangedEvent | ContextContentUpdatedEvent | ContextDefinitionUpdatedEvent | ContextResourcesUpdatedEvent;
142
150
  export type ExecutionEvent = ExecutionCreatedEvent | ExecutionCompletedEvent | ExecutionFailedEvent;
143
151
  export type ItemEvent = ItemCreatedEvent | ItemUpdatedEvent | ItemPendingEvent | ItemCompletedEvent;
144
152
  export type StepEvent = StepCreatedEvent | StepUpdatedEvent | StepCompletedEvent | StepFailedEvent;
@@ -48,6 +48,14 @@ export function parseContextStreamEvent(value) {
48
48
  assertString(value.contextId, `${type}.contextId`);
49
49
  return value;
50
50
  }
51
+ case "context.definition_updated": {
52
+ assertString(value.contextId, `${type}.contextId`);
53
+ return value;
54
+ }
55
+ case "context.resources_updated": {
56
+ assertString(value.contextId, `${type}.contextId`);
57
+ return value;
58
+ }
51
59
  case "execution.created":
52
60
  case "execution.completed":
53
61
  case "execution.failed": {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { context, createContext, createAiSdkReactor, createScriptedReactor, type CreateAiSdkReactorOptions, type CreateScriptedReactorOptions, type ScriptedReactorStep, type ContextConfig, type ContextInstance, type ContextOptions, type ContextStreamOptions, type ContextReactor, type ContextReactorParams, type ContextReactionResult, type ContextActionRequest, type ContextReactionLLM, ContextEngine, defineAction, action, type RegistrableContextBuilder, type ContextReactParams, type ContextDirectReactParams, type ContextDurableReactParams, type ContextReactResult, type ContextReactBase, type ContextReactFinalResult, type ContextDirectRun, type ContextReactRun, type ContextWorkflowRun, type ContextDurableWorkflowPayload, type ContextDurableWorkflowFunction, type ContextModelInit, type ContextTool, type ContextAction, type ContextActionBase, type ContextActionExecuteParams, type AnyContextAction, type ContextActionDefinition, type DefineContextActionDefinition, type DefineContextActionExecute, type LegacyContextActionDefinition, type LegacyContextActionExecute, type ContextActionExecute, type ContextActionInput, type ContextActionOutput, type ContextProviderDefinedAction, type ContextActionSchema, type ContextToolExecuteContext, runContextReactionDirect, } from "./context.js";
2
- export type { ContextStore, ContextIdentifier, StoredContext, ContextItem, ContextExecution, } from "./context.store.js";
1
+ export { context, createContext, createAiSdkReactor, createScriptedReactor, type CreateAiSdkReactorOptions, type CreateScriptedReactorOptions, type ScriptedReactorStep, type ContextConfig, type ContextResourcesParams, type ContextInstance, type ContextOptions, type ContextStreamOptions, type ContextReactor, type ContextReactorParams, type ContextReactionResult, type ContextActionRequest, type ContextReactionLLM, ContextEngine, defineAction, action, type RegistrableContextBuilder, type ContextReactParams, type ContextDirectReactParams, type ContextDurableReactParams, type ContextReactResult, type ContextReactBase, type ContextReactFinalResult, type ContextDirectRun, type ContextReactRun, type ContextWorkflowRun, type ContextDurableWorkflowPayload, type ContextDurableWorkflowFunction, type ContextModelInit, type ContextTool, type ContextAction, type ContextActionBase, type ContextActionExecuteParams, type AnyContextAction, type ContextActionDefinition, type DefineContextActionDefinition, type DefineContextActionExecute, type LegacyContextActionDefinition, type LegacyContextActionExecute, type ContextActionExecute, type ContextActionInput, type ContextActionOutput, type ContextProviderDefinedAction, type ContextActionSchema, type ContextToolExecuteContext, runContextReactionDirect, } from "./context.js";
2
+ export type { ContextStore, ContextIdentifier, StoredContext, ContextResource, ContextResourceBase, ContextFileResource, ContextLinkResource, ContextRepositoryResource, ContextDatasetResource, ContextExternalResource, StoredContextResource, ContextItem, ContextExecution, } from "./context.store.js";
3
3
  export type { WireDate, ContextMirrorContext, ContextMirrorExecution, ContextMirrorWrite, ContextMirrorRequest, } from "./mirror.js";
4
4
  export { registerContext, getContext, getContextFactory, hasContext, listContexts, type ContextKey, } from "./context.registry.js";
5
5
  export { eventsDomain } from "./schema.js";
@@ -16,6 +16,6 @@ export { CONTEXT_STEP_STREAM_VERSION, createContextStepStreamChunk, validateCont
16
16
  export type { ContextStepStreamChunkValidationOptions, } from "./context.step-stream.js";
17
17
  export { CONTEXT_PART_ID_NAMESPACE, CONTEXT_PART_UUID_RE, CONTEXT_STREAM_PART_TYPES, assertValidContextPartChunkIdentity, resolveContextPartChunkDescriptor, resolveContextPartChunkIdentity, resolveContextPartId, resolveContextStreamPartSlot, resolveContextStreamPartType, uuidV5, } from "./context.part-identity.js";
18
18
  export type { ContextPartChunkDescriptor, ContextPartChunkIdentity, ContextPartChunkIdentityInput, ContextPartChunkValidationInput, ContextStreamPartSlot, ContextStreamPartType, } from "./context.part-identity.js";
19
- export type { ContextStreamEvent, ContextCreatedEvent, ContextResolvedEvent, ContextStatusChangedEvent, ContextContentUpdatedEvent, ExecutionCreatedEvent, ExecutionCompletedEvent, ExecutionFailedEvent, ItemCreatedEvent, ItemUpdatedEvent, ItemPendingEvent, ItemCompletedEvent, StepCreatedEvent, StepUpdatedEvent, StepCompletedEvent, StepFailedEvent, PartCreatedEvent, PartUpdatedEvent, ChunkEmittedEvent, } from "./context.stream.js";
19
+ export type { ContextStreamEvent, ContextCreatedEvent, ContextResolvedEvent, ContextStatusChangedEvent, ContextContentUpdatedEvent, ContextDefinitionUpdatedEvent, ContextResourcesUpdatedEvent, ExecutionCreatedEvent, ExecutionCompletedEvent, ExecutionFailedEvent, ItemCreatedEvent, ItemUpdatedEvent, ItemPendingEvent, ItemCompletedEvent, StepCreatedEvent, StepUpdatedEvent, StepCompletedEvent, StepFailedEvent, PartCreatedEvent, PartUpdatedEvent, ChunkEmittedEvent, } from "./context.stream.js";
20
20
  export type { ContextStepStreamChunk } from "./context.step-stream.js";
21
21
  export type { ContextSkillPackage, ContextSkillPackageFile } from "./context.skill.js";
@@ -46,7 +46,6 @@ export function createAiSdkReactor(options) {
46
46
  iteration: params.iteration,
47
47
  maxSteps,
48
48
  sendStart: params.sendStart,
49
- silent: params.silent,
50
49
  contextStepStream: params.contextStepStream,
51
50
  writable: params.writable,
52
51
  executionId: params.executionId,
@@ -24,7 +24,6 @@ export declare function executeAiSdkReaction<Env extends ContextEnvironment = Co
24
24
  iteration?: number;
25
25
  maxSteps: number;
26
26
  sendStart?: boolean;
27
- silent?: boolean;
28
27
  contextStepStream?: WritableStream<string>;
29
28
  writable?: WritableStream<UIMessageChunk>;
30
29
  executionId?: string;
@@ -4,7 +4,7 @@ import type { ContextEnvironment } from "../context.config.js";
4
4
  import type { ContextTool } from "../context.action.js";
5
5
  import type { ContextRuntime, ContextRuntimeHandleForDomain } from "../context.runtime.js";
6
6
  import type { ContextModelInit } from "../context.engine.js";
7
- import type { ContextIdentifier, StoredContext, ContextItem } from "../context.store.js";
7
+ import type { ContextIdentifier, StoredContext, StoredContextResource, ContextItem } from "../context.store.js";
8
8
  import type { ContextSkillPackage } from "../context.skill.js";
9
9
  import { eventsDomain } from "../schema.js";
10
10
  export type ContextActionRequest = {
@@ -38,6 +38,7 @@ export type ContextReactorParams<Context = unknown, Env extends ContextEnvironme
38
38
  runtime: ContextRuntimeHandleForDomain<Env, RequiredDomain>;
39
39
  context: StoredContext<Context>;
40
40
  contextIdentifier: ContextIdentifier;
41
+ resources: StoredContextResource[];
41
42
  /**
42
43
  * Context items after the engine-level expansion stage.
43
44
  *
@@ -59,7 +60,6 @@ export type ContextReactorParams<Context = unknown, Env extends ContextEnvironme
59
60
  iteration: number;
60
61
  maxModelSteps: number;
61
62
  sendStart: boolean;
62
- silent: boolean;
63
63
  contextStepStream?: WritableStream<string>;
64
64
  writable?: WritableStream<UIMessageChunk>;
65
65
  persistReactionParts?: (parts: any[]) => Promise<void>;
package/dist/schema.d.ts CHANGED
@@ -6,6 +6,9 @@ export declare const eventsDomain: import("@ekairos/domain").DomainSchemaResult<
6
6
  name: import("@instantdb/core").DataAttrDef<string, false, false, false>;
7
7
  status: import("@instantdb/core").DataAttrDef<string, false, true, false>;
8
8
  content: import("@instantdb/core").DataAttrDef<any, false, false, false>;
9
+ description: import("@instantdb/core").DataAttrDef<string, false, false, false>;
10
+ goal: import("@instantdb/core").DataAttrDef<string, false, false, false>;
11
+ resources: import("@instantdb/core").DataAttrDef<any, false, false, false>;
9
12
  reactor: import("@instantdb/core").DataAttrDef<any, false, false, false>;
10
13
  }, {}, unknown>;
11
14
  event_items: import("@instantdb/core").EntityDef<{
package/dist/schema.js CHANGED
@@ -10,6 +10,9 @@ export const eventsDomain = domain("events")
10
10
  name: i.string().optional(),
11
11
  status: i.string().optional().indexed(), // open_idle | open_streaming | closed
12
12
  content: i.any().optional(),
13
+ description: i.string().optional(),
14
+ goal: i.string().optional(),
15
+ resources: i.any().optional(),
13
16
  reactor: i.json().optional(),
14
17
  }),
15
18
  event_items: i.entity({
@@ -1,7 +1,6 @@
1
- import type { UIMessageChunk } from "ai";
2
1
  import type { ContextEnvironment } from "../context.config.js";
3
2
  import type { ContextRuntime } from "../context.runtime.js";
4
- import type { ContextExecution, ContextItem, ContextIdentifier, StoredContext, ContextStatus } from "../context.store.js";
3
+ import type { ContextExecution, ContextItem, ContextIdentifier, ContextResource, StoredContextResource, StoredContext, ContextStatus } from "../context.store.js";
5
4
  import type { ContextStreamEvent } from "../context.stream.js";
6
5
  import { type ContextActionResultForStream, type PersistedContextStepStreamSession } from "./stream.steps.js";
7
6
  type RuntimeParams<Env extends ContextEnvironment = ContextEnvironment> = {
@@ -22,10 +21,6 @@ type ContextStepPatch = {
22
21
  */
23
22
  export declare function initializeContext<C>(params: RuntimeParams & {
24
23
  contextIdentifier: ContextIdentifier | null;
25
- opts?: {
26
- silent?: boolean;
27
- writable?: WritableStream<UIMessageChunk>;
28
- };
29
24
  }): Promise<{
30
25
  context: StoredContext<C>;
31
26
  isNew: boolean;
@@ -34,6 +29,17 @@ export declare function updateContextContent<C>(params: RuntimeParams & {
34
29
  contextIdentifier: ContextIdentifier;
35
30
  content: C;
36
31
  }): Promise<StoredContext<C>>;
32
+ export declare function updateContextDefinition<C>(params: RuntimeParams & {
33
+ contextIdentifier: ContextIdentifier;
34
+ definition: {
35
+ description?: string | null;
36
+ goal?: string | null;
37
+ };
38
+ }): Promise<StoredContext<C>>;
39
+ export declare function upsertContextResources(params: RuntimeParams & {
40
+ contextIdentifier: ContextIdentifier;
41
+ resources: ContextResource[];
42
+ }): Promise<StoredContextResource[]>;
37
43
  export declare function updateContextReactor<C>(params: RuntimeParams & {
38
44
  contextIdentifier: ContextIdentifier;
39
45
  reactor: {
@@ -143,6 +143,16 @@ export async function updateContextContent(params) {
143
143
  const { runtime } = await getRuntimeAndEnv(params);
144
144
  return await runtime.store.updateContextContent(params.contextIdentifier, params.content);
145
145
  }
146
+ export async function updateContextDefinition(params) {
147
+ "use step";
148
+ const { runtime } = await getRuntimeAndEnv(params);
149
+ return await runtime.store.updateContextDefinition(params.contextIdentifier, params.definition);
150
+ }
151
+ export async function upsertContextResources(params) {
152
+ "use step";
153
+ const { runtime } = await getRuntimeAndEnv(params);
154
+ return await runtime.store.upsertContextResources(params.contextIdentifier, params.resources);
155
+ }
146
156
  export async function updateContextReactor(params) {
147
157
  "use step";
148
158
  const { runtime } = await getRuntimeAndEnv(params);
@@ -1,7 +1,7 @@
1
1
  import "../polyfills/dom-events.js";
2
2
  import type { DomainLike } from "@ekairos/domain";
3
3
  import type { ModelMessage } from "ai";
4
- import type { ContextItem, ContextIdentifier, ContextStatus, StoredContext, ContextStore } from "../context.store.js";
4
+ import type { ContextItem, ContextIdentifier, ContextResource, ContextStatus, StoredContextResource, StoredContext, ContextStore } from "../context.store.js";
5
5
  export { parseAndStoreDocument } from "./instant.document-parser.js";
6
6
  export { coerceDocumentTextPages, expandEventsWithInstantDocuments, } from "./instant.documents.js";
7
7
  export type InstantStoreDb = any;
@@ -14,12 +14,20 @@ export declare class InstantStore implements ContextStore {
14
14
  getOrCreateContext<C>(contextIdentifier: ContextIdentifier | null): Promise<StoredContext<C>>;
15
15
  getContext<C>(contextIdentifier: ContextIdentifier): Promise<StoredContext<C> | null>;
16
16
  updateContextContent<C>(contextIdentifier: ContextIdentifier, content: C): Promise<StoredContext<C>>;
17
+ updateContextDefinition<C>(contextIdentifier: ContextIdentifier, definition: {
18
+ description?: string | null;
19
+ goal?: string | null;
20
+ }): Promise<StoredContext<C>>;
17
21
  updateContextReactor<C>(contextIdentifier: ContextIdentifier, reactor: {
18
22
  kind: string;
19
23
  state?: Record<string, unknown> | null;
20
24
  }): Promise<StoredContext<C>>;
21
25
  updateContextStatus(contextIdentifier: ContextIdentifier, status: ContextStatus): Promise<void>;
22
26
  private resolveContext;
27
+ private normalizeContextResource;
28
+ private normalizeContextResources;
29
+ getContextResources(contextIdentifier: ContextIdentifier): Promise<StoredContextResource[]>;
30
+ upsertContextResources(contextIdentifier: ContextIdentifier, resources: ContextResource[]): Promise<StoredContextResource[]>;
23
31
  saveItem(contextIdentifier: ContextIdentifier, event: ContextItem): Promise<ContextItem>;
24
32
  updateItem(eventId: string, event: ContextItem): Promise<ContextItem>;
25
33
  getItem(eventId: string): Promise<ContextItem | null>;
@@ -155,6 +155,9 @@ export class InstantStore {
155
155
  ? new Date(row.updatedAt)
156
156
  : undefined,
157
157
  content: row?.content ?? null,
158
+ description: typeof row?.description === "string" ? row.description : null,
159
+ goal: typeof row?.goal === "string" ? row.goal : null,
160
+ resources: this.normalizeContextResources(row?.resources),
158
161
  reactor: row?.reactor && typeof row.reactor === "object"
159
162
  ? row.reactor
160
163
  : null,
@@ -184,6 +187,9 @@ export class InstantStore {
184
187
  key,
185
188
  status: "open_idle",
186
189
  content: {},
190
+ description: undefined,
191
+ goal: undefined,
192
+ resources: [],
187
193
  reactor: undefined,
188
194
  }),
189
195
  ]);
@@ -244,6 +250,28 @@ export class InstantStore {
244
250
  throw new Error("InstantStore: context not found after update");
245
251
  return updated;
246
252
  }
253
+ async updateContextDefinition(contextIdentifier, definition) {
254
+ const context = await this.getContext(contextIdentifier);
255
+ if (!context?.id)
256
+ throw new Error("InstantStore: context not found");
257
+ const update = {
258
+ updatedAt: new Date(),
259
+ };
260
+ if (definition.description !== undefined) {
261
+ update.description =
262
+ typeof definition.description === "string" ? definition.description : undefined;
263
+ }
264
+ if (definition.goal !== undefined) {
265
+ update.goal = typeof definition.goal === "string" ? definition.goal : undefined;
266
+ }
267
+ await this.db.transact([
268
+ this.db.tx.event_contexts[context.id].update(update),
269
+ ]);
270
+ const updated = await this.getContext({ id: context.id });
271
+ if (!updated)
272
+ throw new Error("InstantStore: context not found after definition update");
273
+ return updated;
274
+ }
247
275
  async updateContextReactor(contextIdentifier, reactor) {
248
276
  const context = await this.getContext(contextIdentifier);
249
277
  if (!context?.id)
@@ -279,6 +307,66 @@ export class InstantStore {
279
307
  throw new Error("InstantStore: context not found");
280
308
  return context;
281
309
  }
310
+ normalizeContextResource(resource) {
311
+ if (!resource || typeof resource !== "object")
312
+ return null;
313
+ const record = resource;
314
+ const key = typeof record.key === "string" ? record.key.trim() : "";
315
+ const type = typeof record.type === "string" ? record.type.trim() : "";
316
+ const name = typeof record.name === "string" ? record.name.trim() : "";
317
+ const description = typeof record.description === "string" ? record.description.trim() : "";
318
+ if (!key || !type || !name || !description)
319
+ return null;
320
+ return {
321
+ ...record,
322
+ key,
323
+ type,
324
+ name,
325
+ description,
326
+ };
327
+ }
328
+ normalizeContextResources(value) {
329
+ if (!Array.isArray(value))
330
+ return [];
331
+ return value.flatMap((resource) => {
332
+ const normalized = this.normalizeContextResource(resource);
333
+ return normalized ? [normalized] : [];
334
+ });
335
+ }
336
+ async getContextResources(contextIdentifier) {
337
+ const context = await this.resolveContext(contextIdentifier);
338
+ return context.resources ?? [];
339
+ }
340
+ async upsertContextResources(contextIdentifier, resources) {
341
+ const context = await this.resolveContext(contextIdentifier);
342
+ const now = new Date();
343
+ const storedResources = [];
344
+ for (const resource of resources) {
345
+ const resourceKey = typeof resource.key === "string" ? resource.key.trim() : "";
346
+ const type = typeof resource.type === "string" ? resource.type.trim() : "";
347
+ const name = typeof resource.name === "string" ? resource.name.trim() : "";
348
+ const description = typeof resource.description === "string" ? resource.description.trim() : "";
349
+ if (!resourceKey || !type || !name || !description) {
350
+ throw new Error("InstantStore: context resources require key, type, name, and description.");
351
+ }
352
+ const sanitizedResource = sanitizeInstantValue(resource);
353
+ const storedResource = {
354
+ ...sanitizedResource,
355
+ key: resourceKey,
356
+ type,
357
+ name,
358
+ description,
359
+ };
360
+ storedResources.push(storedResource);
361
+ }
362
+ await this.db.transact([
363
+ this.db.tx.event_contexts[context.id].update({
364
+ resources: storedResources,
365
+ updatedAt: now,
366
+ }),
367
+ ]);
368
+ return await this.getContextResources({ id: context.id });
369
+ }
282
370
  async saveItem(contextIdentifier, event) {
283
371
  const eventId = ensureValidEntityId(event?.id, "event.id");
284
372
  const sanitizedEvent = sanitizeInstantValue(event);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ekairos/events",
3
- "version": "1.22.83-beta.development.0",
3
+ "version": "1.22.85-beta.development.0",
4
4
  "description": "Ekairos Events - Context-first workflow runtime",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -127,7 +127,7 @@
127
127
  },
128
128
  "dependencies": {
129
129
  "@ai-sdk/openai": "^2.0.52",
130
- "@ekairos/domain": "^1.22.83-beta.development.0",
130
+ "@ekairos/domain": "^1.22.85-beta.development.0",
131
131
  "@instantdb/admin": "0.22.158",
132
132
  "@instantdb/core": "0.22.142",
133
133
  "@vercel/mcp-adapter": "^1.0.0",