@outputai/cli 0.17.1-next.b47353f.0 โ†’ 0.18.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 (39) hide show
  1. package/dist/assets/docker/docker-compose-dev.yml +1 -1
  2. package/dist/commands/workflow/dataset/generate.d.ts +8 -6
  3. package/dist/commands/workflow/dataset/generate.js +46 -80
  4. package/dist/commands/workflow/dataset/generate.spec.js +154 -83
  5. package/dist/commands/workflow/debug.d.ts +8 -3
  6. package/dist/commands/workflow/debug.js +35 -25
  7. package/dist/commands/workflow/debug.spec.js +76 -22
  8. package/dist/commands/workflow/test.js +0 -3
  9. package/dist/commands/workflow/test.spec.js +19 -0
  10. package/dist/generated/framework_version.json +1 -1
  11. package/dist/services/datasets.d.ts +1 -3
  12. package/dist/services/datasets.js +1 -19
  13. package/dist/services/datasets.test.js +45 -3
  14. package/dist/services/temporal_client.d.ts +50 -0
  15. package/dist/services/temporal_client.js +84 -0
  16. package/dist/services/temporal_client.spec.d.ts +1 -0
  17. package/dist/services/temporal_client.spec.js +129 -0
  18. package/dist/services/workflow_debug.d.ts +68 -0
  19. package/dist/services/workflow_debug.js +273 -0
  20. package/dist/services/workflow_debug.spec.d.ts +1 -0
  21. package/dist/services/workflow_debug.spec.js +363 -0
  22. package/dist/services/workflow_run_data.d.ts +26 -0
  23. package/dist/services/workflow_run_data.js +67 -0
  24. package/dist/services/workflow_run_data.spec.d.ts +1 -0
  25. package/dist/services/workflow_run_data.spec.js +190 -0
  26. package/dist/types/trace.d.ts +1 -73
  27. package/dist/types/trace.js +1 -12
  28. package/dist/utils/payload_truncator.d.ts +23 -0
  29. package/dist/utils/payload_truncator.js +92 -0
  30. package/dist/utils/payload_truncator.spec.d.ts +1 -0
  31. package/dist/utils/payload_truncator.spec.js +51 -0
  32. package/dist/utils/temporal_flags.d.ts +14 -0
  33. package/dist/utils/temporal_flags.js +16 -0
  34. package/oclif.manifest.json +80 -36
  35. package/package.json +10 -2
  36. package/dist/utils/trace_extractor.d.ts +0 -27
  37. package/dist/utils/trace_extractor.js +0 -53
  38. package/dist/utils/trace_formatter.d.ts +0 -11
  39. package/dist/utils/trace_formatter.js +0 -401
@@ -0,0 +1,67 @@
1
+ import { defaultPayloadConverter } from '@temporalio/common';
2
+ import { callTemporal } from '#services/temporal_client.js';
3
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ const formatStatus = (name) => name.toLowerCase().replaceAll('_', ' ');
5
+ const formatRunLabel = (workflowId, runId) => `Workflow ${workflowId} (run ${runId})`;
6
+ const fetchStartedAttributes = async (client, workflowId, runId) => {
7
+ const response = await callTemporal(client, () => client.connection.workflowService.getWorkflowExecutionHistory({
8
+ namespace: client.options.namespace,
9
+ execution: { workflowId, runId },
10
+ maximumPageSize: 1
11
+ }));
12
+ const started = response.history?.events?.[0]?.workflowExecutionStartedEventAttributes;
13
+ if (!started) {
14
+ throw new Error(`${formatRunLabel(workflowId, runId)} has no start event in its history.`);
15
+ }
16
+ return started;
17
+ };
18
+ const decodeInput = (started) => {
19
+ const payload = started.input?.payloads?.[0];
20
+ // No payload, or a payload that encodes "nothing", means the workflow started without input
21
+ const input = payload ? defaultPayloadConverter.fromPayload(payload) : undefined;
22
+ return input === undefined ? {} : input;
23
+ };
24
+ /**
25
+ * Reads the input the workflow was started with. A run that continued as new from earlier runs holds the continuation
26
+ * arguments as its own input, so the input of the first run of the chain is read instead.
27
+ */
28
+ const fetchRunInput = async (client, workflowId, runId) => {
29
+ const started = await fetchStartedAttributes(client, workflowId, runId);
30
+ const firstRunId = started.firstExecutionRunId;
31
+ if (!firstRunId || firstRunId === runId) {
32
+ return { input: decodeInput(started), inputRunId: runId };
33
+ }
34
+ const first = await fetchStartedAttributes(client, workflowId, firstRunId).catch((error) => {
35
+ const reason = error instanceof Error ? error.message : String(error);
36
+ const label = formatRunLabel(workflowId, runId);
37
+ throw new Error(`${label} continued from run ${firstRunId}, which could not be read, so its original input is unknown. ${reason}`);
38
+ });
39
+ return { input: decodeInput(first), inputRunId: firstRunId };
40
+ };
41
+ /**
42
+ * Reads the start input and the result of a completed workflow run from Temporal, to turn it into a dataset case.
43
+ * Nothing is truncated. A run that is missing, of another workflow type or not completed is an error.
44
+ *
45
+ * @param client - The Temporal client
46
+ * @param options - The run to read
47
+ * @returns The run's ids, the run its input was read from, its input (an object) and its output
48
+ */
49
+ export async function collectWorkflowRunData(client, { workflowName, workflowId, runId }) {
50
+ const description = await callTemporal(client, () => client.workflow.getHandle(workflowId, runId).describe());
51
+ const label = formatRunLabel(workflowId, description.runId);
52
+ if (description.type !== workflowName) {
53
+ const hint = `Use "${description.type}" as the workflow name; aliases are not accepted.`;
54
+ throw new Error(`${label} is a "${description.type}" workflow, not "${workflowName}". ${hint}`);
55
+ }
56
+ if (description.status.name !== 'COMPLETED') {
57
+ const hint = description.status.name === 'CONTINUED_AS_NEW' ? ' Omit the run id or pass the run id of the last run.' : '';
58
+ throw new Error(`${label} is ${formatStatus(description.status.name)}. Only completed runs can be turned into a dataset case.${hint}`);
59
+ }
60
+ const { input, inputRunId } = await fetchRunInput(client, workflowId, description.runId);
61
+ if (!isRecord(input)) {
62
+ throw new Error(`${formatRunLabel(workflowId, inputRunId)} has an input that is not an object. A dataset case needs an object input.`);
63
+ }
64
+ const output = await callTemporal(client, () => client.workflow.getHandle(workflowId, description.runId).result());
65
+ // A workflow that returns nothing has an undefined result; a case keeps it as null so it still counts as cached output
66
+ return { workflowId, runId: description.runId, inputRunId, input, output: output ?? null };
67
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,190 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { WorkflowNotFoundError } from '@temporalio/client';
3
+ import { collectWorkflowRunData } from './workflow_run_data.js';
4
+ const encodeJson = (value) => ({
5
+ metadata: { encoding: Buffer.from('json/plain') },
6
+ data: Buffer.from(JSON.stringify(value))
7
+ });
8
+ const nullPayload = { metadata: { encoding: Buffer.from('binary/null') } };
9
+ const startedEvent = (payloads, firstExecutionRunId) => ({
10
+ eventId: 1,
11
+ workflowExecutionStartedEventAttributes: { ...(payloads ? { input: { payloads } } : {}), firstExecutionRunId }
12
+ });
13
+ const rejectWith = (error) => async () => {
14
+ throw error;
15
+ };
16
+ const buildClient = (clientOptions = {}) => {
17
+ const { type = 'simple', status = 'COMPLETED', runId = 'run-1', describe, eventsByRun, events = [startedEvent([encodeJson({ values: [1, 2, 3] })])] } = clientOptions;
18
+ // An explicit undefined result must stay undefined, so a default cannot be used here
19
+ const result = 'result' in clientOptions ? clientOptions.result : { total: 6 };
20
+ const handle = {
21
+ describe: vi.fn(describe ?? (async () => ({ type, runId, status: { name: status } }))),
22
+ result: vi.fn(async () => result)
23
+ };
24
+ const getHandle = vi.fn(() => handle);
25
+ const getWorkflowExecutionHistory = vi.fn(async (request) => {
26
+ if (!eventsByRun) {
27
+ return { history: { events } };
28
+ }
29
+ const runEvents = eventsByRun[request.execution.runId];
30
+ if (!runEvents) {
31
+ throw new Error(`5 NOT_FOUND: workflow execution not found (${request.execution.runId})`);
32
+ }
33
+ return { history: { events: runEvents } };
34
+ });
35
+ const withDeadline = vi.fn(async (_deadline, fn) => fn());
36
+ const client = {
37
+ options: { namespace: 'default' },
38
+ workflow: { getHandle },
39
+ connection: { withDeadline, workflowService: { getWorkflowExecutionHistory } }
40
+ };
41
+ return { client, handle, getHandle, getWorkflowExecutionHistory, withDeadline };
42
+ };
43
+ const options = { workflowName: 'simple', workflowId: 'wf-1' };
44
+ describe('collectWorkflowRunData', () => {
45
+ it('returns the ids, the decoded start input and the result of a completed run', async () => {
46
+ const { client } = buildClient();
47
+ await expect(collectWorkflowRunData(client, options)).resolves.toEqual({
48
+ workflowId: 'wf-1',
49
+ runId: 'run-1',
50
+ inputRunId: 'run-1',
51
+ input: { values: [1, 2, 3] },
52
+ output: { total: 6 }
53
+ });
54
+ });
55
+ it('describes the requested run, or the latest one when no run id is given', async () => {
56
+ const { client, getHandle } = buildClient();
57
+ await collectWorkflowRunData(client, { ...options, runId: 'run-9' });
58
+ await collectWorkflowRunData(client, options);
59
+ // Each run reads: describe, then (pinned to the described run) the result
60
+ expect(getHandle).toHaveBeenNthCalledWith(1, 'wf-1', 'run-9');
61
+ expect(getHandle).toHaveBeenNthCalledWith(3, 'wf-1', undefined);
62
+ });
63
+ it('reads the input and the result of the run it described, even when no run id was given', async () => {
64
+ const { client, getHandle, getWorkflowExecutionHistory } = buildClient({ runId: 'run-latest' });
65
+ const data = await collectWorkflowRunData(client, options);
66
+ expect(data.runId).toBe('run-latest');
67
+ expect(getWorkflowExecutionHistory).toHaveBeenCalledWith({
68
+ namespace: 'default',
69
+ execution: { workflowId: 'wf-1', runId: 'run-latest' },
70
+ maximumPageSize: 1
71
+ });
72
+ expect(getHandle).toHaveBeenLastCalledWith('wf-1', 'run-latest');
73
+ });
74
+ it('runs every Temporal call under a deadline', async () => {
75
+ const { client, withDeadline } = buildClient();
76
+ await collectWorkflowRunData(client, options);
77
+ expect(withDeadline).toHaveBeenCalledTimes(3);
78
+ expect(withDeadline.mock.calls[0][0]).toBeGreaterThan(Date.now());
79
+ });
80
+ it('fails for a run of another workflow type and reads nothing else', async () => {
81
+ const { client, getWorkflowExecutionHistory, handle } = buildClient({ type: 'other' });
82
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow('Workflow wf-1 (run run-1) is a "other" workflow, not "simple". Use "other" as the workflow name; aliases are not accepted.');
83
+ expect(getWorkflowExecutionHistory).not.toHaveBeenCalled();
84
+ expect(handle.result).not.toHaveBeenCalled();
85
+ });
86
+ it.each([
87
+ ['RUNNING', 'running'],
88
+ ['FAILED', 'failed'],
89
+ ['CANCELLED', 'cancelled'],
90
+ ['TERMINATED', 'terminated'],
91
+ ['TIMED_OUT', 'timed out']
92
+ ])('fails for a %s run', async (status, label) => {
93
+ const { client, getWorkflowExecutionHistory, handle } = buildClient({ status });
94
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow(`Workflow wf-1 (run run-1) is ${label}. Only completed runs can be turned into a dataset case.`);
95
+ expect(getWorkflowExecutionHistory).not.toHaveBeenCalled();
96
+ expect(handle.result).not.toHaveBeenCalled();
97
+ });
98
+ it('tells the user which run to use for a run that continued as new', async () => {
99
+ const { client } = buildClient({ status: 'CONTINUED_AS_NEW' });
100
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow('Workflow wf-1 (run run-1) is continued as new. Only completed runs can be turned into a dataset case. ' +
101
+ 'Omit the run id or pass the run id of the last run.');
102
+ });
103
+ it('rethrows a missing workflow or run untouched, for the command to explain', async () => {
104
+ const missing = new WorkflowNotFoundError('workflow not found for ID: wf-1', 'wf-1', undefined);
105
+ const { client } = buildClient({ describe: rejectWith(missing) });
106
+ await expect(collectWorkflowRunData(client, options)).rejects.toBe(missing);
107
+ });
108
+ it('rethrows other describe failures untouched', async () => {
109
+ const failure = new Error('Temporal did not answer within 30s');
110
+ const { client } = buildClient({ describe: rejectWith(failure) });
111
+ await expect(collectWorkflowRunData(client, options)).rejects.toBe(failure);
112
+ });
113
+ describe('a run that continued as new from earlier runs', () => {
114
+ const chain = {
115
+ 'run-3': [startedEvent([encodeJson({ value: 2 })], 'run-1')],
116
+ 'run-1': [startedEvent([encodeJson({ value: 0 })], 'run-1')]
117
+ };
118
+ it('reads the input of the first run and the result of the described run', async () => {
119
+ const { client, handle } = buildClient({ runId: 'run-3', eventsByRun: chain, result: { result: 3 } });
120
+ await expect(collectWorkflowRunData(client, options)).resolves.toEqual({
121
+ workflowId: 'wf-1',
122
+ runId: 'run-3',
123
+ inputRunId: 'run-1',
124
+ input: { value: 0 },
125
+ output: { result: 3 }
126
+ });
127
+ expect(handle.result).toHaveBeenCalledTimes(1);
128
+ });
129
+ it('does the same when the last run id is given', async () => {
130
+ const { client } = buildClient({ runId: 'run-3', eventsByRun: chain });
131
+ await expect(collectWorkflowRunData(client, { ...options, runId: 'run-3' })).resolves.toMatchObject({
132
+ runId: 'run-3', inputRunId: 'run-1', input: { value: 0 }
133
+ });
134
+ });
135
+ it('fails when the first run can no longer be read, and does not fall back to the continuation input', async () => {
136
+ const { client, handle } = buildClient({ runId: 'run-3', eventsByRun: { 'run-3': chain['run-3'] } });
137
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow('Workflow wf-1 (run run-3) continued from run run-1, which could not be read, so its original input is unknown. ' +
138
+ '5 NOT_FOUND: workflow execution not found (run-1)');
139
+ expect(handle.result).not.toHaveBeenCalled();
140
+ });
141
+ it('fails when the first run has no start event', async () => {
142
+ const { client } = buildClient({ runId: 'run-3', eventsByRun: { 'run-3': chain['run-3'], 'run-1': [] } });
143
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow('Workflow wf-1 (run run-1) has no start event in its history.');
144
+ });
145
+ it('does not read another run for a run that is its own first run', async () => {
146
+ const { client, getWorkflowExecutionHistory } = buildClient({ runId: 'run-1', eventsByRun: chain });
147
+ await collectWorkflowRunData(client, options);
148
+ expect(getWorkflowExecutionHistory).toHaveBeenCalledTimes(1);
149
+ });
150
+ });
151
+ it('uses an empty input for a run that started without input', async () => {
152
+ const { client } = buildClient({ events: [startedEvent()] });
153
+ await expect(collectWorkflowRunData(client, options)).resolves.toMatchObject({ input: {} });
154
+ });
155
+ it('fails when the history has no start event', async () => {
156
+ const { client, handle } = buildClient({ events: [] });
157
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow('Workflow wf-1 (run run-1) has no start event in its history.');
158
+ expect(handle.result).not.toHaveBeenCalled();
159
+ });
160
+ it.each([
161
+ ['a string', 'hello'],
162
+ ['a number', 7],
163
+ ['an array', [1, 2]],
164
+ ['null', null]
165
+ ])('fails when the input is %s, not an object', async (_label, value) => {
166
+ const { client, handle } = buildClient({ events: [startedEvent([encodeJson(value)])] });
167
+ await expect(collectWorkflowRunData(client, options)).rejects.toThrow('Workflow wf-1 (run run-1) has an input that is not an object. A dataset case needs an object input.');
168
+ expect(handle.result).not.toHaveBeenCalled();
169
+ });
170
+ it('reads only the first input payload', async () => {
171
+ const { client } = buildClient({ events: [startedEvent([encodeJson({ first: true }), encodeJson({ second: true })])] });
172
+ await expect(collectWorkflowRunData(client, options)).resolves.toMatchObject({ input: { first: true } });
173
+ });
174
+ it('keeps a result that is not an object', async () => {
175
+ const { client } = buildClient({ result: 'done' });
176
+ await expect(collectWorkflowRunData(client, options)).resolves.toMatchObject({ output: 'done' });
177
+ });
178
+ it('returns a null output for a workflow that returned nothing', async () => {
179
+ const { client } = buildClient({ result: undefined });
180
+ await expect(collectWorkflowRunData(client, options)).resolves.toMatchObject({ output: null });
181
+ });
182
+ it('keeps an explicit null result as null', async () => {
183
+ const { client } = buildClient({ result: null });
184
+ await expect(collectWorkflowRunData(client, options)).resolves.toMatchObject({ output: null });
185
+ });
186
+ it('uses an empty input when the input payload encodes nothing', async () => {
187
+ const { client } = buildClient({ events: [startedEvent([nullPayload])] });
188
+ await expect(collectWorkflowRunData(client, options)).resolves.toMatchObject({ input: {} });
189
+ });
190
+ });
@@ -10,49 +10,9 @@ export type NodeKind = 'workflow' | 'activity' | 'step' | 'internal_step' | stri
10
10
  export type NodePhase = 'start' | 'end' | 'error' | string;
11
11
  /** Execution status of a node */
12
12
  export type NodeStatus = 'completed' | 'failed' | 'running' | string;
13
- /**
14
- * Details associated with a trace event.
15
- * Contains input/output data and identifying information for the event.
16
- */
17
- export interface TraceDetails {
18
- /** Input data passed to the step/activity */
19
- input?: unknown;
20
- /** Output data returned from the step/activity */
21
- output?: unknown;
22
- /** Name of the activity (for activity events) */
23
- activityName?: string;
24
- /** Name of the step (for step events) */
25
- stepName?: string;
26
- /** Generic name field */
27
- name?: string;
28
- }
29
- /**
30
- * A trace event representing a point in workflow execution.
31
- * Used for timeline display and event-based analysis.
32
- */
33
- export interface TraceEvent {
34
- /** The type of event (workflow, activity, step, etc.) */
35
- kind: NodeKind;
36
- /** The lifecycle phase of the event */
37
- phase: NodePhase;
38
- /** Unix timestamp when the event occurred */
39
- timestamp: number;
40
- /** Unique identifier for the workflow run */
41
- workflowId: string;
42
- /** Name of the workflow being executed */
43
- workflowName: string;
44
- /** Additional event details including input/output */
45
- details?: TraceDetails;
46
- /** Child events for nested executions */
47
- children?: TraceEvent[];
48
- /** Error information if the event represents a failure */
49
- error?: unknown;
50
- /** Duration of the event in milliseconds */
51
- duration?: number;
52
- }
53
13
  /**
54
14
  * A node in the debug tree representation of workflow execution.
55
- * Contains more detailed timing and state information than TraceEvent.
15
+ * Contains timing and state information for one step or activity.
56
16
  */
57
17
  export interface DebugNode {
58
18
  /** The type of node (workflow, activity, step, internal_step) */
@@ -94,18 +54,6 @@ export interface DebugNode {
94
54
  /** Child nodes representing nested executions */
95
55
  children?: DebugNode[];
96
56
  }
97
- /**
98
- * Root structure of a workflow trace.
99
- * Contains the execution tree and optional flat event list.
100
- */
101
- export interface TraceStructure {
102
- /** Root node of the execution tree */
103
- root?: TraceEvent | DebugNode;
104
- /** Flat list of execution events for timeline display */
105
- events?: TraceEvent[];
106
- /** Hierarchical tree of execution nodes (alternative to root.children) */
107
- children?: DebugNode[];
108
- }
109
57
  /**
110
58
  * The structure of a workflow trace file generated by Output.ai workflow runs.
111
59
  * This file is written to the local filesystem during workflow execution and contains
@@ -139,23 +87,3 @@ export interface TraceData {
139
87
  /** Hierarchical tree of execution nodes */
140
88
  children?: DebugNode[];
141
89
  }
142
- /**
143
- * Extracted node information for display formatting.
144
- * Used internally by the trace formatter.
145
- */
146
- export interface NodeInfo {
147
- /** Display name for the node */
148
- name: string;
149
- /** Formatted phase indicator */
150
- phase: string;
151
- /** Formatted duration string */
152
- duration: string;
153
- }
154
- /**
155
- * Type guard to check if a node is a TraceEvent.
156
- */
157
- export declare const isTraceEvent: (node: TraceEvent | DebugNode) => node is TraceEvent;
158
- /**
159
- * Type guard to check if a value is a valid timestamp.
160
- */
161
- export declare const isValidTimestamp: (value: unknown) => value is number | string;
@@ -4,15 +4,4 @@
4
4
  * These types represent the structure of trace files generated during workflow execution,
5
5
  * used for debugging, visualization, and analysis of workflow runs.
6
6
  */
7
- /**
8
- * Type guard to check if a node is a TraceEvent.
9
- */
10
- export const isTraceEvent = (node) => {
11
- return 'workflowId' in node && 'timestamp' in node;
12
- };
13
- /**
14
- * Type guard to check if a value is a valid timestamp.
15
- */
16
- export const isValidTimestamp = (value) => {
17
- return typeof value === 'number' || typeof value === 'string';
18
- };
7
+ export {};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Cuts a long string to its first 1,000 characters, a `... [N more characters omitted] ...` marker and its last 24 characters.
3
+ * Strings up to 1,024 characters are returned whole. Cuts never split a grapheme cluster (emoji, accents).
4
+ *
5
+ * @param value - String to truncate
6
+ * @returns The string, or its truncated form
7
+ */
8
+ export declare const truncateString: (value: string) => string;
9
+ /**
10
+ * Keeps the first 10 lines of a stack trace and notes how many were omitted.
11
+ *
12
+ * @param stack - Stack trace text
13
+ * @returns The stack, or its first lines
14
+ */
15
+ export declare const truncateStack: (stack: string) => string;
16
+ /**
17
+ * Caps a decoded JSON value: long strings, long arrays, wide objects, deep nesting and many values are cut
18
+ * with a marker that says what was left out. Short values pass through unchanged.
19
+ *
20
+ * @param value - Decoded JSON value
21
+ * @returns A copy within the limits
22
+ */
23
+ export declare const truncateValue: (value: unknown) => unknown;
@@ -0,0 +1,92 @@
1
+ const MAX_VALUE_DEPTH = 10;
2
+ const MAX_STRING_LENGTH = 1024;
3
+ const HEAD_LENGTH = 1000;
4
+ const TAIL_LENGTH = 24;
5
+ const MAX_ARRAY_ITEMS = 20;
6
+ const MAX_OBJECT_KEYS = 50;
7
+ const MAX_VISITED_VALUES = 1000;
8
+ const MAX_STACK_LINES = 10;
9
+ // Extra characters segmented around a cut so the cluster at the boundary is seen whole
10
+ const SEGMENT_WINDOW = 64;
11
+ const Marker = {
12
+ maxDepth: '[Maximum Depth Reached]',
13
+ maxKeys: '[Maximum Object Properties Reached]',
14
+ maxValues: '[Serialization Limit Reached]'
15
+ };
16
+ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
17
+ /** The longest prefix of at most `HEAD_LENGTH` characters that does not end inside a grapheme cluster */
18
+ const sliceHead = (value) => {
19
+ const ends = [...segmenter.segment(value.slice(0, HEAD_LENGTH + SEGMENT_WINDOW))].map(({ index, segment }) => index + segment.length);
20
+ return value.slice(0, Math.max(0, ...ends.filter(end => end <= HEAD_LENGTH)));
21
+ };
22
+ /** The longest suffix of at most `TAIL_LENGTH` characters that does not start inside a grapheme cluster */
23
+ const sliceTail = (value) => {
24
+ const windowStart = Math.max(0, value.length - TAIL_LENGTH - SEGMENT_WINDOW);
25
+ // Segment 0 may begin inside a cluster and is never needed: the window is wider than the tail
26
+ const starts = [...segmenter.segment(value.slice(windowStart))].slice(1).map(({ index }) => windowStart + index);
27
+ return value.slice(Math.min(value.length, ...starts.filter(start => value.length - start <= TAIL_LENGTH)));
28
+ };
29
+ /**
30
+ * Cuts a long string to its first 1,000 characters, a `... [N more characters omitted] ...` marker and its last 24 characters.
31
+ * Strings up to 1,024 characters are returned whole. Cuts never split a grapheme cluster (emoji, accents).
32
+ *
33
+ * @param value - String to truncate
34
+ * @returns The string, or its truncated form
35
+ */
36
+ export const truncateString = (value) => {
37
+ if (value.length <= MAX_STRING_LENGTH) {
38
+ return value;
39
+ }
40
+ const head = sliceHead(value);
41
+ const tail = sliceTail(value);
42
+ return `${head}... [${value.length - head.length - tail.length} more characters omitted] ...${tail}`;
43
+ };
44
+ /**
45
+ * Keeps the first 10 lines of a stack trace and notes how many were omitted.
46
+ *
47
+ * @param stack - Stack trace text
48
+ * @returns The stack, or its first lines
49
+ */
50
+ export const truncateStack = (stack) => {
51
+ const lines = stack.split('\n');
52
+ if (lines.length <= MAX_STACK_LINES) {
53
+ return stack;
54
+ }
55
+ return [...lines.slice(0, MAX_STACK_LINES), `... [${lines.length - MAX_STACK_LINES} more lines omitted]`].join('\n');
56
+ };
57
+ const walkValue = (value, depth, state) => {
58
+ if (state.visited >= MAX_VISITED_VALUES) {
59
+ return Marker.maxValues;
60
+ }
61
+ if (depth >= MAX_VALUE_DEPTH) {
62
+ return Marker.maxDepth;
63
+ }
64
+ state.visited++;
65
+ if (typeof value === 'string') {
66
+ return truncateString(value);
67
+ }
68
+ if (Array.isArray(value)) {
69
+ const items = value.slice(0, MAX_ARRAY_ITEMS).map(item => walkValue(item, depth + 1, state));
70
+ return value.length > MAX_ARRAY_ITEMS ? [...items, `... [${value.length - MAX_ARRAY_ITEMS} more items omitted]`] : items;
71
+ }
72
+ if (value === null || typeof value !== 'object') {
73
+ return value;
74
+ }
75
+ const result = {};
76
+ for (const [key, item] of Object.entries(value)) {
77
+ if (Object.keys(result).length === MAX_OBJECT_KEYS) {
78
+ result['...'] = Marker.maxKeys;
79
+ break;
80
+ }
81
+ result[key] = walkValue(item, depth + 1, state);
82
+ }
83
+ return result;
84
+ };
85
+ /**
86
+ * Caps a decoded JSON value: long strings, long arrays, wide objects, deep nesting and many values are cut
87
+ * with a marker that says what was left out. Short values pass through unchanged.
88
+ *
89
+ * @param value - Decoded JSON value
90
+ * @returns A copy within the limits
91
+ */
92
+ export const truncateValue = (value) => walkValue(value, 0, { visited: 0 });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,51 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { truncateString, truncateStack, truncateValue } from './payload_truncator.js';
3
+ describe('truncateString', () => {
4
+ it('keeps strings up to 1,024 characters whole', () => {
5
+ const value = 'a'.repeat(1024);
6
+ expect(truncateString(value)).toBe(value);
7
+ });
8
+ it('keeps the first 1,000 and last 24 characters around a marker', () => {
9
+ const value = `${'a'.repeat(1000)}${'m'.repeat(5000)}${'z'.repeat(24)}`;
10
+ expect(truncateString(value)).toBe(`${'a'.repeat(1000)}... [5000 more characters omitted] ...${'z'.repeat(24)}`);
11
+ });
12
+ it('does not split a grapheme cluster at either cut', () => {
13
+ const family = '๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ'; // 11 UTF-16 units, one cluster
14
+ const value = `${'a'.repeat(995)}${family}${'m'.repeat(3000)}${family.repeat(3)}`;
15
+ const omitted = value.length - 995 - (family.length * 2);
16
+ expect(truncateString(value)).toBe(`${'a'.repeat(995)}... [${omitted} more characters omitted] ...${family.repeat(2)}`);
17
+ });
18
+ });
19
+ describe('truncateStack', () => {
20
+ it('keeps the first 10 lines', () => {
21
+ const stack = Array.from({ length: 12 }, (_, i) => `line ${i}`).join('\n');
22
+ expect(truncateStack(stack).split('\n')).toHaveLength(11);
23
+ expect(truncateStack(stack)).toContain('... [2 more lines omitted]');
24
+ });
25
+ });
26
+ describe('truncateValue', () => {
27
+ it('caps arrays at 20 items with a marker', () => {
28
+ const result = truncateValue(Array.from({ length: 25 }, (_, i) => i));
29
+ expect(result).toHaveLength(21);
30
+ expect(result[20]).toBe('... [5 more items omitted]');
31
+ });
32
+ it('caps objects at 50 keys with a marker', () => {
33
+ const value = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`k${i}`, i]));
34
+ const result = truncateValue(value);
35
+ expect(Object.keys(result)).toHaveLength(51);
36
+ expect(result['...']).toBe('[Maximum Object Properties Reached]');
37
+ });
38
+ it('stops at depth 10', () => {
39
+ const nest = (n) => (n === 0 ? 'leaf' : { next: nest(n - 1) });
40
+ expect(JSON.stringify(truncateValue(nest(12)))).toContain('[Maximum Depth Reached]');
41
+ });
42
+ it('stops after 1,000 visited values', () => {
43
+ const wide = Object.fromEntries(Array.from({ length: 50 }, (_, i) => [`k${i}`, i]));
44
+ const value = Array.from({ length: 20 }, () => wide);
45
+ expect(JSON.stringify(truncateValue(value))).toContain('[Serialization Limit Reached]');
46
+ });
47
+ it('passes short values through unchanged', () => {
48
+ const value = { a: [1, 'two', null], b: { c: true } };
49
+ expect(truncateValue(value)).toEqual(value);
50
+ });
51
+ });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Flags shared by every command that talks to Temporal directly.
3
+ * Spread into `static flags`. Secrets (API key, TLS material) have no flag on purpose: they come from the profile or the env.
4
+ */
5
+ export declare const temporalFlags: {
6
+ profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ address: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ namespace: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ };
10
+ export type TemporalFlags = {
11
+ profile?: string;
12
+ address?: string;
13
+ namespace?: string;
14
+ };
@@ -0,0 +1,16 @@
1
+ import { Flags } from '@oclif/core';
2
+ /**
3
+ * Flags shared by every command that talks to Temporal directly.
4
+ * Spread into `static flags`. Secrets (API key, TLS material) have no flag on purpose: they come from the profile or the env.
5
+ */
6
+ export const temporalFlags = {
7
+ profile: Flags.string({
8
+ description: 'Temporal profile to read from temporal.toml (defaults to TEMPORAL_PROFILE, then "default")'
9
+ }),
10
+ address: Flags.string({
11
+ description: 'Temporal server address, overrides the profile and TEMPORAL_ADDRESS (default: localhost on the dev Temporal port, 7233)'
12
+ }),
13
+ namespace: Flags.string({
14
+ description: 'Temporal namespace, overrides the profile and TEMPORAL_NAMESPACE (default: default)'
15
+ })
16
+ };