@opengeni/worker-bundle 0.7.0 → 0.7.2
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.
- package/dist/index.d.ts +182 -67
- package/dist/index.js +7127 -1654
- package/dist/index.js.map +1 -1
- package/package.json +19 -19
- package/src/activities/agent-turn.ts +4405 -1089
- package/src/activities/capabilities.ts +43 -8
- package/src/activities/codex-capacity.ts +223 -0
- package/src/activities/codex-rotation.ts +550 -54
- package/src/activities/common.ts +7 -1
- package/src/activities/context-compaction.ts +152 -118
- package/src/activities/documents.ts +32 -27
- package/src/activities/environment.ts +318 -75
- package/src/activities/file-upload-reaper.ts +79 -0
- package/src/activities/git-credential-renewal.ts +183 -0
- package/src/activities/goals.ts +142 -123
- package/src/activities/packs.ts +55 -5
- package/src/activities/parent-wake.ts +228 -41
- package/src/activities/recording.ts +154 -122
- package/src/activities/redaction.ts +3 -1
- package/src/activities/rig-verification.ts +441 -0
- package/src/activities/run-input.ts +110 -122
- package/src/activities/sandbox-lease.ts +186 -51
- package/src/activities/scheduled-tasks.ts +287 -171
- package/src/activities/session-state.ts +168 -157
- package/src/activities/streaming.ts +143 -19
- package/src/activities/turn-attempt-fenced.ts +14 -0
- package/src/activities/types.ts +102 -32
- package/src/activities/workflow-wake.ts +44 -0
- package/src/activities/workspace-capture.ts +964 -0
- package/src/activities.ts +75 -35
- package/src/concurrency.ts +11 -0
- package/src/http.ts +16 -6
- package/src/index.ts +322 -49
- package/src/observability-metrics.ts +441 -8
- package/src/op-journal.ts +46 -0
- package/src/sandbox-resume.ts +431 -201
- package/src/sandbox-routing.ts +209 -22
- package/src/workflow-wake-contract.ts +5 -0
- package/src/workflows/activities.ts +58 -7
- package/src/workflows/file-upload-reaper.ts +12 -0
- package/src/workflows/rig-verification.ts +28 -0
- package/src/workflows/scheduled-tasks.ts +12 -26
- package/src/workflows/session.ts +330 -173
- package/src/workflows/workflow-wake.ts +12 -0
- package/src/workflows.ts +9 -7
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import type { GitCredentialProvider } from "@opengeni/contracts";
|
|
2
|
+
import type { GitTokenExpiries, GitTokenSeeds, MintedRunGitCredentials } from "./environment";
|
|
3
|
+
|
|
4
|
+
export const GIT_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;
|
|
5
|
+
export const GIT_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;
|
|
6
|
+
export const GIT_CREDENTIAL_MIN_REFRESH_MS = 5_000;
|
|
7
|
+
export const GIT_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;
|
|
8
|
+
|
|
9
|
+
type RenewalTimer = unknown;
|
|
10
|
+
|
|
11
|
+
export type GitCredentialRenewalResult = {
|
|
12
|
+
providers: readonly GitCredentialProvider[];
|
|
13
|
+
nextDelayMs: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type GitCredentialRenewalFailure = {
|
|
17
|
+
providers: readonly GitCredentialProvider[];
|
|
18
|
+
retryDelayMs: number;
|
|
19
|
+
errorClass: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type GitCredentialRenewalController = {
|
|
23
|
+
refreshNow(): Promise<void>;
|
|
24
|
+
stop(): Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type GitCredentialRenewalOptions = {
|
|
28
|
+
expectedProviders: readonly GitCredentialProvider[];
|
|
29
|
+
initialExpiresAt?: GitTokenExpiries;
|
|
30
|
+
mint: () => Promise<MintedRunGitCredentials | undefined>;
|
|
31
|
+
write: (tokens: GitTokenSeeds) => Promise<void>;
|
|
32
|
+
now?: () => number;
|
|
33
|
+
schedule?: (callback: () => void, delayMs: number) => RenewalTimer;
|
|
34
|
+
clearSchedule?: (timer: RenewalTimer) => void;
|
|
35
|
+
onSuccess?: (result: GitCredentialRenewalResult) => void;
|
|
36
|
+
onFailure?: (failure: GitCredentialRenewalFailure) => void;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Return a conservative refresh delay for a provider set.
|
|
41
|
+
*
|
|
42
|
+
* The fixed cadence caps long/unknown provider TTLs; a known earlier expiry
|
|
43
|
+
* pulls renewal forward. Invalid metadata is treated as unknown rather than
|
|
44
|
+
* allowing a token to live indefinitely.
|
|
45
|
+
*/
|
|
46
|
+
export function nextGitCredentialRenewalDelay(
|
|
47
|
+
expiresAt: GitTokenExpiries | undefined,
|
|
48
|
+
providers: readonly GitCredentialProvider[],
|
|
49
|
+
nowMs = Date.now(),
|
|
50
|
+
): number {
|
|
51
|
+
let delay = GIT_CREDENTIAL_DEFAULT_REFRESH_MS;
|
|
52
|
+
for (const provider of providers) {
|
|
53
|
+
const rawExpiry = expiresAt?.[provider];
|
|
54
|
+
if (!rawExpiry) continue;
|
|
55
|
+
const expiryMs = Date.parse(rawExpiry);
|
|
56
|
+
if (!Number.isFinite(expiryMs)) continue;
|
|
57
|
+
delay = Math.min(
|
|
58
|
+
delay,
|
|
59
|
+
Math.max(GIT_CREDENTIAL_MIN_REFRESH_MS, expiryMs - nowMs - GIT_CREDENTIAL_EXPIRY_LEAD_MS),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return delay;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function startGitCredentialRenewalLoop(
|
|
66
|
+
options: GitCredentialRenewalOptions,
|
|
67
|
+
): GitCredentialRenewalController {
|
|
68
|
+
const providers = [...new Set(options.expectedProviders)];
|
|
69
|
+
const now = options.now ?? Date.now;
|
|
70
|
+
const schedule =
|
|
71
|
+
options.schedule ??
|
|
72
|
+
((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {
|
|
73
|
+
const timer = setTimeout(callback, delayMs);
|
|
74
|
+
timer.unref?.();
|
|
75
|
+
return timer;
|
|
76
|
+
});
|
|
77
|
+
const clearSchedule =
|
|
78
|
+
options.clearSchedule ??
|
|
79
|
+
((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));
|
|
80
|
+
|
|
81
|
+
let stopped = false;
|
|
82
|
+
let timer: RenewalTimer | null = null;
|
|
83
|
+
let inFlight: Promise<void> | null = null;
|
|
84
|
+
let writeInFlight: Promise<void> | null = null;
|
|
85
|
+
let retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;
|
|
86
|
+
|
|
87
|
+
const clearTimer = (): void => {
|
|
88
|
+
if (timer === null) return;
|
|
89
|
+
clearSchedule(timer);
|
|
90
|
+
timer = null;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const scheduleRefresh = (delayMs: number): void => {
|
|
94
|
+
if (stopped || providers.length === 0) return;
|
|
95
|
+
clearTimer();
|
|
96
|
+
timer = schedule(() => {
|
|
97
|
+
timer = null;
|
|
98
|
+
void refreshNow();
|
|
99
|
+
}, delayMs);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const validateMintedTokens = (
|
|
103
|
+
minted: MintedRunGitCredentials | undefined,
|
|
104
|
+
): MintedRunGitCredentials => {
|
|
105
|
+
if (!minted) {
|
|
106
|
+
throw new GitCredentialRenewalError("credential provider returned no token bundle");
|
|
107
|
+
}
|
|
108
|
+
for (const provider of providers) {
|
|
109
|
+
if (!minted.gitTokens[provider]) {
|
|
110
|
+
throw new GitCredentialRenewalError(`credential provider omitted ${provider}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return minted;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const performRefresh = async (): Promise<void> => {
|
|
117
|
+
try {
|
|
118
|
+
const minted = validateMintedTokens(await options.mint());
|
|
119
|
+
if (stopped) return;
|
|
120
|
+
const write = options.write(minted.gitTokens);
|
|
121
|
+
writeInFlight = write;
|
|
122
|
+
try {
|
|
123
|
+
await write;
|
|
124
|
+
} finally {
|
|
125
|
+
if (writeInFlight === write) writeInFlight = null;
|
|
126
|
+
}
|
|
127
|
+
if (stopped) return;
|
|
128
|
+
retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;
|
|
129
|
+
const nextDelayMs = nextGitCredentialRenewalDelay(minted.expiresAt, providers, now());
|
|
130
|
+
try {
|
|
131
|
+
options.onSuccess?.({ providers, nextDelayMs });
|
|
132
|
+
} catch {
|
|
133
|
+
// Observability callbacks never own credential liveness.
|
|
134
|
+
}
|
|
135
|
+
scheduleRefresh(nextDelayMs);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (stopped) return;
|
|
138
|
+
const scheduledRetryMs = retryDelayMs;
|
|
139
|
+
retryDelayMs = Math.min(retryDelayMs * 2, GIT_CREDENTIAL_MAX_RETRY_MS);
|
|
140
|
+
try {
|
|
141
|
+
options.onFailure?.({
|
|
142
|
+
providers,
|
|
143
|
+
retryDelayMs: scheduledRetryMs,
|
|
144
|
+
errorClass: error instanceof Error ? error.name : "UnknownError",
|
|
145
|
+
});
|
|
146
|
+
} catch {
|
|
147
|
+
// Observability callbacks never own credential liveness.
|
|
148
|
+
}
|
|
149
|
+
scheduleRefresh(scheduledRetryMs);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const refreshNow = (): Promise<void> => {
|
|
154
|
+
if (stopped || providers.length === 0) return Promise.resolve();
|
|
155
|
+
if (inFlight) return inFlight;
|
|
156
|
+
clearTimer();
|
|
157
|
+
const operation = performRefresh();
|
|
158
|
+
inFlight = operation;
|
|
159
|
+
void operation.finally(() => {
|
|
160
|
+
if (inFlight === operation) inFlight = null;
|
|
161
|
+
});
|
|
162
|
+
return operation;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
scheduleRefresh(nextGitCredentialRenewalDelay(options.initialExpiresAt, providers, now()));
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
refreshNow,
|
|
169
|
+
stop: async () => {
|
|
170
|
+
stopped = true;
|
|
171
|
+
clearTimer();
|
|
172
|
+
// A broker mint can be a remote host call with no cancellation seam. It
|
|
173
|
+
// cannot mutate the sandbox, and the stopped check above rejects its late
|
|
174
|
+
// result, so never hold turn settlement hostage to a hung mint. A write
|
|
175
|
+
// does mutate the box and must drain before capture/teardown.
|
|
176
|
+
await writeInFlight?.catch(() => undefined);
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
class GitCredentialRenewalError extends Error {
|
|
182
|
+
override readonly name = "GitCredentialRenewalError";
|
|
183
|
+
}
|
package/src/activities/goals.ts
CHANGED
|
@@ -1,74 +1,143 @@
|
|
|
1
|
-
import { configuredStaticUsageLimits, type Settings } from "@opengeni/config";
|
|
2
1
|
import {
|
|
2
|
+
configuredStaticUsageLimits,
|
|
3
|
+
policyProviderIdForModel,
|
|
4
|
+
type Settings,
|
|
5
|
+
} from "@opengeni/config";
|
|
6
|
+
import {
|
|
7
|
+
evaluateWorkspaceModelPolicy,
|
|
3
8
|
mergeToolRefs,
|
|
4
9
|
reasoningEffortForMetadata,
|
|
5
10
|
type SessionGoal,
|
|
6
11
|
type ToolRef,
|
|
7
12
|
} from "@opengeni/contracts";
|
|
8
13
|
import {
|
|
9
|
-
|
|
14
|
+
addSessionSystemUpdate,
|
|
15
|
+
enqueueSessionWorkflowWakeIfRunnable,
|
|
10
16
|
evaluateGoalContinuation,
|
|
11
17
|
getBillingBalance,
|
|
12
|
-
|
|
18
|
+
getLatestStartedSessionTurn,
|
|
19
|
+
getWorkspaceModelPolicy,
|
|
13
20
|
getSessionGoal,
|
|
14
21
|
isCodexBilledTurn,
|
|
15
22
|
recordUsageEvent,
|
|
16
23
|
requireSession,
|
|
17
|
-
setSessionGoalLastContinuationTurn,
|
|
18
|
-
setSessionGoalStatus,
|
|
19
24
|
sumUsageQuantity,
|
|
20
25
|
type Database,
|
|
21
26
|
} from "@opengeni/db";
|
|
22
|
-
import { appendAndPublishEvents
|
|
23
|
-
import type {
|
|
24
|
-
ActivityServices,
|
|
25
|
-
MaybeContinueGoalInput,
|
|
26
|
-
MaybeContinueGoalResult,
|
|
27
|
-
PauseGoalForInterruptInput,
|
|
28
|
-
} from "./types";
|
|
27
|
+
import { appendAndPublishEvents } from "@opengeni/events";
|
|
28
|
+
import type { ActivityServices, MaybeContinueGoalInput, MaybeContinueGoalResult } from "./types";
|
|
29
29
|
|
|
30
30
|
export function createGoalActivities(services: () => Promise<ActivityServices>) {
|
|
31
|
-
async function
|
|
31
|
+
async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {
|
|
32
|
+
const { db } = await services();
|
|
33
|
+
await enqueueSessionWorkflowWakeIfRunnable(db, {
|
|
34
|
+
accountId: input.accountId,
|
|
35
|
+
workspaceId: input.workspaceId,
|
|
36
|
+
sessionId: input.sessionId,
|
|
37
|
+
temporalWorkflowId: input.workflowId,
|
|
38
|
+
reason: "goal_retry",
|
|
39
|
+
// A permanently invalid goal must not become a tight workflow loop. One
|
|
40
|
+
// durable retry after a short delay preserves liveness without scanning.
|
|
41
|
+
notBefore: new Date(Date.now() + 30_000),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function maybeContinueGoal(
|
|
46
|
+
input: MaybeContinueGoalInput,
|
|
47
|
+
): Promise<MaybeContinueGoalResult> {
|
|
32
48
|
const { settings, db, bus } = await services();
|
|
33
49
|
// Cheap pre-read: the common goal-less session skips the budget queries.
|
|
34
50
|
const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);
|
|
35
51
|
if (!existingGoal || existingGoal.status !== "active") {
|
|
36
52
|
return { action: "none" };
|
|
37
53
|
}
|
|
38
|
-
// Loaded before the budget check so the codex-billed predicate
|
|
39
|
-
//
|
|
40
|
-
//
|
|
54
|
+
// Loaded before the budget check so the codex-billed predicate and the
|
|
55
|
+
// synthesized turn use the SAME effective policy. An explicit per-turn
|
|
56
|
+
// model can differ from the persisted session default; follow-up goal work
|
|
57
|
+
// must preserve the newest policy that actually emitted `turn.started`.
|
|
58
|
+
// Admission-rejected turns have no such event and cannot poison it.
|
|
59
|
+
// Kept below the goal-less fast path so a non-goal session still skips the
|
|
60
|
+
// reads entirely.
|
|
41
61
|
const session = await requireSession(db, input.workspaceId, input.sessionId);
|
|
62
|
+
const latestStartedTurn = await getLatestStartedSessionTurn(
|
|
63
|
+
db,
|
|
64
|
+
input.workspaceId,
|
|
65
|
+
input.sessionId,
|
|
66
|
+
);
|
|
67
|
+
let continuationModel = latestStartedTurn?.model ?? session.model;
|
|
68
|
+
const continuationReasoningEffort =
|
|
69
|
+
latestStartedTurn?.reasoningEffort ??
|
|
70
|
+
reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort);
|
|
71
|
+
// Workspace model policy: a continuation inherits the last STARTED turn's
|
|
72
|
+
// model, so a single policy-violating turn would otherwise re-arm itself on
|
|
73
|
+
// every continuation (exactly how one bare-model turn kept a goal loop on
|
|
74
|
+
// the paid built-in provider all night). If the inherited model is blocked
|
|
75
|
+
// but the session's own default is allowed, recover to the default; if
|
|
76
|
+
// both are blocked, pause the goal visibly (the budget-pause channel, with
|
|
77
|
+
// a truthful rationale) instead of synthesizing a turn the worker's hard
|
|
78
|
+
// gate would fail over and over.
|
|
79
|
+
let modelPolicyBlocked: string | null = null;
|
|
80
|
+
const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);
|
|
81
|
+
if (workspaceModelPolicy) {
|
|
82
|
+
const policyBlocks = (modelId: string): boolean =>
|
|
83
|
+
!evaluateWorkspaceModelPolicy(workspaceModelPolicy, {
|
|
84
|
+
providerId: policyProviderIdForModel(settings, modelId),
|
|
85
|
+
modelId,
|
|
86
|
+
}).allowed;
|
|
87
|
+
if (policyBlocks(continuationModel)) {
|
|
88
|
+
if (continuationModel !== session.model && !policyBlocks(session.model)) {
|
|
89
|
+
continuationModel = session.model;
|
|
90
|
+
} else {
|
|
91
|
+
modelPolicyBlocked = `workspace model policy blocks model "${continuationModel}"; pick an allowed model or change the workspace model policy`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
42
95
|
// A codex-model goal continuation is paid by the user's ChatGPT/Codex plan,
|
|
43
96
|
// so it must not be budget-paused for zero OpenGeni credits. This file uses
|
|
44
97
|
// BASE settings (no codex overlay); the predicate does its own credential read.
|
|
45
|
-
const isCodexRun = await isCodexBilledTurn({
|
|
98
|
+
const isCodexRun = await isCodexBilledTurn({
|
|
99
|
+
db,
|
|
100
|
+
settings,
|
|
101
|
+
workspaceId: input.workspaceId,
|
|
102
|
+
model: continuationModel,
|
|
103
|
+
});
|
|
46
104
|
// Budget exhaustion pauses the goal visibly instead of failing the
|
|
47
105
|
// session. Computed up front and applied inside the locked decision so a
|
|
48
106
|
// limits pause never consumes continuation budget.
|
|
49
|
-
const budgetBlocked = await goalRunBudgetBlocked(
|
|
107
|
+
const budgetBlocked = await goalRunBudgetBlocked(
|
|
108
|
+
settings,
|
|
109
|
+
db,
|
|
110
|
+
input.accountId,
|
|
111
|
+
input.workspaceId,
|
|
112
|
+
isCodexRun,
|
|
113
|
+
);
|
|
50
114
|
const decision = await evaluateGoalContinuation(db, {
|
|
51
115
|
workspaceId: input.workspaceId,
|
|
52
116
|
sessionId: input.sessionId,
|
|
53
117
|
defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,
|
|
54
118
|
noProgressLimit: settings.goalNoProgressLimit,
|
|
55
|
-
|
|
119
|
+
// A model-policy block takes precedence: it is deterministic (a budget
|
|
120
|
+
// pause can clear on its own; a policy pause needs a model/policy change)
|
|
121
|
+
// and rides the same visible-pause channel.
|
|
122
|
+
budgetBlocked: modelPolicyBlocked ?? budgetBlocked,
|
|
56
123
|
});
|
|
57
124
|
if (decision.decision === "none" || decision.decision === "queue") {
|
|
58
125
|
return { action: decision.decision };
|
|
59
126
|
}
|
|
60
127
|
if (decision.decision === "paused") {
|
|
61
|
-
await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
128
|
+
await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [
|
|
129
|
+
{
|
|
130
|
+
type: "goal.paused",
|
|
131
|
+
payload: {
|
|
132
|
+
goalId: decision.goal.id,
|
|
133
|
+
actor: "system",
|
|
134
|
+
reason: decision.reason,
|
|
135
|
+
...(decision.goal.rationale ? { rationale: decision.goal.rationale } : {}),
|
|
136
|
+
autoContinuations: decision.goal.autoContinuations,
|
|
137
|
+
noProgressStreak: decision.goal.noProgressStreak,
|
|
138
|
+
},
|
|
70
139
|
},
|
|
71
|
-
|
|
140
|
+
]);
|
|
72
141
|
return { action: "paused" };
|
|
73
142
|
}
|
|
74
143
|
// Stop/continue race guard: a concurrent goal_complete/goal_pause/operator
|
|
@@ -82,42 +151,35 @@ export function createGoalActivities(services: () => Promise<ActivityServices>)
|
|
|
82
151
|
return { action: "none" };
|
|
83
152
|
}
|
|
84
153
|
const prompt = goalContinuationPrompt(decision.goal, decision.autoContinuation, decision.cap);
|
|
85
|
-
const
|
|
86
|
-
|
|
154
|
+
const update = await addSessionSystemUpdate(db, {
|
|
155
|
+
accountId: input.accountId,
|
|
156
|
+
workspaceId: input.workspaceId,
|
|
157
|
+
sessionId: input.sessionId,
|
|
158
|
+
kind: "lifecycle_event",
|
|
159
|
+
classification: "info",
|
|
160
|
+
sourceId: decision.goal.id,
|
|
161
|
+
dedupeKey: `goal-continuation:${decision.goal.id}:${decision.goal.version}:${decision.autoContinuation}`,
|
|
162
|
+
summary: prompt,
|
|
87
163
|
payload: {
|
|
164
|
+
type: "goal_continuation",
|
|
88
165
|
goalId: decision.goal.id,
|
|
89
|
-
|
|
166
|
+
goalVersion: decision.goal.version,
|
|
90
167
|
autoContinuation: decision.autoContinuation,
|
|
91
168
|
maxAutoContinuations: decision.cap,
|
|
92
|
-
|
|
169
|
+
prompt,
|
|
170
|
+
policy: {
|
|
171
|
+
model: continuationModel,
|
|
172
|
+
reasoningEffort: continuationReasoningEffort,
|
|
173
|
+
tools: withFirstPartyTools(settings, session.tools),
|
|
174
|
+
sandboxBackend: session.sandboxBackend,
|
|
175
|
+
},
|
|
93
176
|
},
|
|
94
|
-
|
|
95
|
-
if (!continuationEvent) {
|
|
96
|
-
throw new Error("failed to append goal continuation trigger event");
|
|
97
|
-
}
|
|
98
|
-
const turn = await enqueueSessionTurn(db, {
|
|
99
|
-
accountId: input.accountId,
|
|
100
|
-
workspaceId: input.workspaceId,
|
|
101
|
-
sessionId: input.sessionId,
|
|
102
|
-
triggerEventId: continuationEvent.id,
|
|
103
|
-
temporalWorkflowId: input.workflowId,
|
|
104
|
-
source: "goal",
|
|
105
|
-
prompt,
|
|
106
|
-
resources: [],
|
|
107
|
-
// Continuations keep the session tool surface and force the first-party
|
|
108
|
-
// server so the goal_complete/goal_pause escape hatches stay reachable.
|
|
109
|
-
tools: withFirstPartyTools(settings, session.tools),
|
|
110
|
-
model: session.model,
|
|
111
|
-
reasoningEffort: reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort),
|
|
112
|
-
sandboxBackend: session.sandboxBackend,
|
|
113
|
-
metadata: { goalId: decision.goal.id, autoContinuation: decision.autoContinuation },
|
|
177
|
+
lineage: { goalId: decision.goal.id },
|
|
114
178
|
});
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
payload: { turnId: turn.id, triggerEventId: continuationEvent.id, source: turn.source },
|
|
120
|
-
}]);
|
|
179
|
+
if (update.reason === "session_cancelled") return { action: "none" };
|
|
180
|
+
if (update.added && update.events.length > 0) {
|
|
181
|
+
await bus.publish(input.workspaceId, input.sessionId, update.events);
|
|
182
|
+
}
|
|
121
183
|
// Continuations count as agent runs for limits/metering parity with
|
|
122
184
|
// user-initiated and scheduled turns.
|
|
123
185
|
await recordUsageEvent(db, {
|
|
@@ -126,81 +188,29 @@ export function createGoalActivities(services: () => Promise<ActivityServices>)
|
|
|
126
188
|
eventType: "agent_run.created",
|
|
127
189
|
quantity: 1,
|
|
128
190
|
unit: "run",
|
|
129
|
-
sourceResourceType: "
|
|
130
|
-
sourceResourceId:
|
|
131
|
-
idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${
|
|
191
|
+
sourceResourceType: "session_system_update",
|
|
192
|
+
sourceResourceId: update.update.id,
|
|
193
|
+
idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${update.update.id}`,
|
|
132
194
|
});
|
|
133
195
|
return { action: "continue" };
|
|
134
196
|
}
|
|
135
197
|
|
|
136
|
-
async function pauseGoalForInterrupt(input: PauseGoalForInterruptInput): Promise<void> {
|
|
137
|
-
const { db, bus } = await services();
|
|
138
|
-
if (input.triggerEventId) {
|
|
139
|
-
const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);
|
|
140
|
-
if (isSteerInterrupt(trigger)) {
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
await pauseActiveGoalOnInterrupt(db, bus, input.workspaceId, input.sessionId);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
198
|
return {
|
|
199
|
+
enqueueGoalRetryWake,
|
|
148
200
|
maybeContinueGoal,
|
|
149
|
-
pauseGoalForInterrupt,
|
|
150
201
|
};
|
|
151
202
|
}
|
|
152
203
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
* other user interrupt (the stop button, a plain `interrupt()` call) is the
|
|
159
|
-
* explicit act of stopping and pauses the goal.
|
|
160
|
-
*/
|
|
161
|
-
export function isSteerInterrupt(trigger: { type: string; payload: unknown } | null | undefined): boolean {
|
|
162
|
-
if (!trigger || trigger.type !== "user.interrupt") {
|
|
163
|
-
return false;
|
|
164
|
-
}
|
|
165
|
-
const payload = trigger.payload;
|
|
166
|
-
return typeof payload === "object" && payload !== null && (payload as { reason?: unknown }).reason === "steer";
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* A user interrupt is the explicit act of stopping, so it pauses an active
|
|
171
|
-
* goal. Shared by the idle-interrupt activity and `interruptActiveTurn` so the
|
|
172
|
-
* loop never auto-continues a goal the user just stopped. Callers gate this
|
|
173
|
-
* on `isSteerInterrupt` first: steer interrupts must NOT pause the goal.
|
|
174
|
-
* No-op when the session has no goal or it is not active.
|
|
175
|
-
*/
|
|
176
|
-
export async function pauseActiveGoalOnInterrupt(db: Database, bus: EventBus, workspaceId: string, sessionId: string): Promise<void> {
|
|
177
|
-
const goal = await getSessionGoal(db, workspaceId, sessionId);
|
|
178
|
-
if (!goal || goal.status !== "active") {
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
const { goal: paused, changed } = await setSessionGoalStatus(db, workspaceId, sessionId, {
|
|
182
|
-
status: "paused",
|
|
183
|
-
pausedReason: "user_interrupt",
|
|
184
|
-
});
|
|
185
|
-
if (changed) {
|
|
186
|
-
await appendAndPublishEvents(db, bus, workspaceId, sessionId, [{
|
|
187
|
-
type: "goal.paused",
|
|
188
|
-
payload: {
|
|
189
|
-
goalId: paused.id,
|
|
190
|
-
actor: "user",
|
|
191
|
-
reason: "user_interrupt",
|
|
192
|
-
autoContinuations: paused.autoContinuations,
|
|
193
|
-
noProgressStreak: paused.noProgressStreak,
|
|
194
|
-
},
|
|
195
|
-
}]);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
export function goalContinuationPrompt(goal: SessionGoal, autoContinuation: number, cap: number | null): string {
|
|
204
|
+
export function goalContinuationPrompt(
|
|
205
|
+
goal: SessionGoal,
|
|
206
|
+
autoContinuation: number,
|
|
207
|
+
cap: number | null,
|
|
208
|
+
): string {
|
|
200
209
|
const counter = cap === null ? `${autoContinuation}` : `${autoContinuation}/${cap}`;
|
|
201
210
|
return [
|
|
202
211
|
`[GOAL CONTINUATION ${counter}] The session goal is not done. Goal: ${goal.text}.`,
|
|
203
212
|
`Success criteria: ${goal.successCriteria ?? "none specified"}.`,
|
|
213
|
+
"Continue from the existing conversation state. Do not repeat completed session setup, persistent metadata settings, or context checks merely because this is a new continuation turn.",
|
|
204
214
|
"Continue working toward the goal now. If it is actually complete, call opengeni__goal_complete with concrete evidence.",
|
|
205
215
|
"If you are blocked or continuing is not productive, call opengeni__goal_pause with your rationale.",
|
|
206
216
|
"You may revise the goal with opengeni__goal_update. Do not stop without one of these explicit actions.",
|
|
@@ -239,11 +249,20 @@ export function withCodexAppsTool(settings: Settings, tools: ToolRef[]): ToolRef
|
|
|
239
249
|
* Non-throwing variant of the scheduled-run admission check: returns a human
|
|
240
250
|
* readable reason when balance or monthly caps block another agent run.
|
|
241
251
|
*/
|
|
242
|
-
async function goalRunBudgetBlocked(
|
|
252
|
+
async function goalRunBudgetBlocked(
|
|
253
|
+
settings: Settings,
|
|
254
|
+
db: Database,
|
|
255
|
+
accountId: string,
|
|
256
|
+
workspaceId: string,
|
|
257
|
+
isCodexRun: boolean,
|
|
258
|
+
): Promise<string | null> {
|
|
243
259
|
// Codex-billed continuations are paid by the user's ChatGPT/Codex plan: skip
|
|
244
260
|
// the credit-balance gate and the monthly model-cost cap. The agent-run COUNT
|
|
245
261
|
// cap below is a volume quota (not a credit/cost gate) and is intentionally kept.
|
|
246
|
-
if (
|
|
262
|
+
if (
|
|
263
|
+
!isCodexRun &&
|
|
264
|
+
(settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
|
|
265
|
+
) {
|
|
247
266
|
const balance = await getBillingBalance(db, accountId);
|
|
248
267
|
if (balance.balanceMicros <= 0) {
|
|
249
268
|
return "insufficient OpenGeni credits";
|
package/src/activities/packs.ts
CHANGED
|
@@ -22,7 +22,10 @@ const emptyPackRuntime: WorkspacePackRuntime = { sandboxImage: null, skills: []
|
|
|
22
22
|
* test on the built-in catalog), so their installations are skipped here
|
|
23
23
|
* without consulting the API's built-in pack list.
|
|
24
24
|
*/
|
|
25
|
-
export async function resolveWorkspacePackRuntime(
|
|
25
|
+
export async function resolveWorkspacePackRuntime(
|
|
26
|
+
db: Database,
|
|
27
|
+
workspaceId: string,
|
|
28
|
+
): Promise<WorkspacePackRuntime> {
|
|
26
29
|
const installations = await listPackInstallations(db, workspaceId);
|
|
27
30
|
const active = installations.filter((installation) => installation.status === "active");
|
|
28
31
|
if (active.length === 0) {
|
|
@@ -49,9 +52,14 @@ export async function resolveWorkspacePackRuntime(db: Database, workspaceId: str
|
|
|
49
52
|
* packs. Violations fail the turn with a plain error instead of guessing.
|
|
50
53
|
*/
|
|
51
54
|
export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): WorkspacePackRuntime {
|
|
52
|
-
const imagePacks = packs.filter(
|
|
55
|
+
const imagePacks = packs.filter(
|
|
56
|
+
(pack) => typeof pack.sandboxImage === "string" && pack.sandboxImage.trim().length > 0,
|
|
57
|
+
);
|
|
53
58
|
if (imagePacks.length > 1) {
|
|
54
|
-
const ids = imagePacks
|
|
59
|
+
const ids = imagePacks
|
|
60
|
+
.map((pack) => pack.id)
|
|
61
|
+
.sort()
|
|
62
|
+
.join(", ");
|
|
55
63
|
throw new Error(
|
|
56
64
|
`Multiple enabled packs declare a sandbox image (${ids}). Only one enabled pack per workspace may declare sandboxImage; disable the others and retry.`,
|
|
57
65
|
);
|
|
@@ -94,7 +102,10 @@ export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): Workspac
|
|
|
94
102
|
* resolution; per-session overrides do not exist in this slice, so the worker
|
|
95
103
|
* resolves workspace > default and passes the result as instructionsTemplate.
|
|
96
104
|
*/
|
|
97
|
-
export async function resolveWorkspaceAgentInstructions(
|
|
105
|
+
export async function resolveWorkspaceAgentInstructions(
|
|
106
|
+
db: Database,
|
|
107
|
+
workspaceId: string,
|
|
108
|
+
): Promise<string | null> {
|
|
98
109
|
const workspace = await getWorkspace(db, workspaceId);
|
|
99
110
|
return workspace?.agentInstructions ?? null;
|
|
100
111
|
}
|
|
@@ -104,7 +115,10 @@ export async function resolveWorkspaceAgentInstructions(db: Database, workspaceI
|
|
|
104
115
|
* the settings pass through untouched, so deployments without packs keep the
|
|
105
116
|
* global OPENGENI_DOCKER_IMAGE / OPENGENI_MODAL_IMAGE_REF behavior exactly.
|
|
106
117
|
*/
|
|
107
|
-
export function settingsWithPackSandboxImage(
|
|
118
|
+
export function settingsWithPackSandboxImage(
|
|
119
|
+
settings: Settings,
|
|
120
|
+
sandboxImage: string | null,
|
|
121
|
+
): Settings {
|
|
108
122
|
if (!sandboxImage) {
|
|
109
123
|
return settings;
|
|
110
124
|
}
|
|
@@ -114,3 +128,39 @@ export function settingsWithPackSandboxImage(settings: Settings, sandboxImage: s
|
|
|
114
128
|
modalImageRef: sandboxImage,
|
|
115
129
|
};
|
|
116
130
|
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Applies the session's frozen rig-version image to run settings. Rig image is
|
|
134
|
+
* the TOP of the image precedence chain (rig > pack > deployment default): when
|
|
135
|
+
* the rig version pins an image it OVERRIDES both the deployment
|
|
136
|
+
* dockerImage/modalImageRef AND any pack-declared sandboxImage. When the rig
|
|
137
|
+
* pins no image (`null`), the settings pass through untouched so the pack /
|
|
138
|
+
* deployment chain below still resolves exactly as today. Applied AFTER
|
|
139
|
+
* settingsWithPackSandboxImage so it wins the collision; identical mechanics to
|
|
140
|
+
* the pack equivalent (write both image fields so docker and modal agree).
|
|
141
|
+
*/
|
|
142
|
+
export function settingsWithRigImage(settings: Settings, rigImage: string | null): Settings {
|
|
143
|
+
if (!rigImage) {
|
|
144
|
+
return settings;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
...settings,
|
|
148
|
+
dockerImage: rigImage,
|
|
149
|
+
modalImageRef: rigImage,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Layers the rig version's default variable sets BELOW the session's own set:
|
|
155
|
+
* the session's values WIN on any key collision (explicit precedence). Both maps
|
|
156
|
+
* are already the decrypted-and-merged values (rig defaults merged in listed
|
|
157
|
+
* order upstream). Pure and deterministic — given the same inputs it returns the
|
|
158
|
+
* same env, which is what keeps a session's box-manifest env stable across turns
|
|
159
|
+
* (the rig version is frozen per session, so its default-set list is fixed).
|
|
160
|
+
*/
|
|
161
|
+
export function mergeRigDefaultVariableSetEnvironment(
|
|
162
|
+
rigDefaultValues: Record<string, string>,
|
|
163
|
+
sessionValues: Record<string, string>,
|
|
164
|
+
): Record<string, string> {
|
|
165
|
+
return { ...rigDefaultValues, ...sessionValues };
|
|
166
|
+
}
|