@terreno/ai 57.11.0 → 57.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/aiApp.d.ts +5 -0
  2. package/dist/aiApp.js +4 -2
  3. package/dist/harness/commit.d.ts +17 -1
  4. package/dist/harness/commit.js +86 -2
  5. package/dist/harness/routes/approvals.js +2 -2
  6. package/dist/harness/routes/conversations.js +1 -1
  7. package/dist/harness/routes/tasks.js +85 -3
  8. package/dist/harness/runtime.js +7 -1
  9. package/dist/harness/subagent.d.ts +17 -2
  10. package/dist/harness/subagent.js +26 -2
  11. package/dist/index.d.ts +5 -1
  12. package/dist/index.js +11 -2
  13. package/dist/models/project.d.ts +13 -0
  14. package/dist/models/project.js +32 -2
  15. package/dist/observability/local/models/obsTrace.js +16 -2
  16. package/dist/observability/local/traceStore.d.ts +5 -0
  17. package/dist/observability/local/traceStore.js +5 -0
  18. package/dist/observability/routes/traces.js +2 -0
  19. package/dist/routes/gptActions.js +15 -2
  20. package/dist/routes/projects.js +3 -3
  21. package/dist/service/agentBlocks.d.ts +20 -0
  22. package/dist/service/agentBlocks.js +92 -0
  23. package/dist/service/chatTurn.d.ts +3 -1
  24. package/dist/service/chatTurn.js +34 -9
  25. package/dist/service/prompts.d.ts +12 -2
  26. package/dist/service/prompts.js +20 -4
  27. package/dist/service/scaleStepper.d.ts +8 -0
  28. package/dist/service/scaleStepper.js +29 -0
  29. package/dist/service/toggleChecklist.d.ts +9 -0
  30. package/dist/service/toggleChecklist.js +37 -0
  31. package/dist/types/harness.d.ts +28 -2
  32. package/dist/types/index.d.ts +19 -4
  33. package/dist/types/observability.d.ts +3 -0
  34. package/package.json +56 -8
  35. package/src/aiApp.test.ts +15 -0
  36. package/src/aiApp.ts +9 -1
  37. package/src/harness/commit.ts +103 -1
  38. package/src/harness/routes/approvals.ts +2 -2
  39. package/src/harness/routes/conversations.ts +1 -1
  40. package/src/harness/routes/tasks.test.ts +34 -0
  41. package/src/harness/routes/tasks.ts +98 -3
  42. package/src/harness/runtime.ts +8 -1
  43. package/src/harness/subagent.test.ts +124 -3
  44. package/src/harness/subagent.ts +43 -1
  45. package/src/index.test.ts +4 -0
  46. package/src/index.ts +5 -1
  47. package/src/isolated/lazyProjectModel.isolated.ts +25 -0
  48. package/src/models/project.ts +31 -1
  49. package/src/observability/local/models/obsTrace.ts +22 -5
  50. package/src/observability/local/traceStore.test.ts +7 -0
  51. package/src/observability/local/traceStore.ts +12 -0
  52. package/src/observability/routes/traces.test.ts +15 -0
  53. package/src/observability/routes/traces.ts +2 -0
  54. package/src/routes/gpt.test.ts +90 -1
  55. package/src/routes/gptActions.test.ts +282 -1
  56. package/src/routes/gptActions.ts +16 -2
  57. package/src/routes/projects.ts +4 -4
  58. package/src/service/agentBlocks.test.ts +95 -0
  59. package/src/service/agentBlocks.ts +114 -0
  60. package/src/service/chatTurn.ts +44 -15
  61. package/src/service/prompts.test.ts +21 -0
  62. package/src/service/prompts.ts +34 -7
  63. package/src/service/scaleStepper.test.ts +105 -0
  64. package/src/service/scaleStepper.ts +29 -0
  65. package/src/service/toggleChecklist.test.ts +126 -0
  66. package/src/service/toggleChecklist.ts +44 -0
  67. package/src/types/harness.ts +31 -2
  68. package/src/types/index.ts +22 -9
  69. package/src/types/observability.ts +3 -0
package/dist/aiApp.d.ts CHANGED
@@ -34,6 +34,11 @@ export interface AiAppOptions {
34
34
  mcpService?: MCPService;
35
35
  /** OpenAPI options passed through to route builders for spec generation. */
36
36
  openApiOptions?: Record<string, unknown>;
37
+ /**
38
+ * Mount the `/gpt/projects` routes, which register the `Project` model. Defaults to `true`;
39
+ * pass `false` when the app owns a model named `Project`.
40
+ */
41
+ projects?: boolean;
37
42
  /** Tool choice strategy for chat requests. Defaults to "auto" when tools are present. */
38
43
  toolChoice?: "auto" | "none" | "required";
39
44
  /** Cheap model ID used for generating conversation titles (e.g. "gemini-3.5-flash-lite"). Falls back to the main model if not set. */
package/dist/aiApp.js CHANGED
@@ -40,7 +40,7 @@ class AiApp {
40
40
  }
41
41
  register(app) {
42
42
  const router = app;
43
- const { aiService, asks, createModelFn, createServerModelFn, demoMode, fileStorageService, fileUploadsEnabled, gcsBucket, maxSteps, mcpService, openApiOptions, titleModelId, toolChoice, tools, } = this.options;
43
+ const { aiService, asks, createModelFn, createServerModelFn, demoMode, fileStorageService, fileUploadsEnabled, gcsBucket, maxSteps, mcpService, openApiOptions, projects, titleModelId, toolChoice, tools, } = this.options;
44
44
  const hasFileRoutes = Boolean(fileStorageService && gcsBucket);
45
45
  const chat = {
46
46
  aiService,
@@ -61,7 +61,9 @@ class AiApp {
61
61
  (0, gptHistories_1.addGptHistoryRoutes)(router, { chat, openApiOptions });
62
62
  (0, gpt_1.addGptRoutes)(router, chat);
63
63
  (0, aiRequestsExplorer_1.addAiRequestsExplorerRoutes)(router, { openApiOptions });
64
- (0, projects_1.addProjectRoutes)(router, { openApiOptions });
64
+ if (projects !== false) {
65
+ (0, projects_1.addProjectRoutes)(router, { openApiOptions });
66
+ }
65
67
  if (fileStorageService && gcsBucket) {
66
68
  (0, files_1.addFileRoutes)(router, {
67
69
  fileStorageService,
@@ -1,7 +1,7 @@
1
1
  import { APIError } from "@terreno/api";
2
2
  import { DateTime } from "luxon";
3
3
  import mongoose, { type ClientSession } from "mongoose";
4
- import type { HarnessApprovalModel, HarnessChildTaskOptions, HarnessCommit, HarnessConversationModel, HarnessCreateTaskOptions, HarnessEventModel, HarnessEventStreamModel, HarnessInboxEventModel, HarnessLeaseSettings, HarnessMemoModel, HarnessMessageModel, HarnessOwnerModel, HarnessOwnership, HarnessResolveInterruptedOptions, HarnessTaskDefinition, HarnessTaskDocument, HarnessTaskModel, HarnessTaskSpanKind, HarnessTestHooks, HarnessWaitCall, HarnessWaiting, HarnessWaitKind } from "../types/harness";
4
+ import type { HarnessApprovalModel, HarnessChildTaskOptions, HarnessCommit, HarnessConversationModel, HarnessCreateTaskOptions, HarnessEventModel, HarnessEventStreamModel, HarnessInboxEventModel, HarnessLeaseSettings, HarnessMemoModel, HarnessMessageModel, HarnessOwnerModel, HarnessOwnership, HarnessPromptRef, HarnessResolveInterruptedOptions, HarnessTaskDefinition, HarnessTaskDocument, HarnessTaskModel, HarnessTaskSpanKind, HarnessTestHooks, HarnessWaitCall, HarnessWaiting, HarnessWaitKind } from "../types/harness";
5
5
  import type { ObsSpanModel, ObsTraceModel } from "../types/observability";
6
6
  export interface HarnessModels {
7
7
  approval: HarnessApprovalModel;
@@ -41,6 +41,22 @@ export declare const newTaskLease: (lease: HarnessLeaseSettings) => {
41
41
  owner: string;
42
42
  token: string;
43
43
  };
44
+ /**
45
+ * Prompt refs as stored on `ObsTrace.prompts` (`{label?, name, version}`; a registry
46
+ * `body` is dropped), once each. Throws `invalidRequest` for a ref without a name, with a
47
+ * non-string label, or without a positive integer version.
48
+ */
49
+ export declare const tracePromptRefs: (refs: HarnessPromptRef[] | undefined) => HarnessPromptRef[];
50
+ /**
51
+ * Record `refs` on `traceId`'s `ObsTrace.prompts`, once each. Pass `session` to write
52
+ * inside a commit's transaction.
53
+ */
54
+ export declare const addTracePrompts: ({ models, refs, session, traceId, }: {
55
+ models: HarnessModels;
56
+ refs: HarnessPromptRef[];
57
+ session?: ClientSession;
58
+ traceId: mongoose.Types.ObjectId;
59
+ }) => Promise<void>;
44
60
  /**
45
61
  * Insert a root task with its `ObsTrace` and root `CHAIN` span in one transaction.
46
62
  * A repeated `requestId` hits the unique index, rolls the whole transaction back (so no
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.commitResolution = exports.commitInterruption = exports.expiredLeaseFilter = exports.commitAbort = exports.claimAbortHandler = exports.fenceForAbort = exports.wakeWaitingTask = exports.commitWaitResolution = exports.commitWaiting = exports.commitRetry = exports.commitPhase = exports.createChildTaskRecords = exports.createTaskRecords = exports.newTaskLease = exports.isDuplicateKeyError = exports.HarnessCommitConflictError = void 0;
6
+ exports.commitResolution = exports.commitInterruption = exports.expiredLeaseFilter = exports.commitAbort = exports.claimAbortHandler = exports.fenceForAbort = exports.wakeWaitingTask = exports.commitWaitResolution = exports.commitWaiting = exports.commitRetry = exports.commitPhase = exports.createChildTaskRecords = exports.createTaskRecords = exports.addTracePrompts = exports.tracePromptRefs = exports.newTaskLease = exports.isDuplicateKeyError = exports.HarnessCommitConflictError = void 0;
7
7
  const node_crypto_1 = require("node:crypto");
8
8
  const api_1 = require("@terreno/api");
9
9
  const luxon_1 = require("luxon");
@@ -75,6 +75,77 @@ const findByRequestId = async ({ definition, models, requestId, userId, }) => {
75
75
  }
76
76
  return existing;
77
77
  };
78
+ /**
79
+ * Prompt refs as stored on `ObsTrace.prompts` (`{label?, name, version}`; a registry
80
+ * `body` is dropped), once each. Throws `invalidRequest` for a ref without a name, with a
81
+ * non-string label, or without a positive integer version.
82
+ */
83
+ const tracePromptRefs = (refs) => {
84
+ if (refs === undefined) {
85
+ return [];
86
+ }
87
+ if (!Array.isArray(refs)) {
88
+ throw (0, errors_1.harnessError)({ detail: "prompts must be an array", kind: "invalidRequest" });
89
+ }
90
+ const unique = new Map();
91
+ for (const ref of refs) {
92
+ if (typeof ref?.name !== "string" || !ref.name.trim()) {
93
+ throw (0, errors_1.harnessError)({ detail: "Each prompt ref needs a name", kind: "invalidRequest" });
94
+ }
95
+ if (!Number.isInteger(ref.version) || ref.version < 1) {
96
+ throw (0, errors_1.harnessError)({
97
+ detail: `Prompt ref "${ref.name}" needs a positive integer version`,
98
+ kind: "invalidRequest",
99
+ });
100
+ }
101
+ if (ref.label !== undefined && typeof ref.label !== "string") {
102
+ throw (0, errors_1.harnessError)({
103
+ detail: `Prompt ref "${ref.name}" label must be a string`,
104
+ kind: "invalidRequest",
105
+ });
106
+ }
107
+ const normalized = {
108
+ ...(ref.label !== undefined ? { label: ref.label } : {}),
109
+ name: ref.name,
110
+ version: ref.version,
111
+ };
112
+ unique.set(JSON.stringify(normalized), normalized);
113
+ }
114
+ return [...unique.values()];
115
+ };
116
+ exports.tracePromptRefs = tracePromptRefs;
117
+ /** The `scope` and `tags` written onto a root task's `ObsTrace`. */
118
+ const traceFields = (trace) => {
119
+ if (trace === undefined) {
120
+ return {};
121
+ }
122
+ const { scope, tags } = trace;
123
+ if (scope !== undefined && (typeof scope !== "string" || !scope.trim())) {
124
+ throw (0, errors_1.harnessError)({ detail: "trace.scope must be a non-empty string", kind: "invalidRequest" });
125
+ }
126
+ const isBlankTag = (tag) => typeof tag !== "string" || !tag.trim();
127
+ if (tags !== undefined && (!Array.isArray(tags) || tags.some(isBlankTag))) {
128
+ throw (0, errors_1.harnessError)({
129
+ detail: "trace.tags must be an array of non-empty strings",
130
+ kind: "invalidRequest",
131
+ });
132
+ }
133
+ return {
134
+ ...(scope !== undefined ? { scope } : {}),
135
+ ...(tags !== undefined ? { tags: [...new Set(tags)] } : {}),
136
+ };
137
+ };
138
+ /**
139
+ * Record `refs` on `traceId`'s `ObsTrace.prompts`, once each. Pass `session` to write
140
+ * inside a commit's transaction.
141
+ */
142
+ const addTracePrompts = async ({ models, refs, session, traceId, }) => {
143
+ if (refs.length === 0) {
144
+ return;
145
+ }
146
+ await models.trace.updateOne({ _id: traceId }, { $addToSet: { prompts: { $each: refs } } }, session ? { session } : {});
147
+ };
148
+ exports.addTracePrompts = addTracePrompts;
78
149
  /**
79
150
  * Insert a root task with its `ObsTrace` and root `CHAIN` span in one transaction.
80
151
  * A repeated `requestId` hits the unique index, rolls the whole transaction back (so no
@@ -92,9 +163,22 @@ const createTaskRecords = async ({ definition, input, models, options, ownership
92
163
  const startedAt = traceStartedAt.toJSDate();
93
164
  const userId = toObjectId(options.userId);
94
165
  const spanIdentity = taskSpanIdentity(definition, input);
166
+ const prompts = (0, exports.tracePromptRefs)(options.prompts);
167
+ const traceExtras = traceFields(options.trace);
95
168
  try {
96
169
  return await (0, transaction_1.inTransaction)(async (session) => {
97
- await models.trace.create([{ _id: traceId, input, name: definition.key, startedAt, status: "ok", userId }], { session });
170
+ await models.trace.create([
171
+ {
172
+ _id: traceId,
173
+ input,
174
+ name: definition.key,
175
+ prompts,
176
+ startedAt,
177
+ status: "ok",
178
+ userId,
179
+ ...traceExtras,
180
+ },
181
+ ], { session });
98
182
  await models.span.create([
99
183
  {
100
184
  _id: rootSpanId,
@@ -43,7 +43,7 @@ const addHarnessApprovalRoutes = (router, { basePath, harness, openApi }) => {
43
43
  method: "POST",
44
44
  permissions: [api_1.Permissions.IsAuthenticated, canApprove],
45
45
  summary: "Approve a harness approval",
46
- tag: "harness",
46
+ tag: "harnessapprovals",
47
47
  },
48
48
  reject: {
49
49
  body: rejectBody,
@@ -52,7 +52,7 @@ const addHarnessApprovalRoutes = (router, { basePath, harness, openApi }) => {
52
52
  method: "POST",
53
53
  permissions: [api_1.Permissions.IsAuthenticated, canApprove],
54
54
  summary: "Reject a harness approval",
55
- tag: "harness",
55
+ tag: "harnessapprovals",
56
56
  },
57
57
  },
58
58
  permissions: {
@@ -48,7 +48,7 @@ const addHarnessConversationRoutes = (router, { basePath, harness, openApi }) =>
48
48
  method: "POST",
49
49
  permissions: [api_1.Permissions.IsAuthenticated, ownerOnly],
50
50
  summary: "Submit a message to a harness conversation",
51
- tag: "harness",
51
+ tag: "harnessconversations",
52
52
  },
53
53
  },
54
54
  permissions: {
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.addHarnessTaskRoutes = void 0;
4
4
  const api_1 = require("@terreno/api");
5
+ /** OpenAPI tag shared with the task read query, so mutations refresh that cache. */
6
+ const TASK_OPENAPI_TAG = "harnesstasks";
5
7
  const harness_1 = require("../../types/harness");
6
8
  const commit_1 = require("../commit");
7
9
  const errors_1 = require("../errors");
@@ -28,6 +30,81 @@ const ownerOrAdmin = (_method, user, task) => task ? (0, events_1.isOwnerOrAdmin
28
30
  // Checked against the document so a non-admin gets 403, not the pre-document 405.
29
31
  const adminOnly = (_method, user, task) => task ? Boolean(user?.admin) : true;
30
32
  const isCommitConflict = (error) => error instanceof commit_1.HarnessCommitConflictError;
33
+ const withoutLease = (value) => {
34
+ const doc = value;
35
+ const json = typeof doc.toObject === "function" ? doc.toObject() : { ...value };
36
+ const { lease: _lease, ...rest } = json;
37
+ return rest;
38
+ };
39
+ /** HTTP task reads omit the lease. The fencing token is a runner secret, not a client field. */
40
+ const taskResponseHandler = async (value) => {
41
+ if (Array.isArray(value)) {
42
+ return value.map((doc) => withoutLease(doc));
43
+ }
44
+ return withoutLease(value);
45
+ };
46
+ const stripLeaseFromOpenApiSpec = (spec) => {
47
+ if (!spec || typeof spec !== "object" || !("responses" in spec)) {
48
+ return spec;
49
+ }
50
+ const responses = spec.responses;
51
+ if (!responses || typeof responses !== "object") {
52
+ return spec;
53
+ }
54
+ const nextResponses = {};
55
+ for (const [status, response] of Object.entries(responses)) {
56
+ const content = response && typeof response === "object"
57
+ ? response.content
58
+ : undefined;
59
+ const json = content?.["application/json"];
60
+ const properties = json?.schema?.properties;
61
+ if (!properties || !("lease" in properties)) {
62
+ nextResponses[status] = response;
63
+ continue;
64
+ }
65
+ const { lease: _lease, ...rest } = properties;
66
+ const required = json?.schema?.required;
67
+ nextResponses[status] = {
68
+ ...response,
69
+ content: {
70
+ ...content,
71
+ "application/json": {
72
+ ...json,
73
+ schema: {
74
+ ...json?.schema,
75
+ properties: rest,
76
+ ...(Array.isArray(required)
77
+ ? { required: required.filter((field) => field !== "lease") }
78
+ : {}),
79
+ },
80
+ },
81
+ },
82
+ };
83
+ }
84
+ return { ...spec, responses: nextResponses };
85
+ };
86
+ /** Task OpenAPI schemas must not publish `lease`, including its fencing token. */
87
+ const openApiWithoutTaskLease = (openApi) => {
88
+ // The registrar is a middleware function with a `path` property, not a plain object.
89
+ if (!openApi ||
90
+ (typeof openApi !== "object" && typeof openApi !== "function") ||
91
+ !("path" in openApi)) {
92
+ return openApi;
93
+ }
94
+ const registrar = openApi;
95
+ return new Proxy(registrar, {
96
+ get(target, prop, receiver) {
97
+ if (prop === "path") {
98
+ return (spec) => target.path(stripLeaseFromOpenApiSpec(spec));
99
+ }
100
+ const value = Reflect.get(target, prop, receiver);
101
+ if (typeof value === "function") {
102
+ return value.bind(target);
103
+ }
104
+ return value;
105
+ },
106
+ });
107
+ };
31
108
  /**
32
109
  * Mount `{basePath}/tasks`: read (owner or admin), plus the `abort` (owner or admin) and
33
110
  * `resolveInterrupted` (admin) instance actions. Tasks are not listed or edited over HTTP.
@@ -75,7 +152,11 @@ const addHarnessTaskRoutes = (router, { basePath, harness, openApi }) => {
75
152
  }
76
153
  };
77
154
  router.use(`${basePath}/tasks`, (0, api_1.modelRouter)(model, {
78
- ...(openApi ? { openApi: openApi } : {}),
155
+ ...(openApi
156
+ ? {
157
+ openApi: openApiWithoutTaskLease(openApi),
158
+ }
159
+ : {}),
79
160
  instanceActions: {
80
161
  abort: {
81
162
  body: abortBody,
@@ -84,7 +165,7 @@ const addHarnessTaskRoutes = (router, { basePath, harness, openApi }) => {
84
165
  method: "POST",
85
166
  permissions: [api_1.Permissions.IsAuthenticated, ownerOrAdmin],
86
167
  summary: "Abort a harness task",
87
- tag: "harness",
168
+ tag: TASK_OPENAPI_TAG,
88
169
  },
89
170
  resolveInterrupted: {
90
171
  body: resolveBody,
@@ -93,7 +174,7 @@ const addHarnessTaskRoutes = (router, { basePath, harness, openApi }) => {
93
174
  method: "POST",
94
175
  permissions: [api_1.Permissions.IsAuthenticated, adminOnly],
95
176
  summary: "Resolve an interrupted harness task",
96
- tag: "harness",
177
+ tag: TASK_OPENAPI_TAG,
97
178
  },
98
179
  },
99
180
  permissions: {
@@ -103,6 +184,7 @@ const addHarnessTaskRoutes = (router, { basePath, harness, openApi }) => {
103
184
  read: [api_1.Permissions.IsAuthenticated, ownerOrAdmin],
104
185
  update: [],
105
186
  },
187
+ responseHandler: taskResponseHandler,
106
188
  }));
107
189
  };
108
190
  exports.addHarnessTaskRoutes = addHarnessTaskRoutes;
@@ -456,16 +456,22 @@ const runPhase = async ({ controller, definition, engine, lease, task, }) => {
456
456
  throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.runAgent output for "${agent.name}" cannot be expressed as JSON Schema: ${(0, errors_1.errorMessage)(error)}`);
457
457
  }
458
458
  }
459
+ const { instructions, prompts } = (0, subagent_1.subagentPrompts)({
460
+ instructions: options.instructions,
461
+ prompts: options.prompts,
462
+ where: `${definition.key}: rt.runAgent`,
463
+ });
459
464
  const { conversationId, turnTask } = await (0, subagent_1.startSubagentTurn)({
460
465
  agent,
461
466
  callIndex,
462
467
  content,
463
468
  extensions: engine.extensions,
464
- instructions: options.instructions,
469
+ instructions,
465
470
  lease,
466
471
  models,
467
472
  outputSchema,
468
473
  parent: task,
474
+ prompts,
469
475
  turn,
470
476
  });
471
477
  engine.wake();
@@ -1,5 +1,5 @@
1
1
  import type { z } from "@terreno/api";
2
- import type { HarnessAgentDefinition, HarnessChildOutcome, HarnessExtensionDefinition, HarnessLeaseSettings, HarnessTaskDefinition, HarnessTaskDocument } from "../types/harness";
2
+ import type { HarnessAgentDefinition, HarnessChildOutcome, HarnessExtensionDefinition, HarnessLeaseSettings, HarnessPromptInstructions, HarnessPromptRef, HarnessTaskDefinition, HarnessTaskDocument } from "../types/harness";
3
3
  import { type HarnessModels } from "./commit";
4
4
  /** A subagent run by `rt.runAgent` did not produce a usable answer. */
5
5
  export declare class HarnessSubagentError extends Error {
@@ -17,6 +17,19 @@ export declare class HarnessSubagentError extends Error {
17
17
  }
18
18
  /** The subagent's user message: strings as-is, anything else as JSON. */
19
19
  export declare const subagentContent: (input: unknown) => string | undefined;
20
+ /**
21
+ * Split `rt.runAgent`'s instructions into the text the agent runs with and the prompt
22
+ * versions to record on the trace. A registry prompt passed as `instructions` is used by
23
+ * its `body` and recorded alongside `prompts`.
24
+ */
25
+ export declare const subagentPrompts: ({ instructions, prompts, where, }: {
26
+ instructions?: HarnessPromptInstructions | string;
27
+ prompts?: HarnessPromptRef[];
28
+ where: string;
29
+ }) => {
30
+ instructions?: string;
31
+ prompts: HarnessPromptRef[];
32
+ };
20
33
  /**
21
34
  * Serialize `schema` as JSON Schema with the AI SDK's own converter, so the turn requests
22
35
  * exactly the structure `Output.object` would. Stored as a string: JSON Schema keys such
@@ -28,7 +41,7 @@ export declare const serializeOutputSchema: (schema: z.ZodType) => Promise<strin
28
41
  * `parent` with an `AGENT` span named after the agent) in one transaction. A re-run of
29
42
  * the same phase attempt finds the turn created first, and with it the same conversation.
30
43
  */
31
- export declare const startSubagentTurn: ({ agent, callIndex, content, extensions, instructions, lease, models, outputSchema, parent, turn, }: {
44
+ export declare const startSubagentTurn: ({ agent, callIndex, content, extensions, instructions, lease, models, outputSchema, parent, prompts, turn, }: {
32
45
  agent: HarnessAgentDefinition;
33
46
  callIndex: number;
34
47
  content: string;
@@ -39,6 +52,8 @@ export declare const startSubagentTurn: ({ agent, callIndex, content, extensions
39
52
  models: HarnessModels;
40
53
  outputSchema?: string;
41
54
  parent: HarnessTaskDocument;
55
+ /** Prompt versions recorded on the parent's trace with the turn. */
56
+ prompts?: HarnessPromptRef[];
42
57
  turn: HarnessTaskDefinition;
43
58
  }) => Promise<{
44
59
  conversationId: string;
@@ -3,12 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.subagentResult = exports.startSubagentTurn = exports.serializeOutputSchema = exports.subagentContent = exports.HarnessSubagentError = void 0;
6
+ exports.subagentResult = exports.startSubagentTurn = exports.serializeOutputSchema = exports.subagentPrompts = exports.subagentContent = exports.HarnessSubagentError = void 0;
7
7
  const ai_1 = require("ai");
8
8
  const mongoose_1 = __importDefault(require("mongoose"));
9
9
  const harness_1 = require("../types/harness");
10
10
  const commit_1 = require("./commit");
11
11
  const conversation_1 = require("./conversation");
12
+ const definitionError_1 = require("./definitionError");
13
+ const errors_1 = require("./errors");
12
14
  const events_1 = require("./events");
13
15
  /** A subagent run by `rt.runAgent` did not produce a usable answer. */
14
16
  class HarnessSubagentError extends Error {
@@ -38,6 +40,27 @@ const subagentContent = (input) => {
38
40
  return JSON.stringify(input);
39
41
  };
40
42
  exports.subagentContent = subagentContent;
43
+ /**
44
+ * Split `rt.runAgent`'s instructions into the text the agent runs with and the prompt
45
+ * versions to record on the trace. A registry prompt passed as `instructions` is used by
46
+ * its `body` and recorded alongside `prompts`.
47
+ */
48
+ const subagentPrompts = ({ instructions, prompts, where, }) => {
49
+ const prompt = instructions !== undefined && typeof instructions !== "string" ? instructions : undefined;
50
+ if (prompt && typeof prompt.body !== "string") {
51
+ throw new definitionError_1.HarnessDefinitionError(`${where} instructions prompt needs a string body`);
52
+ }
53
+ try {
54
+ return {
55
+ instructions: prompt ? prompt.body : instructions,
56
+ prompts: (0, commit_1.tracePromptRefs)(prompt ? [prompt, ...(prompts ?? [])] : prompts),
57
+ };
58
+ }
59
+ catch (error) {
60
+ throw new definitionError_1.HarnessDefinitionError(`${where}: ${(0, errors_1.errorMessage)(error)}`);
61
+ }
62
+ };
63
+ exports.subagentPrompts = subagentPrompts;
41
64
  /**
42
65
  * Serialize `schema` as JSON Schema with the AI SDK's own converter, so the turn requests
43
66
  * exactly the structure `Output.object` would. Stored as a string: JSON Schema keys such
@@ -53,7 +76,7 @@ exports.serializeOutputSchema = serializeOutputSchema;
53
76
  * `parent` with an `AGENT` span named after the agent) in one transaction. A re-run of
54
77
  * the same phase attempt finds the turn created first, and with it the same conversation.
55
78
  */
56
- const startSubagentTurn = async ({ agent, callIndex, content, extensions, instructions, lease, models, outputSchema, parent, turn, }) => {
79
+ const startSubagentTurn = async ({ agent, callIndex, content, extensions, instructions, lease, models, outputSchema, parent, prompts = [], turn, }) => {
57
80
  const key = `agent:${callIndex}`;
58
81
  const newConversationId = new mongoose_1.default.Types.ObjectId();
59
82
  const input = { conversationId: String(newConversationId) };
@@ -72,6 +95,7 @@ const startSubagentTurn = async ({ agent, callIndex, content, extensions, instru
72
95
  name: agent.name,
73
96
  },
74
97
  writes: async ({ session, task }) => {
98
+ await (0, commit_1.addTracePrompts)({ models, refs: prompts, session, traceId: parent.traceId });
75
99
  await models.conversation.create([
76
100
  {
77
101
  _id: newConversationId,
package/dist/index.d.ts CHANGED
@@ -16,7 +16,7 @@ export { AIDataset } from "./models/aiDataset";
16
16
  export { AIRequest } from "./models/aiRequest";
17
17
  export { FileAttachment } from "./models/fileAttachment";
18
18
  export { GptHistory } from "./models/gptHistory";
19
- export { Project } from "./models/project";
19
+ export { getProjectModel, Project } from "./models/project";
20
20
  export { AI_OBSERVABILITY_GROUP, observabilityAdminScreens } from "./observability/adminScreens";
21
21
  export { LocalDatasetStore } from "./observability/local/datasetStore";
22
22
  export { LocalEvaluatorStore } from "./observability/local/evaluatorStore";
@@ -36,10 +36,12 @@ export { addGptRoutes } from "./routes/gpt";
36
36
  export { addGptHistoryRoutes } from "./routes/gptHistories";
37
37
  export { addMcpRoutes } from "./routes/mcp";
38
38
  export { addProjectRoutes } from "./routes/projects";
39
+ export { findAgentBlock } from "./service/agentBlocks";
39
40
  export type { RegisteredDataset } from "./service/aiDatasets";
40
41
  export { configureAiDatasets, registerAiDataset } from "./service/aiDatasets";
41
42
  export { AIService, TemperaturePresets } from "./service/aiService";
42
43
  export { createAskTools } from "./service/asks";
44
+ export { runBufferedChatTurn } from "./service/chatTurn";
43
45
  export { FileStorageService } from "./service/fileStorage";
44
46
  export type { ListGeminiApiModelsOptions } from "./service/gemini";
45
47
  export { GEMINI_API_BASE_URL, listGeminiApiModels, normalizeGeminiModelId, } from "./service/gemini";
@@ -48,6 +50,8 @@ export { MCPService } from "./service/mcpService";
48
50
  export type { ParseFailure, ParseResult, ParseSuccess } from "./service/parseAiJson";
49
51
  export { normalizeLlmJsonTextForStructuredOutput, parseAiJson, } from "./service/parseAiJson";
50
52
  export { COMPACT_SURFACE_SYSTEM_PROMPT, CONTENT_SUMMARY_PROMPT, DEFAULT_GPT_MEMORY, JSON_VALUE_SYSTEM_PROMPT, REMIX_PROMPT, TERRENO_ASKS_SYSTEM_PROMPT, TITLE_GENERATION_PROMPT, TRANSLATION_PROMPT, } from "./service/prompts";
53
+ export { scaleStepperHostAction } from "./service/scaleStepper";
54
+ export { toggleChecklistHostAction } from "./service/toggleChecklist";
51
55
  export type { CreateVertexProviderOptions, ListEnabledVertexModelsOptions, TerrenoVertexProvider, VerifyVertexModelsOptions, VertexLanguageModelProvider, VertexModelAvailability, } from "./service/vertex";
52
56
  export { assertVertexModelsEnabled, createVertexProvider, DEFAULT_VERTEX_LOCATION, isVertexModelAllowed, listEnabledVertexModels, normalizeVertexModelId, verifyVertexModelsEnabled, } from "./service/vertex";
53
57
  export type { WebSearchProvider, WebSearchResult } from "./service/webSearchTool";
package/dist/index.js CHANGED
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.addAiRequestsExplorerRoutes = exports.validateObservabilityConfig = exports.resolveObservabilityControl = exports.DEFAULT_OBSERVABILITY_CONTROL = exports.isLocalObservabilityPluginOn = exports.buildPlaygroundAiStatus = exports.buildObservabilityStatus = exports.resetObservabilityApp = exports.ObservabilityApp = exports.getObservabilityApp = exports.MemoryTraceSink = exports.MemoryScoreSink = exports.LocalTraceStore = exports.LocalTraceSink = exports.LocalScoreSink = exports.LocalReviewStore = exports.LocalPromptStore = exports.createLocalObservabilityPlugin = exports.createLocalObservabilityBundle = exports.LocalExperimentRunner = exports.LocalEvaluatorStore = exports.LocalDatasetStore = exports.observabilityAdminScreens = exports.AI_OBSERVABILITY_GROUP = exports.Project = exports.GptHistory = exports.FileAttachment = exports.AIRequest = exports.AIDataset = exports.preparePromptForAI = exports.createTelemetryConfig = exports.shutdownTracing = exports.initTracing = exports.invalidatePromptCache = exports.getPrompt = exports.createPrompt = exports.compilePrompt = exports.shutdownLangfuseClient = exports.isLangfuseInitialized = exports.initLangfuseClient = exports.getLangfuseClient = exports.setCached = exports.LangfuseCache = exports.invalidateCache = exports.getCached = exports.LangfuseApp = exports.AiApp = exports.AIAdminApp = exports.Output = exports.jsonSchema = void 0;
18
- exports.verifyVertexModelsEnabled = exports.normalizeVertexModelId = exports.listEnabledVertexModels = exports.isVertexModelAllowed = exports.DEFAULT_VERTEX_LOCATION = exports.createVertexProvider = exports.assertVertexModelsEnabled = exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.TERRENO_ASKS_SYSTEM_PROMPT = exports.REMIX_PROMPT = exports.JSON_VALUE_SYSTEM_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.COMPACT_SURFACE_SYSTEM_PROMPT = exports.parseAiJson = exports.normalizeLlmJsonTextForStructuredOutput = exports.MCPService = exports.getMCPTools = exports.normalizeGeminiModelId = exports.listGeminiApiModels = exports.GEMINI_API_BASE_URL = exports.FileStorageService = exports.createAskTools = exports.TemperaturePresets = exports.AIService = exports.registerAiDataset = exports.configureAiDatasets = exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = void 0;
17
+ exports.validateObservabilityConfig = exports.resolveObservabilityControl = exports.DEFAULT_OBSERVABILITY_CONTROL = exports.isLocalObservabilityPluginOn = exports.buildPlaygroundAiStatus = exports.buildObservabilityStatus = exports.resetObservabilityApp = exports.ObservabilityApp = exports.getObservabilityApp = exports.MemoryTraceSink = exports.MemoryScoreSink = exports.LocalTraceStore = exports.LocalTraceSink = exports.LocalScoreSink = exports.LocalReviewStore = exports.LocalPromptStore = exports.createLocalObservabilityPlugin = exports.createLocalObservabilityBundle = exports.LocalExperimentRunner = exports.LocalEvaluatorStore = exports.LocalDatasetStore = exports.observabilityAdminScreens = exports.AI_OBSERVABILITY_GROUP = exports.Project = exports.getProjectModel = exports.GptHistory = exports.FileAttachment = exports.AIRequest = exports.AIDataset = exports.preparePromptForAI = exports.createTelemetryConfig = exports.shutdownTracing = exports.initTracing = exports.invalidatePromptCache = exports.getPrompt = exports.createPrompt = exports.compilePrompt = exports.shutdownLangfuseClient = exports.isLangfuseInitialized = exports.initLangfuseClient = exports.getLangfuseClient = exports.setCached = exports.LangfuseCache = exports.invalidateCache = exports.getCached = exports.LangfuseApp = exports.AiApp = exports.AIAdminApp = exports.Output = exports.jsonSchema = void 0;
18
+ exports.verifyVertexModelsEnabled = exports.normalizeVertexModelId = exports.listEnabledVertexModels = exports.isVertexModelAllowed = exports.DEFAULT_VERTEX_LOCATION = exports.createVertexProvider = exports.assertVertexModelsEnabled = exports.toggleChecklistHostAction = exports.scaleStepperHostAction = exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.TERRENO_ASKS_SYSTEM_PROMPT = exports.REMIX_PROMPT = exports.JSON_VALUE_SYSTEM_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.COMPACT_SURFACE_SYSTEM_PROMPT = exports.parseAiJson = exports.normalizeLlmJsonTextForStructuredOutput = exports.MCPService = exports.getMCPTools = exports.normalizeGeminiModelId = exports.listGeminiApiModels = exports.GEMINI_API_BASE_URL = exports.FileStorageService = exports.runBufferedChatTurn = exports.createAskTools = exports.TemperaturePresets = exports.AIService = exports.registerAiDataset = exports.configureAiDatasets = exports.findAgentBlock = exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = void 0;
19
19
  var ai_1 = require("ai");
20
20
  Object.defineProperty(exports, "jsonSchema", { enumerable: true, get: function () { return ai_1.jsonSchema; } });
21
21
  Object.defineProperty(exports, "Output", { enumerable: true, get: function () { return ai_1.Output; } });
@@ -55,6 +55,7 @@ Object.defineProperty(exports, "FileAttachment", { enumerable: true, get: functi
55
55
  var gptHistory_1 = require("./models/gptHistory");
56
56
  Object.defineProperty(exports, "GptHistory", { enumerable: true, get: function () { return gptHistory_1.GptHistory; } });
57
57
  var project_1 = require("./models/project");
58
+ Object.defineProperty(exports, "getProjectModel", { enumerable: true, get: function () { return project_1.getProjectModel; } });
58
59
  Object.defineProperty(exports, "Project", { enumerable: true, get: function () { return project_1.Project; } });
59
60
  var adminScreens_1 = require("./observability/adminScreens");
60
61
  Object.defineProperty(exports, "AI_OBSERVABILITY_GROUP", { enumerable: true, get: function () { return adminScreens_1.AI_OBSERVABILITY_GROUP; } });
@@ -102,6 +103,8 @@ var mcp_1 = require("./routes/mcp");
102
103
  Object.defineProperty(exports, "addMcpRoutes", { enumerable: true, get: function () { return mcp_1.addMcpRoutes; } });
103
104
  var projects_1 = require("./routes/projects");
104
105
  Object.defineProperty(exports, "addProjectRoutes", { enumerable: true, get: function () { return projects_1.addProjectRoutes; } });
106
+ var agentBlocks_1 = require("./service/agentBlocks");
107
+ Object.defineProperty(exports, "findAgentBlock", { enumerable: true, get: function () { return agentBlocks_1.findAgentBlock; } });
105
108
  var aiDatasets_1 = require("./service/aiDatasets");
106
109
  Object.defineProperty(exports, "configureAiDatasets", { enumerable: true, get: function () { return aiDatasets_1.configureAiDatasets; } });
107
110
  Object.defineProperty(exports, "registerAiDataset", { enumerable: true, get: function () { return aiDatasets_1.registerAiDataset; } });
@@ -110,6 +113,8 @@ Object.defineProperty(exports, "AIService", { enumerable: true, get: function ()
110
113
  Object.defineProperty(exports, "TemperaturePresets", { enumerable: true, get: function () { return aiService_1.TemperaturePresets; } });
111
114
  var asks_1 = require("./service/asks");
112
115
  Object.defineProperty(exports, "createAskTools", { enumerable: true, get: function () { return asks_1.createAskTools; } });
116
+ var chatTurn_1 = require("./service/chatTurn");
117
+ Object.defineProperty(exports, "runBufferedChatTurn", { enumerable: true, get: function () { return chatTurn_1.runBufferedChatTurn; } });
113
118
  var fileStorage_1 = require("./service/fileStorage");
114
119
  Object.defineProperty(exports, "FileStorageService", { enumerable: true, get: function () { return fileStorage_1.FileStorageService; } });
115
120
  var gemini_1 = require("./service/gemini");
@@ -132,6 +137,10 @@ Object.defineProperty(exports, "REMIX_PROMPT", { enumerable: true, get: function
132
137
  Object.defineProperty(exports, "TERRENO_ASKS_SYSTEM_PROMPT", { enumerable: true, get: function () { return prompts_1.TERRENO_ASKS_SYSTEM_PROMPT; } });
133
138
  Object.defineProperty(exports, "TITLE_GENERATION_PROMPT", { enumerable: true, get: function () { return prompts_1.TITLE_GENERATION_PROMPT; } });
134
139
  Object.defineProperty(exports, "TRANSLATION_PROMPT", { enumerable: true, get: function () { return prompts_1.TRANSLATION_PROMPT; } });
140
+ var scaleStepper_1 = require("./service/scaleStepper");
141
+ Object.defineProperty(exports, "scaleStepperHostAction", { enumerable: true, get: function () { return scaleStepper_1.scaleStepperHostAction; } });
142
+ var toggleChecklist_1 = require("./service/toggleChecklist");
143
+ Object.defineProperty(exports, "toggleChecklistHostAction", { enumerable: true, get: function () { return toggleChecklist_1.toggleChecklistHostAction; } });
135
144
  var vertex_1 = require("./service/vertex");
136
145
  Object.defineProperty(exports, "assertVertexModelsEnabled", { enumerable: true, get: function () { return vertex_1.assertVertexModelsEnabled; } });
137
146
  Object.defineProperty(exports, "createVertexProvider", { enumerable: true, get: function () { return vertex_1.createVertexProvider; } });
@@ -1,2 +1,15 @@
1
1
  import type { ProjectModel } from "../types";
2
+ /**
3
+ * The AI chat `Project` model, registered on first use rather than on import, so an app
4
+ * that imports `@terreno/ai` can own a model named `Project` as long as it does not also
5
+ * use AI projects.
6
+ */
7
+ export declare const getProjectModel: () => ProjectModel;
8
+ /**
9
+ * Lazy stand-in for the `Project` model: every access registers it via `getProjectModel`.
10
+ * Statics, `new Project(...)` and `instanceof Project` work, but the proxy is not the model
11
+ * itself (`Project !== mongoose.models.Project`, `Object.keys(Project)` is empty, and reading
12
+ * `Project.prototype` throws).
13
+ * @deprecated Use `getProjectModel()`.
14
+ */
2
15
  export declare const Project: ProjectModel;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Project = void 0;
6
+ exports.Project = exports.getProjectModel = void 0;
7
7
  const api_1 = require("@terreno/api");
8
8
  const mongoose_1 = __importDefault(require("mongoose"));
9
9
  const memorySchema = new mongoose_1.default.Schema({
@@ -44,4 +44,34 @@ projectSchema.plugin(api_1.findExactlyOne);
44
44
  projectSchema.virtual("ownerId").get(function () {
45
45
  return this.userId;
46
46
  });
47
- exports.Project = mongoose_1.default.model("Project", projectSchema);
47
+ let projectModel;
48
+ /**
49
+ * The AI chat `Project` model, registered on first use rather than on import, so an app
50
+ * that imports `@terreno/ai` can own a model named `Project` as long as it does not also
51
+ * use AI projects.
52
+ */
53
+ const getProjectModel = () => {
54
+ projectModel ??= mongoose_1.default.model("Project", projectSchema);
55
+ return projectModel;
56
+ };
57
+ exports.getProjectModel = getProjectModel;
58
+ /**
59
+ * Lazy stand-in for the `Project` model: every access registers it via `getProjectModel`.
60
+ * Statics, `new Project(...)` and `instanceof Project` work, but the proxy is not the model
61
+ * itself (`Project !== mongoose.models.Project`, `Object.keys(Project)` is empty, and reading
62
+ * `Project.prototype` throws).
63
+ * @deprecated Use `getProjectModel()`.
64
+ */
65
+ // A class target keeps the proxy constructible, like a mongoose Model.
66
+ exports.Project = new Proxy(class LazyProject {
67
+ }, {
68
+ construct: (_target, args) => Reflect.construct((0, exports.getProjectModel)(), args),
69
+ get: (_target, property) => {
70
+ const model = (0, exports.getProjectModel)();
71
+ const value = Reflect.get(model, property, model);
72
+ return typeof value === "function" ? value.bind(model) : value;
73
+ },
74
+ getPrototypeOf: () => Reflect.getPrototypeOf((0, exports.getProjectModel)()),
75
+ has: (_target, property) => Reflect.has((0, exports.getProjectModel)(), property),
76
+ set: (_target, property, value) => Reflect.set((0, exports.getProjectModel)(), property, value),
77
+ });