@standardagents/builder 0.39.1 → 0.40.1

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.
Files changed (43) hide show
  1. package/dist/built-in-routes.js +609 -94
  2. package/dist/built-in-routes.js.map +1 -1
  3. package/dist/client/{ApiKeysView-AH5i-H6j.js → ApiKeysView-DoYvZZ7e.js} +1 -1
  4. package/dist/client/{CenteredContentView-DaBp0K-A.js → CenteredContentView-53PY0cqY.js} +1 -1
  5. package/dist/client/{CompositionView-yY1Q4M23.js → CompositionView-fp-0YnPt.js} +1 -1
  6. package/dist/client/{ConfirmDialog.vue_vue_type_script_setup_true_lang-Bwo5CJzF.js → ConfirmDialog.vue_vue_type_script_setup_true_lang-Cvcagja2.js} +1 -1
  7. package/dist/client/{CopyButton.vue_vue_type_script_setup_true_lang-D0WYwWyA.js → CopyButton.vue_vue_type_script_setup_true_lang-jYvO2v1K.js} +1 -1
  8. package/dist/client/{DataTable.vue_vue_type_script_setup_true_lang-1wwPn2aY.js → DataTable.vue_vue_type_script_setup_true_lang-DQ3Ufa7y.js} +1 -1
  9. package/dist/client/{JsonViewer-Bi8Zdmir.js → JsonViewer-6aaGzutE.js} +1 -1
  10. package/dist/client/{LoginView-BIKahEU6.js → LoginView-DwpCmNw9.js} +1 -1
  11. package/dist/client/{MarketplaceView-DPDPVH68.js → MarketplaceView-Da02L0J5.js} +1 -1
  12. package/dist/client/{Modal.vue_vue_type_script_setup_true_lang-D1_rfOsy.js → Modal.vue_vue_type_script_setup_true_lang-Bi8OjiBf.js} +1 -1
  13. package/dist/client/{ModelModal.vue_vue_type_script_setup_true_lang-DSLeOdxr.js → ModelModal.vue_vue_type_script_setup_true_lang-cYZLOYY7.js} +1 -1
  14. package/dist/client/{ModelsView-Q2WXu1Gw.js → ModelsView-BLlHO9Ud.js} +1 -1
  15. package/dist/client/{PromptEditView-BzA-3n1w.js → PromptEditView-EeNwTDtT.js} +1 -1
  16. package/dist/client/{PromptModal-CJWh_cru.js → PromptModal-BkwrKJ2d.js} +1 -1
  17. package/dist/client/{PromptsView-BezNl-Et.js → PromptsView-D1r7tsLu.js} +1 -1
  18. package/dist/client/{ProvidersView-BuzSKxuT.js → ProvidersView-CmUDl5nM.js} +1 -1
  19. package/dist/client/{ThreadInspectorPane.vue_vue_type_script_setup_true_lang-DOxNp_3C.js → ThreadInspectorPane.vue_vue_type_script_setup_true_lang-cRs3tApQ.js} +1 -1
  20. package/dist/client/{ThreadsView-DPCpZA4J.js → ThreadsView-Bl5fSIO1.js} +1 -1
  21. package/dist/client/{ToolsView-DMjFMAhH.js → ToolsView-DlVEF8-7.js} +1 -1
  22. package/dist/client/{UsersView-B7jXLNQs.js → UsersView-CGlA7a7R.js} +1 -1
  23. package/dist/client/{VariablesView-CF7x0G8g.js → VariablesView-BpYmJL4V.js} +1 -1
  24. package/dist/client/index-CKtIkI0N.js +6 -0
  25. package/dist/client/index.html +1 -1
  26. package/dist/{discovery-DiMJWisl.d.ts → discovery-DZ7fv-b4.d.ts} +3 -2
  27. package/dist/{index-yIcqf7DC.d.ts → index-0NI3m5DR.d.ts} +8 -2
  28. package/dist/index.d.ts +4 -4
  29. package/dist/index.js +1299 -758
  30. package/dist/index.js.map +1 -1
  31. package/dist/packing.d.ts +5 -3
  32. package/dist/packing.js +180 -5
  33. package/dist/packing.js.map +1 -1
  34. package/dist/plugin.d.ts +12 -1
  35. package/dist/plugin.js +299 -19
  36. package/dist/plugin.js.map +1 -1
  37. package/dist/runtime.d.ts +12 -5
  38. package/dist/runtime.js +1009 -750
  39. package/dist/runtime.js.map +1 -1
  40. package/dist/test.d.ts +2 -2
  41. package/dist/{types-Bpe7IANZ.d.ts → types-BMnBYNwn.d.ts} +3 -1
  42. package/package.json +5 -5
  43. package/dist/client/index-eGECJFYe.js +0 -6
package/dist/runtime.js CHANGED
@@ -6800,6 +6800,547 @@ var init_context = __esm({
6800
6800
  }
6801
6801
  });
6802
6802
 
6803
+ // src/packing/resolver.ts
6804
+ function parseQualifiedName(name) {
6805
+ if (name.startsWith("@")) {
6806
+ const firstSlash = name.indexOf("/");
6807
+ if (firstSlash === -1) {
6808
+ return [null, name];
6809
+ }
6810
+ const secondSlash = name.indexOf("/", firstSlash + 1);
6811
+ if (secondSlash === -1) {
6812
+ return [null, name];
6813
+ }
6814
+ return [name.substring(0, secondSlash), name.substring(secondSlash + 1)];
6815
+ }
6816
+ const separatorIndex = name.indexOf("/");
6817
+ if (separatorIndex === -1) {
6818
+ return [null, name];
6819
+ }
6820
+ return [name.substring(0, separatorIndex), name.substring(separatorIndex + 1)];
6821
+ }
6822
+ function qualifyName(packageId, shortName) {
6823
+ return `${packageId}/${shortName}`;
6824
+ }
6825
+ function getShortName(name) {
6826
+ const [, shortName] = parseQualifiedName(name);
6827
+ return shortName;
6828
+ }
6829
+ function resolveTool(registry, name, namespace) {
6830
+ const [pkgId, shortName] = parseQualifiedName(name);
6831
+ if (pkgId !== null) {
6832
+ const pkg = registry.packages[pkgId];
6833
+ if (!pkg) {
6834
+ throw new NamespaceResolutionError(
6835
+ "tool",
6836
+ name,
6837
+ namespace,
6838
+ `Package "${pkgId}" not found`
6839
+ );
6840
+ }
6841
+ throw new NamespaceResolutionError(
6842
+ "tool",
6843
+ name,
6844
+ namespace,
6845
+ `Cannot access tool "${shortName}" from package "${pkgId}". Only entry point agents are accessible cross-package.`
6846
+ );
6847
+ }
6848
+ if (namespace.type === "packed") {
6849
+ const pkg = registry.packages[namespace.packageId];
6850
+ if (!pkg) {
6851
+ throw new NamespaceResolutionError(
6852
+ "tool",
6853
+ name,
6854
+ namespace,
6855
+ `Package "${namespace.packageId}" not found`
6856
+ );
6857
+ }
6858
+ const loader2 = pkg.tools[shortName];
6859
+ if (!loader2) {
6860
+ throw new NamespaceResolutionError(
6861
+ "tool",
6862
+ name,
6863
+ namespace,
6864
+ `Tool "${shortName}" not found in package "${namespace.packageId}"`
6865
+ );
6866
+ }
6867
+ return loader2;
6868
+ }
6869
+ const loader = registry.global.tools[shortName];
6870
+ if (!loader) {
6871
+ throw new NamespaceResolutionError(
6872
+ "tool",
6873
+ name,
6874
+ namespace,
6875
+ `Tool "${shortName}" not found in global namespace`
6876
+ );
6877
+ }
6878
+ return loader;
6879
+ }
6880
+ function resolvePrompt(registry, name, namespace) {
6881
+ const [pkgId, shortName] = parseQualifiedName(name);
6882
+ if (pkgId !== null) {
6883
+ throw new NamespaceResolutionError(
6884
+ "prompt",
6885
+ name,
6886
+ namespace,
6887
+ `Cannot access prompt "${shortName}" from package "${pkgId}". Prompts are package-internal.`
6888
+ );
6889
+ }
6890
+ if (namespace.type === "packed") {
6891
+ const pkg = registry.packages[namespace.packageId];
6892
+ if (!pkg) {
6893
+ throw new NamespaceResolutionError(
6894
+ "prompt",
6895
+ name,
6896
+ namespace,
6897
+ `Package "${namespace.packageId}" not found`
6898
+ );
6899
+ }
6900
+ const loader2 = pkg.prompts[shortName];
6901
+ if (!loader2) {
6902
+ throw new NamespaceResolutionError(
6903
+ "prompt",
6904
+ name,
6905
+ namespace,
6906
+ `Prompt "${shortName}" not found in package "${namespace.packageId}"`
6907
+ );
6908
+ }
6909
+ return loader2;
6910
+ }
6911
+ const loader = registry.global.prompts[shortName];
6912
+ if (!loader) {
6913
+ throw new NamespaceResolutionError(
6914
+ "prompt",
6915
+ name,
6916
+ namespace,
6917
+ `Prompt "${shortName}" not found in global namespace`
6918
+ );
6919
+ }
6920
+ return loader;
6921
+ }
6922
+ function resolveModel(registry, name, namespace) {
6923
+ const [possiblePkgId, shortName] = parseQualifiedName(name);
6924
+ if (possiblePkgId !== null && registry.packages[possiblePkgId]) {
6925
+ throw new NamespaceResolutionError(
6926
+ "model",
6927
+ name,
6928
+ namespace,
6929
+ `Cannot use qualified model name "${name}". Models must be unqualified. If this is a provider model name, ensure no package named "${possiblePkgId}" exists.`
6930
+ );
6931
+ }
6932
+ const lookupName = name;
6933
+ if (namespace.type === "packed") {
6934
+ const pkg = registry.packages[namespace.packageId];
6935
+ if (pkg) {
6936
+ const loader2 = pkg.models[lookupName];
6937
+ if (loader2) {
6938
+ return loader2;
6939
+ }
6940
+ }
6941
+ const globalLoader = registry.global.models[lookupName];
6942
+ if (globalLoader) {
6943
+ return globalLoader;
6944
+ }
6945
+ throw new NamespaceResolutionError(
6946
+ "model",
6947
+ name,
6948
+ namespace,
6949
+ `Model "${lookupName}" not found in package "${namespace.packageId}" or global namespace`
6950
+ );
6951
+ }
6952
+ const loader = registry.global.models[lookupName];
6953
+ if (!loader) {
6954
+ throw new NamespaceResolutionError(
6955
+ "model",
6956
+ name,
6957
+ namespace,
6958
+ `Model "${lookupName}" not found in global namespace`
6959
+ );
6960
+ }
6961
+ return loader;
6962
+ }
6963
+ function resolveAgent(registry, name, namespace) {
6964
+ const [pkgId, shortName] = parseQualifiedName(name);
6965
+ if (pkgId !== null) {
6966
+ const pkg = registry.packages[pkgId];
6967
+ if (!pkg) {
6968
+ throw new NamespaceResolutionError(
6969
+ "agent",
6970
+ name,
6971
+ namespace,
6972
+ `Package "${pkgId}" not found`
6973
+ );
6974
+ }
6975
+ if (!pkg.entryAgents.includes(shortName)) {
6976
+ throw new NamespaceResolutionError(
6977
+ "agent",
6978
+ name,
6979
+ namespace,
6980
+ `Agent "${shortName}" is not an entry point in package "${pkgId}"`
6981
+ );
6982
+ }
6983
+ const loader = pkg.agents[shortName];
6984
+ if (!loader) {
6985
+ throw new NamespaceResolutionError(
6986
+ "agent",
6987
+ name,
6988
+ namespace,
6989
+ `Agent "${shortName}" not found in package "${pkgId}"`
6990
+ );
6991
+ }
6992
+ return loader;
6993
+ }
6994
+ if (namespace.type === "packed") {
6995
+ const pkg = registry.packages[namespace.packageId];
6996
+ if (!pkg) {
6997
+ throw new NamespaceResolutionError(
6998
+ "agent",
6999
+ name,
7000
+ namespace,
7001
+ `Package "${namespace.packageId}" not found`
7002
+ );
7003
+ }
7004
+ const loader = pkg.agents[shortName];
7005
+ if (!loader) {
7006
+ throw new NamespaceResolutionError(
7007
+ "agent",
7008
+ name,
7009
+ namespace,
7010
+ `Agent "${shortName}" not found in package "${namespace.packageId}"`
7011
+ );
7012
+ }
7013
+ return loader;
7014
+ }
7015
+ const globalLoader = registry.global.agents[shortName];
7016
+ if (globalLoader) {
7017
+ return globalLoader;
7018
+ }
7019
+ for (const [pkgId2, pkg] of Object.entries(registry.packages)) {
7020
+ if (pkg.entryAgents.includes(shortName)) {
7021
+ const loader = pkg.agents[shortName];
7022
+ if (loader) {
7023
+ return loader;
7024
+ }
7025
+ }
7026
+ }
7027
+ throw new NamespaceResolutionError(
7028
+ "agent",
7029
+ name,
7030
+ namespace,
7031
+ `Agent "${shortName}" not found in global namespace`
7032
+ );
7033
+ }
7034
+ function resolveHook(registry, name, namespace) {
7035
+ const [pkgId, shortName] = parseQualifiedName(name);
7036
+ if (pkgId !== null) {
7037
+ throw new NamespaceResolutionError(
7038
+ "hook",
7039
+ name,
7040
+ namespace,
7041
+ `Cannot use qualified hook name "${name}". Hooks must be unqualified.`
7042
+ );
7043
+ }
7044
+ if (namespace.type === "packed") {
7045
+ const pkg = registry.packages[namespace.packageId];
7046
+ if (pkg) {
7047
+ const loader2 = pkg.hooks[shortName];
7048
+ if (loader2) {
7049
+ return loader2;
7050
+ }
7051
+ }
7052
+ return null;
7053
+ }
7054
+ const loader = registry.global.hooks[shortName];
7055
+ return loader || null;
7056
+ }
7057
+ function getVisibleToolNames(registry, namespace) {
7058
+ if (namespace.type === "packed") {
7059
+ const pkg = registry.packages[namespace.packageId];
7060
+ return pkg ? Object.keys(pkg.tools) : [];
7061
+ }
7062
+ return Object.keys(registry.global.tools);
7063
+ }
7064
+ function getVisibleAgentNames(registry, namespace) {
7065
+ if (namespace.type === "packed") {
7066
+ const pkg = registry.packages[namespace.packageId];
7067
+ const ownAgents = pkg ? Object.keys(pkg.agents) : [];
7068
+ const otherEntryPoints = Object.entries(registry.packages).filter(([id]) => id !== namespace.packageId).flatMap(
7069
+ ([pkgId, pkg2]) => pkg2.entryAgents.map((name) => qualifyName(pkgId, name))
7070
+ );
7071
+ return [...ownAgents, ...otherEntryPoints];
7072
+ }
7073
+ const globalAgents = Object.keys(registry.global.agents);
7074
+ const entryPoints = Object.values(registry.packages).flatMap((pkg) => pkg.entryAgents);
7075
+ return [.../* @__PURE__ */ new Set([...globalAgents, ...entryPoints])];
7076
+ }
7077
+ function getVisiblePromptNames(registry, namespace) {
7078
+ if (namespace.type === "packed") {
7079
+ const pkg = registry.packages[namespace.packageId];
7080
+ return pkg ? Object.keys(pkg.prompts) : [];
7081
+ }
7082
+ return Object.keys(registry.global.prompts);
7083
+ }
7084
+ function getVisibleModelNames(registry, namespace) {
7085
+ if (namespace.type === "packed") {
7086
+ const pkg = registry.packages[namespace.packageId];
7087
+ const ownModels = pkg ? Object.keys(pkg.models) : [];
7088
+ const globalModels = Object.keys(registry.global.models);
7089
+ return [.../* @__PURE__ */ new Set([...ownModels, ...globalModels])];
7090
+ }
7091
+ return Object.keys(registry.global.models);
7092
+ }
7093
+ function createNamespaceContext(agentDef) {
7094
+ if (agentDef?.__package) {
7095
+ return { type: "packed", packageId: agentDef.__package.packageId };
7096
+ }
7097
+ return { type: "global" };
7098
+ }
7099
+ function isQualifiedName(name) {
7100
+ if (name.startsWith("@")) {
7101
+ const firstSlash = name.indexOf("/");
7102
+ if (firstSlash === -1) return false;
7103
+ return name.indexOf("/", firstSlash + 1) !== -1;
7104
+ }
7105
+ return name.includes("/");
7106
+ }
7107
+ var NamespaceResolutionError;
7108
+ var init_resolver = __esm({
7109
+ "src/packing/resolver.ts"() {
7110
+ NamespaceResolutionError = class extends Error {
7111
+ constructor(itemType, itemName, namespace, message) {
7112
+ super(message);
7113
+ this.itemType = itemType;
7114
+ this.itemName = itemName;
7115
+ this.namespace = namespace;
7116
+ this.name = "NamespaceResolutionError";
7117
+ }
7118
+ };
7119
+ }
7120
+ });
7121
+
7122
+ // src/agents/ParentHookResolver.ts
7123
+ function packageOf(definition) {
7124
+ return definition?.__package ?? definition?._package;
7125
+ }
7126
+ function qualifyWithinPackage(name, packageId) {
7127
+ if (!packageId || parseQualifiedName(name)[0] !== null) {
7128
+ return name;
7129
+ }
7130
+ return qualifyName(packageId, name);
7131
+ }
7132
+ function promptHooks(prompt) {
7133
+ if (!prompt) return [];
7134
+ return Array.isArray(prompt.hooks) ? prompt.hooks : Array.isArray(prompt._hooks) ? prompt._hooks : [];
7135
+ }
7136
+ function promptTools(prompt) {
7137
+ if (!prompt) return [];
7138
+ return Array.isArray(prompt.tools) ? prompt.tools : Array.isArray(prompt._tools) ? prompt._tools : [];
7139
+ }
7140
+ function relationDescriptor(entry) {
7141
+ if (typeof entry === "string") {
7142
+ return {
7143
+ relationshipName: entry,
7144
+ implementingAgent: entry,
7145
+ explicitlyAgentShaped: false
7146
+ };
7147
+ }
7148
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
7149
+ return null;
7150
+ }
7151
+ const config = entry;
7152
+ if (typeof config.name !== "string" || !config.name) {
7153
+ return null;
7154
+ }
7155
+ const implementingAgent = typeof config.agent === "string" && config.agent ? config.agent : config.name;
7156
+ const explicitlyAgentShaped = "agent" in config || "blocking" in config || "resumable" in config || "immediate" in config || "parentCommunication" in config || "hidden" in config;
7157
+ return {
7158
+ relationshipName: config.name,
7159
+ implementingAgent,
7160
+ optional: typeof config.optional === "string" ? config.optional : void 0,
7161
+ explicitlyAgentShaped
7162
+ };
7163
+ }
7164
+ function hookLoader(host, owner, hookId) {
7165
+ const ownerPackage = packageOf(owner);
7166
+ if (!ownerPackage) {
7167
+ return host.hooks()[hookId];
7168
+ }
7169
+ return host.registry?.()?.packages?.[ownerPackage.packageId]?.hooks?.[hookId];
7170
+ }
7171
+ async function loadBinding(host, owner, hookId, hookType, context, required) {
7172
+ const loader = hookLoader(host, owner, hookId);
7173
+ if (!loader) {
7174
+ if (required) {
7175
+ throw new Error(
7176
+ `Required parent hook '${hookId}' was not found in the child agent namespace`
7177
+ );
7178
+ }
7179
+ return null;
7180
+ }
7181
+ let loaded;
7182
+ try {
7183
+ loaded = await loader();
7184
+ } catch (error) {
7185
+ if (required) throw error;
7186
+ console.error(`[Hooks] Failed to load hook '${hookId}':`, error);
7187
+ return null;
7188
+ }
7189
+ if (!loaded) {
7190
+ if (required) {
7191
+ throw new Error(`Required parent hook '${hookId}' did not export a hook definition`);
7192
+ }
7193
+ return null;
7194
+ }
7195
+ if (typeof loaded.id !== "string" || loaded.id !== hookId) {
7196
+ if (required) {
7197
+ throw new Error(`Required parent hook '${hookId}' exported a mismatched hook ID`);
7198
+ }
7199
+ return null;
7200
+ }
7201
+ if (typeof loaded.execute !== "function") {
7202
+ if (required) {
7203
+ throw new Error(`Required parent hook '${hookId}' did not export an execute function`);
7204
+ }
7205
+ return null;
7206
+ }
7207
+ if (USER_HOOK_NAMES.has(loaded.hook)) {
7208
+ if (required) {
7209
+ throw new Error(
7210
+ `Required parent hook '${hookId}' uses user-scoped hook type '${loaded.hook}'`
7211
+ );
7212
+ }
7213
+ return null;
7214
+ }
7215
+ if (!THREAD_HOOK_NAMES.has(loaded.hook)) {
7216
+ if (required) {
7217
+ throw new Error(`Required parent hook '${hookId}' exported invalid hook type '${loaded.hook}'`);
7218
+ }
7219
+ return null;
7220
+ }
7221
+ if (loaded.hook !== hookType) {
7222
+ return null;
7223
+ }
7224
+ return {
7225
+ id: hookId,
7226
+ hook: hookType,
7227
+ execute: loaded.execute,
7228
+ context
7229
+ };
7230
+ }
7231
+ async function resolveHooksForPrompt(input, hookType) {
7232
+ const agent = input.agent ?? await input.host.loadAgent(input.agentName);
7233
+ const agentPackage = packageOf(agent);
7234
+ const unqualifiedPromptName = input.promptName ?? agent.sideA?.prompt;
7235
+ const resolvedPromptName = unqualifiedPromptName ? qualifyWithinPackage(unqualifiedPromptName, agentPackage?.packageId) : void 0;
7236
+ const prompt = input.prompt ?? (resolvedPromptName ? await input.host.loadPrompt(resolvedPromptName) : void 0);
7237
+ const promptName = prompt?.name ?? prompt?.id ?? resolvedPromptName ?? "unknown_prompt";
7238
+ const before = [];
7239
+ const after = [];
7240
+ for (const entry of promptTools(prompt)) {
7241
+ const relation = relationDescriptor(entry);
7242
+ if (!relation) continue;
7243
+ if (relation.optional && input.isOptionalRelationshipEnabled && !await input.isOptionalRelationshipEnabled(relation.optional)) {
7244
+ continue;
7245
+ }
7246
+ const promptPackage = packageOf(prompt) ?? agentPackage;
7247
+ const childReference = qualifyWithinPackage(
7248
+ relation.implementingAgent,
7249
+ promptPackage?.packageId
7250
+ );
7251
+ let child;
7252
+ try {
7253
+ child = await input.host.loadAgent(childReference);
7254
+ } catch (error) {
7255
+ if (relation.explicitlyAgentShaped) throw error;
7256
+ continue;
7257
+ }
7258
+ if (child.type !== "dual_ai") continue;
7259
+ if (child.parentHooks !== void 0 && child.exposeAsTool !== true) {
7260
+ throw new Error(
7261
+ `Child agent '${childReference}' declares parentHooks but is not exposed as a tool`
7262
+ );
7263
+ }
7264
+ if (child.parentHooks !== void 0 && !Array.isArray(child.parentHooks)) {
7265
+ throw new Error(`Child agent '${childReference}' has an invalid parentHooks declaration`);
7266
+ }
7267
+ const requirements = child.parentHooks ?? [];
7268
+ const seenRequirements = /* @__PURE__ */ new Set();
7269
+ for (const requirement of requirements) {
7270
+ if (!requirement || typeof requirement !== "object" || typeof requirement.hook !== "string" || !requirement.hook || typeof requirement.reason !== "string" || !requirement.reason.trim() || requirement.stage !== void 0 && requirement.stage !== "before_parent" && requirement.stage !== "after_parent" || seenRequirements.has(requirement.hook)) {
7271
+ throw new Error(`Child agent '${childReference}' has an invalid parentHooks requirement`);
7272
+ }
7273
+ seenRequirements.add(requirement.hook);
7274
+ const loaded = await loadBinding(
7275
+ input.host,
7276
+ child,
7277
+ requirement.hook,
7278
+ hookType,
7279
+ {
7280
+ source: {
7281
+ kind: "child",
7282
+ relationshipName: relation.relationshipName,
7283
+ agentName: childReference,
7284
+ package: packageOf(child)
7285
+ }
7286
+ },
7287
+ true
7288
+ );
7289
+ if (!loaded) continue;
7290
+ if ((requirement.stage ?? "after_parent") === "before_parent") {
7291
+ before.push(loaded);
7292
+ } else {
7293
+ after.push(loaded);
7294
+ }
7295
+ }
7296
+ }
7297
+ const promptHookIds = promptHooks(prompt);
7298
+ const promptOwnsBaseHooks = promptHookIds.length > 0 && prompt !== void 0;
7299
+ const baseOwner = promptOwnsBaseHooks ? prompt : agent;
7300
+ const baseIds = promptHookIds.length > 0 ? promptHookIds : Array.isArray(agent.hooks) ? agent.hooks : [];
7301
+ const baseContext = promptOwnsBaseHooks ? { source: { kind: "prompt", promptName } } : { source: { kind: "agent", agentName: input.agentName } };
7302
+ const base = [];
7303
+ for (const hookId of baseIds) {
7304
+ const loaded = await loadBinding(
7305
+ input.host,
7306
+ baseOwner,
7307
+ hookId,
7308
+ hookType,
7309
+ baseContext,
7310
+ false
7311
+ );
7312
+ if (loaded) base.push(loaded);
7313
+ }
7314
+ return [...before, ...base, ...after];
7315
+ }
7316
+ var USER_HOOK_NAMES, THREAD_HOOK_NAMES;
7317
+ var init_ParentHookResolver = __esm({
7318
+ "src/agents/ParentHookResolver.ts"() {
7319
+ init_resolver();
7320
+ USER_HOOK_NAMES = /* @__PURE__ */ new Set([
7321
+ "user_client_attached",
7322
+ "user_client_detached",
7323
+ "user_value_changed"
7324
+ ]);
7325
+ THREAD_HOOK_NAMES = /* @__PURE__ */ new Set([
7326
+ "after_thread_created",
7327
+ "after_subagent_created",
7328
+ "after_system_message",
7329
+ "filter_messages",
7330
+ "prefilter_llm_history",
7331
+ "before_create_message",
7332
+ "after_create_message",
7333
+ "before_update_message",
7334
+ "after_update_message",
7335
+ "before_store_tool_result",
7336
+ "after_tool_call_success",
7337
+ "after_tool_call_failure",
7338
+ "tool_call_started",
7339
+ "tool_call_done"
7340
+ ]);
7341
+ }
7342
+ });
7343
+
6803
7344
  // src/agents/FlowEngine.ts
6804
7345
  var FlowEngine_exports = {};
6805
7346
  __export(FlowEngine_exports, {
@@ -6816,6 +7357,7 @@ var init_FlowEngine = __esm({
6816
7357
  init_context();
6817
7358
  init_sessionTools();
6818
7359
  init_ThreadStateImpl();
7360
+ init_ParentHookResolver();
6819
7361
  IMMEDIATE_BOOTSTRAP_TOOL_NAME = "bootstrap_immediate_subagent";
6820
7362
  HookBlockedExecutionError = class extends Error {
6821
7363
  constructor(message) {
@@ -7158,7 +7700,8 @@ This usually points to something I can't fix from here \u2014 for example the wo
7158
7700
  _variables: def.variables ?? [],
7159
7701
  _env: def.env ?? def.tenvs ?? {},
7160
7702
  _requiredSchema: def.requiredSchema ?? null,
7161
- _hooks: def.hooks ?? []
7703
+ _hooks: def.hooks ?? [],
7704
+ _package: def.__package
7162
7705
  };
7163
7706
  }
7164
7707
  /**
@@ -7548,6 +8091,8 @@ This usually points to something I can't fix from here \u2014 for example the wo
7548
8091
  type: newAgentDef.type,
7549
8092
  created_at: Date.now(),
7550
8093
  max_session_turns: newAgentDef.maxSessionTurns ?? null,
8094
+ hooks: newAgentDef.hooks ?? [],
8095
+ _package: newAgentDef.__package,
7551
8096
  side_a_label: newAgentDef.sideA?.label ?? null,
7552
8097
  side_a_agent_prompt: newAgentDef.sideA?.prompt ?? null,
7553
8098
  side_a_stop_on_response: newAgentDef.sideA?.stopOnResponse ?? true,
@@ -7708,7 +8253,7 @@ This usually points to something I can't fix from here \u2014 for example the wo
7708
8253
  return null;
7709
8254
  }
7710
8255
  return await stub.resolveThreadEnv({
7711
- threadId: state.threadId,
8256
+ threadId: state.thread.metadata.id,
7712
8257
  property,
7713
8258
  promptName: state.prompt?.name
7714
8259
  });
@@ -8230,8 +8775,8 @@ This usually points to something I can't fix from here \u2014 for example the wo
8230
8775
  state.context[key] = existing;
8231
8776
  }
8232
8777
  static async runImmediateToolsIfNeeded(state) {
8233
- const promptTools = Array.isArray(state.prompt._tools) ? state.prompt._tools : [];
8234
- if (promptTools.length === 0) {
8778
+ const promptTools2 = Array.isArray(state.prompt._tools) ? state.prompt._tools : [];
8779
+ if (promptTools2.length === 0) {
8235
8780
  return false;
8236
8781
  }
8237
8782
  if (!state.immediatePromptRuns) {
@@ -8267,7 +8812,7 @@ This usually points to something I can't fix from here \u2014 for example the wo
8267
8812
  (activeInstanceCounts.get(child.name) ?? 0) + 1
8268
8813
  );
8269
8814
  }
8270
- for (const toolConfig of promptTools) {
8815
+ for (const toolConfig of promptTools2) {
8271
8816
  if (!toolConfig || typeof toolConfig !== "object") {
8272
8817
  continue;
8273
8818
  }
@@ -8433,10 +8978,10 @@ This usually points to something I can't fix from here \u2014 for example the wo
8433
8978
  * model's to clean up, and terminate_subagent on an infrastructure child
8434
8979
  * kills work the runtime depends on. Static and pure for direct testing.
8435
8980
  */
8436
- static filterModelVisibleSubagents(registry, promptTools) {
8981
+ static filterModelVisibleSubagents(registry, promptTools2) {
8437
8982
  if (registry.length === 0) return registry;
8438
8983
  const hidden = /* @__PURE__ */ new Set();
8439
- for (const config of promptTools ?? []) {
8984
+ for (const config of promptTools2 ?? []) {
8440
8985
  if (typeof config === "object" && config !== null && "name" in config && config.hidden === true) {
8441
8986
  hidden.add(config.name);
8442
8987
  }
@@ -9466,8 +10011,8 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9466
10011
  try {
9467
10012
  const nativeTools = await this.loadNativeTools(state);
9468
10013
  tools.push(...nativeTools);
9469
- const promptTools = await this.loadPromptTools(state);
9470
- tools.push(...promptTools);
10014
+ const promptTools2 = await this.loadPromptTools(state);
10015
+ tools.push(...promptTools2);
9471
10016
  const agentTools = await this.loadAgentTools(state);
9472
10017
  tools.push(...agentTools);
9473
10018
  const toolNameSources = /* @__PURE__ */ new Map();
@@ -9476,7 +10021,7 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9476
10021
  sources.add("native tool");
9477
10022
  toolNameSources.set(tool.function.name, sources);
9478
10023
  }
9479
- for (const tool of promptTools) {
10024
+ for (const tool of promptTools2) {
9480
10025
  const sources = toolNameSources.get(tool.function.name) || /* @__PURE__ */ new Set();
9481
10026
  sources.add("prompt");
9482
10027
  toolNameSources.set(tool.function.name, sources);
@@ -9618,49 +10163,26 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9618
10163
  // Hook Resolution Helpers
9619
10164
  // ==========================================================================
9620
10165
  /**
9621
- * Get the list of hook IDs that should run for the current context.
9622
- * Resolution: prompt hooks > agent hooks > empty array
9623
- *
9624
- * @param state - Flow state with prompt and agent configuration
9625
- * @returns Array of hook IDs to execute
9626
- */
9627
- static getActiveHookIds(state) {
9628
- if (state.prompt?._hooks !== void 0 && state.prompt._hooks.length > 0) {
9629
- return state.prompt._hooks;
9630
- }
9631
- if (state.agentConfig.hooks !== void 0 && state.agentConfig.hooks.length > 0) {
9632
- return state.agentConfig.hooks;
9633
- }
9634
- return [];
9635
- }
9636
- /**
9637
- * Get hooks of a specific type from the active hook IDs.
9638
- * Returns typed hook executors in the order they appear in the hooks array.
10166
+ * Resolve hooks of a specific type for the active prompt, including required
10167
+ * hooks contributed automatically by its enabled direct child agents.
9639
10168
  *
9640
10169
  * @template K - The hook type name (ensures type-safe executors)
9641
10170
  * @param state - Flow state with hook configuration
9642
- * @param hookType - The hook type to filter for
9643
- * @returns Array of typed hook executor functions
9644
- */
9645
- static async getHooksForType(state, hookType) {
9646
- const hookIds = this.getActiveHookIds(state);
9647
- if (hookIds.length === 0) return [];
9648
- const hooksRegistry = state.thread.instance.hooks();
9649
- if (!hooksRegistry) return [];
9650
- const executors = [];
9651
- for (const hookId of hookIds) {
9652
- const hookLoader = hooksRegistry[hookId];
9653
- if (!hookLoader) continue;
9654
- try {
9655
- const hookDef = await hookLoader();
9656
- if (hookDef && hookDef.hook === hookType) {
9657
- executors.push(hookDef.execute);
9658
- }
9659
- } catch (error) {
9660
- console.error(`[Hooks] Failed to load hook '${hookId}':`, error);
9661
- }
9662
- }
9663
- return executors;
10171
+ * @param hookType - The hook type to filter for
10172
+ * @returns Array of typed hook executor functions
10173
+ */
10174
+ static async getHooksForType(state, hookType) {
10175
+ return await resolveHooksForPrompt(
10176
+ {
10177
+ host: state.thread.instance,
10178
+ agentName: state.agentConfig.id,
10179
+ agent: state.agentConfig,
10180
+ promptName: state.prompt?.id,
10181
+ prompt: state.prompt,
10182
+ isOptionalRelationshipEnabled: (envName) => this.isOptionalToolEnabled(state, envName)
10183
+ },
10184
+ hookType
10185
+ );
9664
10186
  }
9665
10187
  // ==========================================================================
9666
10188
  // Hook Runner Methods
@@ -9678,9 +10200,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9678
10200
  if (executors.length === 0) return messages;
9679
10201
  let result = messages;
9680
10202
  const threadState = ThreadStateImpl.fromFlowState(state);
9681
- for (const executor of executors) {
10203
+ for (const { execute, context } of executors) {
9682
10204
  try {
9683
- result = await executor(threadState, result);
10205
+ result = await execute(threadState, result, context);
9684
10206
  } catch (error) {
9685
10207
  if (error && typeof error === "object" && error.block === true) {
9686
10208
  throw new HookBlockedExecutionError(error instanceof Error ? error.message : String(error));
@@ -9698,9 +10220,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9698
10220
  if (executors.length === 0) return systemMessage;
9699
10221
  let result = systemMessage;
9700
10222
  const threadState = ThreadStateImpl.fromFlowState(state);
9701
- for (const executor of executors) {
10223
+ for (const { execute, context } of executors) {
9702
10224
  try {
9703
- const next = await executor(threadState, result);
10225
+ const next = await execute(threadState, result, context);
9704
10226
  if (next !== null && next !== void 0) {
9705
10227
  result = next;
9706
10228
  }
@@ -9717,9 +10239,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9717
10239
  const executors = await this.getHooksForType(state, "after_subagent_created");
9718
10240
  if (executors.length === 0) return;
9719
10241
  const threadState = ThreadStateImpl.fromFlowState(state);
9720
- for (const executor of executors) {
10242
+ for (const { execute, context } of executors) {
9721
10243
  try {
9722
- await executor(threadState, childState);
10244
+ await execute(threadState, childState, context);
9723
10245
  } catch (error) {
9724
10246
  console.error("[Hooks] \u2717 Error running after_subagent_created hook:", error);
9725
10247
  }
@@ -9738,9 +10260,13 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9738
10260
  if (executors.length === 0) return message;
9739
10261
  let result = message;
9740
10262
  const threadState = threadStateOverride ?? ThreadStateImpl.fromFlowState(state);
9741
- for (const executor of executors) {
10263
+ for (const { execute, context } of executors) {
9742
10264
  try {
9743
- const hooked = await executor(threadState, _FlowEngine.rowToHookMessage(result));
10265
+ const hooked = await execute(
10266
+ threadState,
10267
+ _FlowEngine.rowToHookMessage(result),
10268
+ context
10269
+ );
9744
10270
  result = {
9745
10271
  ...result,
9746
10272
  ...hooked,
@@ -9766,9 +10292,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9766
10292
  const executors = await this.getHooksForType(state, "after_create_message");
9767
10293
  if (executors.length === 0) return;
9768
10294
  const threadState = threadStateOverride ?? ThreadStateImpl.fromFlowState(state);
9769
- for (const executor of executors) {
10295
+ for (const { execute, context } of executors) {
9770
10296
  try {
9771
- await executor(threadState, _FlowEngine.rowToHookMessage(message));
10297
+ await execute(threadState, _FlowEngine.rowToHookMessage(message), context);
9772
10298
  } catch (error) {
9773
10299
  console.error("[Hooks] \u2717 Error running after_create_message hook:", error);
9774
10300
  }
@@ -9809,9 +10335,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9809
10335
  if (executors.length === 0) return updates;
9810
10336
  let result = updates;
9811
10337
  const threadState = ThreadStateImpl.fromFlowState(state);
9812
- for (const executor of executors) {
10338
+ for (const { execute, context } of executors) {
9813
10339
  try {
9814
- result = await executor(threadState, messageId, result);
10340
+ result = await execute(threadState, messageId, result, context);
9815
10341
  } catch (error) {
9816
10342
  console.error("[Hooks] \u2717 Error running before_update_message hook:", error);
9817
10343
  }
@@ -9829,9 +10355,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9829
10355
  const executors = await this.getHooksForType(state, "after_update_message");
9830
10356
  if (executors.length === 0) return;
9831
10357
  const threadState = ThreadStateImpl.fromFlowState(state);
9832
- for (const executor of executors) {
10358
+ for (const { execute, context } of executors) {
9833
10359
  try {
9834
- await executor(threadState, _FlowEngine.rowToHookMessage(message));
10360
+ await execute(threadState, _FlowEngine.rowToHookMessage(message), context);
9835
10361
  } catch (error) {
9836
10362
  console.error("[Hooks] \u2717 Error running after_update_message hook:", error);
9837
10363
  }
@@ -9851,9 +10377,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9851
10377
  if (executors.length === 0) return toolResult;
9852
10378
  let result = toolResult;
9853
10379
  const threadState = ThreadStateImpl.fromFlowState(state);
9854
- for (const executor of executors) {
10380
+ for (const { execute, context } of executors) {
9855
10381
  try {
9856
- result = await executor(threadState, toolCall, result);
10382
+ result = await execute(threadState, toolCall, result, context);
9857
10383
  } catch (error) {
9858
10384
  console.error("[Hooks] \u2717 Error running before_store_tool_result hook:", error);
9859
10385
  }
@@ -9873,10 +10399,10 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9873
10399
  if (executors.length === 0) return toolResult;
9874
10400
  let result = toolResult;
9875
10401
  const threadState = ThreadStateImpl.fromFlowState(state);
9876
- for (const executor of executors) {
10402
+ for (const { execute, context } of executors) {
9877
10403
  if (result === null) break;
9878
10404
  try {
9879
- result = await executor(threadState, toolCall, result);
10405
+ result = await execute(threadState, toolCall, result, context);
9880
10406
  } catch (error) {
9881
10407
  console.error("[Hooks] \u2717 Error running after_tool_call_success hook:", error);
9882
10408
  }
@@ -9896,10 +10422,10 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9896
10422
  if (executors.length === 0) return toolResult;
9897
10423
  let result = toolResult;
9898
10424
  const threadState = ThreadStateImpl.fromFlowState(state);
9899
- for (const executor of executors) {
10425
+ for (const { execute, context } of executors) {
9900
10426
  if (result === null) break;
9901
10427
  try {
9902
- result = await executor(threadState, toolCall, result);
10428
+ result = await execute(threadState, toolCall, result, context);
9903
10429
  } catch (error) {
9904
10430
  console.error("[Hooks] \u2717 Error running after_tool_call_failure hook:", error);
9905
10431
  }
@@ -9929,9 +10455,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9929
10455
  const executors = await this.getHooksForType(state, "tool_call_started");
9930
10456
  if (executors.length === 0) return;
9931
10457
  const threadState = ThreadStateImpl.fromFlowState(state);
9932
- for (const executor of executors) {
10458
+ for (const { execute, context } of executors) {
9933
10459
  try {
9934
- await executor(threadState, toolCall, progress);
10460
+ await execute(threadState, toolCall, progress, context);
9935
10461
  } catch (error) {
9936
10462
  console.error("[Hooks] \u2717 Error running tool_call_started hook:", error);
9937
10463
  }
@@ -9959,9 +10485,9 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9959
10485
  const executors = await this.getHooksForType(state, "tool_call_done");
9960
10486
  if (executors.length === 0) return;
9961
10487
  const threadState = ThreadStateImpl.fromFlowState(state);
9962
- for (const executor of executors) {
10488
+ for (const { execute, context } of executors) {
9963
10489
  try {
9964
- await executor(threadState, toolCall, toolResult);
10490
+ await execute(threadState, toolCall, toolResult, context);
9965
10491
  } catch (error) {
9966
10492
  console.error("[Hooks] \u2717 Error running tool_call_done hook:", error);
9967
10493
  }
@@ -10914,12 +11440,12 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
10914
11440
  if (executors.length === 0) return messages;
10915
11441
  let result = messages;
10916
11442
  const threadState = ThreadStateImpl.fromFlowState(state);
10917
- for (const executor of executors) {
11443
+ for (const { execute, context } of executors) {
10918
11444
  try {
10919
11445
  const byId = /* @__PURE__ */ new Map();
10920
11446
  for (const row of result) if (row.id) byId.set(row.id, row);
10921
11447
  const hookView = result.map((row) => _FlowEngine.rowToHookMessage(row));
10922
- const kept = await executor(threadState, hookView);
11448
+ const kept = await execute(threadState, hookView, context);
10923
11449
  result = kept.map((hookedMessage) => {
10924
11450
  const original = hookedMessage.id ? byId.get(hookedMessage.id) : void 0;
10925
11451
  if (original) {
@@ -11166,7 +11692,12 @@ function queueTool(flow, toolName, args = {}) {
11166
11692
  }
11167
11693
  async function injectMessage(flow, options) {
11168
11694
  const messageId = options.id ?? crypto.randomUUID();
11169
- const timestamp = Date.now() * TIMESTAMP_MULTIPLIER;
11695
+ const wallClockTimestamp = Date.now() * TIMESTAMP_MULTIPLIER;
11696
+ const latestLiveTimestamp = flow.messageHistory.reduce(
11697
+ (latest, entry) => Math.max(latest, entry.created_at),
11698
+ 0
11699
+ );
11700
+ const timestamp = options.beforeMessageId ? wallClockTimestamp : Math.max(wallClockTimestamp, latestLiveTimestamp + 1);
11170
11701
  const silent = options.silent ?? false;
11171
11702
  const forceTopLevel = options.forceTopLevel ?? false;
11172
11703
  let message = {
@@ -17701,700 +18232,387 @@ var migration48 = {
17701
18232
  permissions TEXT
17702
18233
  )
17703
18234
  `);
17704
- sql.exec(`
17705
- INSERT INTO users (
17706
- id, username, password_hash, role, created_at, updated_at,
17707
- platform_user_id, email, display_name, avatar_url, instance_role,
17708
- source, replica_active, replica_updated_at, deleted_at, permissions
17709
- )
17710
- SELECT
17711
- id, username, password_hash, role, created_at, updated_at,
17712
- platform_user_id, email, display_name, avatar_url, instance_role,
17713
- source, replica_active, replica_updated_at, deleted_at, permissions
17714
- FROM users_0012_old
17715
- `);
17716
- sql.exec(`DROP TABLE users_0012_old`);
17717
- sql.exec(`CREATE INDEX idx_users_username ON users(username)`);
17718
- sql.exec(`CREATE INDEX idx_users_role ON users(role)`);
17719
- sql.exec(`CREATE INDEX idx_users_platform_user_id ON users(platform_user_id)`);
17720
- sql.exec(`CREATE INDEX idx_users_replica_active ON users(replica_active)`);
17721
- sql.exec(`CREATE INDEX idx_users_instance_role ON users(instance_role)`);
17722
- sql.exec(`
17723
- CREATE TABLE oauth_accounts (
17724
- id TEXT PRIMARY KEY NOT NULL,
17725
- user_id TEXT NOT NULL,
17726
- provider TEXT NOT NULL CHECK (provider IN ('github', 'google')),
17727
- provider_user_id TEXT NOT NULL,
17728
- provider_username TEXT,
17729
- created_at INTEGER DEFAULT (strftime('%s', 'now')),
17730
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
17731
- )
17732
- `);
17733
- sql.exec(`INSERT INTO oauth_accounts SELECT * FROM oauth_accounts_0012_backup`);
17734
- sql.exec(`CREATE UNIQUE INDEX idx_oauth_accounts_provider ON oauth_accounts(provider, provider_user_id)`);
17735
- sql.exec(`CREATE INDEX idx_oauth_accounts_user_id ON oauth_accounts(user_id)`);
17736
- sql.exec(`
17737
- CREATE TABLE api_keys (
17738
- id TEXT PRIMARY KEY NOT NULL,
17739
- name TEXT NOT NULL,
17740
- key_hash TEXT NOT NULL,
17741
- key_prefix TEXT NOT NULL,
17742
- last_five TEXT NOT NULL,
17743
- user_id TEXT NOT NULL,
17744
- created_at INTEGER DEFAULT (strftime('%s', 'now')),
17745
- last_used_at INTEGER,
17746
- platform_key_id TEXT,
17747
- scope TEXT,
17748
- source TEXT NOT NULL DEFAULT 'local' CHECK (source IN ('local', 'standard_agents')),
17749
- replica_active INTEGER NOT NULL DEFAULT 1,
17750
- replica_updated_at INTEGER,
17751
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
17752
- )
17753
- `);
17754
- sql.exec(`INSERT INTO api_keys SELECT * FROM api_keys_0012_backup`);
17755
- sql.exec(`CREATE INDEX idx_api_keys_key_hash ON api_keys(key_hash)`);
17756
- sql.exec(`CREATE INDEX idx_api_keys_user_id ON api_keys(user_id)`);
17757
- sql.exec(`CREATE INDEX idx_api_keys_key_prefix ON api_keys(key_prefix)`);
17758
- sql.exec(`CREATE INDEX idx_api_keys_platform_key_id ON api_keys(platform_key_id)`);
17759
- sql.exec(`CREATE INDEX idx_api_keys_replica_active ON api_keys(replica_active)`);
17760
- sql.exec(`
17761
- CREATE TABLE sessions (
17762
- id TEXT PRIMARY KEY NOT NULL,
17763
- user_id TEXT NOT NULL,
17764
- token_hash TEXT NOT NULL,
17765
- expires_at INTEGER NOT NULL,
17766
- created_at INTEGER DEFAULT (strftime('%s', 'now')),
17767
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
17768
- )
17769
- `);
17770
- sql.exec(`INSERT INTO sessions SELECT * FROM sessions_0012_backup`);
17771
- sql.exec(`CREATE INDEX idx_sessions_token_hash ON sessions(token_hash)`);
17772
- sql.exec(`CREATE INDEX idx_sessions_user_id ON sessions(user_id)`);
17773
- sql.exec(`CREATE INDEX idx_sessions_expires_at ON sessions(expires_at)`);
17774
- sql.exec(`DROP TABLE oauth_accounts_0012_backup`);
17775
- sql.exec(`DROP TABLE api_keys_0012_backup`);
17776
- sql.exec(`DROP TABLE sessions_0012_backup`);
17777
- sql.exec(`
17778
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '12')
17779
- `);
17780
- }
17781
- };
17782
-
17783
- // src/durable-objects/agentbuilder-migrations/0013_add_thread_activity.ts
17784
- var migration49 = {
17785
- version: 13,
17786
- async up(sql) {
17787
- sql.exec(`ALTER TABLE threads ADD COLUMN last_activity_at INTEGER`);
17788
- sql.exec(`ALTER TABLE threads ADD COLUMN executing_since INTEGER`);
17789
- sql.exec(
17790
- `CREATE INDEX IF NOT EXISTS idx_threads_last_activity_at ON threads(last_activity_at)`
17791
- );
17792
- sql.exec(`UPDATE threads SET last_activity_at = created_at`);
17793
- sql.exec(`
17794
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '13')
17795
- `);
17796
- }
17797
- };
17798
-
17799
- // src/durable-objects/agentbuilder-migrations/0014_thread_activity_scale.ts
17800
- var migration50 = {
17801
- version: 14,
17802
- async up(sql) {
17803
- sql.exec(`ALTER TABLE threads ADD COLUMN last_message_preview TEXT`);
17804
- sql.exec(
17805
- `CREATE INDEX IF NOT EXISTS idx_threads_executing_since
17806
- ON threads(executing_since) WHERE executing_since IS NOT NULL`
17807
- );
17808
- sql.exec(
17809
- `UPDATE threads SET last_activity_at = created_at WHERE last_activity_at IS NULL`
17810
- );
17811
- sql.exec(`
17812
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '14')
17813
- `);
17814
- }
17815
- };
17816
-
17817
- // src/durable-objects/agentbuilder-migrations/0015_clear_envelope_previews.ts
17818
- var migration51 = {
17819
- version: 15,
17820
- async up(sql) {
17821
- sql.exec(
17822
- `UPDATE threads SET last_message_preview = NULL
17823
- WHERE last_message_preview LIKE 'Subagent (reference: %'`
17824
- );
17825
- sql.exec(`
17826
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '15')
17827
- `);
17828
- }
17829
- };
17830
-
17831
- // src/durable-objects/agentbuilder-migrations/0016_add_origin_agent.ts
17832
- var migration52 = {
17833
- version: 16,
17834
- async up(sql) {
17835
- sql.exec(`ALTER TABLE threads ADD COLUMN origin_agent_name TEXT`);
17836
- sql.exec(
17837
- `CREATE INDEX IF NOT EXISTS idx_threads_origin_agent_name ON threads(origin_agent_name)`
17838
- );
17839
- sql.exec(`UPDATE threads SET origin_agent_name = agent_name`);
17840
- sql.exec(`
17841
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '16')
17842
- `);
17843
- }
17844
- };
17845
-
17846
- // src/durable-objects/agentbuilder-migrations/0017_add_thread_message_recency.ts
17847
- var migration53 = {
17848
- version: 17,
17849
- async up(sql) {
17850
- sql.exec(`ALTER TABLE threads ADD COLUMN last_message_at INTEGER`);
17851
- sql.exec(`UPDATE threads SET last_message_at = created_at`);
17852
- sql.exec(`
17853
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '17')
17854
- `);
17855
- }
17856
- };
17857
-
17858
- // src/durable-objects/agentbuilder-migrations/0018_auth_security.ts
17859
- var migration54 = {
17860
- version: 18,
17861
- async up(sql) {
17862
- sql.exec(`
17863
- CREATE TABLE IF NOT EXISTS super_admin_sessions (
17864
- token_hash TEXT PRIMARY KEY,
17865
- created_at INTEGER NOT NULL,
17866
- expires_at INTEGER NOT NULL
17867
- )
17868
- `);
17869
- sql.exec(`
17870
- CREATE INDEX IF NOT EXISTS idx_super_admin_sessions_expires
17871
- ON super_admin_sessions(expires_at)
17872
- `);
17873
- sql.exec(`
17874
- CREATE TABLE IF NOT EXISTS auth_rate_limits (
17875
- bucket_key TEXT PRIMARY KEY,
17876
- attempts INTEGER NOT NULL,
17877
- reset_at INTEGER NOT NULL
17878
- )
17879
- `);
17880
- sql.exec(`
17881
- CREATE INDEX IF NOT EXISTS idx_auth_rate_limits_reset
17882
- ON auth_rate_limits(reset_at)
17883
- `);
17884
- sql.exec(`
17885
- INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '18')
17886
- `);
17887
- }
17888
- };
17889
-
17890
- // src/durable-objects/agentbuilder-migrations/0019_scope_skills.ts
17891
- var migration55 = {
17892
- version: 19,
17893
- async up(sql) {
17894
- sql.exec(`
17895
- CREATE TABLE skills_0019 (
17896
- owner_id TEXT NOT NULL,
17897
- name TEXT NOT NULL,
17898
- description TEXT NOT NULL,
17899
- version TEXT,
17900
- enabled INTEGER NOT NULL DEFAULT 1,
17901
- shared INTEGER NOT NULL DEFAULT 0,
17902
- created_at INTEGER DEFAULT (strftime('%s', 'now')),
17903
- updated_at INTEGER DEFAULT (strftime('%s', 'now')),
17904
- PRIMARY KEY (owner_id, name)
17905
- )
17906
- `);
17907
- sql.exec(`
17908
- INSERT INTO skills_0019 (
17909
- owner_id, name, description, version, enabled, shared, created_at, updated_at
17910
- )
17911
- SELECT '__instance_shared__', name, description, version, enabled, 1, created_at, updated_at
17912
- FROM skills
17913
- `);
17914
- sql.exec(`
17915
- CREATE TABLE skill_files_0019 (
17916
- owner_id TEXT NOT NULL,
17917
- skill_name TEXT NOT NULL,
17918
- path TEXT NOT NULL,
17919
- content TEXT NOT NULL,
17920
- size INTEGER NOT NULL,
17921
- PRIMARY KEY (owner_id, skill_name, path),
17922
- FOREIGN KEY (owner_id, skill_name) REFERENCES skills_0019(owner_id, name) ON DELETE CASCADE
17923
- )
17924
- `);
17925
- sql.exec(`
17926
- INSERT INTO skill_files_0019 (owner_id, skill_name, path, content, size)
17927
- SELECT '__instance_shared__', skill_name, path, content, size FROM skill_files
17928
- `);
17929
- sql.exec(`DROP TABLE skill_files`);
17930
- sql.exec(`DROP TABLE skills`);
17931
- sql.exec(`ALTER TABLE skills_0019 RENAME TO skills`);
17932
- sql.exec(`ALTER TABLE skill_files_0019 RENAME TO skill_files`);
17933
- sql.exec(`CREATE INDEX idx_skills_owner_enabled ON skills(owner_id, enabled)`);
17934
- sql.exec(`CREATE INDEX idx_skills_shared_enabled ON skills(shared, enabled)`);
17935
- sql.exec(`CREATE INDEX idx_skill_files_skill ON skill_files(owner_id, skill_name)`);
17936
- sql.exec(`INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '19')`);
17937
- }
17938
- };
17939
-
17940
- // src/durable-objects/agentbuilder-migrations/0020_websocket_tickets.ts
17941
- var migration56 = {
17942
- version: 20,
17943
- async up(sql) {
17944
- sql.exec(`
17945
- CREATE TABLE websocket_tickets (
17946
- ticket_hash TEXT PRIMARY KEY,
17947
- pathname TEXT NOT NULL,
17948
- auth_json TEXT NOT NULL,
17949
- created_at INTEGER NOT NULL,
17950
- expires_at INTEGER NOT NULL
18235
+ sql.exec(`
18236
+ INSERT INTO users (
18237
+ id, username, password_hash, role, created_at, updated_at,
18238
+ platform_user_id, email, display_name, avatar_url, instance_role,
18239
+ source, replica_active, replica_updated_at, deleted_at, permissions
17951
18240
  )
18241
+ SELECT
18242
+ id, username, password_hash, role, created_at, updated_at,
18243
+ platform_user_id, email, display_name, avatar_url, instance_role,
18244
+ source, replica_active, replica_updated_at, deleted_at, permissions
18245
+ FROM users_0012_old
17952
18246
  `);
18247
+ sql.exec(`DROP TABLE users_0012_old`);
18248
+ sql.exec(`CREATE INDEX idx_users_username ON users(username)`);
18249
+ sql.exec(`CREATE INDEX idx_users_role ON users(role)`);
18250
+ sql.exec(`CREATE INDEX idx_users_platform_user_id ON users(platform_user_id)`);
18251
+ sql.exec(`CREATE INDEX idx_users_replica_active ON users(replica_active)`);
18252
+ sql.exec(`CREATE INDEX idx_users_instance_role ON users(instance_role)`);
17953
18253
  sql.exec(`
17954
- CREATE INDEX idx_websocket_tickets_expires
17955
- ON websocket_tickets(expires_at)
18254
+ CREATE TABLE oauth_accounts (
18255
+ id TEXT PRIMARY KEY NOT NULL,
18256
+ user_id TEXT NOT NULL,
18257
+ provider TEXT NOT NULL CHECK (provider IN ('github', 'google')),
18258
+ provider_user_id TEXT NOT NULL,
18259
+ provider_username TEXT,
18260
+ created_at INTEGER DEFAULT (strftime('%s', 'now')),
18261
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
18262
+ )
17956
18263
  `);
17957
- sql.exec(`INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '20')`);
17958
- }
17959
- };
17960
-
17961
- // src/durable-objects/agentbuilder-migrations/0021_platform_handoff_jtis.ts
17962
- var migration57 = {
17963
- version: 21,
17964
- async up(sql) {
18264
+ sql.exec(`INSERT INTO oauth_accounts SELECT * FROM oauth_accounts_0012_backup`);
18265
+ sql.exec(`CREATE UNIQUE INDEX idx_oauth_accounts_provider ON oauth_accounts(provider, provider_user_id)`);
18266
+ sql.exec(`CREATE INDEX idx_oauth_accounts_user_id ON oauth_accounts(user_id)`);
17965
18267
  sql.exec(`
17966
- CREATE TABLE platform_handoff_jtis (
17967
- jti TEXT PRIMARY KEY,
17968
- consumed_at INTEGER NOT NULL,
17969
- expires_at INTEGER NOT NULL
18268
+ CREATE TABLE api_keys (
18269
+ id TEXT PRIMARY KEY NOT NULL,
18270
+ name TEXT NOT NULL,
18271
+ key_hash TEXT NOT NULL,
18272
+ key_prefix TEXT NOT NULL,
18273
+ last_five TEXT NOT NULL,
18274
+ user_id TEXT NOT NULL,
18275
+ created_at INTEGER DEFAULT (strftime('%s', 'now')),
18276
+ last_used_at INTEGER,
18277
+ platform_key_id TEXT,
18278
+ scope TEXT,
18279
+ source TEXT NOT NULL DEFAULT 'local' CHECK (source IN ('local', 'standard_agents')),
18280
+ replica_active INTEGER NOT NULL DEFAULT 1,
18281
+ replica_updated_at INTEGER,
18282
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
17970
18283
  )
17971
18284
  `);
18285
+ sql.exec(`INSERT INTO api_keys SELECT * FROM api_keys_0012_backup`);
18286
+ sql.exec(`CREATE INDEX idx_api_keys_key_hash ON api_keys(key_hash)`);
18287
+ sql.exec(`CREATE INDEX idx_api_keys_user_id ON api_keys(user_id)`);
18288
+ sql.exec(`CREATE INDEX idx_api_keys_key_prefix ON api_keys(key_prefix)`);
18289
+ sql.exec(`CREATE INDEX idx_api_keys_platform_key_id ON api_keys(platform_key_id)`);
18290
+ sql.exec(`CREATE INDEX idx_api_keys_replica_active ON api_keys(replica_active)`);
17972
18291
  sql.exec(`
17973
- CREATE INDEX idx_platform_handoff_jtis_expires
17974
- ON platform_handoff_jtis(expires_at)
18292
+ CREATE TABLE sessions (
18293
+ id TEXT PRIMARY KEY NOT NULL,
18294
+ user_id TEXT NOT NULL,
18295
+ token_hash TEXT NOT NULL,
18296
+ expires_at INTEGER NOT NULL,
18297
+ created_at INTEGER DEFAULT (strftime('%s', 'now')),
18298
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
18299
+ )
18300
+ `);
18301
+ sql.exec(`INSERT INTO sessions SELECT * FROM sessions_0012_backup`);
18302
+ sql.exec(`CREATE INDEX idx_sessions_token_hash ON sessions(token_hash)`);
18303
+ sql.exec(`CREATE INDEX idx_sessions_user_id ON sessions(user_id)`);
18304
+ sql.exec(`CREATE INDEX idx_sessions_expires_at ON sessions(expires_at)`);
18305
+ sql.exec(`DROP TABLE oauth_accounts_0012_backup`);
18306
+ sql.exec(`DROP TABLE api_keys_0012_backup`);
18307
+ sql.exec(`DROP TABLE sessions_0012_backup`);
18308
+ sql.exec(`
18309
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '12')
17975
18310
  `);
17976
- sql.exec(`INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '21')`);
17977
- }
17978
- };
17979
-
17980
- // src/durable-objects/agentbuilder-migrations/index.ts
17981
- var migrations2 = [migration37, migration38, migration39, migration40, migration41, migration42, migration43, migration44, migration45, migration46, migration47, migration48, migration49, migration50, migration51, migration52, migration53, migration54, migration55, migration56, migration57];
17982
- var LATEST_SCHEMA_VERSION2 = migrations2.reduce(
17983
- (max, migration58) => Math.max(max, migration58.version),
17984
- 0
17985
- );
17986
-
17987
- // src/utils/crypto.ts
17988
- var CryptoUtil = class {
17989
- static algorithm = "aes-256-gcm";
17990
- /**
17991
- * Encrypt a string value
17992
- */
17993
- static async encrypt(text, key) {
17994
- const encoder = new TextEncoder();
17995
- const data = encoder.encode(text);
17996
- const cryptoKey = await crypto.subtle.importKey(
17997
- "raw",
17998
- hexToBuffer(key),
17999
- { name: "AES-GCM" },
18000
- false,
18001
- ["encrypt"]
18002
- );
18003
- const iv = crypto.getRandomValues(new Uint8Array(12));
18004
- const encrypted = await crypto.subtle.encrypt(
18005
- {
18006
- name: "AES-GCM",
18007
- iv
18008
- },
18009
- cryptoKey,
18010
- data
18011
- );
18012
- const combined = new Uint8Array(iv.length + encrypted.byteLength);
18013
- combined.set(iv);
18014
- combined.set(new Uint8Array(encrypted), iv.length);
18015
- return bufferToBase64(combined);
18016
- }
18017
- /**
18018
- * Decrypt a string value
18019
- */
18020
- static async decrypt(encryptedText, key) {
18021
- const combined = base64ToBuffer2(encryptedText);
18022
- const iv = combined.slice(0, 12);
18023
- const encrypted = combined.slice(12);
18024
- const cryptoKey = await crypto.subtle.importKey(
18025
- "raw",
18026
- hexToBuffer(key),
18027
- { name: "AES-GCM" },
18028
- false,
18029
- ["decrypt"]
18030
- );
18031
- const decrypted = await crypto.subtle.decrypt(
18032
- {
18033
- name: "AES-GCM",
18034
- iv
18035
- },
18036
- cryptoKey,
18037
- encrypted
18038
- );
18039
- const decoder = new TextDecoder();
18040
- return decoder.decode(decrypted);
18041
- }
18042
- };
18043
- function hexToBuffer(hex) {
18044
- const bytes = new Uint8Array(hex.length / 2);
18045
- for (let i = 0; i < hex.length; i += 2) {
18046
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
18047
- }
18048
- return bytes;
18049
- }
18050
- function bufferToBase64(buffer) {
18051
- let binary = "";
18052
- for (let i = 0; i < buffer.byteLength; i++) {
18053
- binary += String.fromCharCode(buffer[i]);
18054
- }
18055
- return btoa(binary);
18056
- }
18057
- function base64ToBuffer2(base64) {
18058
- const binary = atob(base64);
18059
- const bytes = new Uint8Array(binary.length);
18060
- for (let i = 0; i < binary.length; i++) {
18061
- bytes[i] = binary.charCodeAt(i);
18062
- }
18063
- return bytes;
18064
- }
18065
- async function encryptEnvs(env, encryptionKey) {
18066
- const plaintext = JSON.stringify(env);
18067
- return CryptoUtil.encrypt(plaintext, encryptionKey);
18068
- }
18069
- async function decryptEnvs(encrypted, encryptionKey) {
18070
- const plaintext = await CryptoUtil.decrypt(encrypted, encryptionKey);
18071
- const parsed = JSON.parse(plaintext);
18072
- if (!parsed || typeof parsed !== "object") {
18073
- return {};
18074
- }
18075
- const result = {};
18076
- for (const [key, value] of Object.entries(parsed)) {
18077
- if (value === void 0 || value === null) continue;
18078
- result[key] = String(value);
18079
- }
18080
- return result;
18081
- }
18082
-
18083
- // src/packing/resolver.ts
18084
- var NamespaceResolutionError = class extends Error {
18085
- constructor(itemType, itemName, namespace, message) {
18086
- super(message);
18087
- this.itemType = itemType;
18088
- this.itemName = itemName;
18089
- this.namespace = namespace;
18090
- this.name = "NamespaceResolutionError";
18091
- }
18092
- };
18093
- function parseQualifiedName(name) {
18094
- if (name.startsWith("@")) {
18095
- const firstSlash = name.indexOf("/");
18096
- if (firstSlash === -1) {
18097
- return [null, name];
18098
- }
18099
- const secondSlash = name.indexOf("/", firstSlash + 1);
18100
- if (secondSlash === -1) {
18101
- return [null, name];
18102
- }
18103
- return [name.substring(0, secondSlash), name.substring(secondSlash + 1)];
18104
- }
18105
- const separatorIndex = name.indexOf("/");
18106
- if (separatorIndex === -1) {
18107
- return [null, name];
18108
- }
18109
- return [name.substring(0, separatorIndex), name.substring(separatorIndex + 1)];
18110
- }
18111
- function qualifyName(packageId, shortName) {
18112
- return `${packageId}/${shortName}`;
18113
- }
18114
- function getShortName(name) {
18115
- const [, shortName] = parseQualifiedName(name);
18116
- return shortName;
18117
- }
18118
- function resolveTool(registry, name, namespace) {
18119
- const [pkgId, shortName] = parseQualifiedName(name);
18120
- if (pkgId !== null) {
18121
- const pkg = registry.packages[pkgId];
18122
- if (!pkg) {
18123
- throw new NamespaceResolutionError(
18124
- "tool",
18125
- name,
18126
- namespace,
18127
- `Package "${pkgId}" not found`
18128
- );
18129
- }
18130
- throw new NamespaceResolutionError(
18131
- "tool",
18132
- name,
18133
- namespace,
18134
- `Cannot access tool "${shortName}" from package "${pkgId}". Only entry point agents are accessible cross-package.`
18135
- );
18136
- }
18137
- if (namespace.type === "packed") {
18138
- const pkg = registry.packages[namespace.packageId];
18139
- if (!pkg) {
18140
- throw new NamespaceResolutionError(
18141
- "tool",
18142
- name,
18143
- namespace,
18144
- `Package "${namespace.packageId}" not found`
18145
- );
18146
- }
18147
- const loader2 = pkg.tools[shortName];
18148
- if (!loader2) {
18149
- throw new NamespaceResolutionError(
18150
- "tool",
18151
- name,
18152
- namespace,
18153
- `Tool "${shortName}" not found in package "${namespace.packageId}"`
18154
- );
18155
- }
18156
- return loader2;
18157
18311
  }
18158
- const loader = registry.global.tools[shortName];
18159
- if (!loader) {
18160
- throw new NamespaceResolutionError(
18161
- "tool",
18162
- name,
18163
- namespace,
18164
- `Tool "${shortName}" not found in global namespace`
18312
+ };
18313
+
18314
+ // src/durable-objects/agentbuilder-migrations/0013_add_thread_activity.ts
18315
+ var migration49 = {
18316
+ version: 13,
18317
+ async up(sql) {
18318
+ sql.exec(`ALTER TABLE threads ADD COLUMN last_activity_at INTEGER`);
18319
+ sql.exec(`ALTER TABLE threads ADD COLUMN executing_since INTEGER`);
18320
+ sql.exec(
18321
+ `CREATE INDEX IF NOT EXISTS idx_threads_last_activity_at ON threads(last_activity_at)`
18165
18322
  );
18323
+ sql.exec(`UPDATE threads SET last_activity_at = created_at`);
18324
+ sql.exec(`
18325
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '13')
18326
+ `);
18166
18327
  }
18167
- return loader;
18168
- }
18169
- function resolvePrompt(registry, name, namespace) {
18170
- const [pkgId, shortName] = parseQualifiedName(name);
18171
- if (pkgId !== null) {
18172
- throw new NamespaceResolutionError(
18173
- "prompt",
18174
- name,
18175
- namespace,
18176
- `Cannot access prompt "${shortName}" from package "${pkgId}". Prompts are package-internal.`
18328
+ };
18329
+
18330
+ // src/durable-objects/agentbuilder-migrations/0014_thread_activity_scale.ts
18331
+ var migration50 = {
18332
+ version: 14,
18333
+ async up(sql) {
18334
+ sql.exec(`ALTER TABLE threads ADD COLUMN last_message_preview TEXT`);
18335
+ sql.exec(
18336
+ `CREATE INDEX IF NOT EXISTS idx_threads_executing_since
18337
+ ON threads(executing_since) WHERE executing_since IS NOT NULL`
18177
18338
  );
18178
- }
18179
- if (namespace.type === "packed") {
18180
- const pkg = registry.packages[namespace.packageId];
18181
- if (!pkg) {
18182
- throw new NamespaceResolutionError(
18183
- "prompt",
18184
- name,
18185
- namespace,
18186
- `Package "${namespace.packageId}" not found`
18187
- );
18188
- }
18189
- const loader2 = pkg.prompts[shortName];
18190
- if (!loader2) {
18191
- throw new NamespaceResolutionError(
18192
- "prompt",
18193
- name,
18194
- namespace,
18195
- `Prompt "${shortName}" not found in package "${namespace.packageId}"`
18196
- );
18197
- }
18198
- return loader2;
18199
- }
18200
- const loader = registry.global.prompts[shortName];
18201
- if (!loader) {
18202
- throw new NamespaceResolutionError(
18203
- "prompt",
18204
- name,
18205
- namespace,
18206
- `Prompt "${shortName}" not found in global namespace`
18339
+ sql.exec(
18340
+ `UPDATE threads SET last_activity_at = created_at WHERE last_activity_at IS NULL`
18207
18341
  );
18342
+ sql.exec(`
18343
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '14')
18344
+ `);
18208
18345
  }
18209
- return loader;
18210
- }
18211
- function resolveModel(registry, name, namespace) {
18212
- const [possiblePkgId, shortName] = parseQualifiedName(name);
18213
- if (possiblePkgId !== null && registry.packages[possiblePkgId]) {
18214
- throw new NamespaceResolutionError(
18215
- "model",
18216
- name,
18217
- namespace,
18218
- `Cannot use qualified model name "${name}". Models must be unqualified. If this is a provider model name, ensure no package named "${possiblePkgId}" exists.`
18346
+ };
18347
+
18348
+ // src/durable-objects/agentbuilder-migrations/0015_clear_envelope_previews.ts
18349
+ var migration51 = {
18350
+ version: 15,
18351
+ async up(sql) {
18352
+ sql.exec(
18353
+ `UPDATE threads SET last_message_preview = NULL
18354
+ WHERE last_message_preview LIKE 'Subagent (reference: %'`
18219
18355
  );
18356
+ sql.exec(`
18357
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '15')
18358
+ `);
18220
18359
  }
18221
- const lookupName = name;
18222
- if (namespace.type === "packed") {
18223
- const pkg = registry.packages[namespace.packageId];
18224
- if (pkg) {
18225
- const loader2 = pkg.models[lookupName];
18226
- if (loader2) {
18227
- return loader2;
18228
- }
18229
- }
18230
- const globalLoader = registry.global.models[lookupName];
18231
- if (globalLoader) {
18232
- return globalLoader;
18233
- }
18234
- throw new NamespaceResolutionError(
18235
- "model",
18236
- name,
18237
- namespace,
18238
- `Model "${lookupName}" not found in package "${namespace.packageId}" or global namespace`
18360
+ };
18361
+
18362
+ // src/durable-objects/agentbuilder-migrations/0016_add_origin_agent.ts
18363
+ var migration52 = {
18364
+ version: 16,
18365
+ async up(sql) {
18366
+ sql.exec(`ALTER TABLE threads ADD COLUMN origin_agent_name TEXT`);
18367
+ sql.exec(
18368
+ `CREATE INDEX IF NOT EXISTS idx_threads_origin_agent_name ON threads(origin_agent_name)`
18239
18369
  );
18370
+ sql.exec(`UPDATE threads SET origin_agent_name = agent_name`);
18371
+ sql.exec(`
18372
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '16')
18373
+ `);
18240
18374
  }
18241
- const loader = registry.global.models[lookupName];
18242
- if (!loader) {
18243
- throw new NamespaceResolutionError(
18244
- "model",
18245
- name,
18246
- namespace,
18247
- `Model "${lookupName}" not found in global namespace`
18248
- );
18375
+ };
18376
+
18377
+ // src/durable-objects/agentbuilder-migrations/0017_add_thread_message_recency.ts
18378
+ var migration53 = {
18379
+ version: 17,
18380
+ async up(sql) {
18381
+ sql.exec(`ALTER TABLE threads ADD COLUMN last_message_at INTEGER`);
18382
+ sql.exec(`UPDATE threads SET last_message_at = created_at`);
18383
+ sql.exec(`
18384
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '17')
18385
+ `);
18249
18386
  }
18250
- return loader;
18251
- }
18252
- function resolveAgent(registry, name, namespace) {
18253
- const [pkgId, shortName] = parseQualifiedName(name);
18254
- if (pkgId !== null) {
18255
- const pkg = registry.packages[pkgId];
18256
- if (!pkg) {
18257
- throw new NamespaceResolutionError(
18258
- "agent",
18259
- name,
18260
- namespace,
18261
- `Package "${pkgId}" not found`
18262
- );
18263
- }
18264
- if (!pkg.entryAgents.includes(shortName)) {
18265
- throw new NamespaceResolutionError(
18266
- "agent",
18267
- name,
18268
- namespace,
18269
- `Agent "${shortName}" is not an entry point in package "${pkgId}"`
18270
- );
18271
- }
18272
- const loader = pkg.agents[shortName];
18273
- if (!loader) {
18274
- throw new NamespaceResolutionError(
18275
- "agent",
18276
- name,
18277
- namespace,
18278
- `Agent "${shortName}" not found in package "${pkgId}"`
18279
- );
18280
- }
18281
- return loader;
18387
+ };
18388
+
18389
+ // src/durable-objects/agentbuilder-migrations/0018_auth_security.ts
18390
+ var migration54 = {
18391
+ version: 18,
18392
+ async up(sql) {
18393
+ sql.exec(`
18394
+ CREATE TABLE IF NOT EXISTS super_admin_sessions (
18395
+ token_hash TEXT PRIMARY KEY,
18396
+ created_at INTEGER NOT NULL,
18397
+ expires_at INTEGER NOT NULL
18398
+ )
18399
+ `);
18400
+ sql.exec(`
18401
+ CREATE INDEX IF NOT EXISTS idx_super_admin_sessions_expires
18402
+ ON super_admin_sessions(expires_at)
18403
+ `);
18404
+ sql.exec(`
18405
+ CREATE TABLE IF NOT EXISTS auth_rate_limits (
18406
+ bucket_key TEXT PRIMARY KEY,
18407
+ attempts INTEGER NOT NULL,
18408
+ reset_at INTEGER NOT NULL
18409
+ )
18410
+ `);
18411
+ sql.exec(`
18412
+ CREATE INDEX IF NOT EXISTS idx_auth_rate_limits_reset
18413
+ ON auth_rate_limits(reset_at)
18414
+ `);
18415
+ sql.exec(`
18416
+ INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '18')
18417
+ `);
18282
18418
  }
18283
- if (namespace.type === "packed") {
18284
- const pkg = registry.packages[namespace.packageId];
18285
- if (!pkg) {
18286
- throw new NamespaceResolutionError(
18287
- "agent",
18288
- name,
18289
- namespace,
18290
- `Package "${namespace.packageId}" not found`
18291
- );
18292
- }
18293
- const loader = pkg.agents[shortName];
18294
- if (!loader) {
18295
- throw new NamespaceResolutionError(
18296
- "agent",
18297
- name,
18298
- namespace,
18299
- `Agent "${shortName}" not found in package "${namespace.packageId}"`
18300
- );
18301
- }
18302
- return loader;
18419
+ };
18420
+
18421
+ // src/durable-objects/agentbuilder-migrations/0019_scope_skills.ts
18422
+ var migration55 = {
18423
+ version: 19,
18424
+ async up(sql) {
18425
+ sql.exec(`
18426
+ CREATE TABLE skills_0019 (
18427
+ owner_id TEXT NOT NULL,
18428
+ name TEXT NOT NULL,
18429
+ description TEXT NOT NULL,
18430
+ version TEXT,
18431
+ enabled INTEGER NOT NULL DEFAULT 1,
18432
+ shared INTEGER NOT NULL DEFAULT 0,
18433
+ created_at INTEGER DEFAULT (strftime('%s', 'now')),
18434
+ updated_at INTEGER DEFAULT (strftime('%s', 'now')),
18435
+ PRIMARY KEY (owner_id, name)
18436
+ )
18437
+ `);
18438
+ sql.exec(`
18439
+ INSERT INTO skills_0019 (
18440
+ owner_id, name, description, version, enabled, shared, created_at, updated_at
18441
+ )
18442
+ SELECT '__instance_shared__', name, description, version, enabled, 1, created_at, updated_at
18443
+ FROM skills
18444
+ `);
18445
+ sql.exec(`
18446
+ CREATE TABLE skill_files_0019 (
18447
+ owner_id TEXT NOT NULL,
18448
+ skill_name TEXT NOT NULL,
18449
+ path TEXT NOT NULL,
18450
+ content TEXT NOT NULL,
18451
+ size INTEGER NOT NULL,
18452
+ PRIMARY KEY (owner_id, skill_name, path),
18453
+ FOREIGN KEY (owner_id, skill_name) REFERENCES skills_0019(owner_id, name) ON DELETE CASCADE
18454
+ )
18455
+ `);
18456
+ sql.exec(`
18457
+ INSERT INTO skill_files_0019 (owner_id, skill_name, path, content, size)
18458
+ SELECT '__instance_shared__', skill_name, path, content, size FROM skill_files
18459
+ `);
18460
+ sql.exec(`DROP TABLE skill_files`);
18461
+ sql.exec(`DROP TABLE skills`);
18462
+ sql.exec(`ALTER TABLE skills_0019 RENAME TO skills`);
18463
+ sql.exec(`ALTER TABLE skill_files_0019 RENAME TO skill_files`);
18464
+ sql.exec(`CREATE INDEX idx_skills_owner_enabled ON skills(owner_id, enabled)`);
18465
+ sql.exec(`CREATE INDEX idx_skills_shared_enabled ON skills(shared, enabled)`);
18466
+ sql.exec(`CREATE INDEX idx_skill_files_skill ON skill_files(owner_id, skill_name)`);
18467
+ sql.exec(`INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '19')`);
18303
18468
  }
18304
- const globalLoader = registry.global.agents[shortName];
18305
- if (globalLoader) {
18306
- return globalLoader;
18469
+ };
18470
+
18471
+ // src/durable-objects/agentbuilder-migrations/0020_websocket_tickets.ts
18472
+ var migration56 = {
18473
+ version: 20,
18474
+ async up(sql) {
18475
+ sql.exec(`
18476
+ CREATE TABLE websocket_tickets (
18477
+ ticket_hash TEXT PRIMARY KEY,
18478
+ pathname TEXT NOT NULL,
18479
+ auth_json TEXT NOT NULL,
18480
+ created_at INTEGER NOT NULL,
18481
+ expires_at INTEGER NOT NULL
18482
+ )
18483
+ `);
18484
+ sql.exec(`
18485
+ CREATE INDEX idx_websocket_tickets_expires
18486
+ ON websocket_tickets(expires_at)
18487
+ `);
18488
+ sql.exec(`INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '20')`);
18307
18489
  }
18308
- for (const [pkgId2, pkg] of Object.entries(registry.packages)) {
18309
- if (pkg.entryAgents.includes(shortName)) {
18310
- const loader = pkg.agents[shortName];
18311
- if (loader) {
18312
- return loader;
18313
- }
18314
- }
18490
+ };
18491
+
18492
+ // src/durable-objects/agentbuilder-migrations/0021_platform_handoff_jtis.ts
18493
+ var migration57 = {
18494
+ version: 21,
18495
+ async up(sql) {
18496
+ sql.exec(`
18497
+ CREATE TABLE platform_handoff_jtis (
18498
+ jti TEXT PRIMARY KEY,
18499
+ consumed_at INTEGER NOT NULL,
18500
+ expires_at INTEGER NOT NULL
18501
+ )
18502
+ `);
18503
+ sql.exec(`
18504
+ CREATE INDEX idx_platform_handoff_jtis_expires
18505
+ ON platform_handoff_jtis(expires_at)
18506
+ `);
18507
+ sql.exec(`INSERT OR REPLACE INTO _metadata (key, value) VALUES ('schema_version', '21')`);
18315
18508
  }
18316
- throw new NamespaceResolutionError(
18317
- "agent",
18318
- name,
18319
- namespace,
18320
- `Agent "${shortName}" not found in global namespace`
18321
- );
18322
- }
18323
- function resolveHook(registry, name, namespace) {
18324
- const [pkgId, shortName] = parseQualifiedName(name);
18325
- if (pkgId !== null) {
18326
- throw new NamespaceResolutionError(
18327
- "hook",
18328
- name,
18329
- namespace,
18330
- `Cannot use qualified hook name "${name}". Hooks must be unqualified.`
18509
+ };
18510
+
18511
+ // src/durable-objects/agentbuilder-migrations/index.ts
18512
+ var migrations2 = [migration37, migration38, migration39, migration40, migration41, migration42, migration43, migration44, migration45, migration46, migration47, migration48, migration49, migration50, migration51, migration52, migration53, migration54, migration55, migration56, migration57];
18513
+ var LATEST_SCHEMA_VERSION2 = migrations2.reduce(
18514
+ (max, migration58) => Math.max(max, migration58.version),
18515
+ 0
18516
+ );
18517
+
18518
+ // src/utils/crypto.ts
18519
+ var CryptoUtil = class {
18520
+ static algorithm = "aes-256-gcm";
18521
+ /**
18522
+ * Encrypt a string value
18523
+ */
18524
+ static async encrypt(text, key) {
18525
+ const encoder = new TextEncoder();
18526
+ const data = encoder.encode(text);
18527
+ const cryptoKey = await crypto.subtle.importKey(
18528
+ "raw",
18529
+ hexToBuffer(key),
18530
+ { name: "AES-GCM" },
18531
+ false,
18532
+ ["encrypt"]
18533
+ );
18534
+ const iv = crypto.getRandomValues(new Uint8Array(12));
18535
+ const encrypted = await crypto.subtle.encrypt(
18536
+ {
18537
+ name: "AES-GCM",
18538
+ iv
18539
+ },
18540
+ cryptoKey,
18541
+ data
18331
18542
  );
18543
+ const combined = new Uint8Array(iv.length + encrypted.byteLength);
18544
+ combined.set(iv);
18545
+ combined.set(new Uint8Array(encrypted), iv.length);
18546
+ return bufferToBase64(combined);
18332
18547
  }
18333
- if (namespace.type === "packed") {
18334
- const pkg = registry.packages[namespace.packageId];
18335
- if (pkg) {
18336
- const loader2 = pkg.hooks[shortName];
18337
- if (loader2) {
18338
- return loader2;
18339
- }
18340
- }
18341
- return null;
18548
+ /**
18549
+ * Decrypt a string value
18550
+ */
18551
+ static async decrypt(encryptedText, key) {
18552
+ const combined = base64ToBuffer2(encryptedText);
18553
+ const iv = combined.slice(0, 12);
18554
+ const encrypted = combined.slice(12);
18555
+ const cryptoKey = await crypto.subtle.importKey(
18556
+ "raw",
18557
+ hexToBuffer(key),
18558
+ { name: "AES-GCM" },
18559
+ false,
18560
+ ["decrypt"]
18561
+ );
18562
+ const decrypted = await crypto.subtle.decrypt(
18563
+ {
18564
+ name: "AES-GCM",
18565
+ iv
18566
+ },
18567
+ cryptoKey,
18568
+ encrypted
18569
+ );
18570
+ const decoder = new TextDecoder();
18571
+ return decoder.decode(decrypted);
18342
18572
  }
18343
- const loader = registry.global.hooks[shortName];
18344
- return loader || null;
18345
- }
18346
- function getVisibleToolNames(registry, namespace) {
18347
- if (namespace.type === "packed") {
18348
- const pkg = registry.packages[namespace.packageId];
18349
- return pkg ? Object.keys(pkg.tools) : [];
18573
+ };
18574
+ function hexToBuffer(hex) {
18575
+ const bytes = new Uint8Array(hex.length / 2);
18576
+ for (let i = 0; i < hex.length; i += 2) {
18577
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
18350
18578
  }
18351
- return Object.keys(registry.global.tools);
18579
+ return bytes;
18352
18580
  }
18353
- function getVisibleAgentNames(registry, namespace) {
18354
- if (namespace.type === "packed") {
18355
- const pkg = registry.packages[namespace.packageId];
18356
- const ownAgents = pkg ? Object.keys(pkg.agents) : [];
18357
- const otherEntryPoints = Object.entries(registry.packages).filter(([id]) => id !== namespace.packageId).flatMap(
18358
- ([pkgId, pkg2]) => pkg2.entryAgents.map((name) => qualifyName(pkgId, name))
18359
- );
18360
- return [...ownAgents, ...otherEntryPoints];
18581
+ function bufferToBase64(buffer) {
18582
+ let binary = "";
18583
+ for (let i = 0; i < buffer.byteLength; i++) {
18584
+ binary += String.fromCharCode(buffer[i]);
18361
18585
  }
18362
- const globalAgents = Object.keys(registry.global.agents);
18363
- const entryPoints = Object.values(registry.packages).flatMap((pkg) => pkg.entryAgents);
18364
- return [.../* @__PURE__ */ new Set([...globalAgents, ...entryPoints])];
18586
+ return btoa(binary);
18365
18587
  }
18366
- function getVisiblePromptNames(registry, namespace) {
18367
- if (namespace.type === "packed") {
18368
- const pkg = registry.packages[namespace.packageId];
18369
- return pkg ? Object.keys(pkg.prompts) : [];
18588
+ function base64ToBuffer2(base64) {
18589
+ const binary = atob(base64);
18590
+ const bytes = new Uint8Array(binary.length);
18591
+ for (let i = 0; i < binary.length; i++) {
18592
+ bytes[i] = binary.charCodeAt(i);
18370
18593
  }
18371
- return Object.keys(registry.global.prompts);
18594
+ return bytes;
18372
18595
  }
18373
- function getVisibleModelNames(registry, namespace) {
18374
- if (namespace.type === "packed") {
18375
- const pkg = registry.packages[namespace.packageId];
18376
- const ownModels = pkg ? Object.keys(pkg.models) : [];
18377
- const globalModels = Object.keys(registry.global.models);
18378
- return [.../* @__PURE__ */ new Set([...ownModels, ...globalModels])];
18379
- }
18380
- return Object.keys(registry.global.models);
18596
+ async function encryptEnvs(env, encryptionKey) {
18597
+ const plaintext = JSON.stringify(env);
18598
+ return CryptoUtil.encrypt(plaintext, encryptionKey);
18381
18599
  }
18382
- function createNamespaceContext(agentDef) {
18383
- if (agentDef?.__package) {
18384
- return { type: "packed", packageId: agentDef.__package.packageId };
18600
+ async function decryptEnvs(encrypted, encryptionKey) {
18601
+ const plaintext = await CryptoUtil.decrypt(encrypted, encryptionKey);
18602
+ const parsed = JSON.parse(plaintext);
18603
+ if (!parsed || typeof parsed !== "object") {
18604
+ return {};
18385
18605
  }
18386
- return { type: "global" };
18387
- }
18388
- function isQualifiedName(name) {
18389
- if (name.startsWith("@")) {
18390
- const firstSlash = name.indexOf("/");
18391
- if (firstSlash === -1) return false;
18392
- return name.indexOf("/", firstSlash + 1) !== -1;
18606
+ const result = {};
18607
+ for (const [key, value] of Object.entries(parsed)) {
18608
+ if (value === void 0 || value === null) continue;
18609
+ result[key] = String(value);
18393
18610
  }
18394
- return name.includes("/");
18611
+ return result;
18395
18612
  }
18396
18613
 
18397
18614
  // src/durable-objects/DurableAgentBuilder.ts
18615
+ init_resolver();
18398
18616
  init_types();
18399
18617
 
18400
18618
  // src/skills/frontmatter.ts
@@ -18486,6 +18704,7 @@ function validateSkillFiles(files) {
18486
18704
 
18487
18705
  // src/durable-objects/DurableAgentBuilder.ts
18488
18706
  init_scope();
18707
+ init_ParentHookResolver();
18489
18708
  var ENV_TYPES_PROPERTY = "__agentbuilder_env_types";
18490
18709
  function parseStoredPermissions(value) {
18491
18710
  if (typeof value !== "string" || !value.trim()) return null;
@@ -19167,16 +19386,29 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
19167
19386
  } catch {
19168
19387
  return;
19169
19388
  }
19170
- const hookIds = Array.isArray(agentDef?.hooks) ? agentDef.hooks : [];
19171
- if (hookIds.length === 0) {
19172
- return;
19173
- }
19174
- let hooksRegistry;
19175
- try {
19176
- hooksRegistry = this.hooks();
19177
- } catch {
19178
- return;
19179
- }
19389
+ const packageId = agentDef?.__package?.packageId;
19390
+ const rawPromptName = agentDef?.sideA?.prompt;
19391
+ const promptName = rawPromptName && packageId && !isQualifiedName(rawPromptName) ? `${packageId}/${rawPromptName}` : rawPromptName;
19392
+ const promptDef = promptName ? await this.loadPrompt(promptName) : void 0;
19393
+ const bindings = await resolveHooksForPrompt(
19394
+ {
19395
+ host: this,
19396
+ agentName: thread.agent_name,
19397
+ agent: agentDef,
19398
+ promptName,
19399
+ prompt: promptDef,
19400
+ isOptionalRelationshipEnabled: async (envName) => {
19401
+ const value = await this.resolveThreadEnv({
19402
+ threadId: thread.id,
19403
+ property: envName,
19404
+ promptName: promptName ?? agentDef.name ?? thread.agent_name
19405
+ });
19406
+ return ["true", "1", "yes"].includes((value ?? "").trim().toLowerCase());
19407
+ }
19408
+ },
19409
+ "after_thread_created"
19410
+ );
19411
+ if (bindings.length === 0) return;
19180
19412
  const durableId = this.env.AGENT_BUILDER_THREAD.idFromName(thread.id);
19181
19413
  const threadStub = this.env.AGENT_BUILDER_THREAD.get(durableId);
19182
19414
  const { ThreadStateImpl: ThreadStateImpl2 } = await Promise.resolve().then(() => (init_ThreadStateImpl(), ThreadStateImpl_exports));
@@ -19191,16 +19423,14 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
19191
19423
  terminated: thread.terminated,
19192
19424
  created_at: thread.created_at
19193
19425
  });
19194
- for (const hookId of hookIds) {
19195
- const hookLoader = hooksRegistry[hookId];
19196
- if (!hookLoader) continue;
19426
+ for (const binding of bindings) {
19197
19427
  try {
19198
- const hookDef = await hookLoader();
19199
- if (hookDef?.hook === "after_thread_created") {
19200
- await hookDef.execute(threadState);
19201
- }
19428
+ await binding.execute(threadState, binding.context);
19202
19429
  } catch (error) {
19203
- console.error(`[Hooks] \u2717 Error running after_thread_created hook '${hookId}':`, error);
19430
+ console.error(
19431
+ `[Hooks] \u2717 Error running after_thread_created hook '${binding.id}':`,
19432
+ error
19433
+ );
19204
19434
  }
19205
19435
  }
19206
19436
  }
@@ -20412,6 +20642,15 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
20412
20642
  * Load a prompt definition by name.
20413
20643
  */
20414
20644
  async loadPrompt(name) {
20645
+ if (isQualifiedName(name)) {
20646
+ const [packageId, promptName] = parseQualifiedName(name);
20647
+ const pkg = packageId ? this.registry()?.packages?.[packageId] : void 0;
20648
+ const loader2 = pkg?.prompts?.[promptName];
20649
+ if (!loader2) {
20650
+ throw new Error(`Prompt not found: ${name}`);
20651
+ }
20652
+ return await loader2();
20653
+ }
20415
20654
  const registry = this.prompts();
20416
20655
  const loader = registry[name];
20417
20656
  if (!loader) {
@@ -21651,6 +21890,17 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
21651
21890
  }
21652
21891
  return { status: row.status };
21653
21892
  }
21893
+ /** Deny a pending device login without creating a user or API key. */
21894
+ async denyDeviceLogin(codeHash) {
21895
+ await this.ensureMigrated();
21896
+ await this.sweepDeviceLogins();
21897
+ const cursor = await this.ctx.storage.sql.exec(
21898
+ `UPDATE device_logins SET status = 'denied', user_id = NULL, token = NULL
21899
+ WHERE code_hash = ? AND status = 'pending'`,
21900
+ codeHash
21901
+ );
21902
+ return cursor.rowsWritten > 0;
21903
+ }
21654
21904
  /** Approve a pending device login: mint a personal API key for the user and
21655
21905
  * park its plaintext for the single claim. Returns false when the code is
21656
21906
  * unknown, expired, or not pending. */
@@ -21701,6 +21951,7 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
21701
21951
  init_StreamManager();
21702
21952
  init_LLMRequest();
21703
21953
  init_ThreadStateImpl();
21954
+ init_resolver();
21704
21955
 
21705
21956
  // src/durable-objects/logDetailStream.ts
21706
21957
  var LOG_DETAIL_HEAVY_FIELDS = [
@@ -22374,6 +22625,7 @@ var DurableThread = class _DurableThread extends DurableObject {
22374
22625
  type: agentDef.type,
22375
22626
  created_at: Date.now(),
22376
22627
  max_session_turns: agentDef.maxSessionTurns,
22628
+ _package: agentDef.__package,
22377
22629
  side_a_label: agentDef.sideA?.label,
22378
22630
  side_a_agent_prompt: qualifyPromptName(agentDef.sideA?.prompt),
22379
22631
  side_a_stop_on_response: agentDef.sideA?.stopOnResponse ?? true,
@@ -27608,6 +27860,8 @@ Its execution was lost (the executor restarted or hung) and automatic recovery w
27608
27860
  type: agentDef.type,
27609
27861
  created_at: Date.now(),
27610
27862
  max_session_turns: agentDef.maxSessionTurns,
27863
+ hooks: agentDef.hooks ?? [],
27864
+ _package: agentDef.__package,
27611
27865
  side_a_label: agentDef.sideA?.label,
27612
27866
  side_a_agent_prompt: qualifyPromptName(agentDef.sideA?.prompt),
27613
27867
  side_a_stop_on_response: agentDef.sideA?.stopOnResponse ?? true,
@@ -27833,6 +28087,8 @@ Its execution was lost (the executor restarted or hung) and automatic recovery w
27833
28087
  type: agentDef.type,
27834
28088
  created_at: Date.now(),
27835
28089
  max_session_turns: agentDef.maxSessionTurns,
28090
+ hooks: agentDef.hooks ?? [],
28091
+ _package: agentDef.__package,
27836
28092
  side_a_label: agentDef.sideA?.label,
27837
28093
  side_a_agent_prompt: qualifyPromptName(agentDef.sideA?.prompt),
27838
28094
  side_a_stop_on_response: agentDef.sideA?.stopOnResponse ?? true,
@@ -27989,6 +28245,8 @@ Its execution was lost (the executor restarted or hung) and automatic recovery w
27989
28245
  type: agentDef.type,
27990
28246
  created_at: Date.now(),
27991
28247
  max_session_turns: agentDef.maxSessionTurns,
28248
+ hooks: agentDef.hooks ?? [],
28249
+ _package: agentDef.__package,
27992
28250
  side_a_label: agentDef.sideA?.label,
27993
28251
  side_a_agent_prompt: qualifyPromptName(agentDef.sideA?.prompt),
27994
28252
  side_a_stop_on_response: agentDef.sideA?.stopOnResponse ?? true,
@@ -29945,6 +30203,7 @@ function enhanceFlowState(flow) {
29945
30203
  init_context();
29946
30204
  init_ProviderRegistry();
29947
30205
  init_types2();
30206
+ init_resolver();
29948
30207
 
29949
30208
  export { CLIENT_STREAM_CHUNK_BYTES, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, NamespaceResolutionError, ProviderRegistry, ThreadWatchdog, applyRuntimeCors, authenticate, buildImageDescription, callClient, callClientStream, canAccessThread, cat, createNamespaceContext, createThreadEndpointHandler, decodeStreamChunk, defineController2 as defineController, emitThreadEvent, encodeStreamChunk, endpointCallerFromAuth, enhanceFlowState, exists, find, forceTurn, generateImageDescription, getFileStats, getMessages, getMessagesToSummarize, getShortName, getThumbnail, getUnsummarizedImageAttachments, getVisibleAgentNames, getVisibleModelNames, getVisiblePromptNames, getVisibleToolNames, grep, hasImageAttachments, head, injectMessage, isAdminOnlyApiRoute, isHostedInstance, isPublicApiRoute, isQualifiedName, isSameOriginBrowserRequest, isTrustedLocalDevelopmentRequest, linkFile, mkdir, move, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, rename, replaceImagesWithDescriptions, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, runtimeCorsHeaders, runtimePreflightResponse, stat, supportsClientForwarding, tail, unlink, updateThread, writeFile, writeImage };
29950
30209
  //# sourceMappingURL=runtime.js.map