@axiom-lattice/core 4.2.2 → 4.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -8546,7 +8546,7 @@ var createBrowserGetInfoTool = ({ vmIsolation }) => {
8546
8546
  };
8547
8547
 
8548
8548
  // src/index.ts
8549
- import { HumanMessage as HumanMessage7 } from "@langchain/core/messages";
8549
+ import { HumanMessage as HumanMessage6 } from "@langchain/core/messages";
8550
8550
 
8551
8551
  // src/agent_lattice/types.ts
8552
8552
  import {
@@ -10070,8 +10070,8 @@ var metricsPlugin = {
10070
10070
  type: "metrics",
10071
10071
  category: "data",
10072
10072
  capabilityBundleEligible: true,
10073
- name: "Metrics",
10074
- description: "Provides metrics querying capabilities",
10073
+ name: "Metrics (DEPRECATED)",
10074
+ description: "DEPRECATED \u2014 use the 'semantic-metrics' plugin instead. Legacy metrics querying over the old server contract; kept for backward compatibility with existing agents. New agents should enable 'semantic-metrics' (connection-backed, /api/v1, table-grant scoping, semantic meta publishing).",
10075
10075
  tools: [
10076
10076
  { name: "list_datasources", description: "List all datasources from all configured servers" },
10077
10077
  { name: "query_metrics_list", description: "Query available metrics from datasources" },
@@ -11510,7 +11510,7 @@ var ConnectionRegistry = class {
11510
11510
  ConnectionRegistry.store = null;
11511
11511
 
11512
11512
  // src/agent_lattice/builders/commonMiddleware.ts
11513
- import { createMiddleware as createMiddleware12 } from "langchain";
11513
+ import { createMiddleware as createMiddleware11 } from "langchain";
11514
11514
 
11515
11515
  // src/agent_lattice/builders/taskMiddlewareValidation.ts
11516
11516
  var REQUIRED_TASK_TOOLS = ["manage_task", "task"];
@@ -11880,373 +11880,6 @@ function createCapabilityGuardMiddleware(registry4) {
11880
11880
  });
11881
11881
  }
11882
11882
 
11883
- // src/middlewares/projectRoomMiddleware.ts
11884
- import { createHash as createHash3 } from "crypto";
11885
- import {
11886
- descriptorDataValue,
11887
- parseTrustedRunContext as parseTrustedRunContext2,
11888
- snapshotExactArray as snapshotExactArray2,
11889
- snapshotExactRecord as snapshotExactRecord2
11890
- } from "@axiom-lattice/protocols";
11891
- import { createMiddleware as createMiddleware11, tool as tool39 } from "langchain";
11892
- import { z as z41 } from "zod";
11893
-
11894
- // src/services/RoomAgentMessageService.ts
11895
- import { randomUUID as randomUUID5 } from "crypto";
11896
- import { snapshotExactArray, snapshotExactRecord } from "@axiom-lattice/protocols";
11897
- var INPUT_KEYS = [
11898
- "tenantId",
11899
- "workspaceId",
11900
- "projectId",
11901
- "roomId",
11902
- "membershipId",
11903
- "assistantId",
11904
- "text",
11905
- "sourceRoomMessageId",
11906
- "sourceId",
11907
- "idempotencyKey"
11908
- ];
11909
- var REPLY_INPUT_KEYS = ["tenantId", "membershipId", "text", "sourceRoomMessageId", "inputMessageId", "sourceId", "idempotencyKey"];
11910
- var RoomAgentMessageService = class {
11911
- /**
11912
- * Creates a room writer over the durable membership and message stores.
11913
- *
11914
- * @param deps Store methods, optional deterministic ID factory, and detached post-commit hooks.
11915
- */
11916
- constructor(deps) {
11917
- this.deps = deps;
11918
- }
11919
- /**
11920
- * Persists a fully scoped Agent response after validating its human source and active membership.
11921
- *
11922
- * @param input Exact trusted scope and response payload.
11923
- * @returns A deep clone of the canonical idempotent room message.
11924
- */
11925
- post(input) {
11926
- const snapshot = exactStringRecord(input, INPUT_KEYS, "Invalid project room message input");
11927
- return this.persist(snapshot);
11928
- }
11929
- /**
11930
- * Persists a channel reply while deriving all scope from validated durable records.
11931
- *
11932
- * @param input Exact correlation IDs, tenant, target membership, and response text.
11933
- * @returns A deep clone of the canonical idempotent room message.
11934
- */
11935
- postReply(input) {
11936
- const snapshot = exactStringRecord(input, REPLY_INPUT_KEYS, "Invalid project room reply input");
11937
- if (snapshot.sourceId !== `reply:${snapshot.inputMessageId}` || snapshot.idempotencyKey !== `room-reply:${snapshot.sourceRoomMessageId}:${snapshot.membershipId}:${snapshot.sourceId}`) {
11938
- throw new Error("Invalid project room reply correlation");
11939
- }
11940
- return this.persistDerived(snapshot);
11941
- }
11942
- async persistDerived(input) {
11943
- const source = snapshotSource(await this.deps.messages.findById(input.tenantId, input.sourceRoomMessageId));
11944
- if (!source || source.id !== input.sourceRoomMessageId || source.tenantId !== input.tenantId) throw new Error("Invalid project room message");
11945
- const member = snapshotMembership(await this.deps.memberships.findById(input.tenantId, input.membershipId));
11946
- if (!member || member.id !== input.membershipId || member.tenantId !== input.tenantId) throw new Error("Invalid project room membership");
11947
- return this.persist({
11948
- ...input,
11949
- workspaceId: source.workspaceId,
11950
- projectId: source.projectId,
11951
- roomId: source.roomId,
11952
- assistantId: member.assistantId
11953
- }, source, member);
11954
- }
11955
- async persist(input, loadedSource, loadedMember) {
11956
- const text = input.text.trim();
11957
- if (text.length < 1 || text.length > 2e4) throw new Error("Invalid project room message text");
11958
- const source = loadedSource ?? snapshotSource(await this.deps.messages.findById(input.tenantId, input.sourceRoomMessageId));
11959
- if (!source || source.id !== input.sourceRoomMessageId || source.tenantId !== input.tenantId || source.workspaceId !== input.workspaceId || source.projectId !== input.projectId || source.roomId !== input.roomId) {
11960
- throw new Error("Invalid project room message");
11961
- }
11962
- const member = loadedMember ?? snapshotMembership(await this.deps.memberships.findById(input.tenantId, input.membershipId));
11963
- if (!member || member.id !== input.membershipId || member.status !== "active" || member.assistantId !== input.assistantId || member.tenantId !== input.tenantId || member.workspaceId !== input.workspaceId || member.projectId !== input.projectId || member.roomId !== input.roomId) {
11964
- throw new Error("Invalid project room membership");
11965
- }
11966
- const candidate = {
11967
- id: (this.deps.idFactory ?? randomUUID5)(),
11968
- tenantId: input.tenantId,
11969
- workspaceId: input.workspaceId,
11970
- projectId: input.projectId,
11971
- roomId: input.roomId,
11972
- author: { type: "bot", membershipId: input.membershipId, assistantId: input.assistantId },
11973
- content: { type: "text", text },
11974
- mentions: [],
11975
- replyToMessageId: input.sourceRoomMessageId,
11976
- source: "agent",
11977
- sourceId: input.sourceId,
11978
- idempotencyKey: input.idempotencyKey
11979
- };
11980
- const canonical = snapshotCanonical(await this.deps.messages.createIdempotent(candidate), candidate);
11981
- if (!canonical) throw new Error("Invalid canonical project room message");
11982
- const result = structuredClone(canonical);
11983
- this.notifyCommitted(result);
11984
- return result;
11985
- }
11986
- notifyCommitted(message) {
11987
- const callback = this.deps.onMessageCommitted;
11988
- if (!callback) return;
11989
- Promise.resolve().then(() => callback(structuredClone(message))).catch(() => {
11990
- try {
11991
- this.deps.onCallbackFailure?.({ messageId: message.id, code: "ROOM_MESSAGE_COMMIT_CALLBACK_FAILED" });
11992
- } catch {
11993
- }
11994
- });
11995
- }
11996
- };
11997
- function exactValues(value, required, optional = []) {
11998
- try {
11999
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
12000
- return snapshotExactRecord(value, required, optional);
12001
- } catch {
12002
- return void 0;
12003
- }
12004
- }
12005
- function exactStringRecord(value, keys, message) {
12006
- const values = exactValues(value, keys);
12007
- if (!values || keys.some((key4) => typeof values[key4] !== "string" || values[key4].length === 0)) throw new Error(message);
12008
- return values;
12009
- }
12010
- function date(value) {
12011
- try {
12012
- const timestamp = Date.prototype.getTime.call(value);
12013
- return Number.isFinite(timestamp) ? new Date(timestamp) : void 0;
12014
- } catch {
12015
- return void 0;
12016
- }
12017
- }
12018
- function snapshotSource(value) {
12019
- const values = exactValues(value, ["id", "tenantId", "workspaceId", "projectId", "roomId", "author", "content", "mentions", "source", "createdAt"], ["replyToMessageId", "sourceId", "idempotencyKey"]);
12020
- const author = exactValues(values?.author, ["type", "userId"]);
12021
- const content = exactValues(values?.content, ["type", "text"]);
12022
- const createdAt = date(values?.createdAt);
12023
- const mentions = snapshotMentions(values?.mentions);
12024
- if (!values || values.source !== "user" || author?.type !== "human" || typeof author.userId !== "string" || !author.userId || content?.type !== "text" || typeof content.text !== "string" || !mentions || !createdAt || ["id", "tenantId", "workspaceId", "projectId", "roomId"].some((key4) => typeof values[key4] !== "string" || !values[key4])) return void 0;
12025
- return {
12026
- id: values.id,
12027
- tenantId: values.tenantId,
12028
- workspaceId: values.workspaceId,
12029
- projectId: values.projectId,
12030
- roomId: values.roomId,
12031
- author: { type: "human", userId: author.userId },
12032
- content: { type: "text", text: content.text },
12033
- mentions,
12034
- source: "user",
12035
- createdAt
12036
- };
12037
- }
12038
- function snapshotMentions(value) {
12039
- const rows = snapshotExactArray(value);
12040
- if (!rows) return void 0;
12041
- const mentions = [];
12042
- for (const row of rows) {
12043
- const team = exactValues(row, ["type"]);
12044
- if (team?.type === "team") {
12045
- mentions.push({ type: "team" });
12046
- continue;
12047
- }
12048
- const bot = exactValues(row, ["type", "membershipId"]);
12049
- if (bot?.type !== "bot" || typeof bot.membershipId !== "string" || !bot.membershipId) return void 0;
12050
- mentions.push({ type: "bot", membershipId: bot.membershipId });
12051
- }
12052
- return mentions;
12053
- }
12054
- function snapshotMembership(value) {
12055
- const required = ["id", "tenantId", "workspaceId", "projectId", "roomId", "assistantId", "role", "title", "mentionName", "status", "roomThreadId", "joinedAt", "updatedAt"];
12056
- const values = exactValues(value, required, ["responsibility"]);
12057
- const joinedAt = date(values?.joinedAt);
12058
- const updatedAt = date(values?.updatedAt);
12059
- if (!values || required.slice(0, 7).some((key4) => typeof values[key4] !== "string" || !values[key4]) || values.role !== "coordinator" && values.role !== "specialist" || typeof values.title !== "string" || !values.title || typeof values.mentionName !== "string" || !values.mentionName || !["active", "paused", "removed"].includes(values.status) || typeof values.roomThreadId !== "string" || !values.roomThreadId || values.responsibility !== void 0 && typeof values.responsibility !== "string" || !joinedAt || !updatedAt) return void 0;
12060
- return { ...values, joinedAt, updatedAt };
12061
- }
12062
- function snapshotCanonical(value, expected) {
12063
- const values = exactValues(value, ["id", "tenantId", "workspaceId", "projectId", "roomId", "author", "content", "mentions", "replyToMessageId", "source", "sourceId", "idempotencyKey", "createdAt"]);
12064
- const author = exactValues(values?.author, ["type", "membershipId", "assistantId"]);
12065
- const content = exactValues(values?.content, ["type", "text"]);
12066
- const createdAt = date(values?.createdAt);
12067
- if (!values || !createdAt || typeof values.id !== "string" || values.id.length === 0 || snapshotExactArray(values.mentions)?.length !== 0 || author?.type !== "bot" || expected.author.type !== "bot" || author.membershipId !== expected.author.membershipId || author.assistantId !== expected.author.assistantId || content?.type !== "text" || content.text !== expected.content.text || values.tenantId !== expected.tenantId || values.workspaceId !== expected.workspaceId || values.projectId !== expected.projectId || values.roomId !== expected.roomId || values.replyToMessageId !== expected.replyToMessageId || values.source !== "agent" || values.sourceId !== expected.sourceId || values.idempotencyKey !== expected.idempotencyKey) return void 0;
12068
- return {
12069
- id: values.id,
12070
- tenantId: expected.tenantId,
12071
- workspaceId: expected.workspaceId,
12072
- projectId: expected.projectId,
12073
- roomId: expected.roomId,
12074
- author: { type: "bot", membershipId: expected.author.membershipId, assistantId: expected.author.assistantId },
12075
- content: { type: "text", text: expected.content.text },
12076
- mentions: [],
12077
- replyToMessageId: expected.replyToMessageId,
12078
- source: "agent",
12079
- sourceId: expected.sourceId,
12080
- idempotencyKey: expected.idempotencyKey,
12081
- createdAt
12082
- };
12083
- }
12084
-
12085
- // src/middlewares/projectRoomMiddleware.ts
12086
- var PROJECT_ROOM_CONTEXT_REQUIRED = "PROJECT_ROOM_CONTEXT_REQUIRED";
12087
- var PROJECT_ROOM_POST_FAILED = "PROJECT_ROOM_POST_FAILED";
12088
- var PROJECT_ROOM_ROSTER_FAILED = "PROJECT_ROOM_ROSTER_FAILED";
12089
- var PROJECT_ROOM_POST_FAILED_MESSAGE = "Project room message could not be posted";
12090
- var PROJECT_ROOM_ROSTER_FAILED_MESSAGE = "Project room roster is unavailable";
12091
- var CONTEXT_REQUIRED = JSON.stringify({
12092
- success: false,
12093
- error: PROJECT_ROOM_CONTEXT_REQUIRED
12094
- });
12095
- var POST_FAILED = JSON.stringify({
12096
- success: false,
12097
- error: PROJECT_ROOM_POST_FAILED,
12098
- message: PROJECT_ROOM_POST_FAILED_MESSAGE
12099
- });
12100
- var ROSTER_FAILED = JSON.stringify({
12101
- success: false,
12102
- error: PROJECT_ROOM_ROSTER_FAILED,
12103
- message: PROJECT_ROOM_ROSTER_FAILED_MESSAGE
12104
- });
12105
- var postSchema = z41.object({
12106
- text: z41.string().trim().min(1).max(2e4)
12107
- }).strict();
12108
- var listSchema = z41.object({}).strict();
12109
- function ownDataValue(record, key4) {
12110
- if (typeof record !== "object" || record === null || Array.isArray(record)) return void 0;
12111
- try {
12112
- const descriptor = Object.getOwnPropertyDescriptor(record, key4);
12113
- return descriptorDataValue(descriptor)?.value;
12114
- } catch {
12115
- return void 0;
12116
- }
12117
- }
12118
- function readTrustedRoomScope(config) {
12119
- const configurable = ownDataValue(config, "configurable");
12120
- const runConfig = ownDataValue(configurable, "runConfig");
12121
- const projectRoom = ownDataValue(runConfig, "projectRoom");
12122
- try {
12123
- return parseTrustedRunContext2({ projectRoom }).projectRoom;
12124
- } catch {
12125
- return void 0;
12126
- }
12127
- }
12128
- function exactValues2(value, required, optional = []) {
12129
- try {
12130
- return snapshotExactRecord2(value, required, optional);
12131
- } catch {
12132
- return void 0;
12133
- }
12134
- }
12135
- function safeDate(value) {
12136
- try {
12137
- const timestamp = Date.prototype.getTime.call(value);
12138
- return Number.isFinite(timestamp) ? new Date(timestamp) : void 0;
12139
- } catch {
12140
- return void 0;
12141
- }
12142
- }
12143
- function snapshotMembership2(value) {
12144
- const required = [
12145
- "id",
12146
- "tenantId",
12147
- "workspaceId",
12148
- "projectId",
12149
- "roomId",
12150
- "assistantId",
12151
- "role",
12152
- "title",
12153
- "mentionName",
12154
- "status",
12155
- "roomThreadId",
12156
- "joinedAt",
12157
- "updatedAt"
12158
- ];
12159
- const values = exactValues2(value, required, ["responsibility"]);
12160
- const joinedAt = safeDate(values?.joinedAt);
12161
- const updatedAt = safeDate(values?.updatedAt);
12162
- if (!values || !joinedAt || !updatedAt || required.slice(0, 6).some((key4) => typeof values[key4] !== "string" || values[key4] === "") || values.role !== "coordinator" && values.role !== "specialist" || typeof values.title !== "string" || values.title === "" || typeof values.mentionName !== "string" || values.mentionName === "" || !["active", "paused", "removed"].includes(values.status) || typeof values.roomThreadId !== "string" || values.roomThreadId === "" || values.responsibility !== void 0 && typeof values.responsibility !== "string") return void 0;
12163
- return { ...values, joinedAt, updatedAt };
12164
- }
12165
- function snapshotRows(value) {
12166
- return snapshotExactArray2(value) ?? [];
12167
- }
12168
- async function hasActiveCurrentMembership(scope) {
12169
- const memberships = getStoreLattice("default", "projectBotMembership").store;
12170
- const member = snapshotMembership2(await memberships.findById(scope.tenantId, scope.membershipId));
12171
- if (!member || member.status !== "active" || member.id !== scope.membershipId || member.tenantId !== scope.tenantId || member.workspaceId !== scope.workspaceId || member.projectId !== scope.projectId || member.roomId !== scope.roomId || member.assistantId !== scope.assistantId) return false;
12172
- return true;
12173
- }
12174
- function createProjectRoomMiddleware() {
12175
- return createMiddleware11({
12176
- name: "ProjectRoomMiddleware",
12177
- tools: [
12178
- tool39(async (input, config) => {
12179
- const { text } = input;
12180
- const scope = readTrustedRoomScope(config);
12181
- if (!scope) return CONTEXT_REQUIRED;
12182
- const digest = createHash3("sha256").update(text).digest("hex");
12183
- try {
12184
- const service2 = new RoomAgentMessageService({
12185
- memberships: getStoreLattice("default", "projectBotMembership").store,
12186
- messages: getStoreLattice("default", "projectRoomMessage").store
12187
- });
12188
- await service2.post({
12189
- tenantId: scope.tenantId,
12190
- workspaceId: scope.workspaceId,
12191
- projectId: scope.projectId,
12192
- roomId: scope.roomId,
12193
- membershipId: scope.membershipId,
12194
- assistantId: scope.assistantId,
12195
- text,
12196
- sourceRoomMessageId: scope.sourceRoomMessageId,
12197
- sourceId: `${scope.inputMessageId}:${digest}`,
12198
- idempotencyKey: `room-tool:${scope.inputMessageId}:${scope.membershipId}:${digest}`
12199
- });
12200
- return JSON.stringify({ success: true, message: "Project room message posted" });
12201
- } catch {
12202
- return POST_FAILED;
12203
- }
12204
- }, {
12205
- name: "post_room_message",
12206
- description: "Post a text reply to the current trusted Project Room message",
12207
- schema: postSchema
12208
- }),
12209
- tool39(async (_input, config) => {
12210
- const scope = readTrustedRoomScope(config);
12211
- if (!scope) return CONTEXT_REQUIRED;
12212
- try {
12213
- if (!await hasActiveCurrentMembership(scope)) return CONTEXT_REQUIRED;
12214
- const rows = await getStoreLattice("default", "projectBotMembership").store.list(scope.tenantId, scope.projectId);
12215
- const members = snapshotRows(rows).map(snapshotMembership2).filter((member) => member !== void 0 && member.status === "active" && member.tenantId === scope.tenantId && member.workspaceId === scope.workspaceId && member.projectId === scope.projectId && member.roomId === scope.roomId).sort((left, right) => left.joinedAt.getTime() - right.joinedAt.getTime() || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).map((member) => ({
12216
- assistantId: member.assistantId,
12217
- mentionName: member.mentionName,
12218
- title: member.title,
12219
- ...member.responsibility === void 0 ? {} : { responsibility: member.responsibility },
12220
- role: member.role
12221
- }));
12222
- return JSON.stringify({ success: true, members });
12223
- } catch {
12224
- return ROSTER_FAILED;
12225
- }
12226
- }, {
12227
- name: "list_room_roster",
12228
- description: "List active Agent roles in the current trusted Project Room, including assistantId for delegation",
12229
- schema: listSchema
12230
- })
12231
- ]
12232
- });
12233
- }
12234
- var projectRoomPlugin = {
12235
- meta: {
12236
- type: "project_room",
12237
- category: "assistant",
12238
- name: "Project Room",
12239
- description: "Trusted Project Room posting and active roster tools",
12240
- tools: [
12241
- { name: "post_room_message", description: "Post to the current trusted Project Room" },
12242
- { name: "list_room_roster", description: "List active Agents in the current trusted Project Room" }
12243
- ],
12244
- configSchema: { type: "object", properties: {}, additionalProperties: false },
12245
- defaultConfig: {}
12246
- },
12247
- middleware: () => createProjectRoomMiddleware()
12248
- };
12249
-
12250
11883
  // src/agent_lattice/builders/commonMiddleware.ts
12251
11884
  var SKILL_RESOURCE_SELECTOR = Object.freeze({
12252
11885
  argumentField: "skill_name",
@@ -12417,7 +12050,7 @@ async function resolveAllConnections(type, tenantId2) {
12417
12050
  }
12418
12051
  }
12419
12052
  function createStandardConnectionRefreshMiddleware(configurations, toolTypes) {
12420
- return createMiddleware12({
12053
+ return createMiddleware11({
12421
12054
  name: "StandardConnectionRefreshMiddleware",
12422
12055
  wrapToolCall: async (request, handler) => {
12423
12056
  const type = toolTypes.get(request.toolCall.name);
@@ -12483,7 +12116,6 @@ async function createCommonMiddlewares(middlewareConfigs, filesystemBackend, fsI
12483
12116
  })
12484
12117
  );
12485
12118
  }
12486
- middlewares.push(createProjectRoomMiddleware());
12487
12119
  const filesystemConfig = normalizedMiddlewareConfigs.find((m) => m.type === "filesystem");
12488
12120
  const clawConfig = normalizedMiddlewareConfigs.find((m) => m.type === "claw");
12489
12121
  const needsFilesystemBackend = filesystemConfig?.enabled || clawConfig?.enabled;
@@ -12510,7 +12142,7 @@ async function createCommonMiddlewares(middlewareConfigs, filesystemBackend, fsI
12510
12142
  }
12511
12143
  }
12512
12144
  for (const config of normalizedMiddlewareConfigs) {
12513
- if (!config.enabled || config.type === "filesystem" || config.type === "project_room") continue;
12145
+ if (!config.enabled || config.type === "filesystem") continue;
12514
12146
  switch (config.type) {
12515
12147
  case "code_eval":
12516
12148
  addConfiguredMiddleware(
@@ -12852,16 +12484,15 @@ import {
12852
12484
  } from "langchain";
12853
12485
 
12854
12486
  // src/deep_agent_new/middleware/subagents.ts
12855
- import { z as z43 } from "zod/v3";
12487
+ import { z as z42 } from "zod/v3";
12856
12488
  import {
12857
- createMiddleware as createMiddleware13,
12489
+ createMiddleware as createMiddleware12,
12858
12490
  createAgent as createAgent2,
12859
- tool as tool40,
12491
+ tool as tool39,
12860
12492
  ToolMessage as ToolMessage6,
12861
12493
  humanInTheLoopMiddleware
12862
12494
  } from "langchain";
12863
12495
  import { Command as Command3, getCurrentTaskInput as getCurrentTaskInput2, GraphInterrupt } from "@langchain/langgraph";
12864
- import { HumanMessage as HumanMessage4 } from "@langchain/core/messages";
12865
12496
 
12866
12497
  // src/agent_worker/agent_worker_graph.ts
12867
12498
  import {
@@ -13268,7 +12899,7 @@ function createAgentWorkerGraph() {
13268
12899
  var agentWorkerGraph = createAgentWorkerGraph();
13269
12900
 
13270
12901
  // src/services/Agent.ts
13271
- import { descriptorDataValue as descriptorDataValue2 } from "@axiom-lattice/protocols";
12902
+ import { descriptorDataValue } from "@axiom-lattice/protocols";
13272
12903
  import { Command as Command2 } from "@langchain/langgraph";
13273
12904
  import { AIMessage as AIMessage3, filterMessages, HumanMessage as HumanMessage3, SystemMessage, ToolMessage as ToolMessage5 } from "langchain";
13274
12905
 
@@ -13590,10 +13221,10 @@ registerChunkBuffer("default", buffer);
13590
13221
  import { v4 as v42 } from "uuid";
13591
13222
 
13592
13223
  // src/capability/CapabilityRuntimeResolver.ts
13593
- import { z as z42 } from "zod";
13224
+ import { z as z41 } from "zod";
13594
13225
 
13595
13226
  // src/capability/CapabilityBundleMerger.ts
13596
- import { createHash as createHash4 } from "crypto";
13227
+ import { createHash as createHash3 } from "crypto";
13597
13228
  import { isDeepStrictEqual } from "util";
13598
13229
 
13599
13230
  // src/capability/CredentialFieldPolicy.ts
@@ -14029,7 +13660,7 @@ function createCapabilityRevision(bundles, effectivePolicy) {
14029
13660
  bundles: bundles.map(({ id, updatedAt }) => [id, updatedAt]),
14030
13661
  effectivePolicy
14031
13662
  };
14032
- return createHash4("sha256").update(JSON.stringify(canonicalize(revisionInput))).digest("hex");
13663
+ return createHash3("sha256").update(JSON.stringify(canonicalize(revisionInput))).digest("hex");
14033
13664
  }
14034
13665
  var LEGACY_UNION_CONFIG_FIELDS = new Set(
14035
13666
  Object.values(LEGACY_PLUGIN_CONNECTION_FIELDS).map(({ selectorField }) => selectorField)
@@ -14372,9 +14003,9 @@ var CapabilityRuntimeResolutionError = class extends Error {
14372
14003
  this.actualRevision = context.actualRevision;
14373
14004
  }
14374
14005
  };
14375
- var bundleIdsSchema = z42.array(z42.string().uuid()).superRefine((ids, context) => {
14006
+ var bundleIdsSchema = z41.array(z41.string().uuid()).superRefine((ids, context) => {
14376
14007
  if (new Set(ids).size !== ids.length) {
14377
- context.addIssue({ code: z42.ZodIssueCode.custom, message: "Bundle IDs must be unique" });
14008
+ context.addIssue({ code: z41.ZodIssueCode.custom, message: "Bundle IDs must be unique" });
14378
14009
  }
14379
14010
  });
14380
14011
  function projectBundleIds(config) {
@@ -14650,7 +14281,7 @@ function cloneRunConfig(value, stripReserved) {
14650
14281
  const clone4 = [];
14651
14282
  for (let index = 0; index < length; index += 1) {
14652
14283
  const key4 = String(index);
14653
- const data = descriptorDataValue2(descriptors[key4]);
14284
+ const data = descriptorDataValue(descriptors[key4]);
14654
14285
  if (!data || data.value === void 0) {
14655
14286
  throw new CallerRunConfigValidationError(`Unsupported caller run config value at ${path8}/${key4}`);
14656
14287
  }
@@ -14665,7 +14296,7 @@ function cloneRunConfig(value, stripReserved) {
14665
14296
  for (const key4 of keys) {
14666
14297
  if (typeof key4 !== "string") continue;
14667
14298
  const fieldPath = callerRunConfigPath(path8, key4);
14668
- const data = descriptorDataValue2(descriptors[key4]);
14299
+ const data = descriptorDataValue(descriptors[key4]);
14669
14300
  if (!data) throw new CallerRunConfigValidationError(`Unsupported caller run config value at ${fieldPath}`);
14670
14301
  if (stripReserved && RESERVED_CALLER_RUN_KEYS.has(key4) || data.value === void 0) continue;
14671
14302
  Object.defineProperty(clone3, key4, {
@@ -14701,7 +14332,7 @@ function sanitizeCallerRunConfig(value, preserveDelegatedContext = true) {
14701
14332
  if (Array.isArray(entry)) {
14702
14333
  const descriptors2 = Object.getOwnPropertyDescriptors(entry);
14703
14334
  for (let index = 0; index < entry.length; index += 1) {
14704
- const data = descriptorDataValue2(descriptors2[String(index)]);
14335
+ const data = descriptorDataValue(descriptors2[String(index)]);
14705
14336
  if (!data) throw new CallerRunConfigValidationError(`Unsupported caller run config value at ${path8}/${index}`);
14706
14337
  visit(data.value, `${path8}/${index}`);
14707
14338
  }
@@ -14720,7 +14351,7 @@ function sanitizeCallerRunConfig(value, preserveDelegatedContext = true) {
14720
14351
  }
14721
14352
  const fieldPath = callerRunConfigPath(path8, key4);
14722
14353
  const descriptor = descriptors[key4];
14723
- const data = descriptorDataValue2(descriptor);
14354
+ const data = descriptorDataValue(descriptor);
14724
14355
  if (!data) throw new CallerRunConfigValidationError(`Unsupported caller run config value at ${fieldPath}`);
14725
14356
  if (isCredentialBearingKey(key4)) {
14726
14357
  throw new CapabilityRuntimeResolutionError(
@@ -14755,7 +14386,7 @@ function cloneExecutionRunConfigBase(value) {
14755
14386
  throw new CallerRunConfigValidationError("Unsupported caller run config value at /run_config");
14756
14387
  }
14757
14388
  const descriptor = descriptors[key4];
14758
- const data = descriptorDataValue2(descriptor);
14389
+ const data = descriptorDataValue(descriptor);
14759
14390
  if (!data) {
14760
14391
  throw new CallerRunConfigValidationError("Unsupported caller run config value at /run_config");
14761
14392
  }
@@ -14838,19 +14469,19 @@ var DelegatedScopeNotQueueableError = class extends Error {
14838
14469
  this.name = "DelegatedScopeNotQueueableError";
14839
14470
  }
14840
14471
  };
14841
- function ownDataValue2(value, key4) {
14472
+ function ownDataValue(value, key4) {
14842
14473
  if (typeof value !== "object" || value === null) return void 0;
14843
14474
  try {
14844
- return descriptorDataValue2(Object.getOwnPropertyDescriptor(value, key4))?.value;
14475
+ return descriptorDataValue(Object.getOwnPropertyDescriptor(value, key4))?.value;
14845
14476
  } catch {
14846
14477
  return void 0;
14847
14478
  }
14848
14479
  }
14849
14480
  function checkpointCapabilityRevision(state) {
14850
- const config = ownDataValue2(state, "config");
14851
- const configurable = ownDataValue2(config, "configurable");
14852
- const runConfig = ownDataValue2(configurable, "runConfig");
14853
- const revision = ownDataValue2(runConfig, "capabilityRuntimeRevision");
14481
+ const config = ownDataValue(state, "config");
14482
+ const configurable = ownDataValue(config, "configurable");
14483
+ const runConfig = ownDataValue(configurable, "runConfig");
14484
+ const revision = ownDataValue(runConfig, "capabilityRuntimeRevision");
14854
14485
  return typeof revision === "string" && revision.length > 0 ? revision : void 0;
14855
14486
  }
14856
14487
  var QUEUE_PROCESSOR_RETRY_BASE_MS = 100;
@@ -15490,10 +15121,14 @@ var Agent = class {
15490
15121
  if (!Array.isArray(messages) || messages.length === 0) {
15491
15122
  return [new HumanMessage3({ id: content.id, content: content.message })];
15492
15123
  }
15124
+ const invalid = messages.filter((message) => !isMessageContent(message.content));
15125
+ if (invalid.length > 0) {
15126
+ console.error(
15127
+ `[Agent] Dropping ${invalid.length} queued message(s) with invalid serialized content for queued message ${content.id}; falling back to stored display content`
15128
+ );
15129
+ return [new HumanMessage3({ id: content.id, content: content.message })];
15130
+ }
15493
15131
  return messages.map((message) => {
15494
- if (!isMessageContent(message.content)) {
15495
- throw new Error(`Invalid structured message content for queued message ${content.id}`);
15496
- }
15497
15132
  const fields = {
15498
15133
  id: message.id,
15499
15134
  content: message.content,
@@ -16802,7 +16437,7 @@ function createTaskTool(options) {
16802
16437
  generalPurposeAgent
16803
16438
  });
16804
16439
  const finalTaskDescription = taskDescription ? taskDescription : getTaskToolDescription(subagentDescriptions);
16805
- return tool40(
16440
+ return tool39(
16806
16441
  async (input, config) => {
16807
16442
  const { description, subagent_type, async } = input;
16808
16443
  if (input.taskId) {
@@ -16858,7 +16493,8 @@ function createTaskTool(options) {
16858
16493
  const currentState = getCurrentTaskInput2();
16859
16494
  const subagentState = filterStateForSubagent(currentState);
16860
16495
  subagentState.messages = input.taskId ? [
16861
- new HumanMessage4({
16496
+ {
16497
+ role: "human",
16862
16498
  content: `${description}
16863
16499
 
16864
16500
  ---
@@ -16868,8 +16504,8 @@ You are executing a persistent task (ID: ${input.taskId}). Use manage_task.updat
16868
16504
  - Preserve the Objective and Acceptance Criteria contract. Do not append progress notes to the description; put progress and evidence in the result or Activity.
16869
16505
  - Complete agent-owned tasks with result plus beliefImpact: [{ key, after, basis }] where key references the belief owner's canonical Belief State; the middleware records completion evidence and writes the parent belief activity automatically.
16870
16506
  - Use add_activity only for additional observations or plan revisions when the result changes the parent belief or plan.`
16871
- })
16872
- ] : [new HumanMessage4({ content: description })];
16507
+ }
16508
+ ] : [{ role: "human", content: description }];
16873
16509
  const subagent_thread_id = config.configurable?.thread_id + "____" + assistant_id + "_" + config.toolCall.id;
16874
16510
  if (async) {
16875
16511
  const tenantId2 = config.configurable?.runConfig?.tenantId;
@@ -16963,19 +16599,19 @@ The result will be delivered as a notification when complete. Do not poll.`,
16963
16599
  {
16964
16600
  name: "task",
16965
16601
  description: finalTaskDescription,
16966
- schema: z43.object({
16967
- description: z43.string().describe("The task to execute with the selected agent"),
16968
- subagent_type: z43.string().describe(
16602
+ schema: z42.object({
16603
+ description: z42.string().describe("The task to execute with the selected agent"),
16604
+ subagent_type: z42.string().describe(
16969
16605
  `Name of the agent to use. Available: ${Object.keys(
16970
16606
  subagentGraphs
16971
16607
  ).join(", ")}`
16972
16608
  ),
16973
16609
  ...allowAsync ? {
16974
- async: z43.boolean().default(false).describe(
16610
+ async: z42.boolean().default(false).describe(
16975
16611
  "When true, runs the task in the background and returns immediately. Use for independent tasks that can run in parallel. The result is delivered as a notification when complete. Use check_async_task or list_async_tasks to monitor progress."
16976
16612
  )
16977
16613
  } : {},
16978
- taskId: z43.string().optional().describe(
16614
+ taskId: z42.string().optional().describe(
16979
16615
  "Optional: ID of a TaskItem created via manage_task. When set, the subagent will update this task's status as it works. Use this when executing a persistent task from the task board."
16980
16616
  )
16981
16617
  })
@@ -16993,7 +16629,7 @@ function getMainAgentFromConfig(config) {
16993
16629
  });
16994
16630
  }
16995
16631
  function createCheckAsyncTaskTool() {
16996
- return tool40(
16632
+ return tool39(
16997
16633
  async (input, config) => {
16998
16634
  const { task_id } = input;
16999
16635
  const mainAgent = getMainAgentFromConfig(config);
@@ -17053,14 +16689,14 @@ Description: ${cached.description}`;
17053
16689
  {
17054
16690
  name: "check_async_task",
17055
16691
  description: "Get the current status and result of an async background task. Use this to check if a previously launched async task has completed.",
17056
- schema: z43.object({
17057
- task_id: z43.string().describe("The task ID returned when the async task was started")
16692
+ schema: z42.object({
16693
+ task_id: z42.string().describe("The task ID returned when the async task was started")
17058
16694
  })
17059
16695
  }
17060
16696
  );
17061
16697
  }
17062
16698
  function createListAsyncTasksTool() {
17063
- return tool40(
16699
+ return tool39(
17064
16700
  async (_input, config) => {
17065
16701
  const mainAgent = getMainAgentFromConfig(config);
17066
16702
  if (!mainAgent) {
@@ -17106,12 +16742,12 @@ function createListAsyncTasksTool() {
17106
16742
  {
17107
16743
  name: "list_async_tasks",
17108
16744
  description: "List all async background tasks with their current status. Use this before reporting task status to the user. Statuses in conversation history may be stale.",
17109
- schema: z43.object({})
16745
+ schema: z42.object({})
17110
16746
  }
17111
16747
  );
17112
16748
  }
17113
16749
  function createCancelAsyncTaskTool() {
17114
- return tool40(
16750
+ return tool39(
17115
16751
  async (input, config) => {
17116
16752
  const { task_id } = input;
17117
16753
  const mainAgent = getMainAgentFromConfig(config);
@@ -17150,8 +16786,8 @@ function createCancelAsyncTaskTool() {
17150
16786
  {
17151
16787
  name: "cancel_async_task",
17152
16788
  description: "Cancel a running async background task.",
17153
- schema: z43.object({
17154
- task_id: z43.string().describe("The task ID to cancel")
16789
+ schema: z42.object({
16790
+ task_id: z42.string().describe("The task ID to cancel")
17155
16791
  })
17156
16792
  }
17157
16793
  );
@@ -17187,7 +16823,7 @@ function createSubAgentMiddleware(options) {
17187
16823
  );
17188
16824
  }
17189
16825
  const effectiveSystemPrompt = allowAsync ? systemPrompt + getAsyncPromptText() : systemPrompt;
17190
- return createMiddleware13({
16826
+ return createMiddleware12({
17191
16827
  name: "subAgentMiddleware",
17192
16828
  tools: allTools,
17193
16829
  wrapModelCall: async (request, handler) => {
@@ -17207,8 +16843,8 @@ ${effectiveSystemPrompt}` : effectiveSystemPrompt;
17207
16843
  }
17208
16844
 
17209
16845
  // src/deep_agent_new/middleware/date.ts
17210
- import { createMiddleware as createMiddleware14, tool as tool41 } from "langchain";
17211
- import { z as z44 } from "zod";
16846
+ import { createMiddleware as createMiddleware13, tool as tool40 } from "langchain";
16847
+ import { z as z43 } from "zod";
17212
16848
  function formatCurrentDate(timezone = "UTC") {
17213
16849
  const now = /* @__PURE__ */ new Date();
17214
16850
  let validTimezone = timezone;
@@ -17236,10 +16872,10 @@ function generateDateContext(timezone = "UTC") {
17236
16872
  function createDateMiddleware(options = {}) {
17237
16873
  const timezone = options.timezone || "UTC";
17238
16874
  const dateContext = generateDateContext(timezone);
17239
- return createMiddleware14({
16875
+ return createMiddleware13({
17240
16876
  name: "DateMiddleware",
17241
16877
  tools: [
17242
- tool41(
16878
+ tool40(
17243
16879
  async () => {
17244
16880
  const now = /* @__PURE__ */ new Date();
17245
16881
  let validTimezone = timezone;
@@ -17269,7 +16905,7 @@ function createDateMiddleware(options = {}) {
17269
16905
  {
17270
16906
  name: "get_current_date_time",
17271
16907
  description: "Get the exact current date and time at the moment of invocation. Use this when the user asks about the current time (e.g., 'what time is it', '\u51E0\u70B9\u4E86', '\u73B0\u5728\u51E0\u70B9'), or when you need to know the precise time for scheduling, deadlines, or time-sensitive operations.",
17272
- schema: z44.object({})
16908
+ schema: z43.object({})
17273
16909
  }
17274
16910
  )
17275
16911
  ],
@@ -17335,8 +16971,8 @@ var datePlugin = {
17335
16971
  };
17336
16972
 
17337
16973
  // src/deep_agent_new/middleware/scheduler.ts
17338
- import { tool as tool42, createMiddleware as createMiddleware15 } from "langchain";
17339
- import { z as z45 } from "zod";
16974
+ import { tool as tool41, createMiddleware as createMiddleware14 } from "langchain";
16975
+ import { z as z44 } from "zod";
17340
16976
  import { v4 as uuidv43 } from "uuid";
17341
16977
  import { ScheduledTaskStatus as ScheduledTaskStatus3, ScheduleExecutionType as ScheduleExecutionType3 } from "@axiom-lattice/protocols";
17342
16978
 
@@ -18410,10 +18046,10 @@ function registerAgentAddMessageHandler() {
18410
18046
  function createSchedulerMiddleware(options = {}) {
18411
18047
  const defaultMaxRetries = options.defaultMaxRetries ?? 0;
18412
18048
  registerAgentAddMessageHandler();
18413
- return createMiddleware15({
18049
+ return createMiddleware14({
18414
18050
  name: "SchedulerMiddleware",
18415
18051
  tools: [
18416
- tool42(
18052
+ tool41(
18417
18053
  async (input, config) => {
18418
18054
  const runConfig = getRunConfig(config);
18419
18055
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
@@ -18441,14 +18077,14 @@ function createSchedulerMiddleware(options = {}) {
18441
18077
  {
18442
18078
  name: "schedule_at",
18443
18079
  description: "Schedule a system message for an absolute future timestamp",
18444
- schema: z45.object({
18445
- executeAt: z45.number(),
18446
- maxRetries: z45.number().int().min(0).optional(),
18447
- message: z45.string()
18080
+ schema: z44.object({
18081
+ executeAt: z44.number(),
18082
+ maxRetries: z44.number().int().min(0).optional(),
18083
+ message: z44.string()
18448
18084
  })
18449
18085
  }
18450
18086
  ),
18451
- tool42(
18087
+ tool41(
18452
18088
  async (input, config) => {
18453
18089
  const runConfig = getRunConfig(config);
18454
18090
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
@@ -18476,14 +18112,14 @@ function createSchedulerMiddleware(options = {}) {
18476
18112
  {
18477
18113
  name: "schedule_after",
18478
18114
  description: "Schedule a system message after a relative delay",
18479
- schema: z45.object({
18480
- delayMs: z45.number().positive(),
18481
- maxRetries: z45.number().int().min(0).optional(),
18482
- message: z45.string()
18115
+ schema: z44.object({
18116
+ delayMs: z44.number().positive(),
18117
+ maxRetries: z44.number().int().min(0).optional(),
18118
+ message: z44.string()
18483
18119
  })
18484
18120
  }
18485
18121
  ),
18486
- tool42(
18122
+ tool41(
18487
18123
  async (input, config) => {
18488
18124
  const runConfig = getRunConfig(config);
18489
18125
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
@@ -18518,16 +18154,16 @@ function createSchedulerMiddleware(options = {}) {
18518
18154
  {
18519
18155
  name: "schedule_recurring",
18520
18156
  description: "Schedule a recurring system message with a cron expression",
18521
- schema: z45.object({
18522
- cronExpression: z45.string(),
18523
- maxRuns: z45.number().int().positive().optional(),
18524
- expiresAt: z45.number().optional(),
18525
- maxRetries: z45.number().int().min(0).optional(),
18526
- message: z45.string()
18157
+ schema: z44.object({
18158
+ cronExpression: z44.string(),
18159
+ maxRuns: z44.number().int().positive().optional(),
18160
+ expiresAt: z44.number().optional(),
18161
+ maxRetries: z44.number().int().min(0).optional(),
18162
+ message: z44.string()
18527
18163
  })
18528
18164
  }
18529
18165
  ),
18530
- tool42(
18166
+ tool41(
18531
18167
  async (input) => {
18532
18168
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
18533
18169
  const success = await scheduleLattice.client.cancel(input.taskId);
@@ -18536,12 +18172,12 @@ function createSchedulerMiddleware(options = {}) {
18536
18172
  {
18537
18173
  name: "cancel_scheduled_task",
18538
18174
  description: "Cancel a scheduled task by task id",
18539
- schema: z45.object({
18540
- taskId: z45.string()
18175
+ schema: z44.object({
18176
+ taskId: z44.string()
18541
18177
  })
18542
18178
  }
18543
18179
  ),
18544
- tool42(
18180
+ tool41(
18545
18181
  async (input, config) => {
18546
18182
  const runConfig = getRunConfig(config);
18547
18183
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
@@ -18563,11 +18199,11 @@ function createSchedulerMiddleware(options = {}) {
18563
18199
  {
18564
18200
  name: "list_scheduled_tasks",
18565
18201
  description: "List scheduled tasks for the current agent context",
18566
- schema: z45.object({
18567
- status: z45.enum(["pending", "running", "completed", "failed", "cancelled", "paused"]).optional(),
18568
- executionType: z45.enum(["once", "cron"]).optional(),
18569
- limit: z45.number().int().positive().optional(),
18570
- offset: z45.number().int().min(0).optional()
18202
+ schema: z44.object({
18203
+ status: z44.enum(["pending", "running", "completed", "failed", "cancelled", "paused"]).optional(),
18204
+ executionType: z44.enum(["once", "cron"]).optional(),
18205
+ limit: z44.number().int().positive().optional(),
18206
+ offset: z44.number().int().min(0).optional()
18571
18207
  })
18572
18208
  }
18573
18209
  )
@@ -19824,8 +19460,8 @@ var MemoryBackend = class {
19824
19460
 
19825
19461
  // src/deep_agent_new/middleware/todos.ts
19826
19462
  import { Command as Command4 } from "@langchain/langgraph";
19827
- import { z as z46 } from "zod";
19828
- import { createMiddleware as createMiddleware16, tool as tool43, ToolMessage as ToolMessage7 } from "langchain";
19463
+ import { z as z45 } from "zod";
19464
+ import { createMiddleware as createMiddleware15, tool as tool42, ToolMessage as ToolMessage7 } from "langchain";
19829
19465
  var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
19830
19466
  It also helps the user understand the progress of the task and overall progress of their requests.
19831
19467
  Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
@@ -20052,14 +19688,14 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
20052
19688
  ## Important To-Do List Usage Notes to Remember
20053
19689
  - The \`write_todos\` tool should never be called multiple times in parallel.
20054
19690
  - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`;
20055
- var TodoStatus = z46.enum(["pending", "in_progress", "completed"]).describe("Status of the todo");
20056
- var TodoSchema = z46.object({
20057
- content: z46.string().describe("Content of the todo item"),
19691
+ var TodoStatus = z45.enum(["pending", "in_progress", "completed"]).describe("Status of the todo");
19692
+ var TodoSchema = z45.object({
19693
+ content: z45.string().describe("Content of the todo item"),
20058
19694
  status: TodoStatus
20059
19695
  });
20060
- var stateSchema = z46.object({ todos: z46.array(TodoSchema).default([]) });
19696
+ var stateSchema = z45.object({ todos: z45.array(TodoSchema).default([]) });
20061
19697
  function todoListMiddleware(options) {
20062
- const writeTodos = tool43(
19698
+ const writeTodos = tool42(
20063
19699
  ({ todos }, config) => {
20064
19700
  return new Command4({
20065
19701
  update: {
@@ -20076,12 +19712,12 @@ function todoListMiddleware(options) {
20076
19712
  {
20077
19713
  name: "write_todos",
20078
19714
  description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION,
20079
- schema: z46.object({
20080
- todos: z46.array(TodoSchema).describe("List of todo items to update")
19715
+ schema: z45.object({
19716
+ todos: z45.array(TodoSchema).describe("List of todo items to update")
20081
19717
  })
20082
19718
  }
20083
19719
  );
20084
- return createMiddleware16({
19720
+ return createMiddleware15({
20085
19721
  name: "todoListMiddleware",
20086
19722
  stateSchema,
20087
19723
  tools: [writeTodos],
@@ -20232,7 +19868,7 @@ var DeepAgentGraphBuilder = class {
20232
19868
  };
20233
19869
 
20234
19870
  // src/agent_team/agent_team.ts
20235
- import { z as z49 } from "zod/v3";
19871
+ import { z as z48 } from "zod/v3";
20236
19872
  import { createAgent as createAgent5 } from "langchain";
20237
19873
 
20238
19874
  // src/agent_team/types.ts
@@ -20668,14 +20304,14 @@ var InMemoryMailboxStore = class {
20668
20304
  };
20669
20305
 
20670
20306
  // src/agent_team/middleware/team.ts
20671
- import { z as z48 } from "zod/v3";
20672
- import { createMiddleware as createMiddleware17, createAgent as createAgent4, tool as tool45, ToolMessage as ToolMessage9 } from "langchain";
20307
+ import { z as z47 } from "zod/v3";
20308
+ import { createMiddleware as createMiddleware16, createAgent as createAgent4, tool as tool44, ToolMessage as ToolMessage9 } from "langchain";
20673
20309
  import { Command as Command6, getCurrentTaskInput as getCurrentTaskInput3 } from "@langchain/langgraph";
20674
20310
  import { v4 as uuidv44 } from "uuid";
20675
20311
 
20676
20312
  // src/agent_team/middleware/teammate_tools.ts
20677
- import { z as z47 } from "zod/v3";
20678
- import { tool as tool44, ToolMessage as ToolMessage8 } from "langchain";
20313
+ import { z as z46 } from "zod/v3";
20314
+ import { tool as tool43, ToolMessage as ToolMessage8 } from "langchain";
20679
20315
  import { Command as Command5 } from "@langchain/langgraph";
20680
20316
 
20681
20317
  // src/agent_team/middleware/formatMessages.ts
@@ -20700,7 +20336,7 @@ ${meta}${body}`;
20700
20336
  // src/agent_team/middleware/teammate_tools.ts
20701
20337
  function createTeammateTools(options) {
20702
20338
  const { teamId, agentId, taskListStore, mailboxStore } = options;
20703
- const claimTaskTool = tool44(
20339
+ const claimTaskTool = tool43(
20704
20340
  async (input) => {
20705
20341
  const task = await taskListStore.claimTaskById(
20706
20342
  teamId,
@@ -20725,12 +20361,12 @@ function createTeammateTools(options) {
20725
20361
  {
20726
20362
  name: "claim_task",
20727
20363
  description: "Pick a task to work on by task_id. Use check_tasks first to see all tasks; then call this with the task_id you choose. The task's assignee is set to you and you should focus on that task until you complete_task or fail_task it.",
20728
- schema: z47.object({
20729
- task_id: z47.string().describe("ID of the task to claim (e.g. task-01). Use check_tasks to see IDs.")
20364
+ schema: z46.object({
20365
+ task_id: z46.string().describe("ID of the task to claim (e.g. task-01). Use check_tasks to see IDs.")
20730
20366
  })
20731
20367
  }
20732
20368
  );
20733
- const completeTaskTool = tool44(
20369
+ const completeTaskTool = tool43(
20734
20370
  async (input) => {
20735
20371
  const task = await taskListStore.completeTask(
20736
20372
  teamId,
@@ -20751,13 +20387,13 @@ function createTeammateTools(options) {
20751
20387
  {
20752
20388
  name: "complete_task",
20753
20389
  description: "Mark a claimed task as completed with a result summary. Call this after you have finished working on a task.",
20754
- schema: z47.object({
20755
- task_id: z47.string().describe("ID of the task to complete"),
20756
- result: z47.string().describe("Summary of the task result")
20390
+ schema: z46.object({
20391
+ task_id: z46.string().describe("ID of the task to complete"),
20392
+ result: z46.string().describe("Summary of the task result")
20757
20393
  })
20758
20394
  }
20759
20395
  );
20760
- const failTaskTool = tool44(
20396
+ const failTaskTool = tool43(
20761
20397
  async (input) => {
20762
20398
  const task = await taskListStore.failTask(
20763
20399
  teamId,
@@ -20778,13 +20414,13 @@ function createTeammateTools(options) {
20778
20414
  {
20779
20415
  name: "fail_task",
20780
20416
  description: "Mark a claimed task as failed with an error description. Call this if you cannot complete the task.",
20781
- schema: z47.object({
20782
- task_id: z47.string().describe("ID of the task to fail"),
20783
- error: z47.string().describe("Description of why the task failed")
20417
+ schema: z46.object({
20418
+ task_id: z46.string().describe("ID of the task to fail"),
20419
+ error: z46.string().describe("Description of why the task failed")
20784
20420
  })
20785
20421
  }
20786
20422
  );
20787
- const sendMessageTool = tool44(
20423
+ const sendMessageTool = tool43(
20788
20424
  async (input) => {
20789
20425
  await mailboxStore.sendMessage(
20790
20426
  teamId,
@@ -20798,11 +20434,11 @@ function createTeammateTools(options) {
20798
20434
  {
20799
20435
  name: "send_message",
20800
20436
  description: 'Send a message to the team lead or another teammate via the mailbox. Use "team_lead" to message the team lead. Use this to report discoveries, request guidance, or suggest new tasks.',
20801
- schema: z47.object({
20802
- to: z47.string().describe(
20437
+ schema: z46.object({
20438
+ to: z46.string().describe(
20803
20439
  'Recipient agent name (e.g. "team_lead" or a teammate name)'
20804
20440
  ),
20805
- content: z47.string().describe("Message content")
20441
+ content: z46.string().describe("Message content")
20806
20442
  })
20807
20443
  }
20808
20444
  );
@@ -20822,7 +20458,7 @@ function createTeammateTools(options) {
20822
20458
  read: msg.read
20823
20459
  }));
20824
20460
  };
20825
- const readMessagesTool = tool44(
20461
+ const readMessagesTool = tool43(
20826
20462
  async (input, config) => {
20827
20463
  const formatAndMarkAsRead = async (msgs2) => {
20828
20464
  for (const msg of msgs2) {
@@ -20881,10 +20517,10 @@ function createTeammateTools(options) {
20881
20517
  {
20882
20518
  name: "read_messages",
20883
20519
  description: "Read unread messages from the mailbox. Returns immediately if messages exist, otherwise waits for up to 3 minutes for new messages.",
20884
- schema: z47.object({})
20520
+ schema: z46.object({})
20885
20521
  }
20886
20522
  );
20887
- const checkTasksTool = tool44(
20523
+ const checkTasksTool = tool43(
20888
20524
  async () => {
20889
20525
  const tasks = await taskListStore.getAllTasks(teamId);
20890
20526
  return formatTaskSummary(tasks);
@@ -20892,10 +20528,10 @@ function createTeammateTools(options) {
20892
20528
  {
20893
20529
  name: "check_tasks",
20894
20530
  description: "Use this tool to get the current status of all tasks in a team. This is your primary way to monitor task progress.",
20895
- schema: z47.object({})
20531
+ schema: z46.object({})
20896
20532
  }
20897
20533
  );
20898
- const broadcastMessageTool = tool44(
20534
+ const broadcastMessageTool = tool43(
20899
20535
  async (input) => {
20900
20536
  const allAgents = await mailboxStore.getRegisteredAgents(teamId);
20901
20537
  const recipients = allAgents.filter((a) => a !== agentId);
@@ -20914,8 +20550,8 @@ function createTeammateTools(options) {
20914
20550
  {
20915
20551
  name: "broadcast_message",
20916
20552
  description: "Send a message to everyone in the team except yourself. Use this to share updates or information with all teammates and the team lead at once.",
20917
- schema: z47.object({
20918
- content: z47.string().describe("Message content to broadcast to others")
20553
+ schema: z46.object({
20554
+ content: z46.string().describe("Message content to broadcast to others")
20919
20555
  })
20920
20556
  }
20921
20557
  );
@@ -21149,7 +20785,7 @@ async function spawnTeammate(options) {
21149
20785
  function createTeamMiddleware(options) {
21150
20786
  const { teamConfig, taskListStore, mailboxStore, tenantId: tenantId2 } = options;
21151
20787
  const defaultModel = teamConfig.model ?? "claude-sonnet-4-5-20250929";
21152
- const createTeamTool = tool45(
20788
+ const createTeamTool = tool44(
21153
20789
  async (input, config) => {
21154
20790
  const state = getCurrentTaskInput3();
21155
20791
  if (state?.team?.teamId) {
@@ -21304,20 +20940,20 @@ After calling create_team, you MUST:
21304
20940
  2. When messages indicate task changes, call check_tasks to get full task status
21305
20941
  3. Continue until all tasks show "completed" or "failed"
21306
20942
  4. Do NOT assume tasks are done - always verify with check_tasks`,
21307
- schema: z48.object({
21308
- tasks: z48.array(
21309
- z48.object({
21310
- id: z48.string().describe("Task ID in format task-01, task-02, etc."),
21311
- title: z48.string().describe("Short task title"),
21312
- description: z48.string().describe("Detailed task description - what exactly needs to be done"),
21313
- dependencies: z48.array(z48.string()).optional().default([]).describe('Array of task IDs that must complete before this task (e.g. ["task-01"])')
20943
+ schema: z47.object({
20944
+ tasks: z47.array(
20945
+ z47.object({
20946
+ id: z47.string().describe("Task ID in format task-01, task-02, etc."),
20947
+ title: z47.string().describe("Short task title"),
20948
+ description: z47.string().describe("Detailed task description - what exactly needs to be done"),
20949
+ dependencies: z47.array(z47.string()).optional().default([]).describe('Array of task IDs that must complete before this task (e.g. ["task-01"])')
21314
20950
  })
21315
20951
  ).describe("List of tasks for teammates to work on. Each task needs unique ID (task-01, task-02, etc.)."),
21316
- teammates: z48.array(
21317
- z48.object({
21318
- name: z48.string().describe("Teammate name (must match a pre-configured teammate type)"),
21319
- role: z48.string().describe("Role category (e.g. researcher, writer, coder, reviewer)"),
21320
- description: z48.string().describe("What this teammate will focus on - specific instructions for their work")
20952
+ teammates: z47.array(
20953
+ z47.object({
20954
+ name: z47.string().describe("Teammate name (must match a pre-configured teammate type)"),
20955
+ role: z47.string().describe("Role category (e.g. researcher, writer, coder, reviewer)"),
20956
+ description: z47.string().describe("What this teammate will focus on - specific instructions for their work")
21321
20957
  })
21322
20958
  ).describe("Teammate agents to create. Each should have a clear role and focus.")
21323
20959
  })
@@ -21328,7 +20964,7 @@ After calling create_team, you MUST:
21328
20964
  if (state?.team?.teamId) return state.team.teamId;
21329
20965
  throw new Error("No team_id provided and no team in state. Call create_team first.");
21330
20966
  };
21331
- const addTasksTool = tool45(
20967
+ const addTasksTool = tool44(
21332
20968
  async (input, config) => {
21333
20969
  const teamId = resolveTeamId();
21334
20970
  const created = await taskListStore.addTasks(
@@ -21380,20 +21016,20 @@ IMPORTANT: Dependencies
21380
21016
 
21381
21017
  IMPORTANT: Assigning to a specific teammate
21382
21018
  - When you need a particular teammate to do the work, set assignee to that teammate's name (e.g. assignee: "researcher"). They can then claim or see the task as assigned to them.`,
21383
- schema: z48.object({
21384
- tasks: z48.array(
21385
- z48.object({
21386
- id: z48.string().describe("Task ID in format task-01, task-02, etc. Must be unique."),
21387
- title: z48.string().describe("Short task title"),
21388
- description: z48.string().describe("Detailed task description - what needs to be done"),
21389
- assignee: z48.string().optional().describe("Teammate name to assign this task to (use when you need that person to do the work)"),
21390
- dependencies: z48.array(z48.string()).optional().default([]).describe("Array of task IDs that must complete before this task")
21019
+ schema: z47.object({
21020
+ tasks: z47.array(
21021
+ z47.object({
21022
+ id: z47.string().describe("Task ID in format task-01, task-02, etc. Must be unique."),
21023
+ title: z47.string().describe("Short task title"),
21024
+ description: z47.string().describe("Detailed task description - what needs to be done"),
21025
+ assignee: z47.string().optional().describe("Teammate name to assign this task to (use when you need that person to do the work)"),
21026
+ dependencies: z47.array(z47.string()).optional().default([]).describe("Array of task IDs that must complete before this task")
21391
21027
  })
21392
21028
  ).describe("New tasks to add to the team")
21393
21029
  })
21394
21030
  }
21395
21031
  );
21396
- const assignTaskTool = tool45(
21032
+ const assignTaskTool = tool44(
21397
21033
  async (input, config) => {
21398
21034
  const teamId = resolveTeamId();
21399
21035
  const task = await taskListStore.updateTask(teamId, input.task_id, {
@@ -21415,13 +21051,13 @@ IMPORTANT: Assigning to a specific teammate
21415
21051
  {
21416
21052
  name: "assign_task",
21417
21053
  description: "Assign a task to a specific teammate. Use when you need to reassign work to a different teammate. Omit team_id to use the active team from state.",
21418
- schema: z48.object({
21419
- task_id: z48.string().describe("Task ID to assign"),
21420
- assignee: z48.string().describe("Teammate name to assign this task to")
21054
+ schema: z47.object({
21055
+ task_id: z47.string().describe("Task ID to assign"),
21056
+ assignee: z47.string().describe("Teammate name to assign this task to")
21421
21057
  })
21422
21058
  }
21423
21059
  );
21424
- const setTaskStatusTool = tool45(
21060
+ const setTaskStatusTool = tool44(
21425
21061
  async (input, config) => {
21426
21062
  const teamId = resolveTeamId();
21427
21063
  const task = await taskListStore.updateTask(teamId, input.task_id, {
@@ -21443,13 +21079,13 @@ IMPORTANT: Assigning to a specific teammate
21443
21079
  {
21444
21080
  name: "set_task_status",
21445
21081
  description: "Set a task's status. Use to reopen a task (set to pending), mark as failed, or correct status. Values: pending, claimed, in_progress, completed, failed. Omit team_id to use the active team from state.",
21446
- schema: z48.object({
21447
- task_id: z48.string().describe("Task ID to update"),
21448
- status: z48.enum(["pending", "claimed", "in_progress", "completed", "failed"]).describe("New status for the task")
21082
+ schema: z47.object({
21083
+ task_id: z47.string().describe("Task ID to update"),
21084
+ status: z47.enum(["pending", "claimed", "in_progress", "completed", "failed"]).describe("New status for the task")
21449
21085
  })
21450
21086
  }
21451
21087
  );
21452
- const setTaskDependenciesTool = tool45(
21088
+ const setTaskDependenciesTool = tool44(
21453
21089
  async (input, config) => {
21454
21090
  const teamId = resolveTeamId();
21455
21091
  const task = await taskListStore.updateTask(teamId, input.task_id, {
@@ -21471,13 +21107,13 @@ IMPORTANT: Assigning to a specific teammate
21471
21107
  {
21472
21108
  name: "set_task_dependencies",
21473
21109
  description: 'Set which task IDs must complete before this task can be claimed. Pass an array of task IDs (e.g. ["task-01", "task-02"]). Use to fix task order or add/remove dependencies. Omit team_id to use the active team from state.',
21474
- schema: z48.object({
21475
- task_id: z48.string().describe("Task ID to update"),
21476
- dependencies: z48.array(z48.string()).describe("Task IDs that must complete before this task can be claimed")
21110
+ schema: z47.object({
21111
+ task_id: z47.string().describe("Task ID to update"),
21112
+ dependencies: z47.array(z47.string()).describe("Task IDs that must complete before this task can be claimed")
21477
21113
  })
21478
21114
  }
21479
21115
  );
21480
- const checkTasksTool = tool45(
21116
+ const checkTasksTool = tool44(
21481
21117
  async (input, config) => {
21482
21118
  const teamId = resolveTeamId();
21483
21119
  const tasks = await taskListStore.getAllTasks(teamId);
@@ -21517,12 +21153,12 @@ Task Status Values:
21517
21153
  - in_progress: Teammate is actively working on this task
21518
21154
  - completed: Task finished successfully
21519
21155
  - failed: Task encountered an error`,
21520
- schema: z48.object({
21521
- team_id: z48.string().optional().describe("Team ID (omit to use active team)")
21156
+ schema: z47.object({
21157
+ team_id: z47.string().optional().describe("Team ID (omit to use active team)")
21522
21158
  })
21523
21159
  }
21524
21160
  );
21525
- const sendMessageTool = tool45(
21161
+ const sendMessageTool = tool44(
21526
21162
  async (input, config) => {
21527
21163
  const teamId = resolveTeamId();
21528
21164
  await mailboxStore.sendMessage(
@@ -21541,13 +21177,13 @@ Task Status Values:
21541
21177
  {
21542
21178
  name: "send_message",
21543
21179
  description: "Send a message to a specific teammate in the team. Omit team_id to use the active team from state.",
21544
- schema: z48.object({
21545
- to: z48.string().describe("Recipient teammate name"),
21546
- content: z48.string().describe("Message content")
21180
+ schema: z47.object({
21181
+ to: z47.string().describe("Recipient teammate name"),
21182
+ content: z47.string().describe("Message content")
21547
21183
  })
21548
21184
  }
21549
21185
  );
21550
- const readMessagesTool = tool45(
21186
+ const readMessagesTool = tool44(
21551
21187
  async (input, config) => {
21552
21188
  const teamId = resolveTeamId();
21553
21189
  const formatAndMarkAsRead = async (msgs2) => {
@@ -21629,12 +21265,12 @@ Task Status Values:
21629
21265
  {
21630
21266
  name: "read_messages",
21631
21267
  description: "Read unread messages from teammates. Returns immediately if messages exist, otherwise waits for up to 3 minutes for new messages.",
21632
- schema: z48.object({
21633
- team_id: z48.string().optional().describe("Team ID (omit to use active team)")
21268
+ schema: z47.object({
21269
+ team_id: z47.string().optional().describe("Team ID (omit to use active team)")
21634
21270
  })
21635
21271
  }
21636
21272
  );
21637
- const disbandTeamTool = tool45(
21273
+ const disbandTeamTool = tool44(
21638
21274
  async (input, config) => {
21639
21275
  const teamId = resolveTeamId();
21640
21276
  await mailboxStore.broadcastMessage(
@@ -21655,7 +21291,7 @@ Task Status Values:
21655
21291
  description: "Disband a team when all work is done. Before calling: (1) Call check_tasks to verify no tasks are still pending/in_progress; (2) if any are, discuss with the team via read_messages and broadcast_message/send_message whether to continue or stop/cancel them; (3) only after alignment (all tasks completed/failed or explicitly stopped), then call this tool. This will: 1) Send a shutdown message to all teammates, 2) Wait briefly for them to clean up, 3) Clear all tasks and messages. Omit team_id to use the active team from state."
21656
21292
  }
21657
21293
  );
21658
- const broadcastMessageTool = tool45(
21294
+ const broadcastMessageTool = tool44(
21659
21295
  async (input, config) => {
21660
21296
  const teamId = resolveTeamId();
21661
21297
  await mailboxStore.broadcastMessage(
@@ -21673,12 +21309,12 @@ Task Status Values:
21673
21309
  {
21674
21310
  name: "broadcast_message",
21675
21311
  description: "Send a message to all teammates at once. Use this to communicate with everyone in the team. Omit team_id to use the active team from state.",
21676
- schema: z48.object({
21677
- content: z48.string().describe("Message content to broadcast to all teammates")
21312
+ schema: z47.object({
21313
+ content: z47.string().describe("Message content to broadcast to all teammates")
21678
21314
  })
21679
21315
  }
21680
21316
  );
21681
- return createMiddleware17({
21317
+ return createMiddleware16({
21682
21318
  name: "teamMiddleware",
21683
21319
  tools: [
21684
21320
  createTeamTool,
@@ -21706,37 +21342,37 @@ ${TEAM_SYSTEM_PROMPT}` : TEAM_SYSTEM_PROMPT;
21706
21342
  }
21707
21343
 
21708
21344
  // src/agent_team/agent_team.ts
21709
- var TeammateInfoSchema = z49.object({
21710
- name: z49.string().describe("Teammate name"),
21711
- role: z49.string().describe("Role category (e.g. research, writing, review)"),
21712
- description: z49.string().describe("What this teammate focuses on")
21345
+ var TeammateInfoSchema = z48.object({
21346
+ name: z48.string().describe("Teammate name"),
21347
+ role: z48.string().describe("Role category (e.g. research, writing, review)"),
21348
+ description: z48.string().describe("What this teammate focuses on")
21713
21349
  });
21714
- var TeamTaskInfoSchema = z49.object({
21715
- id: z49.string(),
21716
- title: z49.string(),
21717
- description: z49.string(),
21718
- status: z49.string().optional()
21350
+ var TeamTaskInfoSchema = z48.object({
21351
+ id: z48.string(),
21352
+ title: z48.string(),
21353
+ description: z48.string(),
21354
+ status: z48.string().optional()
21719
21355
  });
21720
- var MailboxMessageSchema = z49.object({
21721
- id: z49.string().describe("Unique message identifier"),
21722
- from: z49.string().describe("Sender agent name"),
21723
- to: z49.string().describe("Recipient agent name"),
21724
- content: z49.string().describe("Message content"),
21725
- timestamp: z49.string().describe("ISO timestamp when the message was sent"),
21726
- type: z49.nativeEnum(MessageType).describe("Message type"),
21727
- read: z49.boolean().describe("Whether the recipient has read this message")
21356
+ var MailboxMessageSchema = z48.object({
21357
+ id: z48.string().describe("Unique message identifier"),
21358
+ from: z48.string().describe("Sender agent name"),
21359
+ to: z48.string().describe("Recipient agent name"),
21360
+ content: z48.string().describe("Message content"),
21361
+ timestamp: z48.string().describe("ISO timestamp when the message was sent"),
21362
+ type: z48.nativeEnum(MessageType).describe("Message type"),
21363
+ read: z48.boolean().describe("Whether the recipient has read this message")
21728
21364
  });
21729
- var TeamInfoSchema = z49.object({
21730
- teamId: z49.string().describe("Unique team identifier"),
21731
- teamLeadId: z49.string().default("team_lead").describe("Team lead agent ID"),
21732
- teammates: z49.array(TeammateInfoSchema).describe("Active teammates in this team"),
21733
- tasks: z49.array(TeamTaskInfoSchema).optional().describe("Initial tasks snapshot"),
21734
- createdAt: z49.string().optional().describe("ISO timestamp when team was created")
21365
+ var TeamInfoSchema = z48.object({
21366
+ teamId: z48.string().describe("Unique team identifier"),
21367
+ teamLeadId: z48.string().default("team_lead").describe("Team lead agent ID"),
21368
+ teammates: z48.array(TeammateInfoSchema).describe("Active teammates in this team"),
21369
+ tasks: z48.array(TeamTaskInfoSchema).optional().describe("Initial tasks snapshot"),
21370
+ createdAt: z48.string().optional().describe("ISO timestamp when team was created")
21735
21371
  });
21736
- var TEAM_STATE_SCHEMA = z49.object({
21372
+ var TEAM_STATE_SCHEMA = z48.object({
21737
21373
  team: TeamInfoSchema.optional().describe("Team info: teamId, teamLeadId, teammates, tasks. Set when create_team succeeds."),
21738
- tasks: z49.array(TeamTaskInfoSchema).optional().describe("Current tasks snapshot from check_tasks. Updated on each check."),
21739
- team_mailbox: z49.array(MailboxMessageSchema).optional().describe("All team mailbox messages for display")
21374
+ tasks: z48.array(TeamTaskInfoSchema).optional().describe("Current tasks snapshot from check_tasks. Updated on each check."),
21375
+ team_mailbox: z48.array(MailboxMessageSchema).optional().describe("All team mailbox messages for display")
21740
21376
  });
21741
21377
  var TEAM_LEAD_BASE_PROMPT = `You are a team lead that coordinates a team of specialized agents. In order to complete the objective that the user asks of you, you will need to:
21742
21378
 
@@ -22990,6 +22626,14 @@ Do not update or change a belief without new evidence. Every update cites the
22990
22626
  observation, states how it supports or contradicts the Claim, and records the
22991
22627
  resulting Decision Impact or explains why the plan remains unchanged.
22992
22628
 
22629
+ An approved scope or criteria change is one reconciliation, not two updates:
22630
+ revise \`## Objective\` / \`## Acceptance Criteria\` and, in the same
22631
+ reconciliation, re-base every affected Belief Key \u2014 its new Basis must cite the
22632
+ user approval \u2014 cancel or replace subtasks that depended on the superseded
22633
+ scope, and revise eval coverage to the revised contract. A downgraded
22634
+ probability after a scope change is an honest reset, not a regression; continue
22635
+ only from the re-based Belief State.
22636
+
22993
22637
  The current runtime requires numeric \`beliefImpact.after\` values and the
22994
22638
  canonical compatibility table below. Treat \`after\` as the evidence support
22995
22639
  percentage for the Claim. It is not an Eval score, Agent quality metric, or Task
@@ -23051,6 +22695,15 @@ that can change the parent goal, acceptance judgment, or next action. It is not
23051
22695
  tool call. Reading a skill, running one command, calling SQL, or editing a file is
23052
22696
  normally an internal \`write_todos\` step.
23053
22697
 
22698
+ Persist the plan before executing it. Announcing work in conversation (for
22699
+ example, "I will create three sub-agents") is not a plan: before that work
22700
+ starts, the parent Belief State must already exist and every planned child must
22701
+ be persisted with its contract (\`pending\` until its phase starts,
22702
+ \`in_progress\` when it starts). The persisted decomposition is what the user
22703
+ aligns on \u2014 in normal approval flows, present the decomposition (children,
22704
+ Targets, and belief dimensions) and confirm it before executing it; a deviation
22705
+ from the approved design is a material boundary requiring renewed confirmation.
22706
+
23054
22707
  Before creating a subtask, identify: (1) the uncertain parent Belief Key, (2) why
23055
22708
  it affects a decision, (3) the observable evidence this subtask will produce, and
23056
22709
  (4) the Prediction contract with positive and negative result branches and their
@@ -24680,6 +24333,9 @@ For a new Orchestra parent \u2014 build the delegation tree before the parent:
24680
24333
  each sub-agent is a bounded specialist with a clear interface (input/output/responsibility).
24681
24334
  A sub-agent qualifies as a sub-agent when it has independent tools, its own skill, or
24682
24335
  needs separate eval. Do not create a sub-agent for a simple inline step.
24336
+ Persist the approved delegation tree as planned child tasks with contracts and
24337
+ \`Targets\` before creating any sub-agent ([[task-tracking]]); in normal approval
24338
+ flows the decomposition is presented for user confirmation first.
24683
24339
 
24684
24340
  **2. Build each sub-agent's skill first.** Per sub-agent:
24685
24341
  - If domain knowledge exists \u2192 load [[document-learning-learn-capability]]
@@ -25838,7 +25494,7 @@ ${body}` : `${frontmatter}
25838
25494
  };
25839
25495
 
25840
25496
  // src/store_lattice/InMemoryMenuStore.ts
25841
- import { randomUUID as randomUUID6 } from "crypto";
25497
+ import { randomUUID as randomUUID5 } from "crypto";
25842
25498
  var InMemoryMenuStore = class {
25843
25499
  constructor() {
25844
25500
  this.items = /* @__PURE__ */ new Map();
@@ -25859,7 +25515,7 @@ var InMemoryMenuStore = class {
25859
25515
  async create(input) {
25860
25516
  const now = /* @__PURE__ */ new Date();
25861
25517
  const item = {
25862
- id: randomUUID6(),
25518
+ id: randomUUID5(),
25863
25519
  tenantId: input.tenantId,
25864
25520
  menuTarget: input.menuTarget,
25865
25521
  group: input.group,
@@ -25895,7 +25551,7 @@ var InMemoryMenuStore = class {
25895
25551
  };
25896
25552
 
25897
25553
  // src/agent_lattice/agentArchitectTools.ts
25898
- import z50 from "zod";
25554
+ import z49 from "zod";
25899
25555
  import { v4 as v43 } from "uuid";
25900
25556
  import { AgentType as AgentType3 } from "@axiom-lattice/protocols";
25901
25557
  function getTenantId2(exeConfig) {
@@ -26004,7 +25660,7 @@ registerToolLattice(
26004
25660
  {
26005
25661
  name: "list_agents",
26006
25662
  description: "List all agents for the current workspace. Returns a summary with id, name, description, and type for each agent.",
26007
- schema: z50.object({})
25663
+ schema: z49.object({})
26008
25664
  },
26009
25665
  async (_input, exeConfig) => {
26010
25666
  try {
@@ -26031,8 +25687,8 @@ registerToolLattice(
26031
25687
  {
26032
25688
  name: "get_agent",
26033
25689
  description: "Get the full configuration of a specific agent by its ID. Returns the complete AgentConfig including prompt, middleware, tools, and sub-agents.",
26034
- schema: z50.object({
26035
- id: z50.string().describe("The agent ID to retrieve")
25690
+ schema: z49.object({
25691
+ id: z49.string().describe("The agent ID to retrieve")
26036
25692
  })
26037
25693
  },
26038
25694
  async (input, exeConfig) => {
@@ -26049,27 +25705,27 @@ registerToolLattice(
26049
25705
  }
26050
25706
  }
26051
25707
  );
26052
- var middlewareConfigSchema = z50.object({
26053
- id: z50.string(),
26054
- type: z50.string(),
26055
- name: z50.string(),
26056
- description: z50.string(),
26057
- enabled: z50.boolean(),
26058
- allowedTools: z50.array(z50.string()).optional().describe("Optional tool-name allowlist. Omit it or pass [] to enable all tools from this middleware. A non-empty task middleware allowlist must include both manage_task and task."),
26059
- config: z50.record(z50.any()).optional()
25708
+ var middlewareConfigSchema = z49.object({
25709
+ id: z49.string(),
25710
+ type: z49.string(),
25711
+ name: z49.string(),
25712
+ description: z49.string(),
25713
+ enabled: z49.boolean(),
25714
+ allowedTools: z49.array(z49.string()).optional().describe("Optional tool-name allowlist. Omit it or pass [] to enable all tools from this middleware. A non-empty task middleware allowlist must include both manage_task and task."),
25715
+ config: z49.record(z49.any()).optional()
26060
25716
  });
26061
- var createAgentSchema = z50.object({
26062
- skillLoaded: z50.literal(true).optional().describe("For agent-architect, set true only after loading agent-architecture in the current conversation context."),
26063
- name: z50.string().describe("Human-friendly display name for the agent. The machine ID (used in other tools) is auto-generated as a slug from this name (e.g. 'My Cool Agent' \u2192 'my-cool-agent')."),
26064
- description: z50.string().optional().describe("Short description"),
26065
- type: z50.enum(["react", "deep_agent"]).describe("Agent type. Use 'react' for simple single-responsibility agents, 'deep_agent' for complex open-ended agents. For PROCESSING agents (workflow orchestration), use create_processing_agent instead."),
26066
- prompt: z50.string().describe("System prompt for the agent"),
26067
- tools: z50.array(z50.string()).optional().describe("Tool keys (strings) to assign. Call list_tools first to see available keys. Each element is a plain string like 'sap_api_search'. IMPORTANT: tools is a FLAT string array of tool names. Do NOT put middleware-like objects here \u2014 middleware goes in the separate 'middleware' field."),
26068
- middleware: z50.array(middlewareConfigSchema).optional().describe("Middleware configuration objects. Each has {id, type, name, description, enabled, config}. IMPORTANT: middleware objects are NOT tools. Do NOT put tool keys (strings) here \u2014 tool names go in the separate 'tools' array. For user approval/confirmation scenarios, use type: 'ask_user_to_clarify' with config: {}."),
26069
- subAgents: z50.array(z50.string()).optional().describe("Sub-agent IDs (deep_agent only)"),
26070
- internalSubAgents: z50.array(z50.any()).optional().describe("Inline sub-agent configs (deep_agent only)"),
26071
- modelKey: z50.string().optional().describe("Model key to use"),
26072
- metadata: z50.record(z50.string(), z50.string()).optional().describe("Arbitrary metadata key-value pairs (e.g. verified: 'human-reviewed', version: '1.0', source: 'PO-Format-SAP.pdf')")
25717
+ var createAgentSchema = z49.object({
25718
+ skillLoaded: z49.literal(true).optional().describe("For agent-architect, set true only after loading agent-architecture in the current conversation context."),
25719
+ name: z49.string().describe("Human-friendly display name for the agent. The machine ID (used in other tools) is auto-generated as a slug from this name (e.g. 'My Cool Agent' \u2192 'my-cool-agent')."),
25720
+ description: z49.string().optional().describe("Short description"),
25721
+ type: z49.enum(["react", "deep_agent"]).describe("Agent type. Use 'react' for simple single-responsibility agents, 'deep_agent' for complex open-ended agents. For PROCESSING agents (workflow orchestration), use create_processing_agent instead."),
25722
+ prompt: z49.string().describe("System prompt for the agent"),
25723
+ tools: z49.array(z49.string()).optional().describe("Tool keys (strings) to assign. Call list_tools first to see available keys. Each element is a plain string like 'sap_api_search'. IMPORTANT: tools is a FLAT string array of tool names. Do NOT put middleware-like objects here \u2014 middleware goes in the separate 'middleware' field."),
25724
+ middleware: z49.array(middlewareConfigSchema).optional().describe("Middleware configuration objects. Each has {id, type, name, description, enabled, config}. IMPORTANT: middleware objects are NOT tools. Do NOT put tool keys (strings) here \u2014 tool names go in the separate 'tools' array. For user approval/confirmation scenarios, use type: 'ask_user_to_clarify' with config: {}."),
25725
+ subAgents: z49.array(z49.string()).optional().describe("Sub-agent IDs (deep_agent only)"),
25726
+ internalSubAgents: z49.array(z49.any()).optional().describe("Inline sub-agent configs (deep_agent only)"),
25727
+ modelKey: z49.string().optional().describe("Model key to use"),
25728
+ metadata: z49.record(z49.string(), z49.string()).optional().describe("Arbitrary metadata key-value pairs (e.g. verified: 'human-reviewed', version: '1.0', source: 'PO-Format-SAP.pdf')")
26073
25729
  });
26074
25730
  registerToolLattice(
26075
25731
  "create_agent",
@@ -26114,14 +25770,14 @@ registerToolLattice(
26114
25770
  }
26115
25771
  }
26116
25772
  );
26117
- var createWorkflowSchema = z50.object({
26118
- name: z50.string().describe("Display name for the workflow agent"),
26119
- description: z50.string().optional().describe("Short description"),
26120
- skillLoaded: z50.literal(true).describe("MUST be true. Set after loading the 'create-workflow' skill."),
26121
- yaml: z50.string().describe("The YAML workflow definition in linear DSL format (steps execute top-to-bottom, use parallel: for concurrency)"),
26122
- tools: z50.array(z50.string()).optional().describe("Tool keys for the workflow agent"),
26123
- middleware: z50.array(middlewareConfigSchema).optional().describe("Middleware configs"),
26124
- modelKey: z50.string().optional().describe("Model key")
25773
+ var createWorkflowSchema = z49.object({
25774
+ name: z49.string().describe("Display name for the workflow agent"),
25775
+ description: z49.string().optional().describe("Short description"),
25776
+ skillLoaded: z49.literal(true).describe("MUST be true. Set after loading the 'create-workflow' skill."),
25777
+ yaml: z49.string().describe("The YAML workflow definition in linear DSL format (steps execute top-to-bottom, use parallel: for concurrency)"),
25778
+ tools: z49.array(z49.string()).optional().describe("Tool keys for the workflow agent"),
25779
+ middleware: z49.array(middlewareConfigSchema).optional().describe("Middleware configs"),
25780
+ modelKey: z49.string().optional().describe("Model key")
26125
25781
  });
26126
25782
  registerToolLattice(
26127
25783
  "create_workflow",
@@ -26172,8 +25828,8 @@ registerToolLattice(
26172
25828
  {
26173
25829
  name: "validate_workflow",
26174
25830
  description: "Validate a workflow agent's DSL for correctness by compiling it.",
26175
- schema: z50.object({
26176
- id: z50.string().describe("The workflow agent ID to validate")
25831
+ schema: z49.object({
25832
+ id: z49.string().describe("The workflow agent ID to validate")
26177
25833
  })
26178
25834
  },
26179
25835
  async (input, exeConfig) => {
@@ -26270,15 +25926,15 @@ registerToolLattice(
26270
25926
  }
26271
25927
  }
26272
25928
  );
26273
- var updateWorkflowSchema = z50.object({
26274
- id: z50.string().describe("The workflow agent ID to update"),
26275
- skillLoaded: z50.literal(true).optional().describe("For agent-architect, set true only after loading agent-architecture in the current conversation context."),
26276
- name: z50.string().optional().describe("New display name"),
26277
- description: z50.string().optional().describe("New description"),
26278
- yaml: z50.string().optional().describe("Replacement YAML workflow DSL. Omit to keep existing."),
26279
- tools: z50.array(z50.string()).optional().describe("Replacement tool keys"),
26280
- middleware: z50.array(middlewareConfigSchema).optional().describe("Replacement middleware configs"),
26281
- modelKey: z50.string().optional().describe("Replacement model key")
25929
+ var updateWorkflowSchema = z49.object({
25930
+ id: z49.string().describe("The workflow agent ID to update"),
25931
+ skillLoaded: z49.literal(true).optional().describe("For agent-architect, set true only after loading agent-architecture in the current conversation context."),
25932
+ name: z49.string().optional().describe("New display name"),
25933
+ description: z49.string().optional().describe("New description"),
25934
+ yaml: z49.string().optional().describe("Replacement YAML workflow DSL. Omit to keep existing."),
25935
+ tools: z49.array(z49.string()).optional().describe("Replacement tool keys"),
25936
+ middleware: z49.array(middlewareConfigSchema).optional().describe("Replacement middleware configs"),
25937
+ modelKey: z49.string().optional().describe("Replacement model key")
26282
25938
  });
26283
25939
  registerToolLattice(
26284
25940
  "update_workflow",
@@ -26384,20 +26040,20 @@ registerToolLattice(
26384
26040
  }
26385
26041
  }
26386
26042
  );
26387
- var updateAgentSchema = z50.object({
26388
- id: z50.string().describe("The agent ID to update"),
26389
- skillLoaded: z50.literal(true).optional().describe("For agent-architect, set true only after loading agent-architecture in the current conversation context."),
26390
- config: z50.object({
26391
- name: z50.string().optional().describe("New display name for the agent"),
26392
- description: z50.string().optional().describe("New short description"),
26393
- type: z50.enum(["react", "deep_agent"]).optional().describe("Agent type"),
26394
- prompt: z50.string().optional().describe("New system prompt for the agent"),
26395
- tools: z50.array(z50.string()).optional().describe("Tool keys to assign to this agent. These are registered tool names (strings), NOT middleware objects."),
26396
- middleware: z50.array(middlewareConfigSchema).optional().describe("Middleware configurations. NOTE: middleware objects have type/name/description/enabled/config fields and are NOT the same as tools. Tool keys go in the 'tools' array. For user approval/confirmation scenarios, use type: 'ask_user_to_clarify' with config: {}."),
26397
- subAgents: z50.array(z50.string()).optional().describe("Sub-agent IDs (deep_agent only)"),
26398
- internalSubAgents: z50.array(z50.any()).optional().describe("Inline sub-agent configs (deep_agent only)"),
26399
- modelKey: z50.string().optional().describe("Model key to use"),
26400
- metadata: z50.record(z50.string(), z50.string()).optional().describe("Arbitrary metadata key-value pairs (e.g. verified: 'machine-confirmed', version: '1.1'). Replaces the whole map when provided.")
26043
+ var updateAgentSchema = z49.object({
26044
+ id: z49.string().describe("The agent ID to update"),
26045
+ skillLoaded: z49.literal(true).optional().describe("For agent-architect, set true only after loading agent-architecture in the current conversation context."),
26046
+ config: z49.object({
26047
+ name: z49.string().optional().describe("New display name for the agent"),
26048
+ description: z49.string().optional().describe("New short description"),
26049
+ type: z49.enum(["react", "deep_agent"]).optional().describe("Agent type"),
26050
+ prompt: z49.string().optional().describe("New system prompt for the agent"),
26051
+ tools: z49.array(z49.string()).optional().describe("Tool keys to assign to this agent. These are registered tool names (strings), NOT middleware objects."),
26052
+ middleware: z49.array(middlewareConfigSchema).optional().describe("Middleware configurations. NOTE: middleware objects have type/name/description/enabled/config fields and are NOT the same as tools. Tool keys go in the 'tools' array. For user approval/confirmation scenarios, use type: 'ask_user_to_clarify' with config: {}."),
26053
+ subAgents: z49.array(z49.string()).optional().describe("Sub-agent IDs (deep_agent only)"),
26054
+ internalSubAgents: z49.array(z49.any()).optional().describe("Inline sub-agent configs (deep_agent only)"),
26055
+ modelKey: z49.string().optional().describe("Model key to use"),
26056
+ metadata: z49.record(z49.string(), z49.string()).optional().describe("Arbitrary metadata key-value pairs (e.g. verified: 'machine-confirmed', version: '1.1'). Replaces the whole map when provided.")
26401
26057
  }).describe("Configuration fields to update. Only include the fields you want to change.")
26402
26058
  });
26403
26059
  registerToolLattice(
@@ -26519,8 +26175,8 @@ registerToolLattice(
26519
26175
  {
26520
26176
  name: "delete_agent",
26521
26177
  description: "Permanently delete an agent by its ID. This action cannot be undone.",
26522
- schema: z50.object({
26523
- id: z50.string().describe("The agent ID to delete")
26178
+ schema: z49.object({
26179
+ id: z49.string().describe("The agent ID to delete")
26524
26180
  })
26525
26181
  },
26526
26182
  async (input, exeConfig) => {
@@ -26546,7 +26202,7 @@ registerToolLattice(
26546
26202
  {
26547
26203
  name: "list_tools",
26548
26204
  description: "List all available tools that can be assigned to agents. Returns each tool's registry key (use this string value in the 'tools' array), name, description, and whether it requires user approval.",
26549
- schema: z50.object({})
26205
+ schema: z49.object({})
26550
26206
  },
26551
26207
  async (_input, _exeConfig) => {
26552
26208
  try {
@@ -26569,7 +26225,7 @@ registerToolLattice(
26569
26225
  {
26570
26226
  name: "list_models",
26571
26227
  description: "List all registered models. Returns each model's key (use this string as modelKey when creating eval projects via manage_eval create_project, or as an agent's modelKey in create_agent/update_agent) and its display name.",
26572
- schema: z50.object({})
26228
+ schema: z49.object({})
26573
26229
  },
26574
26230
  async (_input) => {
26575
26231
  try {
@@ -26590,9 +26246,9 @@ registerToolLattice(
26590
26246
  {
26591
26247
  name: "invoke_agent",
26592
26248
  description: "Invoke an agent with a test message and return its response. Use this to verify an agent works correctly after creating or modifying it. The agent must be compiled (already created and valid).",
26593
- schema: z50.object({
26594
- id: z50.string().describe("The agent ID to invoke"),
26595
- message: z50.string().describe("The test message to send to the agent")
26249
+ schema: z49.object({
26250
+ id: z49.string().describe("The agent ID to invoke"),
26251
+ message: z49.string().describe("The test message to send to the agent")
26596
26252
  })
26597
26253
  },
26598
26254
  async (input, exeConfig) => {
@@ -26628,7 +26284,7 @@ registerToolLattice(
26628
26284
  {
26629
26285
  name: "list_middleware_types",
26630
26286
  description: "\u5217\u51FA\u5F53\u524D\u7CFB\u7EDF\u4E2D\u6240\u6709\u53EF\u7528\u7684\u4E2D\u95F4\u4EF6\u7C7B\u578B\uFF08Middlewares\uFF09\uFF0C\u5305\u62EC\u5185\u7F6E\u548C\u81EA\u5B9A\u4E49\u63D2\u4EF6\u3002\u8FD4\u56DE\u6BCF\u4E2A\u4E2D\u95F4\u4EF6\u7684 type\u3001name\u3001description\u3001tools \u6E05\u5355\uFF08\u652F\u6301 allowedTools \u8FC7\u6EE4\uFF09\u3001configSchema\uFF08\u914D\u7F6E\u9762\u677F\u9700\u8981\u54EA\u4E9B\u5B57\u6BB5\uFF09\u548C connectionSchema\uFF08\u662F\u5426\u652F\u6301\u8FDE\u63A5\u6D4B\u8BD5\u548C\u8D44\u6E90\u53D1\u73B0\uFF09\u3002\n\n\u4F7F\u7528\u573A\u666F\uFF1A\n1. \u5728\u521B\u5EFA agent \u524D\uFF0C\u5148\u8C03\u6B64\u5DE5\u5177\u4E86\u89E3\u6709\u54EA\u4E9B\u4E2D\u95F4\u4EF6\u53EF\u914D\u7F6E\n2. \u6839\u636E configSchema \u51B3\u5B9A\u9700\u8981\u63D0\u4F9B\u54EA\u4E9B\u914D\u7F6E\u5B57\u6BB5\uFF1B\u65B0\u8FDE\u63A5\u578B\u63D2\u4EF6\u4F7F\u7528 connections \u548C connectAll\uFF0C\u5185\u7F6E\u65E7\u63D2\u4EF6\u7684 selector \u5B57\u6BB5\u7531 core \u7684 legacy compatibility map \u5B9A\u4E49\n3. \u5982\u679C\u67D0\u4E2A\u4E2D\u95F4\u4EF6\u7684 connectionSchema \u5B58\u5728\uFF0C\u8BF4\u660E\u5B83\u662F\u8FDE\u63A5\u578B\u4E2D\u95F4\u4EF6\uFF0C\u9700\u8981\u518D\u8C03 list_connections \u83B7\u53D6\u53EF\u7528\u8FDE\u63A5\n4. \u7528\u8FD4\u56DE\u7684 type \u5B57\u6BB5\u6784\u5EFA middleware \u6570\u7EC4\u4F20\u7ED9 create_agent / update_agent",
26631
- schema: z50.object({})
26287
+ schema: z49.object({})
26632
26288
  },
26633
26289
  async () => {
26634
26290
  const availableMiddlewareTypes = getAvailableMiddlewareTypes();
@@ -26641,8 +26297,8 @@ registerToolLattice(
26641
26297
  {
26642
26298
  name: "list_connections",
26643
26299
  description: "\u5217\u51FA\u6307\u5B9A\u63D2\u4EF6\u7C7B\u578B\u7684\u6240\u6709\u5DF2\u914D\u7F6E\u8FDE\u63A5\u3002\u7528\u4E8E\u67E5\u8BE2\u6709\u54EA\u4E9B\u53EF\u7528\u7684\u8FDE\u63A5\u5B9E\u4F8B\uFF08\u5982 'sap-prod', 'sap-dev'\uFF09\uFF0C\u65B9\u4FBF\u5728 agent \u914D\u7F6E\u4E2D\u9009\u62E9\u5177\u4F53\u8FDE\u63A5\u3002\n\n\u4F7F\u7528\u573A\u666F\uFF1A\n1. \u5148\u8C03 list_middleware_types \u786E\u5B9A\u67D0\u4E2A\u4E2D\u95F4\u4EF6\u662F\u8FDE\u63A5\u578B\uFF08\u6709 connectionSchema\uFF09\n2. \u8C03\u6B64\u5DE5\u5177\u4F20\u5165 type\uFF08\u5982 'erp'\uFF09\uFF0C\u83B7\u53D6\u8BE5\u7C7B\u578B\u4E0B\u5DF2\u914D\u597D\u7684\u8FDE\u63A5\u5217\u8868\n3. \u5728 create_agent \u7684 middleware[i].config.connections \u4E2D\u586B\u5165\u5BF9\u5E94\u7684 key \u503C\n\n\u8FD4\u56DE\u683C\u5F0F\uFF1A{ success: true, data: { records: [{ key, name, ... }] } }",
26644
- schema: z50.object({
26645
- type: z50.string().describe("\u63D2\u4EF6\u7C7B\u578B\u6807\u8BC6\uFF0C\u5982 'erp'\u3002\u4ECE list_middleware_types \u7684\u8FD4\u56DE\u4E2D\u83B7\u53D6")
26300
+ schema: z49.object({
26301
+ type: z49.string().describe("\u63D2\u4EF6\u7C7B\u578B\u6807\u8BC6\uFF0C\u5982 'erp'\u3002\u4ECE list_middleware_types \u7684\u8FD4\u56DE\u4E2D\u83B7\u53D6")
26646
26302
  }),
26647
26303
  needUserApprove: false
26648
26304
  },
@@ -26918,6 +26574,14 @@ var roomCoordinatorConfig = {
26918
26574
  description: "Wait for user input at approval gates",
26919
26575
  enabled: true,
26920
26576
  config: {}
26577
+ },
26578
+ {
26579
+ id: "project_room",
26580
+ type: "project_room",
26581
+ name: "Project Room",
26582
+ description: "Post to the room and list active members for delegation",
26583
+ enabled: true,
26584
+ config: {}
26921
26585
  }
26922
26586
  ]
26923
26587
  };
@@ -26960,7 +26624,7 @@ function assistantToConfig(assistant) {
26960
26624
  Object.assign(config, graphDef);
26961
26625
  return config;
26962
26626
  }
26963
- var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager {
26627
+ var _AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager {
26964
26628
  constructor() {
26965
26629
  super();
26966
26630
  this.initialized = false;
@@ -27069,7 +26733,18 @@ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager
27069
26733
  getLatticeType() {
27070
26734
  return "agents";
27071
26735
  }
27072
- // ========== 带租户的新API ==========
26736
+ /**
26737
+ * Returns the parent assistant key for a `{parent}-general-purpose` key, or
26738
+ * `null` when the key is not a suffixed GP key (including the bare
26739
+ * `general-purpose` key itself).
26740
+ */
26741
+ generalPurposeParentKey(key4) {
26742
+ const suffix = _AgentLatticeManager.GENERAL_PURPOSE_SUFFIX;
26743
+ if (!key4.endsWith(suffix) || key4.length <= suffix.length) {
26744
+ return null;
26745
+ }
26746
+ return key4.slice(0, -suffix.length);
26747
+ }
27073
26748
  /**
27074
26749
  * 带租户注册Agent Lattice
27075
26750
  * @param tenantId 租户ID
@@ -27085,20 +26760,66 @@ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager
27085
26760
  }
27086
26761
  /**
27087
26762
  * 带租户获取AgentLattice
26763
+ *
26764
+ * @remarks
26765
+ * For unregistered `{parent}-general-purpose` keys (ephemeral subagent
26766
+ * assistants created by the subagents middleware), this falls back to the
26767
+ * parent assistant's lattice so that read paths (thread state/messages)
26768
+ * resolve in processes where the runtime GP registration is absent.
26769
+ * {@link hasAgentLatticeWithTenant} stays strict.
26770
+ *
27088
26771
  * @param tenantId 租户ID
27089
26772
  * @param key Lattice键名
27090
26773
  */
27091
26774
  getAgentLatticeWithTenant(tenantId2, key4) {
27092
- return this.getWithTenant(tenantId2, key4);
26775
+ const exact = this.getWithTenant(tenantId2, key4);
26776
+ if (exact) {
26777
+ return exact;
26778
+ }
26779
+ const parentKey = this.generalPurposeParentKey(key4);
26780
+ if (!parentKey) {
26781
+ return void 0;
26782
+ }
26783
+ return this.getWithTenant(tenantId2, parentKey);
27093
26784
  }
27094
26785
  /**
27095
26786
  * 带租户检查Lattice是否存在
26787
+ *
26788
+ * @remarks
26789
+ * Deliberately strict: `{parent}-general-purpose` keys are NOT covered by
26790
+ * the read fallback. The subagents middleware relies on this check to decide
26791
+ * whether to register the real GP runtime agent; a permissive check would
26792
+ * skip that registration and silently run the parent graph for GP tasks.
26793
+ *
27096
26794
  * @param tenantId 租户ID
27097
26795
  * @param key Lattice键名
27098
26796
  */
27099
26797
  hasAgentLatticeWithTenant(tenantId2, key4) {
27100
26798
  return this.hasWithTenant(tenantId2, key4);
27101
26799
  }
26800
+ /**
26801
+ * 异步获取AgentLattice(内存未命中时尝试从store加载)
26802
+ *
26803
+ * @remarks
26804
+ * Mirrors {@link getAgentLatticeWithTenant}'s general-purpose fallback: an
26805
+ * unregistered `{parent}-general-purpose` key resolves to the parent
26806
+ * assistant's lattice. This is the lookup used by `getAgentClientAsync`,
26807
+ * which backs Gateway thread state/message reads for GP subagent threads.
26808
+ *
26809
+ * @param tenantId 租户ID
26810
+ * @param key Lattice键名
26811
+ */
26812
+ async getOrLoadWithTenant(tenantId2, key4) {
26813
+ const exact = await super.getOrLoadWithTenant(tenantId2, key4);
26814
+ if (exact) {
26815
+ return exact;
26816
+ }
26817
+ const parentKey = this.generalPurposeParentKey(key4);
26818
+ if (!parentKey) {
26819
+ return void 0;
26820
+ }
26821
+ return super.getOrLoadWithTenant(tenantId2, parentKey);
26822
+ }
27102
26823
  /**
27103
26824
  * 带租户移除Lattice
27104
26825
  * @param tenantId 租户ID
@@ -27422,6 +27143,18 @@ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager
27422
27143
  }
27423
27144
  }
27424
27145
  };
27146
+ // ========== 带租户的新API ==========
27147
+ /**
27148
+ * Suffix that identifies ephemeral general-purpose subagent assistants.
27149
+ *
27150
+ * The subagents middleware (deep_agent_new) registers a runtime agent
27151
+ * `{assistant_id}-general-purpose` in the process that executes the task.
27152
+ * Other processes (e.g. the Gateway serving thread state/messages) never see
27153
+ * that in-memory registration, so lattice lookups for the suffixed key fall
27154
+ * back to the parent assistant's lattice.
27155
+ */
27156
+ _AgentLatticeManager.GENERAL_PURPOSE_SUFFIX = "-general-purpose";
27157
+ var AgentLatticeManager = _AgentLatticeManager;
27425
27158
  var agentLatticeManager = AgentLatticeManager.getInstance();
27426
27159
  var registerAgentLattice = (config) => {
27427
27160
  agentLatticeManager.registerLattice(config);
@@ -30801,7 +30534,7 @@ function clearEvalRunService() {
30801
30534
  }
30802
30535
 
30803
30536
  // src/eval_lattice/LatticeEval.ts
30804
- import { HumanMessage as HumanMessage5 } from "@langchain/core/messages";
30537
+ import { HumanMessage as HumanMessage4 } from "@langchain/core/messages";
30805
30538
  import { v4 as v44 } from "uuid";
30806
30539
  function parseJudgeVerdict(raw) {
30807
30540
  try {
@@ -31210,7 +30943,7 @@ Note: if final_score >= 80 and there are no fatal errors, pass should be true; o
31210
30943
  const judgeAgent = await getAgentClient(judgeTenantId, judgeAgentKey);
31211
30944
  const testResponse = await judgeAgent.invoke(
31212
30945
  {
31213
- messages: [new HumanMessage5(testPrompt)]
30946
+ messages: [new HumanMessage4(testPrompt)]
31214
30947
  },
31215
30948
  {
31216
30949
  configurable: {
@@ -31581,7 +31314,7 @@ var LatticeEvalSuite = class {
31581
31314
 
31582
31315
  // src/eval_lattice/LatticeEvalProject.ts
31583
31316
  import { AgentType as AgentType7 } from "@axiom-lattice/protocols";
31584
- import { HumanMessage as HumanMessage6 } from "@langchain/core/messages";
31317
+ import { HumanMessage as HumanMessage5 } from "@langchain/core/messages";
31585
31318
  import { v4 as uuidv46 } from "uuid";
31586
31319
  var DEFAULT_CALIBRATION_PROBES = [
31587
31320
  {
@@ -31745,7 +31478,7 @@ Respond with JSON only: {"pass": true|false, "final_score": 0-100, "summary": "r
31745
31478
  for (let attempt = 0; attempt < 2; attempt++) {
31746
31479
  try {
31747
31480
  const resp = await judgeAgent.invoke(
31748
- { messages: [new HumanMessage6(prompt)] },
31481
+ { messages: [new HumanMessage5(prompt)] },
31749
31482
  { configurable: { thread_id: uuidv46() } }
31750
31483
  );
31751
31484
  const last = resp?.messages?.[resp.messages.length - 1];
@@ -31862,7 +31595,7 @@ function getMenuRegistry() {
31862
31595
  }
31863
31596
 
31864
31597
  // src/services/ProjectTaskReassignmentAuthorization.ts
31865
- import { snapshotExactRecord as snapshotExactRecord3 } from "@axiom-lattice/protocols";
31598
+ import { snapshotExactRecord } from "@axiom-lattice/protocols";
31866
31599
  var issued = /* @__PURE__ */ new WeakMap();
31867
31600
  function createProjectTaskReassignmentAuthorizer(policy, threadValidator) {
31868
31601
  return {
@@ -31895,7 +31628,7 @@ function inspectProjectTaskReassignmentAuthorization(authorization) {
31895
31628
  return snapshot ? { ...snapshot } : void 0;
31896
31629
  }
31897
31630
  function snapshotInput(input) {
31898
- const row = snapshotExactRecord3(input, [
31631
+ const row = snapshotExactRecord(input, [
31899
31632
  "tenantId",
31900
31633
  "workspaceId",
31901
31634
  "projectId",
@@ -31938,7 +31671,7 @@ function snapshotInput(input) {
31938
31671
  }
31939
31672
 
31940
31673
  // src/services/TaskLifecycleNotifier.ts
31941
- import { snapshotExactRecord as snapshotExactRecord4 } from "@axiom-lattice/protocols";
31674
+ import { snapshotExactRecord as snapshotExactRecord2 } from "@axiom-lattice/protocols";
31942
31675
  var TaskLifecycleNotifier = class {
31943
31676
  constructor() {
31944
31677
  this.listeners = /* @__PURE__ */ new Set();
@@ -31982,7 +31715,7 @@ var TaskLifecycleNotifier = class {
31982
31715
  };
31983
31716
  var taskLifecycleNotifier = new TaskLifecycleNotifier();
31984
31717
  function snapshotNotification(value) {
31985
- const row = snapshotExactRecord4(value, [
31718
+ const row = snapshotExactRecord2(value, [
31986
31719
  "tenantId",
31987
31720
  "workspaceId",
31988
31721
  "projectId",
@@ -32014,7 +31747,7 @@ function nonempty(value) {
32014
31747
  }
32015
31748
 
32016
31749
  // src/services/ProjectTaskAdmissionNotifier.ts
32017
- import { snapshotExactRecord as snapshotExactRecord5 } from "@axiom-lattice/protocols";
31750
+ import { snapshotExactRecord as snapshotExactRecord3 } from "@axiom-lattice/protocols";
32018
31751
  var ProjectTaskAdmissionNotifier = class {
32019
31752
  /**
32020
31753
  * Creates a bounded Project task admission notifier.
@@ -32087,7 +31820,7 @@ var ProjectTaskAdmissionNotifier = class {
32087
31820
  };
32088
31821
  var projectTaskAdmissionNotifier = new ProjectTaskAdmissionNotifier();
32089
31822
  function snapshotNotification2(value) {
32090
- const row = snapshotExactRecord5(value, [
31823
+ const row = snapshotExactRecord3(value, [
32091
31824
  "tenantId",
32092
31825
  "workspaceId",
32093
31826
  "projectId",
@@ -32117,9 +31850,9 @@ function canonicalTimestamp(value) {
32117
31850
  }
32118
31851
 
32119
31852
  // src/services/ProjectMutationMutex.ts
32120
- import { snapshotExactRecord as snapshotExactRecord6 } from "@axiom-lattice/protocols";
31853
+ import { snapshotExactRecord as snapshotExactRecord4 } from "@axiom-lattice/protocols";
32121
31854
  function projectKey(scope) {
32122
- const row = snapshotExactRecord6(scope, ["tenantId", "projectId"]);
31855
+ const row = snapshotExactRecord4(scope, ["tenantId", "projectId"]);
32123
31856
  if (!row || typeof row.tenantId !== "string" || !row.tenantId || row.tenantId.includes("\0") || typeof row.projectId !== "string" || !row.projectId || row.projectId.includes("\0")) {
32124
31857
  throw new Error("Invalid Project mutation scope");
32125
31858
  }
@@ -32192,8 +31925,199 @@ function createTrustedAgentMessageDispatcher(resolve4) {
32192
31925
  };
32193
31926
  }
32194
31927
 
31928
+ // src/services/RoomAgentMessageService.ts
31929
+ import { randomUUID as randomUUID6 } from "crypto";
31930
+ import { snapshotExactArray, snapshotExactRecord as snapshotExactRecord5 } from "@axiom-lattice/protocols";
31931
+ var INPUT_KEYS = [
31932
+ "tenantId",
31933
+ "workspaceId",
31934
+ "projectId",
31935
+ "roomId",
31936
+ "membershipId",
31937
+ "assistantId",
31938
+ "text",
31939
+ "sourceRoomMessageId",
31940
+ "sourceId",
31941
+ "idempotencyKey"
31942
+ ];
31943
+ var REPLY_INPUT_KEYS = ["tenantId", "membershipId", "text", "sourceRoomMessageId", "inputMessageId", "sourceId", "idempotencyKey"];
31944
+ var RoomAgentMessageService = class {
31945
+ /**
31946
+ * Creates a room writer over the durable membership and message stores.
31947
+ *
31948
+ * @param deps Store methods, optional deterministic ID factory, and detached post-commit hooks.
31949
+ */
31950
+ constructor(deps) {
31951
+ this.deps = deps;
31952
+ }
31953
+ /**
31954
+ * Persists a fully scoped Agent response after validating its human source and active membership.
31955
+ *
31956
+ * @param input Exact trusted scope and response payload.
31957
+ * @returns A deep clone of the canonical idempotent room message.
31958
+ */
31959
+ post(input) {
31960
+ const snapshot = exactStringRecord(input, INPUT_KEYS, "Invalid project room message input");
31961
+ return this.persist(snapshot);
31962
+ }
31963
+ /**
31964
+ * Persists a channel reply while deriving all scope from validated durable records.
31965
+ *
31966
+ * @param input Exact correlation IDs, tenant, target membership, and response text.
31967
+ * @returns A deep clone of the canonical idempotent room message.
31968
+ */
31969
+ postReply(input) {
31970
+ const snapshot = exactStringRecord(input, REPLY_INPUT_KEYS, "Invalid project room reply input");
31971
+ if (snapshot.sourceId !== `reply:${snapshot.inputMessageId}` || snapshot.idempotencyKey !== `room-reply:${snapshot.sourceRoomMessageId}:${snapshot.membershipId}:${snapshot.sourceId}`) {
31972
+ throw new Error("Invalid project room reply correlation");
31973
+ }
31974
+ return this.persistDerived(snapshot);
31975
+ }
31976
+ async persistDerived(input) {
31977
+ const source = snapshotSource(await this.deps.messages.findById(input.tenantId, input.sourceRoomMessageId));
31978
+ if (!source || source.id !== input.sourceRoomMessageId || source.tenantId !== input.tenantId) throw new Error("Invalid project room message");
31979
+ const member = snapshotMembership(await this.deps.memberships.findById(input.tenantId, input.membershipId));
31980
+ if (!member || member.id !== input.membershipId || member.tenantId !== input.tenantId) throw new Error("Invalid project room membership");
31981
+ return this.persist({
31982
+ ...input,
31983
+ workspaceId: source.workspaceId,
31984
+ projectId: source.projectId,
31985
+ roomId: source.roomId,
31986
+ assistantId: member.assistantId
31987
+ }, source, member);
31988
+ }
31989
+ async persist(input, loadedSource, loadedMember) {
31990
+ const text = input.text.trim();
31991
+ if (text.length < 1 || text.length > 2e4) throw new Error("Invalid project room message text");
31992
+ const source = loadedSource ?? snapshotSource(await this.deps.messages.findById(input.tenantId, input.sourceRoomMessageId));
31993
+ if (!source || source.id !== input.sourceRoomMessageId || source.tenantId !== input.tenantId || source.workspaceId !== input.workspaceId || source.projectId !== input.projectId || source.roomId !== input.roomId) {
31994
+ throw new Error("Invalid project room message");
31995
+ }
31996
+ const member = loadedMember ?? snapshotMembership(await this.deps.memberships.findById(input.tenantId, input.membershipId));
31997
+ if (!member || member.id !== input.membershipId || member.status !== "active" || member.assistantId !== input.assistantId || member.tenantId !== input.tenantId || member.workspaceId !== input.workspaceId || member.projectId !== input.projectId || member.roomId !== input.roomId) {
31998
+ throw new Error("Invalid project room membership");
31999
+ }
32000
+ const candidate = {
32001
+ id: (this.deps.idFactory ?? randomUUID6)(),
32002
+ tenantId: input.tenantId,
32003
+ workspaceId: input.workspaceId,
32004
+ projectId: input.projectId,
32005
+ roomId: input.roomId,
32006
+ author: { type: "bot", membershipId: input.membershipId, assistantId: input.assistantId },
32007
+ content: { type: "text", text },
32008
+ mentions: [],
32009
+ replyToMessageId: input.sourceRoomMessageId,
32010
+ source: "agent",
32011
+ sourceId: input.sourceId,
32012
+ idempotencyKey: input.idempotencyKey
32013
+ };
32014
+ const canonical = snapshotCanonical(await this.deps.messages.createIdempotent(candidate), candidate);
32015
+ if (!canonical) throw new Error("Invalid canonical project room message");
32016
+ const result = structuredClone(canonical);
32017
+ this.notifyCommitted(result);
32018
+ return result;
32019
+ }
32020
+ notifyCommitted(message) {
32021
+ const callback = this.deps.onMessageCommitted;
32022
+ if (!callback) return;
32023
+ Promise.resolve().then(() => callback(structuredClone(message))).catch(() => {
32024
+ try {
32025
+ this.deps.onCallbackFailure?.({ messageId: message.id, code: "ROOM_MESSAGE_COMMIT_CALLBACK_FAILED" });
32026
+ } catch {
32027
+ }
32028
+ });
32029
+ }
32030
+ };
32031
+ function exactValues(value, required, optional = []) {
32032
+ try {
32033
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
32034
+ return snapshotExactRecord5(value, required, optional);
32035
+ } catch {
32036
+ return void 0;
32037
+ }
32038
+ }
32039
+ function exactStringRecord(value, keys, message) {
32040
+ const values = exactValues(value, keys);
32041
+ if (!values || keys.some((key4) => typeof values[key4] !== "string" || values[key4].length === 0)) throw new Error(message);
32042
+ return values;
32043
+ }
32044
+ function date(value) {
32045
+ try {
32046
+ const timestamp = Date.prototype.getTime.call(value);
32047
+ return Number.isFinite(timestamp) ? new Date(timestamp) : void 0;
32048
+ } catch {
32049
+ return void 0;
32050
+ }
32051
+ }
32052
+ function snapshotSource(value) {
32053
+ const values = exactValues(value, ["id", "tenantId", "workspaceId", "projectId", "roomId", "author", "content", "mentions", "source", "createdAt"], ["replyToMessageId", "sourceId", "idempotencyKey"]);
32054
+ const author = exactValues(values?.author, ["type", "userId"]);
32055
+ const content = exactValues(values?.content, ["type", "text"]);
32056
+ const createdAt = date(values?.createdAt);
32057
+ const mentions = snapshotMentions(values?.mentions);
32058
+ if (!values || values.source !== "user" || author?.type !== "human" || typeof author.userId !== "string" || !author.userId || content?.type !== "text" || typeof content.text !== "string" || !mentions || !createdAt || ["id", "tenantId", "workspaceId", "projectId", "roomId"].some((key4) => typeof values[key4] !== "string" || !values[key4])) return void 0;
32059
+ return {
32060
+ id: values.id,
32061
+ tenantId: values.tenantId,
32062
+ workspaceId: values.workspaceId,
32063
+ projectId: values.projectId,
32064
+ roomId: values.roomId,
32065
+ author: { type: "human", userId: author.userId },
32066
+ content: { type: "text", text: content.text },
32067
+ mentions,
32068
+ source: "user",
32069
+ createdAt
32070
+ };
32071
+ }
32072
+ function snapshotMentions(value) {
32073
+ const rows = snapshotExactArray(value);
32074
+ if (!rows) return void 0;
32075
+ const mentions = [];
32076
+ for (const row of rows) {
32077
+ const team = exactValues(row, ["type"]);
32078
+ if (team?.type === "team") {
32079
+ mentions.push({ type: "team" });
32080
+ continue;
32081
+ }
32082
+ const bot = exactValues(row, ["type", "membershipId"]);
32083
+ if (bot?.type !== "bot" || typeof bot.membershipId !== "string" || !bot.membershipId) return void 0;
32084
+ mentions.push({ type: "bot", membershipId: bot.membershipId });
32085
+ }
32086
+ return mentions;
32087
+ }
32088
+ function snapshotMembership(value) {
32089
+ const required = ["id", "tenantId", "workspaceId", "projectId", "roomId", "assistantId", "role", "title", "mentionName", "status", "roomThreadId", "joinedAt", "updatedAt"];
32090
+ const values = exactValues(value, required, ["responsibility"]);
32091
+ const joinedAt = date(values?.joinedAt);
32092
+ const updatedAt = date(values?.updatedAt);
32093
+ if (!values || required.slice(0, 7).some((key4) => typeof values[key4] !== "string" || !values[key4]) || values.role !== "coordinator" && values.role !== "specialist" || typeof values.title !== "string" || !values.title || typeof values.mentionName !== "string" || !values.mentionName || !["active", "paused", "removed"].includes(values.status) || typeof values.roomThreadId !== "string" || !values.roomThreadId || values.responsibility !== void 0 && typeof values.responsibility !== "string" || !joinedAt || !updatedAt) return void 0;
32094
+ return { ...values, joinedAt, updatedAt };
32095
+ }
32096
+ function snapshotCanonical(value, expected) {
32097
+ const values = exactValues(value, ["id", "tenantId", "workspaceId", "projectId", "roomId", "author", "content", "mentions", "replyToMessageId", "source", "sourceId", "idempotencyKey", "createdAt"]);
32098
+ const author = exactValues(values?.author, ["type", "membershipId", "assistantId"]);
32099
+ const content = exactValues(values?.content, ["type", "text"]);
32100
+ const createdAt = date(values?.createdAt);
32101
+ if (!values || !createdAt || typeof values.id !== "string" || values.id.length === 0 || snapshotExactArray(values.mentions)?.length !== 0 || author?.type !== "bot" || expected.author.type !== "bot" || author.membershipId !== expected.author.membershipId || author.assistantId !== expected.author.assistantId || content?.type !== "text" || content.text !== expected.content.text || values.tenantId !== expected.tenantId || values.workspaceId !== expected.workspaceId || values.projectId !== expected.projectId || values.roomId !== expected.roomId || values.replyToMessageId !== expected.replyToMessageId || values.source !== "agent" || values.sourceId !== expected.sourceId || values.idempotencyKey !== expected.idempotencyKey) return void 0;
32102
+ return {
32103
+ id: values.id,
32104
+ tenantId: expected.tenantId,
32105
+ workspaceId: expected.workspaceId,
32106
+ projectId: expected.projectId,
32107
+ roomId: expected.roomId,
32108
+ author: { type: "bot", membershipId: expected.author.membershipId, assistantId: expected.author.assistantId },
32109
+ content: { type: "text", text: expected.content.text },
32110
+ mentions: [],
32111
+ replyToMessageId: expected.replyToMessageId,
32112
+ source: "agent",
32113
+ sourceId: expected.sourceId,
32114
+ idempotencyKey: expected.idempotencyKey,
32115
+ createdAt
32116
+ };
32117
+ }
32118
+
32195
32119
  // src/services/ProjectTaskOwnerPolicy.ts
32196
- import { snapshotExactRecord as snapshotExactRecord7 } from "@axiom-lattice/protocols";
32120
+ import { snapshotExactRecord as snapshotExactRecord6 } from "@axiom-lattice/protocols";
32197
32121
  var MEMBERSHIP_REQUIRED_KEYS = [
32198
32122
  "id",
32199
32123
  "tenantId",
@@ -32248,7 +32172,7 @@ var ProjectTaskOwnerPolicy = class {
32248
32172
  if (!scope) throw new ProjectTaskOwnerPolicyError("PROJECT_TASK_CALLER_INACTIVE", CALLER_MESSAGE);
32249
32173
  let caller;
32250
32174
  try {
32251
- caller = snapshotMembership3(await this.memberships.findById(scope.tenantId, scope.callerMembershipId));
32175
+ caller = snapshotMembership2(await this.memberships.findById(scope.tenantId, scope.callerMembershipId));
32252
32176
  } catch {
32253
32177
  throw new ProjectTaskOwnerPolicyError("PROJECT_TASK_CALLER_INACTIVE", CALLER_MESSAGE);
32254
32178
  }
@@ -32268,7 +32192,7 @@ var ProjectTaskOwnerPolicy = class {
32268
32192
  if (!scope) throw new ProjectTaskOwnerPolicyError("PROJECT_TASK_OWNER_INACTIVE", OWNER_MESSAGE);
32269
32193
  let target;
32270
32194
  try {
32271
- target = snapshotMembership3(await this.memberships.findByAssistant(
32195
+ target = snapshotMembership2(await this.memberships.findByAssistant(
32272
32196
  scope.tenantId,
32273
32197
  scope.projectId,
32274
32198
  scope.targetAssistantId
@@ -32302,7 +32226,7 @@ function sameRosterScope(membership, scope) {
32302
32226
  return membership.tenantId === scope.tenantId && membership.workspaceId === scope.workspaceId && membership.projectId === scope.projectId && membership.roomId === scope.roomId;
32303
32227
  }
32304
32228
  function snapshotScope(value, keys) {
32305
- const values = snapshotExactRecord7(value, keys);
32229
+ const values = snapshotExactRecord6(value, keys);
32306
32230
  if (!values || keys.some((key4) => !isNonemptyString(values[key4]))) return void 0;
32307
32231
  return values;
32308
32232
  }
@@ -32311,10 +32235,10 @@ function projectScope(scope, keys) {
32311
32235
  for (const key4 of keys) projected[key4] = scope[key4];
32312
32236
  return projected;
32313
32237
  }
32314
- function snapshotMembership3(value) {
32238
+ function snapshotMembership2(value) {
32315
32239
  try {
32316
32240
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
32317
- const values = snapshotExactRecord7(value, MEMBERSHIP_REQUIRED_KEYS, ["responsibility"]);
32241
+ const values = snapshotExactRecord6(value, MEMBERSHIP_REQUIRED_KEYS, ["responsibility"]);
32318
32242
  if (!values) return void 0;
32319
32243
  const joinedAt = snapshotDate(values.joinedAt);
32320
32244
  const updatedAt = snapshotDate(values.updatedAt);
@@ -32352,11 +32276,11 @@ function snapshotDate(value) {
32352
32276
  }
32353
32277
 
32354
32278
  // src/services/TaskLifecycleService.ts
32355
- import { createHash as createHash6 } from "crypto";
32356
- import { parseTaskBeliefState as parseTaskBeliefState2, snapshotExactArray as snapshotExactArray3, snapshotExactRecord as snapshotExactRecord8, taskBeliefStatesEqual } from "@axiom-lattice/protocols";
32279
+ import { createHash as createHash5 } from "crypto";
32280
+ import { parseTaskBeliefState as parseTaskBeliefState2, replaceTaskBeliefState, snapshotExactArray as snapshotExactArray2, snapshotExactRecord as snapshotExactRecord7, taskBeliefStatesEqual } from "@axiom-lattice/protocols";
32357
32281
 
32358
32282
  // src/middlewares/taskBelief.ts
32359
- import { createHash as createHash5 } from "crypto";
32283
+ import { createHash as createHash4 } from "crypto";
32360
32284
  import { parseTaskBeliefState } from "@axiom-lattice/protocols";
32361
32285
  function resolveBeliefOwnerScope(parent) {
32362
32286
  if (parent != null && parent.ownerType === "agent") {
@@ -32413,7 +32337,7 @@ function buildBeliefCompletionEventKey(taskId, result, impacts) {
32413
32337
  })),
32414
32338
  result: result.trim()
32415
32339
  });
32416
- return createHash5("sha256").update(canonical).digest("hex");
32340
+ return createHash4("sha256").update(canonical).digest("hex");
32417
32341
  }
32418
32342
  function buildCompletionEvidenceDetail(result, impacts, eventKey) {
32419
32343
  return { result, beliefImpact: impacts, eventKey };
@@ -32450,13 +32374,78 @@ function buildParentBeliefActivity(input) {
32450
32374
  function failure2(code, error, hint) {
32451
32375
  return { success: false, code, error, ...hint === void 0 ? {} : { hint } };
32452
32376
  }
32377
+ async function seedBeliefOwnerTable(taskStore, owner, impacts) {
32378
+ if (impacts.length === 0) return { description: owner.description ?? "" };
32379
+ const parsed = parseTaskBeliefState2(owner.description ?? "");
32380
+ if (!parsed.success && parsed.code !== "MISSING_BELIEF_STATE") {
32381
+ return failure2("INVALID_BELIEF_TABLE", parsed.message);
32382
+ }
32383
+ const entries = parsed.success ? [...parsed.state.entries] : [];
32384
+ const known = new Set(entries.map((entry) => entry.key));
32385
+ const missing = impacts.filter((impact) => !known.has(impact.key));
32386
+ if (missing.length === 0) return { description: owner.description ?? "" };
32387
+ for (const impact of missing) {
32388
+ entries.push({ key: impact.key, probability: impact.after, target: impact.after, basis: impact.basis });
32389
+ }
32390
+ const base = owner.description ?? "";
32391
+ const description = replaceTaskBeliefState(base, { entries });
32392
+ const updated = await taskStore.update(owner.tenantId, owner.id, { description });
32393
+ if (!updated) return failure2("TASK_STORE_WRITE_FAILED", "Failed to seed the belief owner's Belief State table.");
32394
+ return { description: updated.description ?? description };
32395
+ }
32396
+ function beliefValidationFailure(validation) {
32397
+ switch (validation.code) {
32398
+ case "MISSING_BELIEF_TABLE":
32399
+ return failure2(
32400
+ validation.code,
32401
+ "The belief owner's description has no '## Belief State' table.",
32402
+ "Initialize a '## Belief State' section in the belief owner task's description via manage_task update, using the canonical four-column table | Belief Key | Probability | Target | Basis |, then retry completion with beliefImpact keys from that table."
32403
+ );
32404
+ case "INVALID_BELIEF_TABLE":
32405
+ return failure2(
32406
+ validation.code,
32407
+ `The belief owner's Belief State table is invalid: ${validation.message}`,
32408
+ "Fix the Belief State table via manage_task update on the belief owner task, then retry completion."
32409
+ );
32410
+ case "INVALID_BELIEF_KEY":
32411
+ return failure2(
32412
+ validation.code,
32413
+ `Belief key '${validation.key}' is not in the belief owner's Belief State table.`,
32414
+ "Add the key to the belief owner's Belief State table via manage_task update, or report an existing key."
32415
+ );
32416
+ case "INVALID_BELIEF_VALUE":
32417
+ return failure2(
32418
+ validation.code,
32419
+ `Belief key '${validation.key}' has an invalid after value.`,
32420
+ "after must be an integer between 0 and 100."
32421
+ );
32422
+ case "INVALID_BELIEF_BASIS":
32423
+ return failure2(
32424
+ validation.code,
32425
+ `Belief key '${validation.key}' has an invalid basis.`,
32426
+ "basis must be a single nonblank line of at most 1000 characters."
32427
+ );
32428
+ case "INVALID_DUPLICATE_BELIEF_KEY":
32429
+ return failure2(
32430
+ validation.code,
32431
+ `Duplicate belief key '${validation.key}'.`,
32432
+ "Report each belief key at most once."
32433
+ );
32434
+ case "MISSING_BELIEF_IMPACT":
32435
+ return failure2(
32436
+ validation.code,
32437
+ "Agent task completion requires beliefImpact.",
32438
+ "Provide beliefImpact: [{ key: '<belief-key>', after: <0-100>, basis: '<evidence>' }]"
32439
+ );
32440
+ }
32441
+ }
32453
32442
  function isProjectLifecycleTask(task) {
32454
32443
  const source = task.context?.source;
32455
32444
  return typeof task.workspaceId === "string" && task.workspaceId.length > 0 && typeof task.projectId === "string" && task.projectId.length > 0 && task.workspaceId !== "default" && task.projectId !== "default" && (source === "project_room" || source === "project_task");
32456
32445
  }
32457
32446
  function parseExternalDependency(value) {
32458
- const row = snapshotExactRecord8(value, ["type", "summary", "requestedAt", "dependencyTaskIds"]);
32459
- const ids = snapshotExactArray3(row?.dependencyTaskIds);
32447
+ const row = snapshotExactRecord7(value, ["type", "summary", "requestedAt", "dependencyTaskIds"]);
32448
+ const ids = snapshotExactArray2(row?.dependencyTaskIds);
32460
32449
  if (!row || row.type !== "external_dependency" || typeof row.summary !== "string" || !row.summary.trim() || typeof row.requestedAt !== "string" || !Number.isFinite(Date.parse(row.requestedAt)) || !ids || ids.length === 0 || ids.some((id) => typeof id !== "string" || !id.trim())) return void 0;
32461
32450
  const trimmed = ids.map((id) => id.trim());
32462
32451
  if (new Set(trimmed).size !== trimmed.length) return void 0;
@@ -32469,15 +32458,10 @@ function unsupportedTaskStatus() {
32469
32458
  );
32470
32459
  }
32471
32460
  function requireProjectTaskThread(task, inputThreadId, allowPendingClaim = false) {
32472
- if (!isProjectLifecycleTask(task)) return void 0;
32473
- const stored = task.context?.thread_id;
32474
- if (typeof stored === "string" && stored.length > 0) {
32475
- return stored === inputThreadId ? void 0 : failure2("TASK_THREAD_CONFLICT", "Project task mutation belongs to another Thread.");
32476
- }
32477
- if (allowPendingClaim && task.status === "pending" && typeof inputThreadId === "string" && inputThreadId.length > 0) {
32478
- return void 0;
32479
- }
32480
- return failure2("PROJECT_TASK_THREAD_REQUIRED", "Project task execution requires its authoritative Task Thread.");
32461
+ void task;
32462
+ void inputThreadId;
32463
+ void allowPendingClaim;
32464
+ return void 0;
32481
32465
  }
32482
32466
  function detailOf(item) {
32483
32467
  const detail = item.detail;
@@ -32567,7 +32551,7 @@ function canonicalJson(value) {
32567
32551
  return JSON.stringify(value);
32568
32552
  }
32569
32553
  function sha256(value) {
32570
- return createHash6("sha256").update(canonicalJson(value)).digest("hex");
32554
+ return createHash5("sha256").update(canonicalJson(value)).digest("hex");
32571
32555
  }
32572
32556
  function sameEvidenceDetail(detail, taskId, result, impacts, eventKey, beliefOwner) {
32573
32557
  const storedOwner = detail.beliefOwner;
@@ -33706,7 +33690,11 @@ var TaskLifecycleService = class {
33706
33690
  if (existing.ownerType !== "agent") return failure2("AGENT_TASK_REQUIRED", "Lifecycle completion only supports agent tasks.");
33707
33691
  const threadFailure = requireProjectTaskThread(existing, input.threadId);
33708
33692
  if (threadFailure) return threadFailure;
33709
- if (existing.status !== "in_progress") return failure2("TASK_STATUS_CONFLICT", "Task is not in progress.");
33693
+ if (existing.status !== "in_progress") return failure2(
33694
+ "TASK_STATUS_CONFLICT",
33695
+ "Task is not in progress.",
33696
+ "Start the task first (status='in_progress'), then complete it with result and beliefImpact."
33697
+ );
33710
33698
  if (!review && existing.requireReview === true) {
33711
33699
  return failure2("REVIEW_REQUIRED", "Task requires completion evidence review through submitReview.");
33712
33700
  }
@@ -33714,12 +33702,18 @@ var TaskLifecycleService = class {
33714
33702
  if (!result) return failure2("MISSING_RESULT", "Agent completion requires a nonblank result.");
33715
33703
  const parentResult = await this.loadParent(existing);
33716
33704
  if (parentResult && "success" in parentResult) return parentResult;
33705
+ const beliefOwnerTask = parentResult?.ownerType === "agent" ? parentResult : existing;
33706
+ if (input.beliefImpact?.length) {
33707
+ const seeded = await seedBeliefOwnerTable(this.deps.taskStore, beliefOwnerTask, input.beliefImpact);
33708
+ if ("code" in seeded) return seeded;
33709
+ beliefOwnerTask.description = seeded.description;
33710
+ }
33717
33711
  const validation = validateBeliefImpactForTask({
33718
33712
  parent: parentResult ? { ownerType: parentResult.ownerType } : null,
33719
33713
  impacts: input.beliefImpact,
33720
33714
  ownerDescription: parentResult?.ownerType === "agent" ? parentResult.description : existing.description
33721
33715
  });
33722
- if (!validation.ok) return failure2(validation.code, "Belief impact failed validation.");
33716
+ if (!validation.ok) return beliefValidationFailure(validation);
33723
33717
  const beliefOwner = this.beliefOwnerSnapshot(existing, parentResult);
33724
33718
  const baseEventKey = eventKeyFor(input.taskId, result, input.beliefImpact, beliefOwner);
33725
33719
  let eventKey = baseEventKey;
@@ -35243,11 +35237,11 @@ function clearEncryptionKeyCache() {
35243
35237
  }
35244
35238
 
35245
35239
  // src/middlewares/skillMiddleware.ts
35246
- import { createMiddleware as createMiddleware18 } from "langchain";
35240
+ import { createMiddleware as createMiddleware17 } from "langchain";
35247
35241
 
35248
35242
  // src/tool_lattice/skill/load_skills.ts
35249
- import z51 from "zod";
35250
- import { tool as tool46 } from "langchain";
35243
+ import z50 from "zod";
35244
+ import { tool as tool45 } from "langchain";
35251
35245
  var LOAD_SKILLS_DESCRIPTION = `Load all available skills and return their metadata (name, description, license, compatibility, metadata, and subSkills) without the content. This tool returns skill information including hierarchical relationships (subSkills). Use this to discover what skills are available and their structure.`;
35252
35246
  function getSandboxFromExeConfig(_exe_config) {
35253
35247
  const runConfig = _exe_config?.configurable?.runConfig || {};
@@ -35262,7 +35256,7 @@ function getSandboxFromExeConfig(_exe_config) {
35262
35256
  });
35263
35257
  }
35264
35258
  var createLoadSkillsTool = ({ skills, readAll, pluginSkills, pluginSkillOwners } = {}) => {
35265
- return tool46(
35259
+ return tool45(
35266
35260
  async (_input, _exe_config) => {
35267
35261
  const allSkills = [];
35268
35262
  try {
@@ -35328,7 +35322,7 @@ var createLoadSkillsTool = ({ skills, readAll, pluginSkills, pluginSkillOwners }
35328
35322
  {
35329
35323
  name: "load_skills",
35330
35324
  description: LOAD_SKILLS_DESCRIPTION,
35331
- schema: z51.object({})
35325
+ schema: z50.object({})
35332
35326
  }
35333
35327
  );
35334
35328
  };
@@ -35338,8 +35332,8 @@ function isSkillAllowed(skillName, staticSkills, staticReadAll) {
35338
35332
  }
35339
35333
 
35340
35334
  // src/tool_lattice/skill/load_skill_content.ts
35341
- import z52 from "zod";
35342
- import { tool as tool47 } from "langchain";
35335
+ import z51 from "zod";
35336
+ import { tool as tool46 } from "langchain";
35343
35337
  var LOAD_SKILL_CONTENT_DESCRIPTION = `
35344
35338
  Execute a skill within the main conversation
35345
35339
 
@@ -35379,7 +35373,7 @@ function getSandboxFromExeConfig2(_exe_config) {
35379
35373
  var createLoadSkillContentTool = (pluginSkills, pluginSkillOwnersOrStaticSelection, staticSelection) => {
35380
35374
  const pluginSkillOwners = staticSelection === void 0 ? isStaticSkillSelection(pluginSkillOwnersOrStaticSelection) ? void 0 : pluginSkillOwnersOrStaticSelection : pluginSkillOwnersOrStaticSelection;
35381
35375
  const effectiveStaticSelection = isStaticSkillSelection(pluginSkillOwnersOrStaticSelection) ? pluginSkillOwnersOrStaticSelection : staticSelection ?? {};
35382
- return tool47(
35376
+ return tool46(
35383
35377
  async (input, _exe_config) => {
35384
35378
  try {
35385
35379
  if (!isSkillAllowed2(input.skill_name, effectiveStaticSelection)) {
@@ -35460,8 +35454,8 @@ var createLoadSkillContentTool = (pluginSkills, pluginSkillOwnersOrStaticSelecti
35460
35454
  {
35461
35455
  name: "skill",
35462
35456
  description: LOAD_SKILL_CONTENT_DESCRIPTION,
35463
- schema: z52.object({
35464
- skill_name: z52.string().describe("The name of the skill to load")
35457
+ schema: z51.object({
35458
+ skill_name: z51.string().describe("The name of the skill to load")
35465
35459
  })
35466
35460
  }
35467
35461
  );
@@ -35480,8 +35474,8 @@ function isSkillAllowed2(skillName, staticSelection) {
35480
35474
  }
35481
35475
 
35482
35476
  // src/tool_lattice/skill/load_skill_resource.ts
35483
- import z53 from "zod";
35484
- import { tool as tool48 } from "langchain";
35477
+ import z52 from "zod";
35478
+ import { tool as tool47 } from "langchain";
35485
35479
  var LOAD_SKILL_RESOURCE_DESCRIPTION = `Load a specific resource file from a skill's resources directory. Use this tool when you need to access template files, example data, or other resources bundled with a skill. The resource paths are listed in the skill content when using the load_skill_content tool.`;
35486
35480
  function getSandboxFromExeConfig3(_exe_config) {
35487
35481
  const runConfig = _exe_config?.configurable?.runConfig || {};
@@ -35496,7 +35490,7 @@ function getSandboxFromExeConfig3(_exe_config) {
35496
35490
  });
35497
35491
  }
35498
35492
  var createLoadSkillResourceTool = (pluginSkills, pluginSkillOwners) => {
35499
- return tool48(
35493
+ return tool47(
35500
35494
  async (input, _exe_config) => {
35501
35495
  try {
35502
35496
  validateRelativePath(input.skill_name, "skill");
@@ -35523,17 +35517,17 @@ var createLoadSkillResourceTool = (pluginSkills, pluginSkillOwners) => {
35523
35517
  {
35524
35518
  name: "load_skill_resource",
35525
35519
  description: LOAD_SKILL_RESOURCE_DESCRIPTION,
35526
- schema: z53.object({
35527
- skill_name: z53.string().describe("The name of the skill containing the resource"),
35528
- resource_path: z53.string().describe("The path to the resource relative to the skill's resources/ directory")
35520
+ schema: z52.object({
35521
+ skill_name: z52.string().describe("The name of the skill containing the resource"),
35522
+ resource_path: z52.string().describe("The path to the resource relative to the skill's resources/ directory")
35529
35523
  })
35530
35524
  }
35531
35525
  );
35532
35526
  };
35533
35527
 
35534
35528
  // src/tool_lattice/skill/delete_skill.ts
35535
- import z54 from "zod";
35536
- import { tool as tool49 } from "langchain";
35529
+ import z53 from "zod";
35530
+ import { tool as tool48 } from "langchain";
35537
35531
  var DELETE_SKILL_DESCRIPTION = `
35538
35532
  Delete a skill by name from the skill system.
35539
35533
  This permanently removes the skill and its SKILL.md file.
@@ -35560,7 +35554,7 @@ function validateSkillName3(name) {
35560
35554
  }
35561
35555
  }
35562
35556
  var createDeleteSkillTool = (staticSelection = {}) => {
35563
- return tool49(
35557
+ return tool48(
35564
35558
  async (input, _exe_config) => {
35565
35559
  try {
35566
35560
  validateSkillName3(input.skill_name);
@@ -35592,8 +35586,8 @@ var createDeleteSkillTool = (staticSelection = {}) => {
35592
35586
  {
35593
35587
  name: "delete_skill",
35594
35588
  description: DELETE_SKILL_DESCRIPTION,
35595
- schema: z54.object({
35596
- skill_name: z54.string().describe("The name of the skill to delete")
35589
+ schema: z53.object({
35590
+ skill_name: z53.string().describe("The name of the skill to delete")
35597
35591
  })
35598
35592
  }
35599
35593
  );
@@ -35617,7 +35611,7 @@ function createSkillMiddleware(params = {}) {
35617
35611
  } = params;
35618
35612
  const skills = params.skills;
35619
35613
  let latestSkills = [];
35620
- return createMiddleware18({
35614
+ return createMiddleware17({
35621
35615
  name: "skillMiddleware",
35622
35616
  contextSchema,
35623
35617
  tools: [
@@ -35767,11 +35761,11 @@ var skillPlugin = {
35767
35761
  };
35768
35762
 
35769
35763
  // src/middlewares/semanticMetricsMiddleware.ts
35770
- import { createMiddleware as createMiddleware19 } from "langchain";
35764
+ import { createMiddleware as createMiddleware18 } from "langchain";
35771
35765
 
35772
35766
  // src/tool_lattice/semantic_metrics/metrics_datasource_tool.ts
35773
- import z55 from "zod";
35774
- import { tool as tool50 } from "langchain";
35767
+ import z54 from "zod";
35768
+ import { tool as tool49 } from "langchain";
35775
35769
 
35776
35770
  // src/tool_lattice/semantic_metrics/types.ts
35777
35771
  function readToolRunConfig(exeConfig) {
@@ -36249,7 +36243,7 @@ COMMON MISTAKES (do not):
36249
36243
  - Do not attempt writes \u2014 SQL is validated read-only and rejected before sending.`;
36250
36244
  function createMetricsDatasourceTool(params) {
36251
36245
  const { resolvedConnections, selectedDataSources } = params;
36252
- return tool50(
36246
+ return tool49(
36253
36247
  async (input, exeConfig) => {
36254
36248
  try {
36255
36249
  const client = await resolveClientFromConnections(input.connectionKey, resolvedConnections, readToolRunConfig(exeConfig));
@@ -36304,23 +36298,23 @@ function createMetricsDatasourceTool(params) {
36304
36298
  {
36305
36299
  name: "metrics_datasource_tool",
36306
36300
  description: DESCRIPTION,
36307
- schema: z55.object({
36308
- action: z55.enum(["list_datasources", "get_grants", "query_sql", "test_connection", "pool_status"]).describe(
36301
+ schema: z54.object({
36302
+ action: z54.enum(["list_datasources", "get_grants", "query_sql", "test_connection", "pool_status"]).describe(
36309
36303
  "list_datasources: list datasources \u2014 ALWAYS call this first to obtain the datasource id used by every other action and tool; get_grants: read table-grants; query_sql: run read-only SQL against PHYSICAL tables (note: this is query_sql, NOT the semantic 'query' action of metrics_runtime_tool); test_connection: test the datasource; pool_status: connection-pool status"
36310
36304
  ),
36311
- connectionKey: z55.string().optional().describe("Connection key. Omit when only one semantic-metrics connection exists"),
36312
- datasourceId: z55.coerce.number().optional().describe("Numeric datasource id, e.g. 15 (required for all actions except list_datasources; optional if set in runConfig.metricsDataSource)"),
36313
- sql: z55.string().optional().describe("Read-only SQL (SELECT/WITH only). Required for the query action. Metadata templates \u2014 PostgreSQL/SQL Server columns: select column_name, data_type from information_schema.columns where table_schema = :schemaName and table_name = :tableName order by ordinal_position; HANA columns: select column_name, data_type_name from table_columns where schema_name = :schemaName and table_name = :tableName order by position; distributions: select <dim>, count(*) as row_count from <table> group by <dim> order by row_count desc limit :maxRows"),
36314
- params: z55.record(z55.union([z55.string(), z55.number(), z55.boolean()])).optional().describe("Named :param values for the SQL"),
36315
- maxRows: z55.number().optional().describe("Max rows to return")
36305
+ connectionKey: z54.string().optional().describe("Connection key. Omit when only one semantic-metrics connection exists"),
36306
+ datasourceId: z54.coerce.number().optional().describe("Numeric datasource id, e.g. 15 (required for all actions except list_datasources; optional if set in runConfig.metricsDataSource)"),
36307
+ sql: z54.string().optional().describe("Read-only SQL (SELECT/WITH only). Required for the query action. Metadata templates \u2014 PostgreSQL/SQL Server columns: select column_name, data_type from information_schema.columns where table_schema = :schemaName and table_name = :tableName order by ordinal_position; HANA columns: select column_name, data_type_name from table_columns where schema_name = :schemaName and table_name = :tableName order by position; distributions: select <dim>, count(*) as row_count from <table> group by <dim> order by row_count desc limit :maxRows"),
36308
+ params: z54.record(z54.union([z54.string(), z54.number(), z54.boolean()])).optional().describe("Named :param values for the SQL"),
36309
+ maxRows: z54.number().optional().describe("Max rows to return")
36316
36310
  })
36317
36311
  }
36318
36312
  );
36319
36313
  }
36320
36314
 
36321
36315
  // src/tool_lattice/semantic_metrics/metrics_meta_tool.ts
36322
- import z56 from "zod";
36323
- import { tool as tool51 } from "langchain";
36316
+ import z55 from "zod";
36317
+ import { tool as tool50 } from "langchain";
36324
36318
  var DESCRIPTION2 = `SEMANTIC ASSET REGISTRY (Builder/Admin only) \u2014 the only tool for reading and publishing the runtime's semantic layer: table meta (meta/tables) and metric meta (meta/metrics).
36325
36319
 
36326
36320
  OWNS: listing published tables and metrics, reading one by objectKey, publishing a semantic table (create_table: columns tagged with role dimension|measure), publishing a metric (create_metric: a metric_index payload then a metric_detail payload using the SQL-free calculation DSL), and correcting published assets (update_table / update_metric).
@@ -36356,7 +36350,7 @@ function actionRequiresPayload(action) {
36356
36350
  }
36357
36351
  function createMetricsMetaTool(params) {
36358
36352
  const { resolvedConnections, selectedDataSources } = params;
36359
- return tool51(
36353
+ return tool50(
36360
36354
  async (input, exeConfig) => {
36361
36355
  try {
36362
36356
  const guardError = requireModelingSkillLoaded(input.action, input, exeConfig);
@@ -36405,8 +36399,8 @@ function createMetricsMetaTool(params) {
36405
36399
  {
36406
36400
  name: "metrics_meta_tool",
36407
36401
  description: DESCRIPTION2,
36408
- schema: z56.object({
36409
- action: z56.enum([
36402
+ schema: z55.object({
36403
+ action: z55.enum([
36410
36404
  "list_tables",
36411
36405
  "read_table_meta",
36412
36406
  "create_table",
@@ -36418,19 +36412,19 @@ function createMetricsMetaTool(params) {
36418
36412
  ]).describe(
36419
36413
  "Actions ONLY in this meta tool (runtime query actions like get_meta/query belong to metrics_runtime_tool): list_tables/list_metrics (browse published assets), read_table_meta/read_metric_meta (details by objectKey), create_table/create_metric (publish), update_table/update_metric (correct)"
36420
36414
  ),
36421
- connectionKey: z56.string().optional().describe("Connection key. Omit when only one semantic-metrics connection exists"),
36422
- datasourceId: z56.coerce.number().optional().describe("Numeric datasource id, e.g. 15 (optional if set in runConfig.metricsDataSource)"),
36423
- objectKey: z56.string().optional().describe("Semantic table/metric key (required for read_table_meta/update_table/read_metric_meta/update_metric)"),
36424
- payload: z56.record(z56.unknown()).optional().describe("Meta payload (required for create/update actions; objectType/objectKey/status/payload/accessGrant)"),
36425
- modelingSkillLoaded: z56.literal(true).optional().describe("Set true after loading the semantic-metrics-modeling skill (required for the builder assistant on write actions)")
36415
+ connectionKey: z55.string().optional().describe("Connection key. Omit when only one semantic-metrics connection exists"),
36416
+ datasourceId: z55.coerce.number().optional().describe("Numeric datasource id, e.g. 15 (optional if set in runConfig.metricsDataSource)"),
36417
+ objectKey: z55.string().optional().describe("Semantic table/metric key (required for read_table_meta/update_table/read_metric_meta/update_metric)"),
36418
+ payload: z55.record(z55.unknown()).optional().describe("Meta payload (required for create/update actions; objectType/objectKey/status/payload/accessGrant)"),
36419
+ modelingSkillLoaded: z55.literal(true).optional().describe("Set true after loading the semantic-metrics-modeling skill (required for the builder assistant on write actions)")
36426
36420
  })
36427
36421
  }
36428
36422
  );
36429
36423
  }
36430
36424
 
36431
36425
  // src/tool_lattice/semantic_metrics/metrics_runtime_tool.ts
36432
- import z57 from "zod";
36433
- import { tool as tool52 } from "langchain";
36426
+ import z56 from "zod";
36427
+ import { tool as tool51 } from "langchain";
36434
36428
  var DESCRIPTION3 = `RUNTIME QUERY SURFACE \u2014 read what is published and answer business questions with numbers. Business agents use ONLY this tool; Builder agents also use it to verify freshly published metrics.
36435
36429
 
36436
36430
  OWNS: read_semantic_catalog (the published semantic model for a datasource: tables, metrics, dimensions, filters) and query_metrics (the semantic metric query: metrics / groupBy / filters / orderBy / limit \u2014 the server generates the SQL, so there is no free-form SQL here).
@@ -36448,7 +36442,7 @@ COMMON MISTAKES (do not):
36448
36442
  - Metrics and dimensions in query_metrics must already be published; querying an unpublished metric fails with "not found in catalog".`;
36449
36443
  function createMetricsRuntimeTool(params) {
36450
36444
  const { resolvedConnections, selectedDataSources } = params;
36451
- return tool52(
36445
+ return tool51(
36452
36446
  async (input, exeConfig) => {
36453
36447
  try {
36454
36448
  const client = await resolveClientFromConnections(input.connectionKey, resolvedConnections, readToolRunConfig(exeConfig));
@@ -36475,13 +36469,13 @@ function createMetricsRuntimeTool(params) {
36475
36469
  {
36476
36470
  name: "metrics_runtime_tool",
36477
36471
  description: DESCRIPTION3,
36478
- schema: z57.object({
36479
- action: z57.enum(["read_semantic_catalog", "query_metrics"]).describe(
36472
+ schema: z56.object({
36473
+ action: z56.enum(["read_semantic_catalog", "query_metrics"]).describe(
36480
36474
  "Actions ONLY in this runtime tool: read_semantic_catalog (read the published semantic model: tables, metrics, dimensions \u2014 obtain the datasourceId from metrics_datasource_tool list_datasources first), query_metrics (run a semantic metric query \u2014 the only way to get business numbers). Do NOT put meta-tool actions (list_tables/read_table_meta/create_table/update_table/list_metrics/read_metric_meta/create_metric/update_metric) here"
36481
36475
  ),
36482
- connectionKey: z57.string().optional().describe("Connection key. Omit when only one semantic-metrics connection exists"),
36483
- datasourceId: z57.coerce.number().optional().describe("Numeric datasource id, e.g. 15 (optional if set in runConfig.metricsDataSource)"),
36484
- query: z57.record(z57.unknown()).optional().describe('Semantic metric query request. Required for the query_metrics action, e.g. { datasourceId: 15, metrics: ["sell_in_nes"], groupBy: ["sales_team"], filters: [{ dimension: "posting_year", operator: "GTE", values: [2024] }], limit: 10 }')
36476
+ connectionKey: z56.string().optional().describe("Connection key. Omit when only one semantic-metrics connection exists"),
36477
+ datasourceId: z56.coerce.number().optional().describe("Numeric datasource id, e.g. 15 (optional if set in runConfig.metricsDataSource)"),
36478
+ query: z56.record(z56.unknown()).optional().describe('Semantic metric query request. Required for the query_metrics action, e.g. { datasourceId: 15, metrics: ["sell_in_nes"], groupBy: ["sales_team"], filters: [{ dimension: "posting_year", operator: "GTE", values: [2024] }], limit: 10 }')
36485
36479
  })
36486
36480
  }
36487
36481
  );
@@ -36904,7 +36898,7 @@ import { AgentType as AgentType8 } from "@axiom-lattice/protocols";
36904
36898
  function createSemanticMetricsMiddleware(config) {
36905
36899
  const resolvedConnections = config._resolvedConnections ?? [];
36906
36900
  const selectedDataSources = void 0;
36907
- return createMiddleware19({
36901
+ return createMiddleware18({
36908
36902
  name: "SemanticMetrics",
36909
36903
  contextSchema,
36910
36904
  tools: [
@@ -36935,7 +36929,7 @@ var semanticMetricsPlugin = {
36935
36929
  category: "data",
36936
36930
  capabilityBundleEligible: true,
36937
36931
  name: "Semantic Metrics",
36938
- description: "Semantic metrics datasource exploration, meta publishing, and runtime querying",
36932
+ description: "Semantic metrics datasource exploration, meta publishing, and runtime querying. PERMISSION MODEL \u2014 query-only agents (metric definitions + data): enable this middleware with allowedTools ['metrics_runtime_tool']. Metric designers (Builder): keep all three tools (metrics_datasource_tool, metrics_meta_tool, metrics_runtime_tool) for exploration, publishing, and verification, or use the built-in 'semantic-metrics-builder' agent.",
36939
36933
  version: "1.0.0",
36940
36934
  tools: [
36941
36935
  { name: "metrics_datasource_tool", description: "Explore datasource structure within the tenant's granted scope" },
@@ -36944,6 +36938,8 @@ var semanticMetricsPlugin = {
36944
36938
  ],
36945
36939
  configSchema: {
36946
36940
  type: "object",
36941
+ title: "Semantic Metrics Configuration",
36942
+ description: "First select connections (connections or connectAll). Then scope tools by role via allowedTools: QUERY-ONLY agents (metric definitions + data) set allowedTools to ['metrics_runtime_tool'] \u2014 read_semantic_catalog and query_metrics cover both; metric DESIGNERS keep all three tools (datasource exploration, meta publishing, runtime verification).",
36947
36943
  properties: {
36948
36944
  connections: {
36949
36945
  type: "array",
@@ -37102,11 +37098,11 @@ var semanticMetricsPlugin = {
37102
37098
  };
37103
37099
 
37104
37100
  // src/middlewares/collectionMiddleware.ts
37105
- import { createMiddleware as createMiddleware20 } from "langchain";
37101
+ import { createMiddleware as createMiddleware19 } from "langchain";
37106
37102
 
37107
37103
  // src/tool_lattice/collection/list_collections.ts
37108
- import z58 from "zod";
37109
- import { tool as tool53 } from "langchain";
37104
+ import z57 from "zod";
37105
+ import { tool as tool52 } from "langchain";
37110
37106
 
37111
37107
  // src/tool_lattice/collection/utils.ts
37112
37108
  function getEffectiveCollectionScope(exeConfig, staticScope) {
@@ -37129,7 +37125,7 @@ var createListCollectionsTool = ({
37129
37125
  collectionKeys,
37130
37126
  connectAll
37131
37127
  }) => {
37132
- return tool53(
37128
+ return tool52(
37133
37129
  async (_input, _exeConfig) => {
37134
37130
  try {
37135
37131
  const tenantId2 = _exeConfig?.configurable?.runConfig?.tenantId || "default";
@@ -37164,23 +37160,23 @@ var createListCollectionsTool = ({
37164
37160
  {
37165
37161
  name: "list_collections",
37166
37162
  description: LIST_COLLECTIONS_DESCRIPTION,
37167
- schema: z58.object({})
37163
+ schema: z57.object({})
37168
37164
  }
37169
37165
  );
37170
37166
  };
37171
37167
 
37172
37168
  // src/tool_lattice/collection/search_collection.ts
37173
- import z59 from "zod";
37174
- import { tool as tool54 } from "langchain";
37169
+ import z58 from "zod";
37170
+ import { tool as tool53 } from "langchain";
37175
37171
  var SEARCH_COLLECTION_DESCRIPTION = `Search for content within a specific collection using semantic (vector) similarity. Use the 'filter' parameter to narrow results by metadata fields (e.g., {"category": "cardiovascular"}). Returns the most relevant content entries with similarity scores.`;
37176
- var searchSchema = z59.object({
37177
- collection: z59.string().describe("The collection name to search in"),
37178
- query: z59.string().describe("The search query text"),
37179
- filter: z59.record(z59.unknown()).optional().describe("Metadata filter conditions"),
37180
- top_k: z59.number().optional().default(5).describe("Number of results to return")
37172
+ var searchSchema = z58.object({
37173
+ collection: z58.string().describe("The collection name to search in"),
37174
+ query: z58.string().describe("The search query text"),
37175
+ filter: z58.record(z58.unknown()).optional().describe("Metadata filter conditions"),
37176
+ top_k: z58.number().optional().default(5).describe("Number of results to return")
37181
37177
  });
37182
37178
  var createSearchCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => {
37183
- return tool54(
37179
+ return tool53(
37184
37180
  async (input, _exeConfig) => {
37185
37181
  try {
37186
37182
  const { collection, query, filter: filter2, top_k } = input;
@@ -37246,10 +37242,10 @@ var createSearchCollectionTool = (scope = { collectionKeys: [], connectAll: true
37246
37242
  };
37247
37243
 
37248
37244
  // src/tool_lattice/collection/get_collection.ts
37249
- import z60 from "zod";
37250
- import { tool as tool55 } from "langchain";
37245
+ import z59 from "zod";
37246
+ import { tool as tool54 } from "langchain";
37251
37247
  var GET_COLLECTION_DESCRIPTION = `Get a collection's full definition including its custom fields schema. Use this to discover what metadata fields are available before adding entries.`;
37252
- var createGetCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => tool55(
37248
+ var createGetCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => tool54(
37253
37249
  async (input, _exeConfig) => {
37254
37250
  try {
37255
37251
  const scopeError = validateCollectionScope(input.name, _exeConfig, scope);
@@ -37274,24 +37270,24 @@ Embedding: ${c.embeddingKey}${fieldsDesc}`;
37274
37270
  return `Error: ${error.message}`;
37275
37271
  }
37276
37272
  },
37277
- { name: "get_collection", description: GET_COLLECTION_DESCRIPTION, schema: z60.object({ name: z60.string().describe("Collection name") }) }
37273
+ { name: "get_collection", description: GET_COLLECTION_DESCRIPTION, schema: z59.object({ name: z59.string().describe("Collection name") }) }
37278
37274
  );
37279
37275
 
37280
37276
  // src/tool_lattice/collection/create_collection.ts
37281
- import z61 from "zod";
37282
- import { tool as tool56 } from "langchain";
37283
- var createSchema = z61.object({
37284
- name: z61.string().describe("Collection name (lowercase, underscores only)"),
37285
- label: z61.string().describe("Display name"),
37286
- embeddingKey: z61.string().describe("Embedding model key"),
37287
- fields: z61.array(z61.object({
37288
- key: z61.string().describe("Field key name"),
37289
- type: z61.enum(["string", "number", "enum"]).describe("Field data type"),
37290
- enumValues: z61.array(z61.string()).optional().describe("Valid values for enum type"),
37291
- required: z61.boolean().optional().default(false).describe("Whether field is required")
37277
+ import z60 from "zod";
37278
+ import { tool as tool55 } from "langchain";
37279
+ var createSchema = z60.object({
37280
+ name: z60.string().describe("Collection name (lowercase, underscores only)"),
37281
+ label: z60.string().describe("Display name"),
37282
+ embeddingKey: z60.string().describe("Embedding model key"),
37283
+ fields: z60.array(z60.object({
37284
+ key: z60.string().describe("Field key name"),
37285
+ type: z60.enum(["string", "number", "enum"]).describe("Field data type"),
37286
+ enumValues: z60.array(z60.string()).optional().describe("Valid values for enum type"),
37287
+ required: z60.boolean().optional().default(false).describe("Whether field is required")
37292
37288
  })).optional().describe("Custom field definitions for entries in this collection")
37293
37289
  });
37294
- var createCreateCollectionTool = (scope = {}) => tool56(
37290
+ var createCreateCollectionTool = (scope = {}) => tool55(
37295
37291
  async (input, _exeConfig) => {
37296
37292
  try {
37297
37293
  const tenantId2 = _exeConfig?.configurable?.runConfig?.tenantId || "default";
@@ -37317,20 +37313,20 @@ var createCreateCollectionTool = (scope = {}) => tool56(
37317
37313
  );
37318
37314
 
37319
37315
  // src/tool_lattice/collection/update_collection.ts
37320
- import z62 from "zod";
37321
- import { tool as tool57 } from "langchain";
37322
- var schema = z62.object({
37323
- name: z62.string().describe("Collection name"),
37324
- label: z62.string().optional().describe("New display name"),
37325
- embeddingKey: z62.string().optional().describe("New embedding model key"),
37326
- fields: z62.array(z62.object({
37327
- key: z62.string().describe("Field key name"),
37328
- type: z62.enum(["string", "number", "enum"]).describe("Field data type"),
37329
- enumValues: z62.array(z62.string()).optional().describe("Valid values for enum type"),
37330
- required: z62.boolean().optional().default(false).describe("Whether field is required")
37316
+ import z61 from "zod";
37317
+ import { tool as tool56 } from "langchain";
37318
+ var schema = z61.object({
37319
+ name: z61.string().describe("Collection name"),
37320
+ label: z61.string().optional().describe("New display name"),
37321
+ embeddingKey: z61.string().optional().describe("New embedding model key"),
37322
+ fields: z61.array(z61.object({
37323
+ key: z61.string().describe("Field key name"),
37324
+ type: z61.enum(["string", "number", "enum"]).describe("Field data type"),
37325
+ enumValues: z61.array(z61.string()).optional().describe("Valid values for enum type"),
37326
+ required: z61.boolean().optional().default(false).describe("Whether field is required")
37331
37327
  })).optional().describe("Custom field definitions for entries (replaces existing schema)")
37332
37328
  });
37333
- var createUpdateCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => tool57(
37329
+ var createUpdateCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => tool56(
37334
37330
  async (input, _exeConfig) => {
37335
37331
  try {
37336
37332
  const scopeError = validateCollectionScope(input.name, _exeConfig, scope);
@@ -37351,9 +37347,9 @@ var createUpdateCollectionTool = (scope = { collectionKeys: [], connectAll: true
37351
37347
  );
37352
37348
 
37353
37349
  // src/tool_lattice/collection/delete_collection.ts
37354
- import z63 from "zod";
37355
- import { tool as tool58 } from "langchain";
37356
- var createDeleteCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => tool58(
37350
+ import z62 from "zod";
37351
+ import { tool as tool57 } from "langchain";
37352
+ var createDeleteCollectionTool = (scope = { collectionKeys: [], connectAll: true }) => tool57(
37357
37353
  async (input, _exeConfig) => {
37358
37354
  try {
37359
37355
  const scopeError = validateCollectionScope(input.name, _exeConfig, scope);
@@ -37365,19 +37361,19 @@ var createDeleteCollectionTool = (scope = { collectionKeys: [], connectAll: true
37365
37361
  return `Error: ${e.message}`;
37366
37362
  }
37367
37363
  },
37368
- { name: "delete_collection", description: `Delete a collection and all its entries. This cannot be undone.`, schema: z63.object({ name: z63.string().describe("Collection name") }) }
37364
+ { name: "delete_collection", description: `Delete a collection and all its entries. This cannot be undone.`, schema: z62.object({ name: z62.string().describe("Collection name") }) }
37369
37365
  );
37370
37366
 
37371
37367
  // src/tool_lattice/collection/list_entries.ts
37372
- import z64 from "zod";
37373
- import { tool as tool59 } from "langchain";
37374
- var schema2 = z64.object({
37375
- collection: z64.string().describe("Collection name")
37368
+ import z63 from "zod";
37369
+ import { tool as tool58 } from "langchain";
37370
+ var schema2 = z63.object({
37371
+ collection: z63.string().describe("Collection name")
37376
37372
  });
37377
37373
  function buildKey2(tenantId2, name) {
37378
37374
  return `${tenantId2}:${name}`;
37379
37375
  }
37380
- var createListEntriesTool = (scope = { collectionKeys: [], connectAll: true }) => tool59(
37376
+ var createListEntriesTool = (scope = { collectionKeys: [], connectAll: true }) => tool58(
37381
37377
  async (input, _exeConfig) => {
37382
37378
  try {
37383
37379
  const scopeError = validateCollectionScope(input.collection, _exeConfig, scope);
@@ -37406,19 +37402,19 @@ var createListEntriesTool = (scope = { collectionKeys: [], connectAll: true }) =
37406
37402
  );
37407
37403
 
37408
37404
  // src/tool_lattice/collection/add_entry.ts
37409
- import z65 from "zod";
37410
- import { tool as tool60 } from "langchain";
37405
+ import z64 from "zod";
37406
+ import { tool as tool59 } from "langchain";
37411
37407
  import { Document } from "@langchain/core/documents";
37412
37408
  import { v4 as uuidv47 } from "uuid";
37413
- var schema3 = z65.object({
37414
- collection: z65.string().describe("Collection name"),
37415
- content: z65.string().describe("Entry content text"),
37416
- metadata: z65.record(z65.unknown()).optional().describe("Metadata fields matching the collection schema")
37409
+ var schema3 = z64.object({
37410
+ collection: z64.string().describe("Collection name"),
37411
+ content: z64.string().describe("Entry content text"),
37412
+ metadata: z64.record(z64.unknown()).optional().describe("Metadata fields matching the collection schema")
37417
37413
  });
37418
37414
  function key(t, n) {
37419
37415
  return `${t}:${n}`;
37420
37416
  }
37421
- var createAddEntryTool = (scope = { collectionKeys: [], connectAll: true }) => tool60(
37417
+ var createAddEntryTool = (scope = { collectionKeys: [], connectAll: true }) => tool59(
37422
37418
  async (input, _exeConfig) => {
37423
37419
  try {
37424
37420
  const scopeError = validateCollectionScope(input.collection, _exeConfig, scope);
@@ -37450,18 +37446,18 @@ var createAddEntryTool = (scope = { collectionKeys: [], connectAll: true }) => t
37450
37446
  );
37451
37447
 
37452
37448
  // src/tool_lattice/collection/update_entry.ts
37453
- import z66 from "zod";
37454
- import { tool as tool61 } from "langchain";
37455
- var schema4 = z66.object({
37456
- collection: z66.string().describe("Collection name"),
37457
- entryId: z66.string().describe("Entry ID to update"),
37458
- content: z66.string().optional().describe("New content"),
37459
- metadata: z66.record(z66.unknown()).optional().describe("New metadata")
37449
+ import z65 from "zod";
37450
+ import { tool as tool60 } from "langchain";
37451
+ var schema4 = z65.object({
37452
+ collection: z65.string().describe("Collection name"),
37453
+ entryId: z65.string().describe("Entry ID to update"),
37454
+ content: z65.string().optional().describe("New content"),
37455
+ metadata: z65.record(z65.unknown()).optional().describe("New metadata")
37460
37456
  });
37461
37457
  function key2(t, n) {
37462
37458
  return `${t}:${n}`;
37463
37459
  }
37464
- var createUpdateEntryTool = (scope = { collectionKeys: [], connectAll: true }) => tool61(
37460
+ var createUpdateEntryTool = (scope = { collectionKeys: [], connectAll: true }) => tool60(
37465
37461
  async (input, _exeConfig) => {
37466
37462
  try {
37467
37463
  const scopeError = validateCollectionScope(input.collection, _exeConfig, scope);
@@ -37482,16 +37478,16 @@ var createUpdateEntryTool = (scope = { collectionKeys: [], connectAll: true }) =
37482
37478
  );
37483
37479
 
37484
37480
  // src/tool_lattice/collection/delete_entry.ts
37485
- import z67 from "zod";
37486
- import { tool as tool62 } from "langchain";
37487
- var schema5 = z67.object({
37488
- collection: z67.string().describe("Collection name"),
37489
- entryId: z67.string().describe("Entry ID to delete")
37481
+ import z66 from "zod";
37482
+ import { tool as tool61 } from "langchain";
37483
+ var schema5 = z66.object({
37484
+ collection: z66.string().describe("Collection name"),
37485
+ entryId: z66.string().describe("Entry ID to delete")
37490
37486
  });
37491
37487
  function key3(t, n) {
37492
37488
  return `${t}:${n}`;
37493
37489
  }
37494
- var createDeleteEntryTool = (scope = { collectionKeys: [], connectAll: true }) => tool62(
37490
+ var createDeleteEntryTool = (scope = { collectionKeys: [], connectAll: true }) => tool61(
37495
37491
  async (input, _exeConfig) => {
37496
37492
  try {
37497
37493
  const scopeError = validateCollectionScope(input.collection, _exeConfig, scope);
@@ -37511,7 +37507,7 @@ var createDeleteEntryTool = (scope = { collectionKeys: [], connectAll: true }) =
37511
37507
  function createCollectionMiddleware(params) {
37512
37508
  const { collectionKeys, connectAll, compileStableCandidateTools = false } = params;
37513
37509
  if (!compileStableCandidateTools && !connectAll && (!collectionKeys || collectionKeys.length === 0)) {
37514
- return createMiddleware20({
37510
+ return createMiddleware19({
37515
37511
  name: "collectionMiddleware",
37516
37512
  contextSchema,
37517
37513
  tools: [
@@ -37521,7 +37517,7 @@ function createCollectionMiddleware(params) {
37521
37517
  });
37522
37518
  }
37523
37519
  const toolParams = { collectionKeys, connectAll };
37524
- return createMiddleware20({
37520
+ return createMiddleware19({
37525
37521
  name: "collectionMiddleware",
37526
37522
  contextSchema,
37527
37523
  tools: [
@@ -37584,24 +37580,24 @@ var collectionPlugin = {
37584
37580
  };
37585
37581
 
37586
37582
  // src/middlewares/askUserClarifyMiddleware.ts
37587
- import { createMiddleware as createMiddleware21, ToolMessage as ToolMessage10 } from "langchain";
37583
+ import { createMiddleware as createMiddleware20, ToolMessage as ToolMessage10 } from "langchain";
37588
37584
  import { interrupt as interrupt3 } from "@langchain/langgraph";
37589
37585
 
37590
37586
  // src/tool_lattice/ask_user_to_clarify/index.ts
37591
- import { tool as tool63 } from "langchain";
37592
- import z68 from "zod";
37593
- var questionSchema = z68.object({
37594
- question: z68.string().describe("The question text to ask the user. MUST include the specific context, options, or details being clarified \u2014 never use a bare generic label. Good: 'Confirm the plan: use Redis cache + PostgreSQL primary, split microservices as needed?' Bad: 'Confirm the plan?'"),
37595
- options: z68.array(z68.string()).optional().default([]).describe("List of EXACT, selectable values. Maximum 3 options allowed. DO NOT include placeholder values like 'Other' or 'Enter manually'. For free-text with predefined choices, use allowOther=true (works with 'single' and 'multiple'). For pure free-text without choices, use type='input' instead. For file_upload and input, pass an empty array."),
37596
- type: z68.enum(["single", "multiple", "file_upload", "input"]).describe("The question format. 'single' = pick one from options (default, see tool description for guidance). 'multiple' = pick several from options. 'input' = free-text field (only when options cannot express the answer). 'file_upload' = file picker."),
37597
- required: z68.boolean().optional().default(false).describe("Whether this question must be answered"),
37598
- allowOther: z68.boolean().optional().default(true).describe("Set to true to append an 'Other' checkbox with a free-text input field. Works with 'single' and 'multiple' types. Use for open-ended answers or when the options cannot cover all possibilities. Not applicable for 'input' or 'file_upload' types.")
37587
+ import { tool as tool62 } from "langchain";
37588
+ import z67 from "zod";
37589
+ var questionSchema = z67.object({
37590
+ question: z67.string().describe("The question text to ask the user. MUST include the specific context, options, or details being clarified \u2014 never use a bare generic label. Good: 'Confirm the plan: use Redis cache + PostgreSQL primary, split microservices as needed?' Bad: 'Confirm the plan?'"),
37591
+ options: z67.array(z67.string()).optional().default([]).describe("List of EXACT, selectable values. Maximum 3 options allowed. DO NOT include placeholder values like 'Other' or 'Enter manually'. For free-text with predefined choices, use allowOther=true (works with 'single' and 'multiple'). For pure free-text without choices, use type='input' instead. For file_upload and input, pass an empty array."),
37592
+ type: z67.enum(["single", "multiple", "file_upload", "input"]).describe("The question format. 'single' = pick one from options (default, see tool description for guidance). 'multiple' = pick several from options. 'input' = free-text field (only when options cannot express the answer). 'file_upload' = file picker."),
37593
+ required: z67.boolean().optional().default(false).describe("Whether this question must be answered"),
37594
+ allowOther: z67.boolean().optional().default(true).describe("Set to true to append an 'Other' checkbox with a free-text input field. Works with 'single' and 'multiple' types. Use for open-ended answers or when the options cannot cover all possibilities. Not applicable for 'input' or 'file_upload' types.")
37599
37595
  });
37600
- var inputSchema = z68.object({
37601
- questions: z68.array(questionSchema).min(1, "At least one question is required").describe("A structured sequence of clarification questions. Use these to gather missing parameters or disambiguate user intent before proceeding.")
37596
+ var inputSchema = z67.object({
37597
+ questions: z67.array(questionSchema).min(1, "At least one question is required").describe("A structured sequence of clarification questions. Use these to gather missing parameters or disambiguate user intent before proceeding.")
37602
37598
  });
37603
37599
  function createAskUserToClarifyTool() {
37604
- return tool63(
37600
+ return tool62(
37605
37601
  async (input) => {
37606
37602
  return JSON.stringify(input);
37607
37603
  },
@@ -37615,7 +37611,7 @@ function createAskUserToClarifyTool() {
37615
37611
 
37616
37612
  // src/middlewares/askUserClarifyMiddleware.ts
37617
37613
  function createAskUserClarifyMiddleware() {
37618
- return createMiddleware21({
37614
+ return createMiddleware20({
37619
37615
  name: "AskUserClarifyMiddleware",
37620
37616
  tools: [createAskUserToClarifyTool()],
37621
37617
  wrapToolCall: async (request, handler) => {
@@ -37712,11 +37708,11 @@ var askUserClarifyPlugin = {
37712
37708
  };
37713
37709
 
37714
37710
  // src/middlewares/widgetMiddleware.ts
37715
- import { createMiddleware as createMiddleware22 } from "langchain";
37711
+ import { createMiddleware as createMiddleware21 } from "langchain";
37716
37712
 
37717
37713
  // src/tool_lattice/widget/loadGuidelines.ts
37718
- import { tool as tool64 } from "langchain";
37719
- import { z as z69 } from "zod";
37714
+ import { tool as tool63 } from "langchain";
37715
+ import { z as z68 } from "zod";
37720
37716
 
37721
37717
  // src/middlewares/guidelines/index.ts
37722
37718
  var CORE = `# Imagine \u2014 Visual Creation Suite
@@ -38507,13 +38503,13 @@ function getGuidelines(modules) {
38507
38503
  var AVAILABLE_MODULES = Object.keys(MODULE_SECTIONS);
38508
38504
 
38509
38505
  // src/tool_lattice/widget/loadGuidelines.ts
38510
- var LoadGuidelinesInputSchema = z69.object({
38511
- modules: z69.array(z69.string()).describe(
38506
+ var LoadGuidelinesInputSchema = z68.object({
38507
+ modules: z68.array(z68.string()).describe(
38512
38508
  "Which design modules to load. Choose all that apply. Available modules: [" + AVAILABLE_MODULES.join(",") + "]"
38513
38509
  )
38514
38510
  });
38515
38511
  function createLoadGuidelinesTool() {
38516
- return tool64(
38512
+ return tool63(
38517
38513
  async (input) => {
38518
38514
  const result = getGuidelines(input.modules);
38519
38515
  return result;
@@ -38527,8 +38523,8 @@ function createLoadGuidelinesTool() {
38527
38523
  }
38528
38524
 
38529
38525
  // src/tool_lattice/widget/showWidget.ts
38530
- import { tool as tool65 } from "langchain";
38531
- import { z as z70 } from "zod";
38526
+ import { tool as tool64 } from "langchain";
38527
+ import { z as z69 } from "zod";
38532
38528
  function containsForbiddenTags(code) {
38533
38529
  const forbiddenPatterns = [
38534
38530
  /<!DOCTYPE/i,
@@ -38550,20 +38546,20 @@ function validateWidgetCode(code) {
38550
38546
  }
38551
38547
  return { valid: true };
38552
38548
  }
38553
- var ShowWidgetInputSchema = z70.object({
38554
- i_have_seen_guidelines: z70.boolean().describe(
38549
+ var ShowWidgetInputSchema = z69.object({
38550
+ i_have_seen_guidelines: z69.boolean().describe(
38555
38551
  "Must be true. Confirm you have called load_guidelines first."
38556
38552
  ),
38557
- title: z70.string().describe("Title displayed above the widget"),
38558
- loading_messages: z70.array(z70.string()).optional().describe(
38553
+ title: z69.string().describe("Title displayed above the widget"),
38554
+ loading_messages: z69.array(z69.string()).optional().describe(
38559
38555
  "1-4 short strings shown while the widget renders"
38560
38556
  ),
38561
- widget_code: z70.string().describe(
38557
+ widget_code: z69.string().describe(
38562
38558
  "HTML fragment to render. Rules: 1. No DOCTYPE, <html>, <head>, or <body> tags. 2. Order: <style> block first, then HTML content, then <script> last. 3. Use only CSS variables for colors (e.g. var(--color-accent)). 4. No gradients, shadows, or blur effects. For SVG: start directly with <svg> tag."
38563
38559
  )
38564
38560
  });
38565
38561
  function createShowWidgetTool() {
38566
- return tool65(
38562
+ return tool64(
38567
38563
  async (input) => {
38568
38564
  if (!input.i_have_seen_guidelines) {
38569
38565
  return "Error: You must call load_guidelines before using show_widget. Set i_have_seen_guidelines to true only after loading guidelines.";
@@ -38594,7 +38590,7 @@ function createWidgetMiddleware() {
38594
38590
  createLoadGuidelinesTool(),
38595
38591
  createShowWidgetTool()
38596
38592
  ];
38597
- return createMiddleware22({
38593
+ return createMiddleware21({
38598
38594
  name: "widgetMiddleware",
38599
38595
  contextSchema,
38600
38596
  tools
@@ -38618,12 +38614,12 @@ var widgetPlugin = {
38618
38614
  };
38619
38615
 
38620
38616
  // src/middlewares/taskMiddleware.ts
38621
- import { createMiddleware as createMiddleware23, tool as tool66 } from "langchain";
38622
- import { z as z71 } from "zod";
38617
+ import { createMiddleware as createMiddleware22, tool as tool65 } from "langchain";
38618
+ import { z as z70 } from "zod";
38623
38619
  import { GraphInterrupt as GraphInterrupt2, interrupt as interrupt4 } from "@langchain/langgraph";
38624
38620
  import {
38625
38621
  isExecutionResultEventKey as isExecutionResultEventKey3,
38626
- parseTrustedRunContext as parseTrustedRunContext3,
38622
+ parseTrustedRunContext as parseTrustedRunContext2,
38627
38623
  requireProjectTaskWorkItemStore
38628
38624
  } from "@axiom-lattice/protocols";
38629
38625
 
@@ -38956,7 +38952,7 @@ function classifyTaskAuthority(runConfig) {
38956
38952
  return delegatedTaskId ? { kind: "delegated", taskId: delegatedTaskId } : { kind: "ordinary" };
38957
38953
  }
38958
38954
  try {
38959
- const trusted = parseTrustedRunContext3(hasProjectTask ? { projectTask: runConfig.projectTask } : { projectRoom: runConfig.projectRoom });
38955
+ const trusted = parseTrustedRunContext2(hasProjectTask ? { projectTask: runConfig.projectTask } : { projectRoom: runConfig.projectRoom });
38960
38956
  return { kind: hasProjectTask ? "projectTask" : "projectRoom", trusted };
38961
38957
  } catch {
38962
38958
  return { kind: "invalid" };
@@ -39309,38 +39305,38 @@ function missingBeliefImpactError() {
39309
39305
  hint: "Provide beliefImpact: [{ key: '<belief-key>', after: <0-100>, basis: '<evidence>' }]"
39310
39306
  });
39311
39307
  }
39312
- var manageTaskSchema = z71.object({
39313
- action: z71.enum(["create", "get", "list", "update", "add_activity", "delete"]).describe("Action to perform. Available: create, get, list, update, add_activity, delete. To mark a task complete, use update with status='completed'"),
39314
- id: z71.string().optional().describe("Task ID (required for get, update, add_activity, and delete)"),
39315
- title: z71.string().optional().describe("Task title (required for create)"),
39316
- description: z71.string().optional().describe("Task description in Markdown"),
39317
- priority: z71.enum(["low", "medium", "high"]).optional().describe("Priority level"),
39318
- status: z71.enum(["pending", "in_progress", "review", "failed", "interrupted", "completed", "cancelled"]).optional().describe("Task status. Agent summary-only interrupted updates default to missing_input"),
39319
- dueDate: z71.string().optional().describe("Due date (ISO 8601 format)"),
39320
- metadata: z71.record(z71.unknown()).optional().describe("Structured metadata (e.g. projectId, module)"),
39321
- parentId: z71.string().optional().describe("Parent task ID for grouping subtasks"),
39322
- sourceId: z71.string().optional().describe("Source session/thread ID"),
39323
- context: z71.record(z71.unknown()).optional().describe("Additional context data"),
39324
- ownerType: z71.enum(["user", "agent"]).optional().describe("Owner type. Defaults to 'user' if omitted"),
39325
- ownerId: z71.string().optional().describe("Owner ID. Auto-filled from current user/agent if omitted"),
39326
- requireReview: z71.boolean().optional().describe("If true, agent completion pauses as interrupted(review_required) for HITL approval"),
39327
- dependencies: z71.array(z71.string()).optional().describe("List of task IDs that must be completed before this task can start"),
39328
- dependencyTaskIds: z71.array(z71.string().trim().min(1)).optional().describe("Exact blocking task IDs required for an external_dependency interruption"),
39329
- result: z71.string().optional().describe("Nonblank result summary required when creating or updating a task with status='completed'"),
39330
- failureReason: z71.string().optional().describe("Nonblank failure reason required when creating or updating a task with status='failed'"),
39331
- files: z71.array(z71.object({
39332
- uri: z71.string().describe("Uniquely locates the resource: http(s):// URL, /s/:token share, or sandbox path"),
39333
- name: z71.string().optional().describe("Display name"),
39334
- addedBy: z71.enum(["user", "agent"]).optional().describe("Who attached the file")
39308
+ var manageTaskSchema = z70.object({
39309
+ action: z70.enum(["create", "get", "list", "update", "add_activity", "delete"]).describe("Action to perform. Available: create, get, list, update, add_activity, delete. To mark a task complete, use update with status='completed'"),
39310
+ id: z70.string().optional().describe("Task ID (required for get, update, add_activity, and delete)"),
39311
+ title: z70.string().optional().describe("Task title (required for create)"),
39312
+ description: z70.string().optional().describe("Task description in Markdown"),
39313
+ priority: z70.enum(["low", "medium", "high"]).optional().describe("Priority level"),
39314
+ status: z70.enum(["pending", "in_progress", "review", "failed", "interrupted", "completed", "cancelled"]).optional().describe("Task status. Agent summary-only interrupted updates default to missing_input"),
39315
+ dueDate: z70.string().optional().describe("Due date (ISO 8601 format)"),
39316
+ metadata: z70.record(z70.unknown()).optional().describe("Structured metadata (e.g. projectId, module)"),
39317
+ parentId: z70.string().optional().describe("Parent task ID for grouping subtasks"),
39318
+ sourceId: z70.string().optional().describe("Source session/thread ID"),
39319
+ context: z70.record(z70.unknown()).optional().describe("Additional context data"),
39320
+ ownerType: z70.enum(["user", "agent"]).optional().describe("Owner type. Defaults to 'user' if omitted"),
39321
+ ownerId: z70.string().optional().describe("Owner ID. Auto-filled from current user/agent if omitted"),
39322
+ requireReview: z70.boolean().optional().describe("If true, agent completion pauses as interrupted(review_required) for HITL approval"),
39323
+ dependencies: z70.array(z70.string()).optional().describe("List of task IDs that must be completed before this task can start"),
39324
+ dependencyTaskIds: z70.array(z70.string().trim().min(1)).optional().describe("Exact blocking task IDs required for an external_dependency interruption"),
39325
+ result: z70.string().optional().describe("Nonblank result summary required when creating or updating a task with status='completed'"),
39326
+ failureReason: z70.string().optional().describe("Nonblank failure reason required when creating or updating a task with status='failed'"),
39327
+ files: z70.array(z70.object({
39328
+ uri: z70.string().describe("Uniquely locates the resource: http(s):// URL, /s/:token share, or sandbox path"),
39329
+ name: z70.string().optional().describe("Display name"),
39330
+ addedBy: z70.enum(["user", "agent"]).optional().describe("Who attached the file")
39335
39331
  })).optional().describe("File references attached to this task"),
39336
- beliefImpact: z71.array(z71.object({
39337
- key: z71.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
39338
- after: z71.number().int().min(0).max(100),
39339
- basis: z71.string().trim().min(1).max(1e3)
39332
+ beliefImpact: z70.array(z70.object({
39333
+ key: z70.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
39334
+ after: z70.number().int().min(0).max(100),
39335
+ basis: z70.string().trim().min(1).max(1e3)
39340
39336
  })).optional().describe("Structured belief reports required when an agent-owned task completes; keys must exist in the belief owner's Belief State"),
39341
- content: z71.string().optional().describe("Markdown content required for add_activity"),
39342
- summary: z71.string().optional().describe("Brief summary of the operation"),
39343
- executionResultId: z71.string().refine(isExecutionResultEventKey3, {
39337
+ content: z70.string().optional().describe("Markdown content required for add_activity"),
39338
+ summary: z70.string().optional().describe("Brief summary of the operation"),
39339
+ executionResultId: z70.string().refine(isExecutionResultEventKey3, {
39344
39340
  message: "executionResultId must be the execution-result:<threadId> event key returned by task()"
39345
39341
  }).optional().describe(
39346
39342
  "Canonical ASCII `execution-result:<suffix>` event key returned by task(); the nonempty suffix allows only A-Z, a-z, 0-9, period, underscore, colon, and hyphen, and is not a database row ID"
@@ -39348,15 +39344,15 @@ var manageTaskSchema = z71.object({
39348
39344
  }).superRefine((input, context) => {
39349
39345
  if (input.executionResultId && input.action !== "update" && input.action !== "add_activity") {
39350
39346
  context.addIssue({
39351
- code: z71.ZodIssueCode.custom,
39347
+ code: z70.ZodIssueCode.custom,
39352
39348
  path: ["executionResultId"],
39353
39349
  message: "executionResultId is valid only for update or add_activity"
39354
39350
  });
39355
39351
  }
39356
39352
  });
39357
- var startTaskSchema = z71.object({
39358
- taskId: z71.string().trim().min(1).describe("ID of the persisted TaskItem to start"),
39359
- agentId: z71.string().trim().min(1).describe("ID of the Agent that should execute the task")
39353
+ var startTaskSchema = z70.object({
39354
+ taskId: z70.string().trim().min(1).describe("ID of the persisted TaskItem to start"),
39355
+ agentId: z70.string().trim().min(1).describe("ID of the Agent that should execute the task")
39360
39356
  });
39361
39357
  function mergeTaskUpdateWarnings(existing, added) {
39362
39358
  const warnings = [...existing ?? [], ...added ?? []];
@@ -39531,6 +39527,15 @@ function createTaskMiddleware(options = {}) {
39531
39527
  });
39532
39528
  }
39533
39529
  const title = input.title;
39530
+ let createScopeWorkspaceId = workspaceId;
39531
+ let createScopeProjectId = projectId;
39532
+ if (!trustedProject && !delegatedTaskId && input.parentId && (!createScopeWorkspaceId || !createScopeProjectId)) {
39533
+ const parentTask = await store.getById(tenantId2, input.parentId);
39534
+ if (parentTask) {
39535
+ createScopeWorkspaceId = createScopeWorkspaceId ?? parentTask.workspaceId;
39536
+ createScopeProjectId = createScopeProjectId ?? parentTask.projectId;
39537
+ }
39538
+ }
39534
39539
  const effectiveOwnerType = delegatedTaskId ? "agent" : trustedProject ? "agent" : input.ownerType || "user";
39535
39540
  const effectiveOwnerId = delegatedTaskId ? rc.assistant_id : ownerId;
39536
39541
  if (delegatedTaskId && !effectiveOwnerId) {
@@ -39605,7 +39610,7 @@ function createTaskMiddleware(options = {}) {
39605
39610
  store,
39606
39611
  tenantId2,
39607
39612
  delegatedTaskId,
39608
- { workspaceId, projectId },
39613
+ { workspaceId: createScopeWorkspaceId, projectId: createScopeProjectId },
39609
39614
  input.parentId,
39610
39615
  input.dependencies
39611
39616
  );
@@ -39614,7 +39619,7 @@ function createTaskMiddleware(options = {}) {
39614
39619
  const referenceError = await validateReferencedTasks(
39615
39620
  store,
39616
39621
  tenantId2,
39617
- { workspaceId, projectId },
39622
+ { workspaceId: createScopeWorkspaceId, projectId: createScopeProjectId },
39618
39623
  input.parentId,
39619
39624
  input.dependencies
39620
39625
  );
@@ -39631,7 +39636,7 @@ function createTaskMiddleware(options = {}) {
39631
39636
  const dependencyError = await validateEffectiveDependencies(
39632
39637
  store,
39633
39638
  tenantId2,
39634
- { workspaceId, projectId },
39639
+ { workspaceId: createScopeWorkspaceId, projectId: createScopeProjectId },
39635
39640
  input.dependencies
39636
39641
  );
39637
39642
  if (dependencyError) return dependencyError;
@@ -39679,8 +39684,8 @@ function createTaskMiddleware(options = {}) {
39679
39684
  dependencies: input.dependencies,
39680
39685
  result: input.result,
39681
39686
  failureReason: input.failureReason,
39682
- workspaceId,
39683
- projectId,
39687
+ workspaceId: createScopeWorkspaceId,
39688
+ projectId: createScopeProjectId,
39684
39689
  files: input.files
39685
39690
  });
39686
39691
  };
@@ -39874,7 +39879,7 @@ function createTaskMiddleware(options = {}) {
39874
39879
  if (delegatedTaskId && input.id !== delegatedTaskId) {
39875
39880
  return delegatedTaskScopeError(delegatedTaskId);
39876
39881
  }
39877
- const existing = await store.getById(tenantId2, input.id);
39882
+ let existing = await store.getById(tenantId2, input.id);
39878
39883
  if (!existing) {
39879
39884
  return JSON.stringify({
39880
39885
  success: false,
@@ -39916,15 +39921,6 @@ function createTaskMiddleware(options = {}) {
39916
39921
  }
39917
39922
  const isAgentTask = existing.ownerType === "agent";
39918
39923
  const candidateReviewInterruption = input.status === "interrupted" && input.context?.interruption && typeof input.context.interruption === "object" && input.context.interruption.type === "review_required" && !!input.result?.trim() && !!input.beliefImpact?.length;
39919
- const trustedLifecycleInterruption = !!trustedProject && input.status === "interrupted" && input.context?.interruption && typeof input.context.interruption === "object";
39920
- if (isAgentTask && input.context !== void 0 && !candidateReviewInterruption && !trustedLifecycleInterruption) {
39921
- return JSON.stringify({
39922
- success: false,
39923
- code: "TASK_LIFECYCLE_CONTEXT_PROTECTED",
39924
- error: "Agent task context is owned by the task lifecycle service.",
39925
- hint: "Use lifecycle status inputs without context; the service preserves thread and interruption audit data."
39926
- });
39927
- }
39928
39924
  const changesOwnerType = input.ownerType !== void 0 && input.ownerType !== existing.ownerType;
39929
39925
  const changesAgentIdentity = isAgentTask && (input.ownerId !== void 0 && input.ownerId !== existing.ownerId || input.parentId !== void 0 && input.parentId !== existing.parentId);
39930
39926
  if (changesOwnerType || changesAgentIdentity) {
@@ -39954,14 +39950,6 @@ function createTaskMiddleware(options = {}) {
39954
39950
  hint: "Persist ownership or parent changes separately before changing lifecycle or task content."
39955
39951
  });
39956
39952
  }
39957
- if (isAgentTask && input.description !== void 0 && input.status !== void 0) {
39958
- return JSON.stringify({
39959
- success: false,
39960
- code: "AGENT_TASK_LIFECYCLE_REQUIRED",
39961
- error: "Agent description and status updates must be separate operations.",
39962
- hint: "Reconcile the description first, then issue the lifecycle status update."
39963
- });
39964
- }
39965
39953
  const actor = trustedActor(trustedProject, rc) ?? (existing.ownerType === "agent" ? `agent:${existing.ownerId}` : `user:${existing.ownerId ?? ownerId}`);
39966
39954
  const threadId = trustedProject?.projectTask?.threadId ?? (trustedProject?.projectRoom ? void 0 : input.sourceId ?? rc.thread_id);
39967
39955
  const lifecycle = isAgentTask ? createTaskLifecycleService({
@@ -39972,29 +39960,36 @@ function createTaskMiddleware(options = {}) {
39972
39960
  if (result.success && result.mutated) markMutation();
39973
39961
  return lifecycleResponse(input.id, result, extra);
39974
39962
  };
39963
+ const hasCarriedContentFields = () => ["title", "description", "priority", "dueDate", "metadata", "files"].some((key4) => input[key4] !== void 0);
39975
39964
  if (lifecycle && input.status === "failed") {
39976
39965
  await validateExecutionResult();
39977
39966
  const callerError = await revalidateCaller();
39978
39967
  if (callerError) return callerError;
39979
- return lifecycleMutationResponse(await lifecycle.failTask({
39968
+ const failed = await lifecycle.failTask({
39980
39969
  tenantId: tenantId2,
39981
39970
  taskId: input.id,
39982
39971
  failureReason: input.failureReason ?? existing.failureReason ?? "",
39983
39972
  actor,
39984
39973
  threadId
39985
- }));
39974
+ });
39975
+ if (!failed.success) return lifecycleMutationResponse(failed);
39976
+ if (trustedProject || !hasCarriedContentFields()) return lifecycleMutationResponse(failed);
39977
+ existing = { ...existing, status: input.status };
39986
39978
  }
39987
39979
  if (lifecycle && input.status === "cancelled") {
39988
39980
  await validateExecutionResult();
39989
39981
  const callerError = await revalidateCaller();
39990
39982
  if (callerError) return callerError;
39991
- return lifecycleMutationResponse(await lifecycle.cancelTask({
39983
+ const cancelled = await lifecycle.cancelTask({
39992
39984
  tenantId: tenantId2,
39993
39985
  taskId: input.id,
39994
39986
  actor,
39995
39987
  threadId,
39996
39988
  summary: input.summary
39997
- }));
39989
+ });
39990
+ if (!cancelled.success) return lifecycleMutationResponse(cancelled);
39991
+ if (trustedProject || !hasCarriedContentFields()) return lifecycleMutationResponse(cancelled);
39992
+ existing = { ...existing, status: input.status };
39998
39993
  }
39999
39994
  if (lifecycle && input.status === "interrupted" && !(input.context?.interruption && typeof input.context.interruption === "object" && input.context.interruption.type === "review_required")) {
40000
39995
  const interruption = input.context?.interruption;
@@ -40010,7 +40005,7 @@ function createTaskMiddleware(options = {}) {
40010
40005
  await validateExecutionResult();
40011
40006
  const callerError = await revalidateCaller();
40012
40007
  if (callerError) return callerError;
40013
- return lifecycleMutationResponse(await lifecycle.interruptTask({
40008
+ const interrupted = await lifecycle.interruptTask({
40014
40009
  tenantId: tenantId2,
40015
40010
  taskId: input.id,
40016
40011
  type,
@@ -40018,40 +40013,52 @@ function createTaskMiddleware(options = {}) {
40018
40013
  actor,
40019
40014
  threadId,
40020
40015
  dependencyTaskIds: input.dependencyTaskIds
40021
- }));
40016
+ });
40017
+ if (!interrupted.success) return lifecycleMutationResponse(interrupted);
40018
+ if (trustedProject || !hasCarriedContentFields()) return lifecycleMutationResponse(interrupted);
40019
+ existing = { ...existing, status: input.status };
40022
40020
  }
40023
40021
  if (lifecycle && input.status === "in_progress" && existing.status === "interrupted") {
40024
40022
  await validateExecutionResult();
40025
40023
  const callerError = await revalidateCaller();
40026
40024
  if (callerError) return callerError;
40027
- return lifecycleMutationResponse(await lifecycle.resumeInterruption({
40025
+ const resumed = await lifecycle.resumeInterruption({
40028
40026
  tenantId: tenantId2,
40029
40027
  taskId: input.id,
40030
40028
  actor,
40031
40029
  threadId
40032
- }));
40030
+ });
40031
+ if (!resumed.success) return lifecycleMutationResponse(resumed);
40032
+ if (trustedProject || !hasCarriedContentFields()) return lifecycleMutationResponse(resumed);
40033
+ existing = { ...existing, status: input.status };
40033
40034
  }
40034
40035
  if (lifecycle && input.status === "in_progress" && existing.status === "pending") {
40035
40036
  await validateExecutionResult();
40036
40037
  const callerError = await revalidateCaller();
40037
40038
  if (callerError) return callerError;
40038
- return lifecycleMutationResponse(await lifecycle.startTask({
40039
+ const started = await lifecycle.startTask({
40039
40040
  tenantId: tenantId2,
40040
40041
  taskId: input.id,
40041
40042
  actor,
40042
40043
  threadId
40043
- }));
40044
+ });
40045
+ if (!started.success) return lifecycleMutationResponse(started);
40046
+ if (trustedProject || !hasCarriedContentFields()) return lifecycleMutationResponse(started);
40047
+ existing = { ...existing, status: input.status };
40044
40048
  }
40045
40049
  if (lifecycle && input.status === "in_progress" && existing.status === "failed") {
40046
40050
  await validateExecutionResult();
40047
40051
  const callerError = await revalidateCaller();
40048
40052
  if (callerError) return callerError;
40049
- return lifecycleMutationResponse(await lifecycle.retryTask({
40053
+ const retried = await lifecycle.retryTask({
40050
40054
  tenantId: tenantId2,
40051
40055
  taskId: input.id,
40052
40056
  actor,
40053
40057
  threadId
40054
- }));
40058
+ });
40059
+ if (!retried.success) return lifecycleMutationResponse(retried);
40060
+ if (trustedProject || !hasCarriedContentFields()) return lifecycleMutationResponse(retried);
40061
+ existing = { ...existing, status: input.status };
40055
40062
  }
40056
40063
  if (isAgentTask && input.requireReview === true && options.reviewMode !== "hitl") {
40057
40064
  return reviewModeDisabledResponse();
@@ -40172,7 +40179,8 @@ function createTaskMiddleware(options = {}) {
40172
40179
  return JSON.stringify({
40173
40180
  success: false,
40174
40181
  code: "AGENT_TASK_LIFECYCLE_REQUIRED",
40175
- error: `Agent task lifecycle cannot transition from '${existing.status}' to '${input.status}'.`
40182
+ error: `Agent task lifecycle cannot transition from '${existing.status}' to '${input.status}'.`,
40183
+ hint: "Valid transitions: pending\u2192in_progress, in_progress\u2192completed (requires result + beliefImpact), in_progress\u2192failed (requires failureReason), in_progress\u2192cancelled, in_progress\u2192interrupted. Check the current status with manage_task get first."
40176
40184
  });
40177
40185
  }
40178
40186
  const persistedStatus = input.status;
@@ -40395,8 +40403,8 @@ function createTaskMiddleware(options = {}) {
40395
40403
  if (!existing) {
40396
40404
  return JSON.stringify({
40397
40405
  success: false,
40398
- error: `Task '${input.id}' not found or could not be deleted`,
40399
- hint: "Use list to verify the task exists"
40406
+ error: `Task '${input.id}' not found`,
40407
+ hint: "Use list to see available tasks and their IDs"
40400
40408
  });
40401
40409
  }
40402
40410
  if (!taskMatchesRuntimeScope3(existing, workspaceId, projectId)) {
@@ -40579,7 +40587,7 @@ function createTaskMiddleware(options = {}) {
40579
40587
  callerThreadId: rc.thread_id
40580
40588
  }));
40581
40589
  };
40582
- return createMiddleware23({
40590
+ return createMiddleware22({
40583
40591
  name: "TaskMiddleware",
40584
40592
  contextSchema,
40585
40593
  wrapModelCall: async (request, handler) => {
@@ -40620,7 +40628,7 @@ ${TASK_CONVERGENCE_GUIDANCE}
40620
40628
  });
40621
40629
  },
40622
40630
  tools: [
40623
- tool66(
40631
+ tool65(
40624
40632
  handleManageTask,
40625
40633
  {
40626
40634
  name: "manage_task",
@@ -40654,7 +40662,7 @@ pending/in_progress, then complete them separately.`,
40654
40662
  schema: manageTaskSchema
40655
40663
  }
40656
40664
  ),
40657
- tool66(handleStartTask, {
40665
+ tool65(handleStartTask, {
40658
40666
  name: "task",
40659
40667
  description: "Start a persisted TaskItem with any Agent in a fresh isolated thread and return an observation plus executionResultId; the caller passes that exact ID to the manage_task update or add_activity that interprets it.",
40660
40668
  schema: startTaskSchema
@@ -40792,8 +40800,8 @@ canonical Belief State:
40792
40800
  };
40793
40801
 
40794
40802
  // src/middlewares/evalMiddleware.ts
40795
- import { createMiddleware as createMiddleware24, tool as tool67 } from "langchain";
40796
- import { z as z72 } from "zod";
40803
+ import { createMiddleware as createMiddleware23, tool as tool66 } from "langchain";
40804
+ import { z as z71 } from "zod";
40797
40805
  import { v4 as uuidv48 } from "uuid";
40798
40806
 
40799
40807
  // src/middlewares/evalSkills.ts
@@ -41012,8 +41020,8 @@ async function runWithResults(tid, store, svc, run, runnerAlive) {
41012
41020
  return { ...run, runnerAlive, results };
41013
41021
  }
41014
41022
  function createReadEvalTool() {
41015
- const schema6 = z72.object({
41016
- action: z72.enum([
41023
+ const schema6 = z71.object({
41024
+ action: z71.enum([
41017
41025
  "list_projects",
41018
41026
  "get_project",
41019
41027
  "list_suites",
@@ -41025,13 +41033,13 @@ function createReadEvalTool() {
41025
41033
  "get_run_results",
41026
41034
  "get_project_report"
41027
41035
  ]).describe("Operation"),
41028
- projectId: z72.string().optional(),
41029
- suiteId: z72.string().optional(),
41030
- caseId: z72.string().optional(),
41031
- runId: z72.string().optional(),
41032
- status: z72.string().optional().describe("Filter: running|completed|failed|aborted")
41036
+ projectId: z71.string().optional(),
41037
+ suiteId: z71.string().optional(),
41038
+ caseId: z71.string().optional(),
41039
+ runId: z71.string().optional(),
41040
+ status: z71.string().optional().describe("Filter: running|completed|failed|aborted")
41033
41041
  });
41034
- return tool67(
41042
+ return tool66(
41035
41043
  async (input, exeConfig) => {
41036
41044
  const tid = tenantId(exeConfig);
41037
41045
  if (!tid) {
@@ -41113,8 +41121,8 @@ ACTIONS:
41113
41121
  );
41114
41122
  }
41115
41123
  function createManageEvalTool() {
41116
- const schema6 = z72.object({
41117
- action: z72.enum([
41124
+ const schema6 = z71.object({
41125
+ action: z71.enum([
41118
41126
  "create_project",
41119
41127
  "update_project",
41120
41128
  "delete_project",
@@ -41125,26 +41133,26 @@ function createManageEvalTool() {
41125
41133
  "update_case",
41126
41134
  "delete_case"
41127
41135
  ]).describe("Operation"),
41128
- projectId: z72.string().optional(),
41129
- name: z72.string().optional(),
41130
- description: z72.string().optional(),
41131
- judgeModelKey: z72.string().optional(),
41132
- concurrency: z72.number().optional(),
41133
- targetAgentId: z72.string().optional().describe("Optional for create_project \u2014 the agent this eval project verifies. Recorded in targetServerConfig so the agent's detail page can find its eval data without relying on project naming."),
41134
- suiteId: z72.string().optional(),
41135
- caseId: z72.string().optional(),
41136
- inputMessage: z72.string().optional(),
41137
- inputFiles: z72.record(z72.string()).optional(),
41138
- steps: z72.array(z72.object({ agent_id: z72.string(), override_message: z72.string().optional() })).optional(),
41139
- outputType: z72.enum(["file_content", "message_content"]).optional(),
41140
- contentAssertion: z72.string().optional(),
41141
- rubrics: z72.array(z72.object({ name: z72.string(), weight: z72.number(), description: z72.string() })).optional(),
41142
- interruptPolicy: z72.object({
41143
- mode: z72.enum(["stop", "auto-approve", "auto-reject", "canned-response"]).describe("stop=judge the pause; auto-approve/auto-reject/canned-response=resume the agent to test the flow after the human input"),
41144
- value: z72.string().optional().describe("Response to inject (defaults: \u540C\u610F / \u62D2\u7EDD; required for canned-response)")
41136
+ projectId: z71.string().optional(),
41137
+ name: z71.string().optional(),
41138
+ description: z71.string().optional(),
41139
+ judgeModelKey: z71.string().optional(),
41140
+ concurrency: z71.number().optional(),
41141
+ targetAgentId: z71.string().optional().describe("Optional for create_project \u2014 the agent this eval project verifies. Recorded in targetServerConfig so the agent's detail page can find its eval data without relying on project naming."),
41142
+ suiteId: z71.string().optional(),
41143
+ caseId: z71.string().optional(),
41144
+ inputMessage: z71.string().optional(),
41145
+ inputFiles: z71.record(z71.string()).optional(),
41146
+ steps: z71.array(z71.object({ agent_id: z71.string(), override_message: z71.string().optional() })).optional(),
41147
+ outputType: z71.enum(["file_content", "message_content"]).optional(),
41148
+ contentAssertion: z71.string().optional(),
41149
+ rubrics: z71.array(z71.object({ name: z71.string(), weight: z71.number(), description: z71.string() })).optional(),
41150
+ interruptPolicy: z71.object({
41151
+ mode: z71.enum(["stop", "auto-approve", "auto-reject", "canned-response"]).describe("stop=judge the pause; auto-approve/auto-reject/canned-response=resume the agent to test the flow after the human input"),
41152
+ value: z71.string().optional().describe("Response to inject (defaults: \u540C\u610F / \u62D2\u7EDD; required for canned-response)")
41145
41153
  }).optional().describe("Optional for create_case/update_case \u2014 how HITL interrupts are handled")
41146
41154
  });
41147
- return tool67(
41155
+ return tool66(
41148
41156
  async (input, exeConfig) => {
41149
41157
  const tid = tenantId(exeConfig);
41150
41158
  if (!tid) {
@@ -41253,17 +41261,17 @@ Case: create_case(suiteId, inputMessage, steps, outputType, contentAssertion, in
41253
41261
  );
41254
41262
  }
41255
41263
  function createRunEvalTool() {
41256
- const schema6 = z72.object({
41257
- action: z72.enum(["start", "status", "resume", "abort"]).describe("Operation"),
41258
- projectId: z72.string().optional().describe("Required for start"),
41259
- suiteIds: z72.array(z72.string()).optional().describe("Optional for start \u2014 only run these suites (e.g. dev set only). Omit to run all."),
41260
- caseIds: z72.array(z72.string()).optional().describe("Optional for start \u2014 only run these cases across the selected suites. Omit to run all cases in those suites."),
41261
- runId: z72.string().optional().describe("Required for status, resume, abort"),
41262
- taskId: z72.string().optional().describe("Optional for start \u2014 training task ID this run belongs to (round association)"),
41263
- sleepMs: z72.number().int().min(0).max(12e4).optional().describe("Optional for status \u2014 sleep this many ms BEFORE checking the run, to pace polling (e.g. 15000 \u2192 30000 \u2192 60000 \u2192 120000). Omit to check immediately."),
41264
- wait: z72.boolean().optional().describe("Optional for start \u2014 defaults to true: block synchronously (up to ~150s) and return final results in one call. Set false to return the runId immediately and poll.")
41264
+ const schema6 = z71.object({
41265
+ action: z71.enum(["start", "status", "resume", "abort"]).describe("Operation"),
41266
+ projectId: z71.string().optional().describe("Required for start"),
41267
+ suiteIds: z71.array(z71.string()).optional().describe("Optional for start \u2014 only run these suites (e.g. dev set only). Omit to run all."),
41268
+ caseIds: z71.array(z71.string()).optional().describe("Optional for start \u2014 only run these cases across the selected suites. Omit to run all cases in those suites."),
41269
+ runId: z71.string().optional().describe("Required for status, resume, abort"),
41270
+ taskId: z71.string().optional().describe("Optional for start \u2014 training task ID this run belongs to (round association)"),
41271
+ sleepMs: z71.number().int().min(0).max(12e4).optional().describe("Optional for status \u2014 sleep this many ms BEFORE checking the run, to pace polling (e.g. 15000 \u2192 30000 \u2192 60000 \u2192 120000). Omit to check immediately."),
41272
+ wait: z71.boolean().optional().describe("Optional for start \u2014 defaults to true: block synchronously (up to ~150s) and return final results in one call. Set false to return the runId immediately and poll.")
41265
41273
  });
41266
- return tool67(
41274
+ return tool66(
41267
41275
  withToolTimeout(
41268
41276
  async (input, exeConfig) => {
41269
41277
  const tid = tenantId(exeConfig);
@@ -41394,7 +41402,7 @@ var evalPlugin = {
41394
41402
  defaultConfig: {}
41395
41403
  },
41396
41404
  skills: EVAL_SKILLS,
41397
- middleware: () => createMiddleware24({
41405
+ middleware: () => createMiddleware23({
41398
41406
  name: "EvalMiddleware",
41399
41407
  tools: [createReadEvalTool(), createManageEvalTool(), createRunEvalTool()]
41400
41408
  })
@@ -41402,7 +41410,7 @@ var evalPlugin = {
41402
41410
 
41403
41411
  // src/middlewares/documentLearningMiddleware.ts
41404
41412
  import { AgentType as AgentType9 } from "@axiom-lattice/protocols";
41405
- import { createMiddleware as createMiddleware25 } from "langchain";
41413
+ import { createMiddleware as createMiddleware24 } from "langchain";
41406
41414
 
41407
41415
  // src/middlewares/documentLearningSkills.ts
41408
41416
  var LEARN_CAPABILITY_SKILL = `---
@@ -41478,6 +41486,10 @@ never plain text. One question per tool call.
41478
41486
  safety boundary): the target identity exists and is fixed. Preserve the IDs. Confirm only
41479
41487
  material-boundary decisions. After architecture approval, apply reversible in-contract updates
41480
41488
  without routine renewed confirmation; every material boundary requires HITL or human confirmation.
41489
+ The bound tracking Task is your main task and belief root: reconcile its description before
41490
+ creating children \u2014 write the confirmed Objective, Acceptance Criteria, and Belief State once the
41491
+ Goal Model is confirmed, and keep reconciling the same task as evidence arrives. Never create a
41492
+ parallel main task under it; children are only independently verifiable outcomes.
41481
41493
  If the exact bound target is missing or cannot be loaded \u2192 hard stop: update the tracking task with status
41482
41494
  "interrupted" and a recovery condition. NEVER create a replacement.
41483
41495
 
@@ -41610,7 +41622,7 @@ patterns discovered, recommendations. Include validation coverage: user-sample N
41610
41622
  `;
41611
41623
 
41612
41624
  // src/middlewares/documentLearningMiddleware.ts
41613
- var createDocumentLearningMiddleware = () => createMiddleware25({
41625
+ var createDocumentLearningMiddleware = () => createMiddleware24({
41614
41626
  name: "DocumentLearningMiddleware",
41615
41627
  contextSchema,
41616
41628
  tools: []
@@ -41728,12 +41740,12 @@ var documentLearningPlugin = {
41728
41740
  };
41729
41741
 
41730
41742
  // src/middlewares/documentParserMiddleware.ts
41731
- import { createMiddleware as createMiddleware26 } from "langchain";
41743
+ import { createMiddleware as createMiddleware25 } from "langchain";
41732
41744
 
41733
41745
  // src/tool_lattice/document_parser/index.ts
41734
41746
  import * as path7 from "path";
41735
- import z73 from "zod";
41736
- import { tool as tool68 } from "langchain";
41747
+ import z72 from "zod";
41748
+ import { tool as tool67 } from "langchain";
41737
41749
  var PARSE_DOCUMENT_DESCRIPTION = `Parse a document file (docx, pdf) into structured Markdown using a remote document parsing service.
41738
41750
  This tool handles the full pipeline internally: file upload \u2192 document parsing \u2192 polling until complete \u2192 download result \u2192 save to filesystem.
41739
41751
 
@@ -41856,7 +41868,7 @@ function createParseDocumentTool({
41856
41868
  baseUrl = "",
41857
41869
  apiKey = ""
41858
41870
  }) {
41859
- return tool68(
41871
+ return tool67(
41860
41872
  async (input, exe_config) => {
41861
41873
  try {
41862
41874
  const runConfig = exe_config?.configurable?.runConfig ?? { assistant_id: "", thread_id: "" };
@@ -41927,17 +41939,17 @@ function createParseDocumentTool({
41927
41939
  {
41928
41940
  name: "parse_document",
41929
41941
  description: PARSE_DOCUMENT_DESCRIPTION,
41930
- schema: z73.object({
41931
- file_path: z73.string().describe(
41942
+ schema: z72.object({
41943
+ file_path: z72.string().describe(
41932
41944
  'Absolute path to the document file. Must point to an existing .docx or .pdf file. Example: "/project/reports/contract.docx". The file must be accessible from the current workspace.'
41933
41945
  ),
41934
- engine: z73.string().describe(
41946
+ engine: z72.string().describe(
41935
41947
  'Parsing engine to use. Available options: "textin" (recommended, works with local files, supports docx/pdf), "datalab" (alternative engine for docx/pdf), "mineru" (requires public URL, use only if textin/datalab fail), "paddleocr_remote" (PaddleOCR, good for scanned documents), "qwen_ocr" (OCR-focused, best for image-heavy PDFs).'
41936
41948
  ),
41937
- output_path: z73.string().optional().describe(
41949
+ output_path: z72.string().optional().describe(
41938
41950
  'Path to save the parsed result. If not specified, the input extension is replaced with .md. Example: "/project/report.docx" becomes "/project/report.md". Parent directories are created automatically.'
41939
41951
  ),
41940
- output_format: z73.enum(["markdown", "json"]).optional().default("markdown").describe(
41952
+ output_format: z72.enum(["markdown", "json"]).optional().default("markdown").describe(
41941
41953
  'Output format. "markdown": structured Markdown with tables, headers, formatting preserved (recommended). "json": raw JSON output from the parsing engine (for programmatic use).'
41942
41954
  )
41943
41955
  })
@@ -42393,7 +42405,7 @@ function createDocumentParserMiddleware(config) {
42393
42405
  const baseUrl = config.baseUrl || "";
42394
42406
  const apiKey = config.apiKey || "";
42395
42407
  const connections = Array.isArray(config.connections) ? config.connections.filter((key4) => typeof key4 === "string") : [];
42396
- return createMiddleware26({
42408
+ return createMiddleware25({
42397
42409
  name: "DocumentParser",
42398
42410
  contextSchema,
42399
42411
  tools: [createParseDocumentTool({ connectAll, connections, baseUrl, apiKey })]
@@ -42505,6 +42517,180 @@ var documentParserPlugin = {
42505
42517
  }
42506
42518
  };
42507
42519
 
42520
+ // src/middlewares/projectRoomMiddleware.ts
42521
+ import { createHash as createHash6 } from "crypto";
42522
+ import {
42523
+ descriptorDataValue as descriptorDataValue2,
42524
+ parseTrustedRunContext as parseTrustedRunContext3,
42525
+ snapshotExactArray as snapshotExactArray3,
42526
+ snapshotExactRecord as snapshotExactRecord8
42527
+ } from "@axiom-lattice/protocols";
42528
+ import { createMiddleware as createMiddleware26, tool as tool68 } from "langchain";
42529
+ import { z as z73 } from "zod";
42530
+ var PROJECT_ROOM_CONTEXT_REQUIRED = "PROJECT_ROOM_CONTEXT_REQUIRED";
42531
+ var PROJECT_ROOM_POST_FAILED = "PROJECT_ROOM_POST_FAILED";
42532
+ var PROJECT_ROOM_ROSTER_FAILED = "PROJECT_ROOM_ROSTER_FAILED";
42533
+ var PROJECT_ROOM_POST_FAILED_MESSAGE = "Project room message could not be posted";
42534
+ var PROJECT_ROOM_ROSTER_FAILED_MESSAGE = "Project room roster is unavailable";
42535
+ var CONTEXT_REQUIRED = JSON.stringify({
42536
+ success: false,
42537
+ error: PROJECT_ROOM_CONTEXT_REQUIRED
42538
+ });
42539
+ var POST_FAILED = JSON.stringify({
42540
+ success: false,
42541
+ error: PROJECT_ROOM_POST_FAILED,
42542
+ message: PROJECT_ROOM_POST_FAILED_MESSAGE
42543
+ });
42544
+ var ROSTER_FAILED = JSON.stringify({
42545
+ success: false,
42546
+ error: PROJECT_ROOM_ROSTER_FAILED,
42547
+ message: PROJECT_ROOM_ROSTER_FAILED_MESSAGE
42548
+ });
42549
+ var postSchema = z73.object({
42550
+ text: z73.string().trim().min(1).max(2e4)
42551
+ }).strict();
42552
+ var listSchema = z73.object({}).strict();
42553
+ function ownDataValue2(record, key4) {
42554
+ if (typeof record !== "object" || record === null || Array.isArray(record)) return void 0;
42555
+ try {
42556
+ const descriptor = Object.getOwnPropertyDescriptor(record, key4);
42557
+ return descriptorDataValue2(descriptor)?.value;
42558
+ } catch {
42559
+ return void 0;
42560
+ }
42561
+ }
42562
+ function readTrustedRoomScope(config) {
42563
+ const configurable = ownDataValue2(config, "configurable");
42564
+ const runConfig = ownDataValue2(configurable, "runConfig");
42565
+ const projectRoom = ownDataValue2(runConfig, "projectRoom");
42566
+ try {
42567
+ return parseTrustedRunContext3({ projectRoom }).projectRoom;
42568
+ } catch {
42569
+ return void 0;
42570
+ }
42571
+ }
42572
+ function exactValues2(value, required, optional = []) {
42573
+ try {
42574
+ return snapshotExactRecord8(value, required, optional);
42575
+ } catch {
42576
+ return void 0;
42577
+ }
42578
+ }
42579
+ function safeDate(value) {
42580
+ try {
42581
+ const timestamp = Date.prototype.getTime.call(value);
42582
+ return Number.isFinite(timestamp) ? new Date(timestamp) : void 0;
42583
+ } catch {
42584
+ return void 0;
42585
+ }
42586
+ }
42587
+ function snapshotMembership3(value) {
42588
+ const required = [
42589
+ "id",
42590
+ "tenantId",
42591
+ "workspaceId",
42592
+ "projectId",
42593
+ "roomId",
42594
+ "assistantId",
42595
+ "role",
42596
+ "title",
42597
+ "mentionName",
42598
+ "status",
42599
+ "roomThreadId",
42600
+ "joinedAt",
42601
+ "updatedAt"
42602
+ ];
42603
+ const values = exactValues2(value, required, ["responsibility"]);
42604
+ const joinedAt = safeDate(values?.joinedAt);
42605
+ const updatedAt = safeDate(values?.updatedAt);
42606
+ if (!values || !joinedAt || !updatedAt || required.slice(0, 6).some((key4) => typeof values[key4] !== "string" || values[key4] === "") || values.role !== "coordinator" && values.role !== "specialist" || typeof values.title !== "string" || values.title === "" || typeof values.mentionName !== "string" || values.mentionName === "" || !["active", "paused", "removed"].includes(values.status) || typeof values.roomThreadId !== "string" || values.roomThreadId === "" || values.responsibility !== void 0 && typeof values.responsibility !== "string") return void 0;
42607
+ return { ...values, joinedAt, updatedAt };
42608
+ }
42609
+ function snapshotRows(value) {
42610
+ return snapshotExactArray3(value) ?? [];
42611
+ }
42612
+ async function hasActiveCurrentMembership(scope) {
42613
+ const memberships = getStoreLattice("default", "projectBotMembership").store;
42614
+ const member = snapshotMembership3(await memberships.findById(scope.tenantId, scope.membershipId));
42615
+ if (!member || member.status !== "active" || member.id !== scope.membershipId || member.tenantId !== scope.tenantId || member.workspaceId !== scope.workspaceId || member.projectId !== scope.projectId || member.roomId !== scope.roomId || member.assistantId !== scope.assistantId) return false;
42616
+ return true;
42617
+ }
42618
+ function createProjectRoomMiddleware() {
42619
+ return createMiddleware26({
42620
+ name: "ProjectRoomMiddleware",
42621
+ tools: [
42622
+ tool68(async (input, config) => {
42623
+ const { text } = input;
42624
+ const scope = readTrustedRoomScope(config);
42625
+ if (!scope) return CONTEXT_REQUIRED;
42626
+ const digest = createHash6("sha256").update(text).digest("hex");
42627
+ try {
42628
+ const service2 = new RoomAgentMessageService({
42629
+ memberships: getStoreLattice("default", "projectBotMembership").store,
42630
+ messages: getStoreLattice("default", "projectRoomMessage").store
42631
+ });
42632
+ await service2.post({
42633
+ tenantId: scope.tenantId,
42634
+ workspaceId: scope.workspaceId,
42635
+ projectId: scope.projectId,
42636
+ roomId: scope.roomId,
42637
+ membershipId: scope.membershipId,
42638
+ assistantId: scope.assistantId,
42639
+ text,
42640
+ sourceRoomMessageId: scope.sourceRoomMessageId,
42641
+ sourceId: `${scope.inputMessageId}:${digest}`,
42642
+ idempotencyKey: `room-tool:${scope.inputMessageId}:${scope.membershipId}:${digest}`
42643
+ });
42644
+ return JSON.stringify({ success: true, message: "Project room message posted" });
42645
+ } catch {
42646
+ return POST_FAILED;
42647
+ }
42648
+ }, {
42649
+ name: "post_room_message",
42650
+ description: "Post a text reply to the current trusted Project Room message",
42651
+ schema: postSchema
42652
+ }),
42653
+ tool68(async (_input, config) => {
42654
+ const scope = readTrustedRoomScope(config);
42655
+ if (!scope) return CONTEXT_REQUIRED;
42656
+ try {
42657
+ if (!await hasActiveCurrentMembership(scope)) return CONTEXT_REQUIRED;
42658
+ const rows = await getStoreLattice("default", "projectBotMembership").store.list(scope.tenantId, scope.projectId);
42659
+ const members = snapshotRows(rows).map(snapshotMembership3).filter((member) => member !== void 0 && member.status === "active" && member.tenantId === scope.tenantId && member.workspaceId === scope.workspaceId && member.projectId === scope.projectId && member.roomId === scope.roomId).sort((left, right) => left.joinedAt.getTime() - right.joinedAt.getTime() || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).map((member) => ({
42660
+ assistantId: member.assistantId,
42661
+ mentionName: member.mentionName,
42662
+ title: member.title,
42663
+ ...member.responsibility === void 0 ? {} : { responsibility: member.responsibility },
42664
+ role: member.role
42665
+ }));
42666
+ return JSON.stringify({ success: true, members });
42667
+ } catch {
42668
+ return ROSTER_FAILED;
42669
+ }
42670
+ }, {
42671
+ name: "list_room_roster",
42672
+ description: "List active Agent roles in the current trusted Project Room, including assistantId for delegation",
42673
+ schema: listSchema
42674
+ })
42675
+ ]
42676
+ });
42677
+ }
42678
+ var projectRoomPlugin = {
42679
+ meta: {
42680
+ type: "project_room",
42681
+ category: "assistant",
42682
+ name: "Project Room",
42683
+ description: "Trusted Project Room posting and active roster tools",
42684
+ tools: [
42685
+ { name: "post_room_message", description: "Post to the current trusted Project Room" },
42686
+ { name: "list_room_roster", description: "List active Agents in the current trusted Project Room" }
42687
+ ],
42688
+ configSchema: { type: "object", properties: {}, additionalProperties: false },
42689
+ defaultConfig: {}
42690
+ },
42691
+ middleware: () => createProjectRoomMiddleware()
42692
+ };
42693
+
42508
42694
  // src/plugin/BuiltinPlugins.ts
42509
42695
  var BUILTIN_PLUGINS = [
42510
42696
  filesystemPlugin,
@@ -42976,7 +43162,7 @@ export {
42976
43162
  ExportableEntityRegistry,
42977
43163
  FileSystemSkillStore,
42978
43164
  FilesystemBackend,
42979
- HumanMessage7 as HumanMessage,
43165
+ HumanMessage6 as HumanMessage,
42980
43166
  IdRemapper,
42981
43167
  InMemoryA2AApiKeyStore,
42982
43168
  InMemoryAgentWebAppStore,