@cognipeer/agent-sdk 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +300 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -3
- package/dist/index.d.ts +59 -3
- package/dist/index.mjs +299 -18
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -2016,27 +2016,71 @@ function convertMessageListToSections(messageList) {
|
|
|
2016
2016
|
}
|
|
2017
2017
|
return sections.length > 0 ? sections : void 0;
|
|
2018
2018
|
}
|
|
2019
|
-
function
|
|
2019
|
+
function readTraceContinuation(value) {
|
|
2020
|
+
if (!value || typeof value !== "object") return void 0;
|
|
2021
|
+
const raw = value;
|
|
2022
|
+
if (raw.v !== 1 || typeof raw.sessionId !== "string" || raw.sessionId.length === 0) return void 0;
|
|
2023
|
+
const nextSequence = Number(raw.nextSequence);
|
|
2024
|
+
const startedAt = Number(raw.startedAt);
|
|
2025
|
+
const part = Number(raw.part);
|
|
2026
|
+
if (!Number.isInteger(nextSequence) || nextSequence < 1) return void 0;
|
|
2027
|
+
if (!Number.isFinite(startedAt) || !Number.isInteger(part) || part < 1) return void 0;
|
|
2028
|
+
const summary = raw.summary && typeof raw.summary === "object" ? { ...createEmptySummary(), ...raw.summary } : createEmptySummary();
|
|
2029
|
+
summary.eventCounts = { ...raw.summary?.eventCounts ?? {} };
|
|
2030
|
+
return {
|
|
2031
|
+
v: 1,
|
|
2032
|
+
sessionId: raw.sessionId,
|
|
2033
|
+
traceId: typeof raw.traceId === "string" ? raw.traceId : void 0,
|
|
2034
|
+
rootSpanId: typeof raw.rootSpanId === "string" ? raw.rootSpanId : void 0,
|
|
2035
|
+
threadId: typeof raw.threadId === "string" ? raw.threadId : void 0,
|
|
2036
|
+
startedAt,
|
|
2037
|
+
nextSequence,
|
|
2038
|
+
part,
|
|
2039
|
+
summary,
|
|
2040
|
+
errors: Array.isArray(raw.errors) ? raw.errors : []
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
function traceContinuationOf(session) {
|
|
2044
|
+
return {
|
|
2045
|
+
v: 1,
|
|
2046
|
+
sessionId: session.sessionId,
|
|
2047
|
+
traceId: session.traceId,
|
|
2048
|
+
rootSpanId: session.rootSpanId,
|
|
2049
|
+
threadId: session.threadId,
|
|
2050
|
+
startedAt: session.startedAt,
|
|
2051
|
+
nextSequence: (session.sequenceOffset ?? 0) + session.events.length + 1,
|
|
2052
|
+
part: session.part ?? 1,
|
|
2053
|
+
summary: JSON.parse(JSON.stringify(session.summary)),
|
|
2054
|
+
// Sink failures belong to the part that hit them; carrying them on would
|
|
2055
|
+
// mark every later part `partial`.
|
|
2056
|
+
errors: session.errors.filter((error) => error.type !== "sink")
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
function createTraceSession(opts, continuation) {
|
|
2020
2060
|
const cfg = withDefaults(opts.tracing);
|
|
2021
2061
|
if (!cfg.enabled) return void 0;
|
|
2022
2062
|
const providedSessionId = opts.tracing?.sessionId?.trim();
|
|
2023
|
-
const sessionId = providedSessionId || generateSessionId();
|
|
2024
|
-
const traceId = generateTraceId();
|
|
2025
|
-
const rootSpanId = generateSpanId();
|
|
2063
|
+
const sessionId = continuation?.sessionId || providedSessionId || generateSessionId();
|
|
2064
|
+
const traceId = continuation?.traceId || generateTraceId();
|
|
2065
|
+
const rootSpanId = continuation?.rootSpanId || generateSpanId();
|
|
2026
2066
|
const runtime = {
|
|
2027
2067
|
sessionId,
|
|
2028
2068
|
traceId,
|
|
2029
2069
|
rootSpanId,
|
|
2030
|
-
threadId: opts.tracing?.threadId,
|
|
2070
|
+
threadId: continuation?.threadId ?? opts.tracing?.threadId,
|
|
2031
2071
|
configAgentName: opts.tracing?.agentName?.trim() || void 0,
|
|
2032
2072
|
configMetadata: opts.tracing?.metadata && Object.keys(opts.tracing.metadata).length > 0 ? opts.tracing.metadata : void 0,
|
|
2033
|
-
startedAt: Date.now(),
|
|
2073
|
+
startedAt: continuation?.startedAt ?? Date.now(),
|
|
2034
2074
|
resolvedConfig: cfg,
|
|
2035
2075
|
events: [],
|
|
2036
|
-
summary: createEmptySummary(),
|
|
2076
|
+
summary: continuation ? continuation.summary : createEmptySummary(),
|
|
2037
2077
|
status: "in_progress",
|
|
2038
|
-
errors: [],
|
|
2039
|
-
|
|
2078
|
+
errors: continuation ? [...continuation.errors] : [],
|
|
2079
|
+
// A continued session was announced by its first part; announcing it
|
|
2080
|
+
// again would reset a streaming receiver's copy.
|
|
2081
|
+
sessionStarted: Boolean(continuation),
|
|
2082
|
+
sequenceOffset: continuation ? continuation.nextSequence - 1 : 0,
|
|
2083
|
+
part: continuation ? continuation.part + 1 : 1
|
|
2040
2084
|
};
|
|
2041
2085
|
if (cfg.sink.type === "file") {
|
|
2042
2086
|
const baseDir = cfg.sink.baseDir;
|
|
@@ -2096,7 +2140,7 @@ async function startStreamingSession(session, agentRuntime) {
|
|
|
2096
2140
|
}
|
|
2097
2141
|
function recordTraceEvent(session, event) {
|
|
2098
2142
|
if (!session) return void 0;
|
|
2099
|
-
const sequence = session.events.length + 1;
|
|
2143
|
+
const sequence = (session.sequenceOffset ?? 0) + session.events.length + 1;
|
|
2100
2144
|
const id = generateEventId(sequence);
|
|
2101
2145
|
const timestampIso = event.timestamp || (/* @__PURE__ */ new Date()).toISOString();
|
|
2102
2146
|
const status = event.status ?? "success";
|
|
@@ -2286,7 +2330,8 @@ async function finalizeTraceSession(session, params = {}) {
|
|
|
2286
2330
|
summary: session.summary,
|
|
2287
2331
|
events: session.events,
|
|
2288
2332
|
status: status2,
|
|
2289
|
-
errors: session.errors
|
|
2333
|
+
errors: session.errors,
|
|
2334
|
+
...(session.part ?? 1) > 1 ? { continuation: { part: session.part, firstSequence: (session.sequenceOffset ?? 0) + 1 } } : {}
|
|
2290
2335
|
});
|
|
2291
2336
|
const payloadForSink = buildPayload(initialStatus);
|
|
2292
2337
|
let sinkFailed = false;
|
|
@@ -2343,7 +2388,17 @@ async function finalizeTraceSession(session, params = {}) {
|
|
|
2343
2388
|
if (sink.type === "file" && session.fileSessionDir) {
|
|
2344
2389
|
try {
|
|
2345
2390
|
const filePath = path.join(session.fileSessionDir, "trace.session.json");
|
|
2346
|
-
|
|
2391
|
+
let filePayload = finalPayload;
|
|
2392
|
+
if (finalPayload.continuation) {
|
|
2393
|
+
try {
|
|
2394
|
+
const previous = JSON.parse(await fs.promises.readFile(filePath, "utf8"));
|
|
2395
|
+
const earlier = (previous.events ?? []).filter((event) => event.sequence < finalPayload.continuation.firstSequence);
|
|
2396
|
+
filePayload = { ...finalPayload, events: [...earlier, ...finalPayload.events] };
|
|
2397
|
+
delete filePayload.continuation;
|
|
2398
|
+
} catch {
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
await fs.promises.writeFile(filePath, JSON.stringify(filePayload, null, 2), "utf8");
|
|
2347
2402
|
} catch (err) {
|
|
2348
2403
|
sinkFailed = true;
|
|
2349
2404
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -4782,6 +4837,207 @@ ${append}`;
|
|
|
4782
4837
|
};
|
|
4783
4838
|
}
|
|
4784
4839
|
|
|
4840
|
+
// src/utils/traceDecisions.ts
|
|
4841
|
+
var TRACED_KEY = "__outcomeTraced";
|
|
4842
|
+
function waitedMs(from, to) {
|
|
4843
|
+
if (!from || !to) return void 0;
|
|
4844
|
+
const ms = Date.parse(to) - Date.parse(from);
|
|
4845
|
+
return Number.isFinite(ms) && ms >= 0 ? ms : void 0;
|
|
4846
|
+
}
|
|
4847
|
+
function sameJson(a, b) {
|
|
4848
|
+
try {
|
|
4849
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
4850
|
+
} catch {
|
|
4851
|
+
return false;
|
|
4852
|
+
}
|
|
4853
|
+
}
|
|
4854
|
+
function recordApprovalRequested(session, entry) {
|
|
4855
|
+
if (!session) return;
|
|
4856
|
+
const logData = session.resolvedConfig.logData;
|
|
4857
|
+
const sections = [
|
|
4858
|
+
{
|
|
4859
|
+
kind: "metadata",
|
|
4860
|
+
label: "Approval",
|
|
4861
|
+
data: {
|
|
4862
|
+
approvalId: entry.id,
|
|
4863
|
+
toolCallId: entry.toolCallId,
|
|
4864
|
+
status: "pending",
|
|
4865
|
+
requestedAt: entry.requestedAt,
|
|
4866
|
+
...entry.metadata?.prompt !== void 0 ? { prompt: entry.metadata.prompt } : {}
|
|
4867
|
+
}
|
|
4868
|
+
}
|
|
4869
|
+
];
|
|
4870
|
+
if (logData) {
|
|
4871
|
+
sections.push({ kind: "tool_call", label: "Arguments to approve", tool: entry.toolName, arguments: sanitizeTracePayload(entry.args) });
|
|
4872
|
+
}
|
|
4873
|
+
recordTraceEvent(session, {
|
|
4874
|
+
type: "tool_approval",
|
|
4875
|
+
label: `Approval requested \xB7 ${entry.toolName}`,
|
|
4876
|
+
timestamp: entry.requestedAt,
|
|
4877
|
+
status: "pending",
|
|
4878
|
+
actor: { scope: "agent", name: entry.toolName, role: "approval_request" },
|
|
4879
|
+
sections
|
|
4880
|
+
});
|
|
4881
|
+
}
|
|
4882
|
+
function recordHumanDecisions(session, state) {
|
|
4883
|
+
if (!session) return;
|
|
4884
|
+
const logData = session.resolvedConfig.logData;
|
|
4885
|
+
for (const entry of state.pendingApprovals ?? []) {
|
|
4886
|
+
if (!entry.decidedAt || entry.metadata?.[TRACED_KEY]) continue;
|
|
4887
|
+
if (entry.status !== "approved" && entry.status !== "rejected") continue;
|
|
4888
|
+
const approved = entry.status === "approved";
|
|
4889
|
+
const edited = approved && entry.approvedArgs !== void 0 && !sameJson(entry.approvedArgs, entry.args);
|
|
4890
|
+
const sections = [
|
|
4891
|
+
{
|
|
4892
|
+
kind: "metadata",
|
|
4893
|
+
label: "Decision",
|
|
4894
|
+
data: {
|
|
4895
|
+
approvalId: entry.id,
|
|
4896
|
+
toolCallId: entry.toolCallId,
|
|
4897
|
+
decision: entry.status,
|
|
4898
|
+
...entry.decidedBy ? { decidedBy: entry.decidedBy } : {},
|
|
4899
|
+
...entry.comment ? { comment: entry.comment } : {},
|
|
4900
|
+
requestedAt: entry.requestedAt,
|
|
4901
|
+
decidedAt: entry.decidedAt,
|
|
4902
|
+
...waitedMs(entry.requestedAt, entry.decidedAt) !== void 0 ? { waitedMs: waitedMs(entry.requestedAt, entry.decidedAt) } : {},
|
|
4903
|
+
...edited ? { argumentsEdited: true } : {}
|
|
4904
|
+
}
|
|
4905
|
+
}
|
|
4906
|
+
];
|
|
4907
|
+
if (logData) {
|
|
4908
|
+
sections.push({ kind: "tool_call", label: "Requested arguments", tool: entry.toolName, arguments: sanitizeTracePayload(entry.args) });
|
|
4909
|
+
if (edited) {
|
|
4910
|
+
sections.push({ kind: "tool_call", label: "Approved arguments", tool: entry.toolName, arguments: sanitizeTracePayload(entry.approvedArgs) });
|
|
4911
|
+
}
|
|
4912
|
+
}
|
|
4913
|
+
recordTraceEvent(session, {
|
|
4914
|
+
type: "tool_approval",
|
|
4915
|
+
label: `${approved ? "Approved" : "Rejected"} \xB7 ${entry.toolName}`,
|
|
4916
|
+
timestamp: entry.decidedAt,
|
|
4917
|
+
durationMs: waitedMs(entry.requestedAt, entry.decidedAt),
|
|
4918
|
+
status: "success",
|
|
4919
|
+
actor: { scope: "human", name: entry.decidedBy || "reviewer", role: "approver" },
|
|
4920
|
+
sections
|
|
4921
|
+
});
|
|
4922
|
+
entry.metadata = { ...entry.metadata || {}, [TRACED_KEY]: true };
|
|
4923
|
+
}
|
|
4924
|
+
for (const entry of state.pendingUserQuestions ?? []) {
|
|
4925
|
+
if (!entry.answeredAt || entry.metadata?.[TRACED_KEY]) continue;
|
|
4926
|
+
if (entry.status !== "answered" && entry.status !== "cancelled") continue;
|
|
4927
|
+
const clientTool = readClientTool(entry);
|
|
4928
|
+
if (clientTool) {
|
|
4929
|
+
recordClientToolResult(session, entry, clientTool, state.toolHistory);
|
|
4930
|
+
entry.metadata = { ...entry.metadata || {}, [TRACED_KEY]: true };
|
|
4931
|
+
continue;
|
|
4932
|
+
}
|
|
4933
|
+
const cancelled = entry.status === "cancelled";
|
|
4934
|
+
const data = {
|
|
4935
|
+
questionId: entry.id,
|
|
4936
|
+
toolCallId: entry.toolCallId,
|
|
4937
|
+
status: entry.status,
|
|
4938
|
+
...entry.answeredBy ? { answeredBy: entry.answeredBy } : {},
|
|
4939
|
+
...entry.notes ? { notes: entry.notes } : {},
|
|
4940
|
+
requestedAt: entry.requestedAt,
|
|
4941
|
+
answeredAt: entry.answeredAt,
|
|
4942
|
+
...waitedMs(entry.requestedAt, entry.answeredAt) !== void 0 ? { waitedMs: waitedMs(entry.requestedAt, entry.answeredAt) } : {}
|
|
4943
|
+
};
|
|
4944
|
+
const sections = [{ kind: "metadata", label: "Answer", data }];
|
|
4945
|
+
if (logData) {
|
|
4946
|
+
sections.push({
|
|
4947
|
+
kind: "metadata",
|
|
4948
|
+
label: "Questions and answers",
|
|
4949
|
+
data: {
|
|
4950
|
+
items: (entry.questions ?? []).map((item) => ({
|
|
4951
|
+
question: item.question,
|
|
4952
|
+
...item.header ? { header: item.header } : {},
|
|
4953
|
+
answer: sanitizeTracePayload(entry.answers?.[item.question] ?? (item.header ? entry.answers?.[item.header] : void 0) ?? null)
|
|
4954
|
+
}))
|
|
4955
|
+
}
|
|
4956
|
+
});
|
|
4957
|
+
}
|
|
4958
|
+
recordTraceEvent(session, {
|
|
4959
|
+
type: "user_question",
|
|
4960
|
+
label: cancelled ? "Question cancelled" : "Answer from user",
|
|
4961
|
+
timestamp: entry.answeredAt,
|
|
4962
|
+
durationMs: waitedMs(entry.requestedAt, entry.answeredAt),
|
|
4963
|
+
status: cancelled ? "skipped" : "success",
|
|
4964
|
+
actor: { scope: "human", name: entry.answeredBy || "user", role: "user" },
|
|
4965
|
+
sections
|
|
4966
|
+
});
|
|
4967
|
+
entry.metadata = { ...entry.metadata || {}, [TRACED_KEY]: true };
|
|
4968
|
+
}
|
|
4969
|
+
}
|
|
4970
|
+
function recordClientToolRequested(session, entry) {
|
|
4971
|
+
if (!session) return;
|
|
4972
|
+
const clientTool = readClientTool(entry);
|
|
4973
|
+
if (!clientTool) return;
|
|
4974
|
+
const sections = [
|
|
4975
|
+
{
|
|
4976
|
+
kind: "metadata",
|
|
4977
|
+
label: "Client tool",
|
|
4978
|
+
data: { questionId: entry.id, toolCallId: entry.toolCallId, status: "pending", requestedAt: entry.requestedAt }
|
|
4979
|
+
}
|
|
4980
|
+
];
|
|
4981
|
+
if (session.resolvedConfig.logData) {
|
|
4982
|
+
sections.push({ kind: "tool_call", label: "Arguments", tool: clientTool.name, arguments: sanitizeTracePayload(clientTool.args) });
|
|
4983
|
+
}
|
|
4984
|
+
recordTraceEvent(session, {
|
|
4985
|
+
type: "tool_call",
|
|
4986
|
+
label: `Tool Execution - ${clientTool.name} (client)`,
|
|
4987
|
+
timestamp: entry.requestedAt,
|
|
4988
|
+
status: "pending",
|
|
4989
|
+
actor: { scope: "client", name: clientTool.name, role: "tool" },
|
|
4990
|
+
sections
|
|
4991
|
+
});
|
|
4992
|
+
}
|
|
4993
|
+
function readClientTool(entry) {
|
|
4994
|
+
const meta = entry.metadata?.clientTool;
|
|
4995
|
+
if (!meta || typeof meta !== "object" || typeof meta.name !== "string") return void 0;
|
|
4996
|
+
return { name: meta.name, args: meta.args };
|
|
4997
|
+
}
|
|
4998
|
+
function recordClientToolResult(session, entry, clientTool, toolHistory) {
|
|
4999
|
+
const step = [...toolHistory ?? []].reverse().find((item) => item?.tool_call_id === entry.toolCallId);
|
|
5000
|
+
const failed = step?.status === "error" || entry.status === "cancelled";
|
|
5001
|
+
const sections = [
|
|
5002
|
+
{
|
|
5003
|
+
kind: "metadata",
|
|
5004
|
+
label: "Client tool",
|
|
5005
|
+
data: {
|
|
5006
|
+
questionId: entry.id,
|
|
5007
|
+
toolCallId: entry.toolCallId,
|
|
5008
|
+
status: failed ? "error" : "answered",
|
|
5009
|
+
...entry.answeredBy ? { answeredBy: entry.answeredBy } : {},
|
|
5010
|
+
requestedAt: entry.requestedAt,
|
|
5011
|
+
answeredAt: entry.answeredAt,
|
|
5012
|
+
...waitedMs(entry.requestedAt, entry.answeredAt) !== void 0 ? { waitedMs: waitedMs(entry.requestedAt, entry.answeredAt) } : {}
|
|
5013
|
+
}
|
|
5014
|
+
}
|
|
5015
|
+
];
|
|
5016
|
+
if (session.resolvedConfig.logData) {
|
|
5017
|
+
sections.push({ kind: "tool_call", label: "Arguments", tool: clientTool.name, arguments: sanitizeTracePayload(clientTool.args) });
|
|
5018
|
+
if (step) {
|
|
5019
|
+
const output = step.rawOutput ?? step.output;
|
|
5020
|
+
sections.push({
|
|
5021
|
+
kind: "tool_result",
|
|
5022
|
+
label: "Result from client",
|
|
5023
|
+
tool: clientTool.name,
|
|
5024
|
+
output: sanitizeTracePayload(output),
|
|
5025
|
+
summary: typeof step.output === "string" ? step.output.slice(0, 2e3) : void 0
|
|
5026
|
+
});
|
|
5027
|
+
}
|
|
5028
|
+
}
|
|
5029
|
+
const ranMs = typeof step?.durationMs === "number" ? step.durationMs : void 0;
|
|
5030
|
+
recordTraceEvent(session, {
|
|
5031
|
+
type: "tool_call",
|
|
5032
|
+
label: `Tool Execution - ${clientTool.name} (client)`,
|
|
5033
|
+
timestamp: entry.answeredAt,
|
|
5034
|
+
durationMs: waitedMs(entry.requestedAt, entry.answeredAt) ?? ranMs,
|
|
5035
|
+
status: failed ? "error" : "success",
|
|
5036
|
+
actor: { scope: "client", name: clientTool.name, role: "tool" },
|
|
5037
|
+
sections
|
|
5038
|
+
});
|
|
5039
|
+
}
|
|
5040
|
+
|
|
4785
5041
|
// src/utils/traceSections.ts
|
|
4786
5042
|
init_content();
|
|
4787
5043
|
function truncate(text, max = 500) {
|
|
@@ -5250,6 +5506,7 @@ function createToolsNode(initialTools, opts) {
|
|
|
5250
5506
|
};
|
|
5251
5507
|
pendingApprovals.push(approvalEntry);
|
|
5252
5508
|
pendingByCallId.set(toolCallId, approvalEntry);
|
|
5509
|
+
recordApprovalRequested(traceSession, approvalEntry);
|
|
5253
5510
|
onEvent?.({ type: "tool_approval", status: "pending", id: approvalEntry.id, toolName: approvalEntry.toolName, toolCallId: approvalEntry.toolCallId, args });
|
|
5254
5511
|
if (host?.has("notification")) {
|
|
5255
5512
|
await host.runObservers("notification", {
|
|
@@ -5513,6 +5770,7 @@ function createToolsNode(initialTools, opts) {
|
|
|
5513
5770
|
if (!pendingApproval) {
|
|
5514
5771
|
throw new Error(`Tool ${toolName} requested approval but no pending approval entry was recorded.`);
|
|
5515
5772
|
}
|
|
5773
|
+
recordApprovalRequested(traceSession, pendingApproval);
|
|
5516
5774
|
awaitingApproval = true;
|
|
5517
5775
|
return {
|
|
5518
5776
|
status: "awaiting_approval",
|
|
@@ -5529,6 +5787,7 @@ function createToolsNode(initialTools, opts) {
|
|
|
5529
5787
|
if (!pendingQuestion) {
|
|
5530
5788
|
throw new Error(`Tool ${toolName} requested a user question but no pending question entry was recorded.`);
|
|
5531
5789
|
}
|
|
5790
|
+
recordClientToolRequested(traceSession, pendingQuestion);
|
|
5532
5791
|
awaitingUserQuestion = true;
|
|
5533
5792
|
if (host?.has("notification")) {
|
|
5534
5793
|
await host.runObservers("notification", {
|
|
@@ -6625,16 +6884,20 @@ function createAskUserQuestionTool(stateRef, config) {
|
|
|
6625
6884
|
});
|
|
6626
6885
|
recordTraceEvent(ctx.__traceSession, {
|
|
6627
6886
|
type: "user_question",
|
|
6628
|
-
label: "
|
|
6887
|
+
label: "Question to user",
|
|
6888
|
+
timestamp: entry.requestedAt,
|
|
6629
6889
|
actor: { scope: "agent", name: "ask_user_question", role: "user_interaction" },
|
|
6630
|
-
status: "
|
|
6890
|
+
status: "pending",
|
|
6631
6891
|
sections: [
|
|
6632
6892
|
{
|
|
6633
6893
|
kind: "metadata",
|
|
6634
6894
|
label: "Pending Question",
|
|
6635
6895
|
data: {
|
|
6636
6896
|
id: entry.id,
|
|
6897
|
+
questionId: entry.id,
|
|
6637
6898
|
toolCallId: entry.toolCallId,
|
|
6899
|
+
status: "pending",
|
|
6900
|
+
requestedAt: entry.requestedAt,
|
|
6638
6901
|
questions: entry.questions,
|
|
6639
6902
|
allowFreeText
|
|
6640
6903
|
}
|
|
@@ -7853,15 +8116,17 @@ function createAgent(opts) {
|
|
|
7853
8116
|
}
|
|
7854
8117
|
const traceSession = state.ctx?.__traceSession;
|
|
7855
8118
|
if (traceSession) {
|
|
8119
|
+
const iterationNumber = (traceSession.summary.eventCounts.agent_iteration ?? 0) + 1;
|
|
7856
8120
|
const iterEvent = recordTraceEvent(traceSession, {
|
|
7857
8121
|
type: "agent_iteration",
|
|
7858
|
-
label: `Iteration ${
|
|
8122
|
+
label: `Iteration ${iterationNumber}`,
|
|
7859
8123
|
actor: { scope: "agent", name: opts.name || "agent", role: "orchestrator" },
|
|
7860
8124
|
parentSpanId: traceSession.rootSpanId
|
|
7861
8125
|
});
|
|
7862
8126
|
if (iterEvent) {
|
|
7863
8127
|
traceSession.currentIterationSpanId = iterEvent.spanId;
|
|
7864
8128
|
}
|
|
8129
|
+
recordHumanDecisions(traceSession, state);
|
|
7865
8130
|
}
|
|
7866
8131
|
if (cancelIfRequested("loop")) break;
|
|
7867
8132
|
const skippingAgent = resumeStage === "tools";
|
|
@@ -8142,7 +8407,7 @@ function createAgent(opts) {
|
|
|
8142
8407
|
}
|
|
8143
8408
|
emit({ type: "progress", ...progress });
|
|
8144
8409
|
};
|
|
8145
|
-
const traceSession = createTraceSession(opts);
|
|
8410
|
+
const traceSession = createTraceSession(opts, readTraceContinuation(input.ctx?.__traceContinuation));
|
|
8146
8411
|
const ctx = {
|
|
8147
8412
|
...input.ctx || {},
|
|
8148
8413
|
__onEvent: onEvent,
|
|
@@ -8150,6 +8415,7 @@ function createAgent(opts) {
|
|
|
8150
8415
|
__onStream: onStream,
|
|
8151
8416
|
__streaming: streamEnabled
|
|
8152
8417
|
};
|
|
8418
|
+
delete ctx.__traceContinuation;
|
|
8153
8419
|
if (traceSession) ctx.__traceSession = traceSession;
|
|
8154
8420
|
delete ctx.__plugins;
|
|
8155
8421
|
delete ctx.__applySystemPromptContribution;
|
|
@@ -8298,10 +8564,17 @@ function createAgent(opts) {
|
|
|
8298
8564
|
}
|
|
8299
8565
|
}
|
|
8300
8566
|
}
|
|
8567
|
+
const pausedForHuman = statusFor(res) === "paused";
|
|
8568
|
+
const midTurn = pausedForHuman || Boolean(res.ctx?.__needsSummarization);
|
|
8301
8569
|
await finalizeTraceSession(traceSession, {
|
|
8302
8570
|
agentRuntime: res.agent || runtime,
|
|
8303
|
-
status: "success"
|
|
8571
|
+
status: pausedForHuman ? "paused" : midTurn ? "in_progress" : "success"
|
|
8304
8572
|
});
|
|
8573
|
+
if (traceSession && midTurn) {
|
|
8574
|
+
res.ctx = { ...res.ctx || {}, __traceContinuation: traceContinuationOf(traceSession) };
|
|
8575
|
+
} else if (res.ctx && "__traceContinuation" in res.ctx) {
|
|
8576
|
+
delete res.ctx.__traceContinuation;
|
|
8577
|
+
}
|
|
8305
8578
|
const isTransientSummarizationExit = !!res.ctx?.__needsSummarization;
|
|
8306
8579
|
const finalAssistantMsg = isTransientSummarizationExit ? void 0 : getLastAssistantMessage(res.messages);
|
|
8307
8580
|
const finalIsSyntheticSummary = !isTransientSummarizationExit && finalAssistantMsg && isSyntheticSummaryMessage(finalAssistantMsg);
|
|
@@ -11205,6 +11478,14 @@ ${pluginAppend}`;
|
|
|
11205
11478
|
} else if (lastResult.state) {
|
|
11206
11479
|
lastResult = { ...lastResult, state: { ...lastResult.state, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
|
|
11207
11480
|
}
|
|
11481
|
+
if (lastResult.state) {
|
|
11482
|
+
const endCtx = lastResult.state.ctx;
|
|
11483
|
+
if (endCtx?.__traceContinuation && !(endCtx.__awaitingApproval || endCtx.__awaitingUserQuestion || endCtx.__paused)) {
|
|
11484
|
+
const strippedCtx = { ...endCtx };
|
|
11485
|
+
delete strippedCtx.__traceContinuation;
|
|
11486
|
+
lastResult = { ...lastResult, state: { ...lastResult.state, ctx: strippedCtx } };
|
|
11487
|
+
}
|
|
11488
|
+
}
|
|
11208
11489
|
if (skillsEnabled && lastResult.state) {
|
|
11209
11490
|
const persisted = skillStateFromRegistry(toolSet.skillRegistryRef);
|
|
11210
11491
|
if (persisted) {
|
|
@@ -19346,6 +19627,6 @@ function createProvider(config) {
|
|
|
19346
19627
|
}
|
|
19347
19628
|
}
|
|
19348
19629
|
|
|
19349
|
-
export { ASK_USER_TOOL_NAME, AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, CCRStore, CONSOLE_HOOK_MAP, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, GuardrailPhase, HOOK_CONTRACT_VERSION, HOOK_NAMES, HookTimeoutError, InMemoryMemoryStore, JevProvider, MAX_ADJUSTMENTS, MODEL_RULES, ModelRequestError, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, PREOPEN_TOOL_CALL_PREFIX, ProviderError, SMALL_TIER_SKILL_POLICY, StructuredOutputManager, TOOL_INPUT_DIGEST_KEY, ToolBasedStrategy, VertexProvider, agentVerdictRule, allowsSampling, appendBoundTools, applyDropParams, asModelRequestError, auditLog, azureContentSafety, bedrockGuardrail, budgetGuard, buildHandoffTools, buildResponseFormatSection, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, buildToolDefinitionsSection, canOpenSkill, canSpawn, captureSnapshot, checkpointing, clearLearnedModelRules, codePresenceRule, coerceToolArgs, cognipeerGuardrail, cognipeerSink, collectAttachments, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, contentPartToText, contentToString, conversationHistory, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createGuardrailPlugin, createJsonGuardrail, createManageTodoListAliasTool, createManageTodoTool, createOpenSkillTool, createParallelTool, createPluginHost, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customGuardrail, customSink, dedupeToolsByName, defaultTokenCounter, defineHook, definePlugin, describeContentPart, detectLanguage, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, effortBudget, emptyUsage, evaluateGuardrails, extractLatestUserQuery, extractMessageText, fileCheckpointStore, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getLearnedModelRulePatch, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasMediaPart, hasToolResponseRecoveryReference, httpGuardrail, httpSink, inMemoryCheckpointStore, inMemoryConversationStore, isHookImplemented, isOpenAIHostedEndpoint, isSmartModel, isValidIban, isValidLuhn, isValidTckn, jsonSchemaRule, defaultBuildPayload as langfuseDefaultPayload, langfuseTracing, languageGuard, listLearnedModelRules, loadSkillsFromDisk, mapConsoleHookVerdict, mapReasoningEffort, mapTextParts, mcp, mediaKindOf, mediaPolicy, mergeRulePatch, modelIdCandidates, normalizeSmartAgentOptions, normalizeVerdicts, openAIModeration, otelTracing, otlpSink, outputGuard, parseApprovalDecision, parseModelError, parseSkillFrontmatter, pathSandbox, piiRedaction, pluginCapabilities, portkeyGateway, portkeyGuardrail, preopenSkills, preopenToolCallId, prepareStrictToolMenu, promptInjectionGuard, rateLimit, readMemoryFacts, redactText, regexGuardrail, regexRule, rememberModelRulePatch, replaceTextContent, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveModelRule, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, responseCache, restoreSnapshot, restoreToolCalls, runSmartAgentEvalHarness, runWithModelAdjustments, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, sessionMetrics, setTokenCounter, startStreamingSession, summarizeObject, supportsAdaptiveThinking, textFromContent, toMessageUsage, toStrictCompatible, toStrictToolSchema, tokenize, toolPolicy, traceSessionToOtlp, validateReasoningConfig, validateToolArgs, webhookApproval, withTools, withinDepth, writeSummaryFactsToMemory };
|
|
19630
|
+
export { ASK_USER_TOOL_NAME, AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, CCRStore, CONSOLE_HOOK_MAP, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, GuardrailPhase, HOOK_CONTRACT_VERSION, HOOK_NAMES, HookTimeoutError, InMemoryMemoryStore, JevProvider, MAX_ADJUSTMENTS, MODEL_RULES, ModelRequestError, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, PREOPEN_TOOL_CALL_PREFIX, ProviderError, SMALL_TIER_SKILL_POLICY, StructuredOutputManager, TOOL_INPUT_DIGEST_KEY, ToolBasedStrategy, VertexProvider, agentVerdictRule, allowsSampling, appendBoundTools, applyDropParams, asModelRequestError, auditLog, azureContentSafety, bedrockGuardrail, budgetGuard, buildHandoffTools, buildResponseFormatSection, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, buildToolDefinitionsSection, canOpenSkill, canSpawn, captureSnapshot, checkpointing, clearLearnedModelRules, codePresenceRule, coerceToolArgs, cognipeerGuardrail, cognipeerSink, collectAttachments, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, contentPartToText, contentToString, conversationHistory, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createGuardrailPlugin, createJsonGuardrail, createManageTodoListAliasTool, createManageTodoTool, createOpenSkillTool, createParallelTool, createPluginHost, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customGuardrail, customSink, dedupeToolsByName, defaultTokenCounter, defineHook, definePlugin, describeContentPart, detectLanguage, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, effortBudget, emptyUsage, evaluateGuardrails, extractLatestUserQuery, extractMessageText, fileCheckpointStore, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getLearnedModelRulePatch, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasMediaPart, hasToolResponseRecoveryReference, httpGuardrail, httpSink, inMemoryCheckpointStore, inMemoryConversationStore, isHookImplemented, isOpenAIHostedEndpoint, isSmartModel, isValidIban, isValidLuhn, isValidTckn, jsonSchemaRule, defaultBuildPayload as langfuseDefaultPayload, langfuseTracing, languageGuard, listLearnedModelRules, loadSkillsFromDisk, mapConsoleHookVerdict, mapReasoningEffort, mapTextParts, mcp, mediaKindOf, mediaPolicy, mergeRulePatch, modelIdCandidates, normalizeSmartAgentOptions, normalizeVerdicts, openAIModeration, otelTracing, otlpSink, outputGuard, parseApprovalDecision, parseModelError, parseSkillFrontmatter, pathSandbox, piiRedaction, pluginCapabilities, portkeyGateway, portkeyGuardrail, preopenSkills, preopenToolCallId, prepareStrictToolMenu, promptInjectionGuard, rateLimit, readMemoryFacts, readTraceContinuation, redactText, regexGuardrail, regexRule, rememberModelRulePatch, replaceTextContent, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveModelRule, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, responseCache, restoreSnapshot, restoreToolCalls, runSmartAgentEvalHarness, runWithModelAdjustments, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, sessionMetrics, setTokenCounter, startStreamingSession, summarizeObject, supportsAdaptiveThinking, textFromContent, toMessageUsage, toStrictCompatible, toStrictToolSchema, tokenize, toolPolicy, traceContinuationOf, traceSessionToOtlp, validateReasoningConfig, validateToolArgs, webhookApproval, withTools, withinDepth, writeSummaryFactsToMemory };
|
|
19350
19631
|
//# sourceMappingURL=index.mjs.map
|
|
19351
19632
|
//# sourceMappingURL=index.mjs.map
|