Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 145 additions & 0 deletions packages/core/api/src/executions/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,134 @@ const ExecuteHeaders = Schema.Struct({
"x-executor-trigger": Schema.optional(Schema.String),
});

const ExecutionStatusLiteral = Schema.Literal(
"pending",
"running",
"waiting_for_interaction",
"completed",
"failed",
"cancelled",
);

const ExecutionRecord = Schema.Struct({
id: Schema.String,
scopeId: Schema.String,
status: ExecutionStatusLiteral,
code: Schema.String,
resultJson: Schema.NullOr(Schema.String),
errorText: Schema.NullOr(Schema.String),
logsJson: Schema.NullOr(Schema.String),
startedAt: Schema.NullOr(Schema.Number),
completedAt: Schema.NullOr(Schema.Number),
triggerKind: Schema.NullOr(Schema.String),
triggerMetaJson: Schema.NullOr(Schema.String),
toolCallCount: Schema.Number,
createdAt: Schema.Number,
updatedAt: Schema.Number,
});

const ExecutionInteractionRecord = Schema.Struct({
id: Schema.String,
executionId: Schema.String,
status: Schema.Literal("pending", "resolved", "cancelled"),
kind: Schema.String,
purpose: Schema.NullOr(Schema.String),
payloadJson: Schema.NullOr(Schema.String),
responseJson: Schema.NullOr(Schema.String),
responsePrivateJson: Schema.NullOr(Schema.String),
createdAt: Schema.Number,
updatedAt: Schema.Number,
});

const ExecutionToolCallRecord = Schema.Struct({
id: Schema.String,
executionId: Schema.String,
status: Schema.Literal("running", "completed", "failed"),
toolPath: Schema.String,
namespace: Schema.NullOr(Schema.String),
argsJson: Schema.NullOr(Schema.String),
resultJson: Schema.NullOr(Schema.String),
errorText: Schema.NullOr(Schema.String),
startedAt: Schema.Number,
completedAt: Schema.NullOr(Schema.Number),
durationMs: Schema.NullOr(Schema.Number),
});

const ExecutionListItemResponse = Schema.Struct({
execution: ExecutionRecord,
pendingInteraction: Schema.NullOr(ExecutionInteractionRecord),
});

const ExecutionStatusCount = Schema.Struct({
status: ExecutionStatusLiteral,
count: Schema.Number,
});
const ExecutionTriggerCount = Schema.Struct({
triggerKind: Schema.NullOr(Schema.String),
count: Schema.Number,
});
const ExecutionToolFacet = Schema.Struct({
toolPath: Schema.String,
count: Schema.Number,
});
const ExecutionChartBucket = Schema.Struct({
bucketStart: Schema.Number,
counts: Schema.Record({ key: Schema.String, value: Schema.Number }),
});
const ExecutionListMeta = Schema.Struct({
totalRowCount: Schema.Number,
filterRowCount: Schema.Number,
statusCounts: Schema.Array(ExecutionStatusCount),
triggerCounts: Schema.Array(ExecutionTriggerCount),
toolFacets: Schema.Array(ExecutionToolFacet),
interactionCounts: Schema.Struct({
withElicitation: Schema.Number,
withoutElicitation: Schema.Number,
}),
chartBucketMs: Schema.Number,
chartData: Schema.Array(ExecutionChartBucket),
});

const ListExecutionsResponse = Schema.Struct({
executions: Schema.Array(ExecutionListItemResponse),
nextCursor: Schema.optional(Schema.String),
meta: Schema.optional(ExecutionListMeta),
});

const GetExecutionResponse = Schema.Struct({
execution: ExecutionRecord,
pendingInteraction: Schema.NullOr(ExecutionInteractionRecord),
});

const ListToolCallsResponse = Schema.Struct({
toolCalls: Schema.Array(ExecutionToolCallRecord),
});

/**
* Query-string filters for `GET /executions`. Every param is optional
* and arrives as a plain string so the client side doesn't need to
* know about Effect Schema. The handler normalizes CSV fields and
* validates enums.
*/
const ListExecutionsParams = Schema.Struct({
limit: Schema.optional(Schema.NumberFromString),
cursor: Schema.optional(Schema.String),
/** CSV of ExecutionStatus. Invalid values are dropped. */
status: Schema.optional(Schema.String),
/** CSV of trigger kinds. Use "unknown" to match rows with null. */
trigger: Schema.optional(Schema.String),
/** CSV of tool paths / globs (`github.*`). */
tool: Schema.optional(Schema.String),
from: Schema.optional(Schema.NumberFromString),
to: Schema.optional(Schema.NumberFromString),
after: Schema.optional(Schema.String),
code: Schema.optional(Schema.String),
/** `<field>,<direction>` — e.g. `createdAt,desc`. */
sort: Schema.optional(Schema.String),
/** `"true"` / `"false"` to filter to runs that did or didn't elicit. */
elicitation: Schema.optional(Schema.String),
});

const CompletedResult = Schema.Struct({
status: Schema.Literal("completed"),
text: Schema.String,
Expand Down Expand Up @@ -74,4 +202,21 @@ export class ExecutionsApi extends HttpApiGroup.make("executions")
.addSuccess(ResumeResponse)
.addError(ExecutionNotFoundError),
)
.add(
HttpApiEndpoint.get("list")`/executions`
.setUrlParams(ListExecutionsParams)
.addSuccess(ListExecutionsResponse),
)
.add(
HttpApiEndpoint.get("get")`/executions/${executionIdParam}`
.addSuccess(GetExecutionResponse)
.addError(ExecutionNotFoundError),
)
.add(
HttpApiEndpoint.get(
"listToolCalls",
)`/executions/${executionIdParam}/tool-calls`
.addSuccess(ListToolCallsResponse)
.addError(ExecutionNotFoundError),
)
.addError(InternalError) {}
143 changes: 142 additions & 1 deletion packages/core/api/src/handlers/executions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,51 @@ import { Effect } from "effect";

import { ExecutorApi } from "../api";
import { formatExecuteResult, formatPausedExecution } from "@executor/execution";
import { ExecutionEngineService } from "../services";
import {
EXECUTION_STATUS_KEYS,
ExecutionId,
type ExecutionSort,
type ExecutionStatus,
} from "@executor/sdk";
import { ExecutionEngineService, ExecutorService } from "../services";
import { capture, captureEngineError } from "@executor/api";

// ---------------------------------------------------------------------------
// Query-string helpers
// ---------------------------------------------------------------------------

const STATUS_SET = new Set<string>(EXECUTION_STATUS_KEYS);
const SORT_FIELDS = new Set(["createdAt", "durationMs"] as const);
const SORT_DIRECTIONS = new Set(["asc", "desc"] as const);

const splitCsv = (value: string | undefined): string[] =>
value
? value.split(",").map((s) => s.trim()).filter((s) => s.length > 0)
: [];

const parseSortParam = (raw: string | undefined): ExecutionSort | undefined => {
if (!raw) return undefined;
const [rawField, rawDirection] = raw.split(",").map((s) => s.trim());
if (!rawField || !rawDirection) return undefined;
if (!SORT_FIELDS.has(rawField as (typeof SORT_FIELDS extends Set<infer T> ? T : never)))
return undefined;
if (!SORT_DIRECTIONS.has(rawDirection as "asc" | "desc")) return undefined;
return {
field: rawField as ExecutionSort["field"],
direction: rawDirection as ExecutionSort["direction"],
};
};

const parseElicitationParam = (raw: string | undefined): boolean | undefined => {
if (raw === "true") return true;
if (raw === "false") return false;
return undefined;
};

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

export const ExecutionsHandlers = HttpApiBuilder.group(ExecutorApi, "executions", (handlers) =>
handlers
.handle("execute", ({ payload, headers }) =>
Expand Down Expand Up @@ -69,5 +111,104 @@ export const ExecutionsHandlers = HttpApiBuilder.group(ExecutorApi, "executions"
isError: false,
};
})),
)
.handle("list", ({ urlParams }) =>
capture(Effect.gen(function* () {
const executor = yield* ExecutorService;
// Executions are scoped to the innermost scope of the current
// executor stack — same rule the engine uses when writing the row.
const scopeId = executor.scopes[0]!.id;

const statusFilter = splitCsv(urlParams.status).filter(
(v): v is ExecutionStatus => STATUS_SET.has(v),
);
const triggerFilter = splitCsv(urlParams.trigger);
const toolPathFilter = splitCsv(urlParams.tool);
const includeMeta =
urlParams.cursor === undefined && urlParams.after === undefined;

const result = yield* executor.executions.list(scopeId, {
limit: urlParams.limit,
cursor: urlParams.cursor,
statusFilter: statusFilter.length > 0 ? statusFilter : undefined,
triggerFilter: triggerFilter.length > 0 ? triggerFilter : undefined,
toolPathFilter: toolPathFilter.length > 0 ? toolPathFilter : undefined,
after: urlParams.after,
timeRange:
urlParams.from !== undefined || urlParams.to !== undefined
? { from: urlParams.from, to: urlParams.to }
: undefined,
codeQuery: urlParams.code,
sort: parseSortParam(urlParams.sort),
hadElicitation: parseElicitationParam(urlParams.elicitation),
includeMeta,
});

return {
executions: result.executions.map((item) => ({
execution: {
...item.execution,
createdAt: item.execution.createdAt.getTime(),
updatedAt: item.execution.updatedAt.getTime(),
},
pendingInteraction: item.pendingInteraction
? {
...item.pendingInteraction,
createdAt: item.pendingInteraction.createdAt.getTime(),
updatedAt: item.pendingInteraction.updatedAt.getTime(),
}
: null,
})),
...(result.nextCursor ? { nextCursor: result.nextCursor } : {}),
...(result.meta ? { meta: result.meta } : {}),
};
})),
)
.handle("get", ({ path }) =>
capture(Effect.gen(function* () {
const executor = yield* ExecutorService;
const detail = yield* executor.executions.get(
ExecutionId.make(path.executionId),
);
if (!detail) {
return yield* Effect.fail({
_tag: "ExecutionNotFoundError" as const,
executionId: path.executionId,
});
}
return {
execution: {
...detail.execution,
createdAt: detail.execution.createdAt.getTime(),
updatedAt: detail.execution.updatedAt.getTime(),
},
pendingInteraction: detail.pendingInteraction
? {
...detail.pendingInteraction,
createdAt: detail.pendingInteraction.createdAt.getTime(),
updatedAt: detail.pendingInteraction.updatedAt.getTime(),
}
: null,
};
})),
)
.handle("listToolCalls", ({ path }) =>
capture(Effect.gen(function* () {
const executor = yield* ExecutorService;
// Guard so missing executions 404 instead of returning `[]`.
const detail = yield* executor.executions.get(
ExecutionId.make(path.executionId),
);
if (!detail) {
return yield* Effect.fail({
_tag: "ExecutionNotFoundError" as const,
executionId: path.executionId,
});
}
const toolCalls = yield* executor.executions.listToolCalls(
ExecutionId.make(path.executionId),
);
return { toolCalls };
})),
),
);
Loading