Repository navigation
Expand file tree
/
Copy pathPythonBlockCommands.ts
More file actions
339 lines (322 loc) · 11.4 KB
/
Copy pathPythonBlockCommands.ts
File metadata and controls
339 lines (322 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import {
BlockDocumentStatefulBlockBlock,
type BlockDocumentBlockType,
type BlockDocumentsSliceState,
} from '@sqlrooms/documents';
import type {BaseRoomStoreState, RoomCommand} from '@sqlrooms/room-store';
import {z} from 'zod';
import {
PythonInput,
PythonOutputDeclaration,
PythonRequirementSpec,
} from './types';
import type {PythonSliceState} from './PythonSlice';
export const PYTHON_BLOCK_TYPE = 'python';
export const PYTHON_BLOCK_COMMAND_SUFFIXES = [
'add-python-block',
'update-python-block-code',
'run-python-block',
'clear-python-block-result',
] as const;
export type PythonBlockCommandSuffix =
(typeof PYTHON_BLOCK_COMMAND_SUFFIXES)[number];
type PythonBlockCommandState = BaseRoomStoreState &
PythonSliceState &
BlockDocumentsSliceState & {
artifacts: {
getArtifact: (id: string) => {type: string} | undefined;
};
};
/** Presentation options for canonical block-document Python commands. */
export type CreatePythonBlockCommandsOptions = {
commandGroup?: string;
};
function createPythonBlockInputSchemas() {
const PythonBlockInput = z.object({
artifactId: z.string().describe('Target block document artifact ID.'),
blockId: z.string().describe('Document Python block ID.'),
});
return {
AddPythonBlockInput: z.object({
artifactId: z.string().describe('Target block document artifact ID.'),
blockId: z.string().optional().describe('Optional document block ID.'),
blockInstanceId: z
.string()
.optional()
.describe('Optional backing Python block ID. Defaults to blockId.'),
title: z.string().optional().describe('Optional Python block title.'),
code: z.string().optional().describe('Initial Python code.'),
inputs: z.array(PythonInput).optional(),
outputs: z.array(PythonOutputDeclaration).optional(),
requirements: z.array(PythonRequirementSpec).optional(),
index: z
.number()
.int()
.min(0)
.optional()
.describe('Optional top-level insertion index. Defaults to append.'),
}),
PythonBlockInput,
UpdatePythonBlockCodeInput: PythonBlockInput.extend({
code: z.string().describe('Replacement Python code.'),
run: z
.boolean()
.optional()
.default(true)
.describe('Whether to run the block after updating the code.'),
}),
};
}
/** Creates command-backed Python block operations for block document artifacts. */
export function createPythonBlockCommands<
TRoomState extends PythonBlockCommandState = PythonBlockCommandState,
>({
commandGroup = 'Block Document',
}: CreatePythonBlockCommandsOptions = {}): RoomCommand<TRoomState>[] {
const commandId = (suffix: PythonBlockCommandSuffix) =>
`block-document.${suffix}`;
const {AddPythonBlockInput, PythonBlockInput, UpdatePythonBlockCodeInput} =
createPythonBlockInputSchemas();
const commands = {
'add-python-block': {
id: commandId('add-python-block'),
name: 'Add Python block',
description:
'Create a visible Python block with persisted code and declarations.',
group: commandGroup,
keywords: ['python', 'block', 'document'],
inputSchema: AddPythonBlockInput,
inputDescription:
'Block document artifact ID plus optional title, code, inputs, outputs, requirements, and insertion index.',
metadata: {readOnly: false, idempotent: false, riskLevel: 'medium'},
execute: ({getState}, input) => {
const state = getState();
const parsed = AddPythonBlockInput.parse(input);
const resolved = resolveBlockDocumentArtifact(
state,
parsed.artifactId,
commandId('add-python-block'),
);
if (!resolved.success) return resolved;
const blockId = parsed.blockId ?? createBlockId();
const blockInstanceId = parsed.blockInstanceId ?? blockId;
const title = parsed.title ?? 'Python';
const pythonBlock = state.python.ensureBlock(blockInstanceId, {
title,
code: parsed.code,
inputs: parsed.inputs,
outputs: parsed.outputs,
requirements: parsed.requirements,
});
const block = BlockDocumentStatefulBlockBlock.parse({
id: blockId,
type: 'statefulBlock',
blockType: PYTHON_BLOCK_TYPE,
blockInstanceId,
ownership: 'owned',
title,
});
insertOrAppendBlocks(state, parsed.artifactId, [block], parsed.index);
return {
success: true,
commandId: commandId('add-python-block'),
message: `Added Python block "${blockId}".`,
data: {
artifactId: parsed.artifactId,
block,
pythonBlock,
},
};
},
},
'update-python-block-code': {
id: commandId('update-python-block-code'),
name: 'Update Python block code',
description: 'Update the code stored for a visible Python block.',
group: commandGroup,
keywords: ['python', 'block', 'code', 'update', 'document'],
inputSchema: UpdatePythonBlockCodeInput,
inputDescription:
'Block document artifact ID, Python block ID, replacement code, and optional run flag.',
metadata: {readOnly: false, idempotent: false, riskLevel: 'high'},
execute: async ({getState}, input) => {
const state = getState();
const parsed = UpdatePythonBlockCodeInput.parse(input);
const block = resolvePythonBlock(
state,
parsed.artifactId,
parsed.blockId,
commandId('update-python-block-code'),
);
if (!block.success) return block;
state.python.updateBlockCode(block.block.blockInstanceId, parsed.code);
const result = parsed.run
? await state.python.runBlock(block.block.blockInstanceId, {
artifactId: parsed.artifactId,
})
: undefined;
return {
success: result ? result.status === 'success' : true,
commandId: commandId('update-python-block-code'),
message: result
? result.status === 'success'
? `Updated and ran Python block "${parsed.blockId}".`
: `Updated Python block "${parsed.blockId}", then run finished with ${result.status}.`
: `Updated Python block "${parsed.blockId}".`,
data: {
artifactId: parsed.artifactId,
block: block.block,
pythonBlock: state.python.getBlock(block.block.blockInstanceId),
...(result ? {executionId: result.executionId, result} : undefined),
},
...(result && result.status !== 'success'
? {error: result.error?.message ?? 'Python execution failed.'}
: {}),
};
},
},
'run-python-block': {
id: commandId('run-python-block'),
name: 'Run Python block',
description:
'Run a visible Python block through the configured Python runtime adapter.',
group: commandGroup,
keywords: ['python', 'block', 'run', 'execute', 'document'],
inputSchema: PythonBlockInput,
inputDescription: 'Block document artifact ID and Python block ID.',
metadata: {readOnly: false, idempotent: false, riskLevel: 'high'},
execute: async ({getState}, input) => {
const state = getState();
const parsed = PythonBlockInput.parse(input);
const block = resolvePythonBlock(
state,
parsed.artifactId,
parsed.blockId,
commandId('run-python-block'),
);
if (!block.success) return block;
const result = await state.python.runBlock(
block.block.blockInstanceId,
{artifactId: parsed.artifactId},
);
return {
success: result.status === 'success',
commandId: commandId('run-python-block'),
message:
result.status === 'success'
? `Ran Python block "${parsed.blockId}".`
: `Python block "${parsed.blockId}" finished with ${result.status}.`,
data: {
artifactId: parsed.artifactId,
block: block.block,
executionId: result.executionId,
result,
},
...(result.status === 'success'
? {}
: {error: result.error?.message ?? 'Python execution failed.'}),
};
},
},
'clear-python-block-result': {
id: commandId('clear-python-block-result'),
name: 'Clear Python block result',
description: 'Clear the persisted result summary for a Python block.',
group: commandGroup,
keywords: ['python', 'block', 'clear', 'result', 'document'],
inputSchema: PythonBlockInput,
inputDescription: 'Block document artifact ID and Python block ID.',
metadata: {readOnly: false, idempotent: true, riskLevel: 'low'},
execute: ({getState}, input) => {
const state = getState();
const parsed = PythonBlockInput.parse(input);
const block = resolvePythonBlock(
state,
parsed.artifactId,
parsed.blockId,
commandId('clear-python-block-result'),
);
if (!block.success) return block;
state.python.clearBlockResult(block.block.blockInstanceId);
return {
success: true,
commandId: commandId('clear-python-block-result'),
message: `Cleared Python block "${parsed.blockId}" result.`,
data: {
artifactId: parsed.artifactId,
block: block.block,
},
};
},
},
} satisfies Record<PythonBlockCommandSuffix, RoomCommand<TRoomState>>;
return PYTHON_BLOCK_COMMAND_SUFFIXES.map((suffix) => commands[suffix]);
}
function resolveBlockDocumentArtifact(
state: PythonBlockCommandState,
artifactId: string,
commandId: string,
) {
const artifact = state.artifacts.getArtifact(artifactId);
if (!artifact) {
return {
success: false as const,
commandId,
error: `Unknown artifact "${artifactId}".`,
};
}
if (artifact.type !== 'block-document') {
return {
success: false as const,
commandId,
error: `Artifact "${artifactId}" is not a block document artifact.`,
};
}
return {success: true as const, artifact};
}
function resolvePythonBlock(
state: PythonBlockCommandState,
artifactId: string,
blockId: string,
commandId: string,
) {
const resolved = resolveBlockDocumentArtifact(state, artifactId, commandId);
if (!resolved.success) return resolved;
const block = state.blockDocuments
.getBlocks(artifactId)
.find((candidate) => candidate.id === blockId);
if (!block) {
return {
success: false as const,
commandId,
error: `Unknown block "${blockId}".`,
};
}
if (block.type !== 'statefulBlock' || block.blockType !== PYTHON_BLOCK_TYPE) {
return {
success: false as const,
commandId,
error: `Block "${blockId}" is not a Python block.`,
};
}
return {success: true as const, block};
}
function insertOrAppendBlocks(
state: PythonBlockCommandState,
artifactId: string,
blocks: BlockDocumentBlockType[],
index: number | undefined,
) {
if (typeof index === 'number') {
state.blockDocuments.insertBlocks(artifactId, index, blocks);
} else {
state.blockDocuments.appendBlocks(artifactId, blocks);
}
}
function createBlockId() {
const randomUUID = globalThis.crypto?.randomUUID;
if (randomUUID) {
return randomUUID.call(globalThis.crypto);
}
return `python-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}