@gemies/sdk 10.0.3 → 10.2.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 (34) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +17 -0
  3. package/package.json +2 -1
  4. package/src/ask-lean.ts +11 -0
  5. package/src/components/GemieAskCore.tsx +1 -0
  6. package/src/components/GemieAskProviderLean.tsx +26 -0
  7. package/src/components/GemieAskSheet.tsx +7 -47
  8. package/src/components/GemieAskSheetBase.tsx +53 -0
  9. package/src/components/GemieAskSheetLean.tsx +10 -0
  10. package/src/components/GemieChatContent.tsx +32 -1
  11. package/src/components/GemieChatSheet.tsx +5 -0
  12. package/src/components/canvas/ChartRenderer.tsx +6 -3
  13. package/src/components/charts/chart-cards.ts +34 -0
  14. package/src/components/charts/default-chart-cards.ts +12 -0
  15. package/src/components/diff/FileChangeSection.tsx +172 -0
  16. package/src/components/diff/FileChangesCard.tsx +51 -0
  17. package/src/components/diff/FileChangesViewer.tsx +135 -0
  18. package/src/components/diff/PatchLines.tsx +119 -0
  19. package/src/components/diff/diff-renderer.ts +38 -0
  20. package/src/components/thread/ActionApprovalCard.tsx +95 -0
  21. package/src/components/thread/GemieThread.tsx +17 -0
  22. package/src/components/thread/ThreadRow.tsx +16 -1
  23. package/src/components/thread/ToolResultCard.tsx +16 -7
  24. package/src/index.ts +10 -0
  25. package/src/lib/copy-en.ts +40 -0
  26. package/src/lib/copy-es.ts +43 -0
  27. package/src/runtime/action-approvals.ts +127 -0
  28. package/src/runtime/config.tsx +16 -0
  29. package/src/runtime/index.ts +1 -0
  30. package/src/runtime/model.ts +1 -0
  31. package/src/runtime/routes.ts +5 -0
  32. package/src/runtime/thread/file-changes.ts +150 -0
  33. package/src/runtime/use-conversation-stream.ts +5 -1
  34. package/src/text.ts +3 -0
@@ -80,7 +80,50 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
80
80
  'chat.dislike': 'No me gusta',
81
81
  'chat.edit': 'Editar',
82
82
  'chat.feedbackFailed': 'No se ha podido guardar tu opinión.',
83
+ 'chat.fileChanges.binary': 'Archivo binario, sin vista previa',
84
+ 'chat.fileChanges.chip': { one: '1 archivo cambiado', other: '{{count}} archivos cambiados' },
85
+ 'chat.fileChanges.collapseAll': 'Contraer todo',
86
+ 'chat.fileChanges.copyPath': 'Copiar ruta',
87
+ 'chat.fileChanges.expandAll': 'Expandir todo',
88
+ 'chat.fileChanges.layout': 'Disposición',
89
+ 'chat.fileChanges.noContent': 'Sin cambios en el contenido',
90
+ 'chat.fileChanges.open': {
91
+ one: 'Revisar 1 archivo cambiado, +{{additions}} −{{deletions}}',
92
+ other: 'Revisar {{count}} archivos cambiados, +{{additions}} −{{deletions}}',
93
+ },
94
+ 'chat.fileChanges.operation.add': 'Añadido',
95
+ 'chat.fileChanges.operation.delete': 'Eliminado',
96
+ 'chat.fileChanges.operation.rename': 'Renombrado',
97
+ 'chat.fileChanges.operation.update': 'Modificado',
98
+ 'chat.fileChanges.renamedFrom': 'Renombrado desde {{path}}',
99
+ 'chat.fileChanges.showMore': {
100
+ one: 'Mostrar 1 línea más',
101
+ other: 'Mostrar {{count}} líneas más',
102
+ },
103
+ 'chat.fileChanges.split': 'Dividida',
104
+ 'chat.fileChanges.stats': '{{additions}} líneas añadidas, {{deletions}} líneas eliminadas',
105
+ 'chat.fileChanges.summary': {
106
+ one: '1 archivo cambiado, +{{additions}} −{{deletions}}',
107
+ other: '{{count}} archivos cambiados, +{{additions}} −{{deletions}}',
108
+ },
109
+ 'chat.fileChanges.title': 'Cambios',
110
+ 'chat.fileChanges.tooLarge': 'Demasiado grande para mostrarlo aquí',
111
+ 'chat.fileChanges.unified': 'Unificada',
112
+ 'chat.fileChanges.unrecorded': 'El agente no registró qué cambió en este archivo',
113
+ 'chat.fileChanges.wrap': 'Ajustar líneas',
83
114
  'chat.like': 'Me gusta',
115
+ 'chat.actionApproval.send': 'Enviar',
116
+ 'chat.actionApproval.approve': 'Aprobar',
117
+ 'chat.actionApproval.reject': 'Rechazar',
118
+ 'chat.actionApproval.status.pending': 'Pendiente de aprobación',
119
+ 'chat.actionApproval.status.approved': 'Aprobado',
120
+ 'chat.actionApproval.status.executing': 'En curso…',
121
+ 'chat.actionApproval.status.executed': 'Completado',
122
+ 'chat.actionApproval.status.failed': 'Fallido',
123
+ 'chat.actionApproval.status.rejected': 'Rechazado',
124
+ 'chat.actionApproval.status.expired': 'Caducado',
125
+ 'chat.actionApproval.sent': 'Enviado',
126
+ 'chat.actionApproval.decisionFailed': 'Tu decisión no se pudo guardar. Inténtalo de nuevo.',
84
127
  'chat.approval.allow': 'Permitir',
85
128
  'chat.approval.deny': 'Denegar',
86
129
  'chat.approval.resolved.allow': '%{tool}: permitido',
@@ -0,0 +1,127 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { useRealtimeEvent, useRealtimeReset } from '../realtime/react';
3
+ import { useGemieApi } from './api';
4
+ import { API_ROUTES } from './routes';
5
+
6
+ const STATUS_ORDER = {
7
+ pending: 0,
8
+ approved: 1,
9
+ executing: 2,
10
+ executed: 3,
11
+ failed: 3,
12
+ rejected: 3,
13
+ expired: 3,
14
+ };
15
+
16
+ export interface ActionApproval {
17
+ id: string;
18
+ conversationId: string;
19
+ messageId: string | null;
20
+ preview: {
21
+ title: string;
22
+ action: 'send' | 'approve';
23
+ fields: { name: string; label: string; value: string }[];
24
+ };
25
+ status: keyof typeof STATUS_ORDER;
26
+ expiresAt: string;
27
+ decidedAt: string | null;
28
+ error: string | null;
29
+ }
30
+
31
+ type DecideAction = (id: string, decision: 'approve' | 'reject') => Promise<void>;
32
+ export interface ConversationActionApprovals {
33
+ entries: readonly ActionApproval[];
34
+ decide: DecideAction;
35
+ }
36
+
37
+ const NO_ENTRIES: readonly ActionApproval[] = [];
38
+
39
+ export function useConversationActionApprovals(
40
+ userId: string | undefined,
41
+ conversationId: string | undefined,
42
+ streaming: boolean,
43
+ ): ConversationActionApprovals {
44
+ const api = useGemieApi();
45
+ const scope = userId && conversationId ? JSON.stringify([userId, conversationId]) : undefined;
46
+ const [snapshot, setSnapshot] = useState<{
47
+ scope: string;
48
+ entries: readonly ActionApproval[];
49
+ }>();
50
+ const entries = snapshot?.scope === scope ? (snapshot?.entries ?? NO_ENTRIES) : NO_ENTRIES;
51
+
52
+ const refresh = useCallback(
53
+ (signal?: AbortSignal) => {
54
+ if (!scope || !conversationId) return;
55
+ void api
56
+ .get<{ approvals: ActionApproval[] }>(API_ROUTES.actionApprovals.list, {
57
+ params: { conversationId },
58
+ signal,
59
+ })
60
+ .then(({ data }) => {
61
+ if (signal?.aborted || !Array.isArray(data?.approvals)) return;
62
+ setSnapshot((previous) => {
63
+ const known = previous?.scope === scope ? previous.entries : NO_ENTRIES;
64
+ const byId = new Map(known.map((entry) => [entry.id, entry]));
65
+ return {
66
+ scope,
67
+ entries: [...data.approvals].reverse().map((entry) => {
68
+ const old = byId.get(entry.id);
69
+ return old && STATUS_ORDER[old.status] > STATUS_ORDER[entry.status] ? old : entry;
70
+ }),
71
+ };
72
+ });
73
+ })
74
+ .catch(() => undefined);
75
+ },
76
+ [api, conversationId, scope],
77
+ );
78
+
79
+ useEffect(() => {
80
+ if (streaming) return;
81
+ const controller = new AbortController();
82
+ refresh(controller.signal);
83
+ return () => controller.abort();
84
+ }, [refresh, streaming]);
85
+
86
+ useRealtimeEvent('conversation', ({ data }) => {
87
+ const change = data as { conversation?: { id?: string } };
88
+ if (change.conversation?.id === conversationId) refresh();
89
+ });
90
+ useRealtimeReset(refresh);
91
+
92
+ // The account event is the usual wake. Poll only while a decision or provider receipt is due.
93
+ const awaitingDecision = entries.some((entry) => STATUS_ORDER[entry.status] < 3);
94
+ useEffect(() => {
95
+ if (!awaitingDecision) return;
96
+ const controller = new AbortController();
97
+ const timer = setInterval(() => refresh(controller.signal), 5000);
98
+ return () => {
99
+ controller.abort();
100
+ clearInterval(timer);
101
+ };
102
+ }, [awaitingDecision, refresh]);
103
+
104
+ const decide = useCallback<DecideAction>(
105
+ async (id, decision) => {
106
+ if (!scope) return;
107
+ const { data } = await api.post<ActionApproval>(
108
+ API_ROUTES.actionApprovals.decide(id, decision),
109
+ );
110
+ setSnapshot((previous) =>
111
+ previous?.scope !== scope
112
+ ? previous
113
+ : {
114
+ scope,
115
+ entries: previous.entries.map((entry) =>
116
+ entry.id === id && STATUS_ORDER[entry.status] <= STATUS_ORDER[data.status]
117
+ ? data
118
+ : entry,
119
+ ),
120
+ },
121
+ );
122
+ },
123
+ [api, scope],
124
+ );
125
+
126
+ return { entries, decide };
127
+ }
@@ -22,9 +22,20 @@ export interface GemieArtifact {
22
22
  timestamp: number;
23
23
  }
24
24
 
25
+ /**
26
+ * A turn answered on a lighter model because the person's credits ran out (`alia.credits_fallback`):
27
+ * why, and that the turn's tools are paused. Gemies pays for it; the person is charged nothing.
28
+ */
29
+ export interface GemieCreditsFallback {
30
+ reason: 'credits';
31
+ tools: 'paused';
32
+ }
33
+
25
34
  /** The usage frame a stream ends with: the balance left and, sometimes, a spending warning. */
26
35
  export interface GemieUsageFrame {
27
36
  credits_remaining?: number;
37
+ /** Present when Gemies funded the turn because the person's credits ran out. */
38
+ fallback?: GemieCreditsFallback;
28
39
  credit_warning?: {
29
40
  level?: string;
30
41
  daysRemaining?: unknown;
@@ -86,6 +97,11 @@ export interface GemieRuntimeHost {
86
97
  onOutput?: () => void;
87
98
  /** The stream's usage frame: credits left and the spending warning. */
88
99
  onUsage?: (usage: GemieUsageFrame) => void;
100
+ /**
101
+ * The turn about to stream is on the credits fallback: a lighter model with tools paused. Sent
102
+ * before the first token, so the host can say so while the answer arrives.
103
+ */
104
+ onCreditsFallback?: (fallback: GemieCreditsFallback) => void;
89
105
  /** A tool finished; `name` is the tool, `output` its structural result. */
90
106
  onToolResult?: (result: {
91
107
  toolCallId: string;
@@ -22,6 +22,7 @@ export type {
22
22
  GemieRuntimeHost,
23
23
  GemieRuntimeProviderProps,
24
24
  GemieTurnRequest,
25
+ GemieCreditsFallback,
25
26
  GemieUsageFrame,
26
27
  OfflineConversationStore,
27
28
  SpeechPreferences,
@@ -15,6 +15,7 @@ export type { Translate } from '../lib/copy';
15
15
  export * from './thread/agent-activity';
16
16
  export * from './thread/automation-labels';
17
17
  export * from './thread/conversation-export';
18
+ export * from './thread/file-changes';
18
19
  export * from './thread/message-days';
19
20
  export * from './thread/message-processor';
20
21
  export * from './thread/task-utils';
@@ -11,6 +11,11 @@
11
11
  */
12
12
  export const API_ROUTES = {
13
13
  chat: '/v1/chat/completions',
14
+ actionApprovals: {
15
+ list: '/v1/action-approvals',
16
+ decide: (id: string, decision: 'approve' | 'reject') =>
17
+ `/v1/action-approvals/${encodeURIComponent(id)}/${decision}`,
18
+ },
14
19
  /** The answer to an awaited host action, read by the turn that is waiting for it. */
15
20
  hostResults: (turnId: string) => `/v1/chat/turns/${encodeURIComponent(turnId)}/host-results`,
16
21
  /** The person's folders and projects (`runtime/collections.ts`). */
@@ -0,0 +1,150 @@
1
+ import type { ToolInvocation } from '../types';
2
+
3
+ /**
4
+ * The files an external agent (Claude Code, Codex, OpenCode) changed, as the conversation keeps
5
+ * them (ADR 0043 §5): the tool result of an edit carries `changes`, one standard `diff --git` patch
6
+ * per file, made by the server from whatever each CLI recorded
7
+ * (`packages/api/src/lib/external-agents/file-changes.ts`).
8
+ *
9
+ * Pure. The result is read like every tool result (`cardOf`): the snapshot is untrusted JSON, so
10
+ * every field is checked and an entry that is not a change is left out.
11
+ */
12
+
13
+ export type FileChangeOperation = 'add' | 'update' | 'delete' | 'rename';
14
+
15
+ export interface FileChange {
16
+ /** Relative to the agent's folder when the daemon said so. */
17
+ path: string;
18
+ /** Where a renamed file was. */
19
+ oldPath?: string;
20
+ operation: FileChangeOperation;
21
+ /** Not text (an image, a binary): its patch only says the file changed. */
22
+ binary: boolean;
23
+ /** Absent when nothing was recorded to build one from, or it was too large to keep. */
24
+ patch?: string;
25
+ additions: number;
26
+ deletions: number;
27
+ /** The patch was left out because it was too large (the stats are still the file's). */
28
+ truncated: boolean;
29
+ }
30
+
31
+ /** A change and the call that made it, so two edits of one file stay two sections. */
32
+ export interface CallFileChange extends FileChange {
33
+ /** Unique within the turn: the call's id and the file's place in it. */
34
+ key: string;
35
+ }
36
+
37
+ export interface FileChangeTotals {
38
+ /** Distinct paths: a file edited twice is one file. */
39
+ files: number;
40
+ additions: number;
41
+ deletions: number;
42
+ }
43
+
44
+ const OPERATIONS: readonly FileChangeOperation[] = ['add', 'update', 'delete', 'rename'];
45
+
46
+ const isCount = (value: unknown): value is number =>
47
+ typeof value === 'number' && Number.isFinite(value) && value >= 0;
48
+
49
+ function fileChange(value: unknown): FileChange | null {
50
+ if (value === null || typeof value !== 'object') return null;
51
+ const v = value as Record<string, unknown>;
52
+ if (typeof v.path !== 'string' || v.path === '') return null;
53
+ if (!OPERATIONS.includes(v.operation as FileChangeOperation)) return null;
54
+ return {
55
+ path: v.path,
56
+ ...(typeof v.oldPath === 'string' && v.oldPath !== '' ? { oldPath: v.oldPath } : {}),
57
+ operation: v.operation as FileChangeOperation,
58
+ binary: v.binary === true,
59
+ ...(typeof v.patch === 'string' ? { patch: v.patch } : {}),
60
+ additions: isCount(v.additions) ? v.additions : 0,
61
+ deletions: isCount(v.deletions) ? v.deletions : 0,
62
+ truncated: v.truncated === true,
63
+ };
64
+ }
65
+
66
+ /** The files a finished call changed, in the order it reported them; none for any other call. */
67
+ export function fileChangesOf(call: ToolInvocation): CallFileChange[] {
68
+ if (call.state !== 'result') return [];
69
+ const changes = (call.result as { changes?: unknown } | undefined)?.changes;
70
+ if (!Array.isArray(changes)) return [];
71
+ return changes.flatMap((entry, index) => {
72
+ const change = fileChange(entry);
73
+ return change === null ? [] : [{ ...change, key: `${call.toolCallId}:${index}` }];
74
+ });
75
+ }
76
+
77
+ /** Every file the calls of a turn changed, call by call. */
78
+ export function turnFileChanges(calls: readonly ToolInvocation[]): CallFileChange[] {
79
+ return calls.flatMap(fileChangesOf);
80
+ }
81
+
82
+ /** What "N files changed +X −Y" says of a list of changes. */
83
+ export function fileChangeTotals(changes: readonly FileChange[]): FileChangeTotals {
84
+ const files = new Set<string>();
85
+ let additions = 0;
86
+ let deletions = 0;
87
+ for (const change of changes) {
88
+ files.add(change.path);
89
+ additions += change.additions;
90
+ deletions += change.deletions;
91
+ }
92
+ return { files: files.size, additions, deletions };
93
+ }
94
+
95
+ /** The file's name, without its folder. */
96
+ export function fileChangeName(path: string): string {
97
+ const parts = path.replaceAll('\\', '/').split('/');
98
+ return parts.at(-1) || path;
99
+ }
100
+
101
+ /** One line of a patch's hunks, as a plain list can draw it. */
102
+ export type PatchLine =
103
+ | { kind: 'hunk'; text: string }
104
+ | { kind: 'context' | 'add' | 'delete'; text: string; oldLine?: number; newLine?: number }
105
+ | { kind: 'note'; text: string };
106
+
107
+ const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/;
108
+
109
+ /**
110
+ * The lines of a patch's hunks with their line numbers, for a view that draws no more than text.
111
+ * The headers before the first hunk (`diff --git`, `---`, `+++`, `new file mode`) are not lines of
112
+ * the file and are left out; `` is kept as a note.
113
+ */
114
+ export function patchLines(patch: string): PatchLine[] {
115
+ const out: PatchLine[] = [];
116
+ let oldLine = 0;
117
+ let newLine = 0;
118
+ let inHunk = false;
119
+ const lines = patch.split('\n');
120
+ if (lines.at(-1) === '') lines.pop();
121
+ for (const line of lines) {
122
+ const header = HUNK_HEADER.exec(line);
123
+ if (header) {
124
+ inHunk = true;
125
+ oldLine = Number(header[1]);
126
+ newLine = Number(header[2]);
127
+ out.push({ kind: 'hunk', text: line });
128
+ continue;
129
+ }
130
+ if (!inHunk) continue;
131
+ if (line.startsWith('\\')) {
132
+ out.push({ kind: 'note', text: line.slice(1).trim() });
133
+ } else if (line.startsWith('+')) {
134
+ out.push({ kind: 'add', text: line.slice(1), newLine: newLine++ });
135
+ } else if (line.startsWith('-')) {
136
+ out.push({ kind: 'delete', text: line.slice(1), oldLine: oldLine++ });
137
+ } else if (line.startsWith('diff --git ')) {
138
+ // A second file's section in a patch of several: the viewer is handed one file's patch.
139
+ break;
140
+ } else {
141
+ out.push({
142
+ kind: 'context',
143
+ text: line.startsWith(' ') ? line.slice(1) : line,
144
+ oldLine: oldLine++,
145
+ newLine: newLine++,
146
+ });
147
+ }
148
+ }
149
+ return out;
150
+ }
@@ -726,7 +726,7 @@ export function useConversationStream({
726
726
  return;
727
727
  }
728
728
  if (isGroupTurn && event.errorCode === 'agent_declined') {
729
- // A superseded room reply was never stored. Drop its provisional text
729
+ // A declined room reply was never stored. Drop its provisional text
730
730
  // across both transports instead of presenting it as a failed saved reply.
731
731
  roomRef.current.ended.add(event.consultId);
732
732
  roomRef.current.discarded.add(event.consultId);
@@ -1213,6 +1213,10 @@ export function useConversationStream({
1213
1213
  }
1214
1214
  continue;
1215
1215
  }
1216
+ case 'alia.credits_fallback': {
1217
+ host.onCreditsFallback?.({ reason: 'credits', tools: 'paused' });
1218
+ continue;
1219
+ }
1216
1220
  case 'alia.agent_turn': {
1217
1221
  if (parsed.turnId) {
1218
1222
  const run = {
package/src/text.ts CHANGED
@@ -5,6 +5,9 @@
5
5
  // Types can be imported from the root entry (they are erased); values from the root would bring
6
6
  // the call along.
7
7
 
8
+ // Bloom's chart cards, the conversation's default (`components/charts/default-chart-cards`).
9
+ import './components/charts/default-chart-cards';
10
+
8
11
  export { GemieChatContent } from './components/GemieChatContent';
9
12
  export type {
10
13
  GemieChatAgentRef,