@stigmer/react-core 0.3.1 → 0.4.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 (60) hide show
  1. package/README.md +1 -1
  2. package/agent/useAgentVersions.d.ts +76 -0
  3. package/agent/useAgentVersions.d.ts.map +1 -0
  4. package/agent/useAgentVersions.js +120 -0
  5. package/agent/useAgentVersions.js.map +1 -0
  6. package/file/useSessionFiles.d.ts +55 -0
  7. package/file/useSessionFiles.d.ts.map +1 -0
  8. package/file/useSessionFiles.js +113 -0
  9. package/file/useSessionFiles.js.map +1 -0
  10. package/index.d.ts +12 -0
  11. package/index.d.ts.map +1 -1
  12. package/index.js +6 -0
  13. package/index.js.map +1 -1
  14. package/package.json +3 -3
  15. package/run/deriveRunFileChanges.d.ts +31 -0
  16. package/run/deriveRunFileChanges.d.ts.map +1 -0
  17. package/run/deriveRunFileChanges.js +124 -0
  18. package/run/deriveRunFileChanges.js.map +1 -0
  19. package/run/tool-categories.d.ts +3 -1
  20. package/run/tool-categories.d.ts.map +1 -1
  21. package/run/useAnswerCustomToolUse.d.ts +62 -0
  22. package/run/useAnswerCustomToolUse.d.ts.map +1 -0
  23. package/run/useAnswerCustomToolUse.js +67 -0
  24. package/run/useAnswerCustomToolUse.js.map +1 -0
  25. package/run/useCreateRun.d.ts +9 -1
  26. package/run/useCreateRun.d.ts.map +1 -1
  27. package/run/useCreateRun.js +1 -0
  28. package/run/useCreateRun.js.map +1 -1
  29. package/session/useSessionConversation.d.ts +19 -0
  30. package/session/useSessionConversation.d.ts.map +1 -1
  31. package/session/useSessionConversation.js +12 -0
  32. package/session/useSessionConversation.js.map +1 -1
  33. package/session/useSessionFileChanges.d.ts +47 -0
  34. package/session/useSessionFileChanges.d.ts.map +1 -0
  35. package/session/useSessionFileChanges.js +46 -0
  36. package/session/useSessionFileChanges.js.map +1 -0
  37. package/session/useSessionOutputs.d.ts +71 -0
  38. package/session/useSessionOutputs.d.ts.map +1 -0
  39. package/session/useSessionOutputs.js +113 -0
  40. package/session/useSessionOutputs.js.map +1 -0
  41. package/src/agent/useAgentVersions.ts +186 -0
  42. package/src/file/useSessionFiles.ts +144 -0
  43. package/src/index.ts +12 -0
  44. package/src/run/deriveRunFileChanges.ts +135 -0
  45. package/src/run/tool-categories.ts +1 -1
  46. package/src/run/useAnswerCustomToolUse.ts +119 -0
  47. package/src/run/useCreateRun.ts +10 -1
  48. package/src/session/useSessionConversation.ts +43 -0
  49. package/src/session/useSessionFileChanges.ts +67 -0
  50. package/src/session/useSessionOutputs.ts +167 -0
  51. package/src/test/samples.ts +30 -0
  52. package/src/version-history/version-entry.ts +41 -0
  53. package/test/samples.d.ts +11 -0
  54. package/test/samples.d.ts.map +1 -1
  55. package/test/samples.js +28 -0
  56. package/test/samples.js.map +1 -1
  57. package/version-history/version-entry.d.ts +37 -0
  58. package/version-history/version-entry.d.ts.map +1 -0
  59. package/version-history/version-entry.js +6 -0
  60. package/version-history/version-entry.js.map +1 -0
package/src/index.ts CHANGED
@@ -19,9 +19,13 @@
19
19
 
20
20
  export { useAgentSearch } from "./agent/useAgentSearch.js";
21
21
  export type { UseAgentSearchOptions, UseAgentSearchReturn } from "./agent/useAgentSearch.js";
22
+ export { agentVersionLabel, useAgentVersions } from "./agent/useAgentVersions.js";
23
+ export type { UseAgentVersionsReturn } from "./agent/useAgentVersions.js";
22
24
  export type { InteractionModeOption } from "./composer/interaction-mode.js";
23
25
  export { StigmerContext } from "./context.js";
24
26
  export { DeploymentModeContext, useDeploymentMode, useResourceAvailable } from "./deployment-mode.js";
27
+ export { sessionFilesRefreshKey, useSessionFiles } from "./file/useSessionFiles.js";
28
+ export type { UseSessionFilesReturn } from "./file/useSessionFiles.js";
25
29
  export { useWhoAmI } from "./grant/useWhoAmI.js";
26
30
  export type { UseWhoAmIOptions, UseWhoAmIReturn } from "./grant/useWhoAmI.js";
27
31
  export { useStigmer } from "./hooks.js";
@@ -66,6 +70,7 @@ export type {
66
70
  FileReviewRowState,
67
71
  FileReviewability,
68
72
  } from "./run/file-review-status.js";
73
+ export { deriveRunFileChanges } from "./run/deriveRunFileChanges.js";
69
74
  export { runPhaseOf } from "./run/run-phases.js";
70
75
  export {
71
76
  defaultDisclosureForCategory,
@@ -81,6 +86,8 @@ export {
81
86
  export type { ToolDisclosure } from "./run/tool-categories.js";
82
87
  export { useAnswerToolUse } from "./run/useAnswerToolUse.js";
83
88
  export type { ToolUseAnswer, UseAnswerToolUseReturn } from "./run/useAnswerToolUse.js";
89
+ export { useAnswerCustomToolUse } from "./run/useAnswerCustomToolUse.js";
90
+ export type { CustomToolAnswerOptions, UseAnswerCustomToolUseReturn } from "./run/useAnswerCustomToolUse.js";
84
91
  export { useArtifactContent } from "./run/useArtifactContent.js";
85
92
  export type { UseArtifactContentReturn } from "./run/useArtifactContent.js";
86
93
  export { useArtifactDownloadUrl } from "./run/useArtifactDownloadUrl.js";
@@ -114,8 +121,12 @@ export { useSessionConversation } from "./session/useSessionConversation.js";
114
121
  export type { SendFollowUpOptions, UseSessionConversationReturn } from "./session/useSessionConversation.js";
115
122
  export { useSessionEvents } from "./session/useSessionEvents.js";
116
123
  export type { UseSessionEventsOptions, UseSessionEventsReturn } from "./session/useSessionEvents.js";
124
+ export { useSessionFileChanges } from "./session/useSessionFileChanges.js";
125
+ export type { UseSessionFileChangesReturn } from "./session/useSessionFileChanges.js";
117
126
  export { useSessionList } from "./session/useSessionList.js";
118
127
  export type { UseSessionListOptions, UseSessionListReturn } from "./session/useSessionList.js";
128
+ export { deriveSessionOutputs, outputKey, useSessionOutputs } from "./session/useSessionOutputs.js";
129
+ export type { SessionOutputEntry, UseSessionOutputsReturn } from "./session/useSessionOutputs.js";
119
130
  export { useSessionRuns } from "./session/useSessionRuns.js";
120
131
  export type { UseSessionRunsReturn } from "./session/useSessionRuns.js";
121
132
  export { useSessionUsage } from "./session/useSessionUsage.js";
@@ -129,6 +140,7 @@ export { useUpdateSession } from "./session/useUpdateSession.js";
129
140
  export type { UseUpdateSessionReturn } from "./session/useUpdateSession.js";
130
141
  export { computeDiff } from "./version-history/computeDiff.js";
131
142
  export type { DiffHunk, DiffLine } from "./version-history/diff-types.js";
143
+ export type { VersionEntry } from "./version-history/version-entry.js";
132
144
 
133
145
  // Types the public hooks' signatures name: exported so a host can type what
134
146
  // it passes and receives.
@@ -0,0 +1,135 @@
1
+ // Pure derivation of net file changes across a chronological list of agent
2
+ // runs.
3
+ // Domain: run (the session's Changes surface collapses per-execution
4
+ // captures into one net change per path; the non-trivial net-diff semantics
5
+ // below live in this one core).
6
+ //
7
+ // Not a hook: callers memoize on their runs reference
8
+ // (`useSessionFileChanges`).
9
+
10
+ import type { Run } from "@stigmer/apis/ai/stigmer/agentic/run/v1/api_pb";
11
+ import {
12
+ displayFileChangeSets,
13
+ toDisplayFileChange,
14
+ type DisplayFileChange,
15
+ type DisplayFileChangeType,
16
+ } from "@stigmer/client";
17
+
18
+ /**
19
+ * Collapses the file changes captured across `executions` into one *net*
20
+ * {@link DisplayFileChange} per path, ordered for a file list (modified, then
21
+ * added/renamed, then deleted; alphabetical within each group).
22
+ *
23
+ * **Source.** Each run's file record ({@link displayFileChangeSets}: the
24
+ * change sets it captured, `RunStatus.file_changes`), each captured change
25
+ * projected via {@link toDisplayFileChange}. A run's record already includes
26
+ * subagent captures, so one pass per run suffices. What was decided about a
27
+ * file is the session's events, not this list.
28
+ *
29
+ * **Net-diff (not latest-wins).** A change is a *delta*: an agent often
30
+ * rewrites the same file several times, and showing only the last edit's diff
31
+ * would misrepresent what changed. So changes to the same path are reduced to
32
+ * a single net change: `before` from the first change, `after` from the last.
33
+ * Every capture is a complete file snapshot, so `first.before -> last.after`
34
+ * is exactly the net change. A group with one change (the common case) is
35
+ * passed through untouched.
36
+ *
37
+ * **Ordering is a correctness input.** `executions` MUST be chronological:
38
+ * the net collapse anchors on each path's first and last change, so two
39
+ * runs touching the same path (a session's follow-up turns) produce a
40
+ * wrong net diff if visited out of order.
41
+ *
42
+ * Counts for captures stay derivable by the presentation layer, matching
43
+ * the contract the SDK `tool-view` established.
44
+ */
45
+ export function deriveRunFileChanges(
46
+ executions: readonly Run[],
47
+ ): readonly DisplayFileChange[] {
48
+ // Path -> chronological list of raw changes to that path.
49
+ const groups = new Map<string, DisplayFileChange[]>();
50
+ // Preserve first-seen path order as a stable tiebreaker before sorting.
51
+ const collect = (change: DisplayFileChange) => {
52
+ const key = change.path;
53
+ if (!key) return;
54
+ const list = groups.get(key);
55
+ if (list) list.push(change);
56
+ else groups.set(key, [change]);
57
+ };
58
+
59
+ for (const execution of executions) {
60
+ for (const set of displayFileChangeSets(execution.status)) {
61
+ for (const captured of set.changes) collect(toDisplayFileChange(captured));
62
+ }
63
+ }
64
+
65
+ const fileChanges = Array.from(groups.values(), netChange);
66
+ fileChanges.sort(fileChangeComparator);
67
+ return fileChanges;
68
+ }
69
+
70
+ /**
71
+ * Reduces a path's chronological change list to a single net change.
72
+ * A one-change group is returned as-is (the common path, no allocation).
73
+ */
74
+ function netChange(changes: DisplayFileChange[]): DisplayFileChange {
75
+ if (changes.length === 1) return changes[0];
76
+
77
+ const first = changes[0];
78
+ const last = changes[changes.length - 1];
79
+ const changeType = netChangeType(first, last);
80
+
81
+ return {
82
+ path: last.path,
83
+ changeType,
84
+ before: first.before,
85
+ after: last.after,
86
+ // Counts belong to one capture; the net diff's are derived from its sides.
87
+ linesAdded: 0,
88
+ linesRemoved: 0,
89
+ renameFrom: changeType === "renamed" ? first.renameFrom : "",
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Reconciles the net change of a path from its first and last change.
95
+ *
96
+ * Intent: the badge should describe the file's journey across the *whole*
97
+ * span of runs, anchored on its two endpoints, in this precedence:
98
+ *
99
+ * 1. Ends deleted (`last` is deleted) -> deleted. The file is gone, regardless
100
+ * of how it got there; this includes add-then-delete, which we deliberately
101
+ * surface as deleted rather than hiding the path. (`before` then comes from
102
+ * the first change, which for an added-then-deleted file is empty, so the
103
+ * diff reads as the removal of whatever briefly existed.)
104
+ * 2. Started added (`first` is added) and still exists -> added. A file born
105
+ * in this span and later modified is, on net, a new file.
106
+ * 3. Started renamed (`first` is renamed) and still exists -> renamed,
107
+ * carrying the original `renameFrom` so the move is preserved across later
108
+ * edits.
109
+ * 4. Otherwise -> modified (the common multi-edit case).
110
+ */
111
+ function netChangeType(
112
+ first: DisplayFileChange,
113
+ last: DisplayFileChange,
114
+ ): DisplayFileChangeType {
115
+ if (last.changeType === "deleted") return "deleted";
116
+ if (first.changeType === "added") return "added";
117
+ if (first.changeType === "renamed") return "renamed";
118
+ return "modified";
119
+ }
120
+
121
+ // Most-actionable first (modified), then additions (added/renamed), then
122
+ // deletions, mirroring GitHub's file-list convention; alphabetical within
123
+ // each group so the list is stable and scannable.
124
+ const CHANGE_TYPE_ORDER: Readonly<Record<DisplayFileChangeType, number>> = {
125
+ modified: 0,
126
+ added: 1,
127
+ renamed: 1,
128
+ deleted: 2,
129
+ };
130
+
131
+ function fileChangeComparator(a: DisplayFileChange, b: DisplayFileChange): number {
132
+ const order = CHANGE_TYPE_ORDER[a.changeType] - CHANGE_TYPE_ORDER[b.changeType];
133
+ if (order !== 0) return order;
134
+ return a.path.localeCompare(b.path, undefined, { sensitivity: "base" });
135
+ }
@@ -9,7 +9,7 @@ import {
9
9
  } from "@stigmer/client";
10
10
 
11
11
  /** What the presentation helpers read of a tool use: its name, MCP server and input. */
12
- export type ToolIdentity = Pick<ToolUse, "name" | "mcpServerName">;
12
+ export type ToolIdentity = Pick<ToolUse, "name" | "mcpServerName"> & { readonly custom?: boolean };
13
13
 
14
14
  /**
15
15
  * Discriminated tool categories for type-aware rendering.
@@ -0,0 +1,119 @@
1
+ "use client";
2
+
3
+ import { useCallback, useMemo, useState } from "react";
4
+ import { create } from "@bufbuild/protobuf";
5
+ import { AnswerCustomToolUseInputSchema } from "@stigmer/apis/ai/stigmer/agentic/session/v1/io_pb";
6
+ import { useStigmer } from "../hooks.js";
7
+ import { toError } from "../internal/toError.js";
8
+ import { useKeyedSubmission } from "../internal/useKeyedSubmission.js";
9
+
10
+ /** How an answer to one of the app's own tools is sent. */
11
+ export interface CustomToolAnswerOptions {
12
+ /**
13
+ * The tool failed, or the person cancelled: the agent reads the text as
14
+ * the tool's error and can try again or say so. Default `false`.
15
+ */
16
+ readonly isError?: boolean;
17
+ }
18
+
19
+ /** Return value of {@link useAnswerCustomToolUse}. */
20
+ export interface UseAnswerCustomToolUseReturn {
21
+ /**
22
+ * Answer a call of one of the app's own tools (a session's
23
+ * `custom_tools`), by its id (`ToolUse.id`, the `agent.custom_tool_use`
24
+ * event's id). The text is what the agent reads as the tool's result.
25
+ *
26
+ * Resolves when the server recorded the answer; the turn resumes on the
27
+ * session's stream once every call and approval it waits on is answered.
28
+ * The same answer sent again resolves (the server replays its first
29
+ * event); a different one rejects, since a call is answered once.
30
+ * Rejects with the server's error, which is also kept per call.
31
+ */
32
+ readonly answerCustomToolUse: (
33
+ sessionId: string,
34
+ customToolUseId: string,
35
+ text: string,
36
+ options?: CustomToolAnswerOptions,
37
+ ) => Promise<void>;
38
+ /** The calls whose answer is in flight, by id. */
39
+ readonly submittingIds: ReadonlySet<string>;
40
+ /**
41
+ * Each call's last failed answer, keyed like {@link submittingIds}.
42
+ * Cleared for a call when it is answered again.
43
+ */
44
+ readonly errorsById: ReadonlyMap<string, Error>;
45
+ /** The most recent failure, or `null`; the map is authoritative. */
46
+ readonly error: Error | null;
47
+ /** Reset every answer error (both {@link errorsById} and {@link error}). */
48
+ readonly clearError: () => void;
49
+ }
50
+
51
+ /**
52
+ * Behavior hook that answers the calls of an app's own tools
53
+ * (`answerCustomToolUse`), with per-call loading and error state. The
54
+ * twin of `useAnswerToolUse`, which answers approvals: an answer here is
55
+ * content the agent reads, never a verdict.
56
+ *
57
+ * Hosts drawing their own screen use it directly; the session viewer binds
58
+ * it for its tool cards and its `onCustomToolUse` callback.
59
+ *
60
+ * @example
61
+ * ```tsx
62
+ * import type { ToolUse } from "@stigmer/client";
63
+ *
64
+ * function RegisterButton({ sessionId, call }: { sessionId: string; call: ToolUse }) {
65
+ * const { answerCustomToolUse, submittingIds } = useAnswerCustomToolUse();
66
+ * return (
67
+ * <button
68
+ * disabled={submittingIds.has(call.id)}
69
+ * onClick={() => answerCustomToolUse(sessionId, call.id, "Registered as acct_7Q2F")}
70
+ * >
71
+ * Register
72
+ * </button>
73
+ * );
74
+ * }
75
+ * ```
76
+ */
77
+ export function useAnswerCustomToolUse(): UseAnswerCustomToolUseReturn {
78
+ const stigmer = useStigmer();
79
+ const keyed = useKeyedSubmission<void>();
80
+ const [error, setError] = useState<Error | null>(null);
81
+
82
+ const clearError = useCallback(() => {
83
+ keyed.clearErrors();
84
+ setError(null);
85
+ }, [keyed.clearErrors]);
86
+
87
+ const answerCustomToolUse = useCallback(
88
+ async (sessionId: string, customToolUseId: string, text: string, options?: CustomToolAnswerOptions): Promise<void> => {
89
+ setError(null);
90
+ try {
91
+ await keyed.run(customToolUseId, async () => {
92
+ await stigmer.session.answerCustomToolUse(
93
+ create(AnswerCustomToolUseInputSchema, {
94
+ sessionId,
95
+ customToolUseId,
96
+ content: [{ type: "text", text }],
97
+ isError: options?.isError === true,
98
+ }),
99
+ );
100
+ });
101
+ } catch (err) {
102
+ setError(toError(err));
103
+ throw err;
104
+ }
105
+ },
106
+ [stigmer, keyed.run],
107
+ );
108
+
109
+ return useMemo(
110
+ () => ({
111
+ answerCustomToolUse,
112
+ submittingIds: keyed.submittingKeys,
113
+ errorsById: keyed.errorsByKey,
114
+ error,
115
+ clearError,
116
+ }),
117
+ [answerCustomToolUse, keyed.submittingKeys, keyed.errorsByKey, error, clearError],
118
+ );
119
+ }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { useCallback, useState } from "react";
4
4
  import type { JsonObject } from "@bufbuild/protobuf";
5
- import { mergeSessionContext, type ResourceRef, type RunConfigInput, type SessionResourceInput } from "@stigmer/client";
5
+ import { mergeSessionContext, type CustomToolInput, type ResourceRef, type RunConfigInput, type SessionResourceInput } from "@stigmer/client";
6
6
  import { useStigmer } from "../hooks.js";
7
7
  import { toError } from "../internal/toError.js";
8
8
  import { toProtoInteractionMode } from "../composer/interaction-mode.js";
@@ -67,6 +67,14 @@ export interface BootstrapSessionSpec {
67
67
  * edits are applied, and an Undo puts a file back.
68
68
  */
69
69
  readonly fileReview?: boolean;
70
+ /**
71
+ * The app's own tools the conversation offers its agent (`custom_tools`;
72
+ * make each with `defineCustomTool` from `@stigmer/client`). A call of one
73
+ * waits for the app's answer (`answerCustomToolUse`). Read once, when the
74
+ * conversation is created: the tools are fixed once a turn has run. The
75
+ * server refuses a declaration it cannot offer, naming the rule.
76
+ */
77
+ readonly customTools?: readonly CustomToolInput[];
70
78
  /**
71
79
  * Custom key-value pairs stored on the created session's
72
80
  * `SessionSpec.metadata`.
@@ -400,6 +408,7 @@ export function useCreateRun(): UseCreateRunReturn {
400
408
  includeMyVault: input.sessionSpec.includeMyVault,
401
409
  environmentRef: input.sessionSpec.environmentRef,
402
410
  fileReview: input.sessionSpec.fileReview,
411
+ customTools: input.sessionSpec.customTools ? [...input.sessionSpec.customTools] : undefined,
403
412
  metadata: mergeSessionContext(
404
413
  input.sessionSpec.metadata,
405
414
  input.sessionSpec.sessionContext,
@@ -36,6 +36,7 @@ import { useConversationStoreRef } from "../internal/store/conversation-store.js
36
36
  import { useCreateRun, type SharedRunFields } from "../run/useCreateRun.js";
37
37
  import { useRunActions } from "../run/useRunActions.js";
38
38
  import { useAnswerToolUse, type ToolUseAnswer } from "../run/useAnswerToolUse.js";
39
+ import { useAnswerCustomToolUse, type CustomToolAnswerOptions } from "../run/useAnswerCustomToolUse.js";
39
40
  import { useStopBackgroundCommand } from "../run/useStopBackgroundCommand.js";
40
41
  import {
41
42
  useReviewFileChanges,
@@ -451,6 +452,29 @@ export interface UseSessionConversationReturn {
451
452
  /** Reset every answer error (both {@link answerErrors} and `answerError`). */
452
453
  readonly clearAnswerError: () => void;
453
454
 
455
+ /**
456
+ * The live turn's calls of the app's own tools (the session's
457
+ * `custom_tools`) that wait for the app's answer (`waiting_on_host`), in
458
+ * log order; empty when none. An answered call leaves the list, and an
459
+ * ended turn's unanswered calls read `stopped`, so a replayed
460
+ * conversation lists only what still waits.
461
+ */
462
+ readonly customToolUses: readonly ToolUse[];
463
+ /**
464
+ * Answer a call of the app's own tools: the text is what the agent reads
465
+ * as the tool's result, and `isError` tells it the tool failed. The
466
+ * session id is managed internally. Rejects with the server's error.
467
+ */
468
+ readonly answerCustomToolUse: (
469
+ customToolUseId: string,
470
+ text: string,
471
+ options?: CustomToolAnswerOptions,
472
+ ) => Promise<void>;
473
+ /** The custom tool calls whose answer is in flight, by id. */
474
+ readonly answeringCustomToolUseIds: ReadonlySet<string>;
475
+ /** Each custom tool call's last failed answer, keyed by its id. */
476
+ readonly customToolAnswerErrors: ReadonlyMap<string, Error>;
477
+
454
478
  /**
455
479
  * Stop one command the agent runs in the background, by the tool use that
456
480
  * started it (`ToolUse.background`); the turn goes on, and the agent is
@@ -646,6 +670,11 @@ export function useSessionConversation(
646
670
  error: answerError,
647
671
  clearError: clearAnswerError,
648
672
  } = useAnswerToolUse();
673
+ const {
674
+ answerCustomToolUse: rawAnswerCustomToolUse,
675
+ submittingIds: answeringCustomToolUseIds,
676
+ errorsById: customToolAnswerErrors,
677
+ } = useAnswerCustomToolUse();
649
678
  const {
650
679
  stopBackgroundCommand: rawStopBackgroundCommand,
651
680
  stoppingToolUseIds: stoppingBackgroundToolUseIds,
@@ -986,6 +1015,15 @@ export function useSessionConversation(
986
1015
  }, [sessionId, updatePendingSend, clearCreateError]);
987
1016
 
988
1017
  const asks = liveTurn?.asks ?? EMPTY_ASKS;
1018
+ const customToolUses = liveTurn?.customToolUses ?? EMPTY_ASKS;
1019
+
1020
+ const answerCustomToolUse = useCallback(
1021
+ async (customToolUseId: string, text: string, options?: CustomToolAnswerOptions): Promise<void> => {
1022
+ if (!sessionId) return;
1023
+ await rawAnswerCustomToolUse(sessionId, customToolUseId, text, options);
1024
+ },
1025
+ [sessionId, rawAnswerCustomToolUse],
1026
+ );
989
1027
 
990
1028
  const answerToolUse = useCallback(
991
1029
  async (toolUseId: string, answer: ToolUseAnswer, denyMessage?: string): Promise<void> => {
@@ -1120,6 +1158,11 @@ export function useSessionConversation(
1120
1158
  answerError,
1121
1159
  clearAnswerError,
1122
1160
 
1161
+ customToolUses,
1162
+ answerCustomToolUse,
1163
+ answeringCustomToolUseIds,
1164
+ customToolAnswerErrors,
1165
+
1123
1166
  stopBackgroundCommand,
1124
1167
  stoppingBackgroundToolUseIds,
1125
1168
  stopBackgroundErrors,
@@ -0,0 +1,67 @@
1
+ "use client";
2
+
3
+ // Every file a conversation's turns changed, one net change per path: the
4
+ // data a side list of the conversation's changes reads. A memoizing wrapper
5
+ // over `deriveRunFileChanges`, which holds the net-change rules.
6
+
7
+ import { useMemo } from "react";
8
+ import type { Run } from "@stigmer/apis/ai/stigmer/agentic/run/v1/api_pb";
9
+ import type { DisplayFileChange } from "@stigmer/client";
10
+ import { deriveRunFileChanges } from "../run/deriveRunFileChanges.js";
11
+
12
+ /** Return value of {@link useSessionFileChanges}. */
13
+ export interface UseSessionFileChangesReturn {
14
+ /**
15
+ * One {@link DisplayFileChange} per file touched in the session — the *net*
16
+ * change for that path (see {@link deriveRunFileChanges} for the
17
+ * net-diff semantics) — ordered for a file-list (modified, then
18
+ * created/renamed, then deleted; alphabetical within each group).
19
+ */
20
+ readonly fileChanges: readonly DisplayFileChange[];
21
+ /** `true` when at least one file was changed across all runs. */
22
+ readonly hasFileChanges: boolean;
23
+ /** Number of distinct files changed. */
24
+ readonly fileChangeCount: number;
25
+ }
26
+
27
+ /**
28
+ * Pure derivation hook that aggregates an agent's file changes across every
29
+ * run in a session into one net change per file. A headless building
30
+ * block for a consolidated session-changes surface (a side list of every
31
+ * file the conversation touched; the React kit draws one as its file
32
+ * changes view); the Console itself renders file changes in the transcript
33
+ * (stamped edit rows + the per-turn decision bar) and does not consume this
34
+ * hook.
35
+ *
36
+ * A thin memoizing wrapper over {@link deriveRunFileChanges} — the
37
+ * execution-domain core. The source (each run's file record, via
38
+ * `displayFileChangeSets`), the net-diff collapse, and the file-list ordering
39
+ * are all documented on the core.
40
+ *
41
+ * @param executions - All runs for a session, in chronological order.
42
+ * Pass both completed and active-stream runs. Ordering matters: the
43
+ * net collapse anchors on each path's first and last change.
44
+ *
45
+ * @example
46
+ * ```tsx
47
+ * function ChangedFileCount({ sessionId, org }: { sessionId: string; org: string }) {
48
+ * const conv = useSessionConversation(sessionId, org);
49
+ * const { fileChangeCount, hasFileChanges } = useSessionFileChanges(conv.runs);
50
+ * return hasFileChanges ? <span>{fileChangeCount} files changed</span> : null;
51
+ * }
52
+ * ```
53
+ *
54
+ * @see useFileChangeContent — resolves a change's before/after text for diffing
55
+ */
56
+ export function useSessionFileChanges(
57
+ executions: readonly Run[],
58
+ ): UseSessionFileChangesReturn {
59
+ return useMemo(() => {
60
+ const fileChanges = deriveRunFileChanges(executions);
61
+ return {
62
+ fileChanges,
63
+ hasFileChanges: fileChanges.length > 0,
64
+ fileChangeCount: fileChanges.length,
65
+ };
66
+ }, [executions]);
67
+ }
@@ -0,0 +1,167 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Pure derivation of what a conversation's agent saved: the Files its turns
5
+ * returned (what agents saved in their outputs folder), one entry per output
6
+ * path, newest turn winning, with the earlier versions behind it.
7
+ *
8
+ * Trade-offs:
9
+ * - Only Files a turn returned are listed; a person's uploads carry no run
10
+ * id and stay out (they are the conversation's inputs, listed by
11
+ * `useSessionGivenFiles`).
12
+ * - Identity is the output path, so a later turn saving `reports/q3.md` again
13
+ * takes the entry, the way a folder shows one file per path; the earlier
14
+ * Files at that path stay reachable in `earlier`, so no turn's output is
15
+ * lost from view.
16
+ */
17
+
18
+ import { useMemo } from "react";
19
+ import type { File as StigmerFile } from "@stigmer/apis/ai/stigmer/agentic/file/v1/api_pb";
20
+ import type { Run } from "@stigmer/apis/ai/stigmer/agentic/run/v1/api_pb";
21
+ import { RunPhase } from "@stigmer/apis/ai/stigmer/agentic/run/v1/enum_pb";
22
+ import { isTerminalPhase } from "../run/run-phases.js";
23
+
24
+ /**
25
+ * One output File, with what content views and Apply gating need about the
26
+ * turn that returned it.
27
+ */
28
+ export interface SessionOutputEntry {
29
+ /** The File the latest turn to save at this path returned. */
30
+ readonly file: StigmerFile;
31
+ /**
32
+ * The older Files saved at the same output path by earlier turns, newest
33
+ * first (the oldest last). Empty when one turn saved the path.
34
+ */
35
+ readonly earlier: readonly StigmerFile[];
36
+ /** ID of the run that returned this File. */
37
+ readonly runId: string;
38
+ /** Whether the run that returned it has ended. */
39
+ readonly isTerminal: boolean;
40
+ /**
41
+ * `true` when another entry shares this File's filename at a different
42
+ * output path. Consumers render the path's folder to tell them apart.
43
+ */
44
+ readonly hasNameCollision: boolean;
45
+ }
46
+
47
+ /** Return value of {@link useSessionOutputs}. */
48
+ export interface UseSessionOutputsReturn {
49
+ /** One entry per output path, sorted by filename. */
50
+ readonly outputs: readonly SessionOutputEntry[];
51
+ /** `true` when at least one turn returned a File. */
52
+ readonly hasOutputs: boolean;
53
+ /** Number of entries (output paths, not versions). */
54
+ readonly outputCount: number;
55
+ }
56
+
57
+ /**
58
+ * The stable identity of an output within a conversation: its output path
59
+ * (where the agent saved it under the outputs folder), falling back to the
60
+ * filename.
61
+ *
62
+ * The one identity of an output: the de-duplication here (newest turn wins
63
+ * per key) reads it, and so must anything that opens an output and later
64
+ * looks its entry up again (the React kit's editor tabs key an open output
65
+ * by it), or the lookup could miss its File.
66
+ */
67
+ export function outputKey(file: StigmerFile): string {
68
+ return file.status?.outputPath || file.spec?.filename || file.metadata?.id || "";
69
+ }
70
+
71
+ /**
72
+ * Pure derivation hook that lists the Files a conversation's turns returned,
73
+ * one per output path, sorted by filename — like a file explorer over the
74
+ * conversation's outputs.
75
+ *
76
+ * @param files - The conversation's Files, newest first (`useSessionFiles`).
77
+ * @param runs - The conversation's runs, in chronological order. A File's
78
+ * turn decides which of two Files at one path wins (the later turn) and
79
+ * whether the File's turn has ended.
80
+ *
81
+ * @example
82
+ * ```tsx
83
+ * function MadeFiles({ sessionId, org }: { sessionId: string; org: string }) {
84
+ * const conv = useSessionConversation(sessionId, org);
85
+ * const { files } = useSessionFiles(org, sessionId, sessionFilesRefreshKey(conv.runs));
86
+ * const { outputCount } = useSessionOutputs(files, conv.runs);
87
+ * return <p>{outputCount} files made</p>;
88
+ * }
89
+ * ```
90
+ */
91
+ export function useSessionOutputs(
92
+ files: readonly StigmerFile[],
93
+ runs: readonly Run[],
94
+ ): UseSessionOutputsReturn {
95
+ return useMemo(() => deriveSessionOutputs(files, runs), [files, runs]);
96
+ }
97
+
98
+ /**
99
+ * The derivation behind {@link useSessionOutputs}, for non-hook callers
100
+ * and tests.
101
+ */
102
+ export function deriveSessionOutputs(
103
+ files: readonly StigmerFile[],
104
+ runs: readonly Run[],
105
+ ): UseSessionOutputsReturn {
106
+ const runOrder = new Map<string, { readonly index: number; readonly terminal: boolean }>();
107
+ runs.forEach((run, index) => {
108
+ const id = run.metadata?.id;
109
+ if (!id) return;
110
+ runOrder.set(id, {
111
+ index,
112
+ terminal: isTerminalPhase(run.status?.phase ?? RunPhase.RUN_PHASE_UNSPECIFIED),
113
+ });
114
+ });
115
+
116
+ // Oldest first, so a later write to the same key wins: by the turn's place
117
+ // in the conversation, then by list position (the list is newest first).
118
+ // A File whose run is not loaded registered at that run's end, so it ranks
119
+ // before every loaded run and counts as ended.
120
+ const outputs = files
121
+ .map((file, position) => ({ file, position, runId: file.status?.runId ?? "" }))
122
+ .filter((output) => output.runId !== "")
123
+ .sort((a, b) => {
124
+ const ia = runOrder.get(a.runId)?.index ?? -1;
125
+ const ib = runOrder.get(b.runId)?.index ?? -1;
126
+ return ia !== ib ? ia - ib : b.position - a.position;
127
+ });
128
+
129
+ const entryMap = new Map<string, SessionOutputEntry>();
130
+ for (const { file, runId } of outputs) {
131
+ const key = outputKey(file);
132
+ const previous = entryMap.get(key);
133
+ entryMap.set(key, {
134
+ file,
135
+ earlier: previous ? [previous.file, ...previous.earlier] : [],
136
+ runId,
137
+ isTerminal: runOrder.get(runId)?.terminal ?? true,
138
+ hasNameCollision: false,
139
+ });
140
+ }
141
+
142
+ const entries = Array.from(entryMap.values());
143
+ entries.sort((a, b) =>
144
+ filenameOf(a.file).localeCompare(filenameOf(b.file), undefined, { sensitivity: "base" }),
145
+ );
146
+
147
+ const nameCount = new Map<string, number>();
148
+ for (const entry of entries) {
149
+ const lower = filenameOf(entry.file).toLowerCase();
150
+ nameCount.set(lower, (nameCount.get(lower) ?? 0) + 1);
151
+ }
152
+ const result = entries.map((entry) =>
153
+ (nameCount.get(filenameOf(entry.file).toLowerCase()) ?? 0) > 1
154
+ ? { ...entry, hasNameCollision: true }
155
+ : entry,
156
+ );
157
+
158
+ return {
159
+ outputs: result,
160
+ hasOutputs: result.length > 0,
161
+ outputCount: result.length,
162
+ };
163
+ }
164
+
165
+ function filenameOf(file: StigmerFile): string {
166
+ return file.spec?.filename ?? "";
167
+ }