feat(agent): add credential refresh and unify learning tools
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { type RuntimeSessionContext } from "../runtime/sessionContext.js";
|
||||
|
||||
export type CredentialRefreshReason =
|
||||
| "access_token_expired"
|
||||
| "access_token_rejected";
|
||||
|
||||
export type CredentialRefreshEvent =
|
||||
| {
|
||||
type: "credential_refresh_required";
|
||||
requestId: string;
|
||||
reason: CredentialRefreshReason;
|
||||
timeoutMs: number;
|
||||
}
|
||||
| {
|
||||
type: "credential_refreshed";
|
||||
requestId: string;
|
||||
}
|
||||
| {
|
||||
type: "credential_refresh_failed";
|
||||
requestId: string;
|
||||
message: string;
|
||||
};
|
||||
|
||||
type PendingRefresh = {
|
||||
deadlineAt: number;
|
||||
promise: Promise<RuntimeSessionContext>;
|
||||
reason: CredentialRefreshReason;
|
||||
reject: (error: Error) => void;
|
||||
requestId: string;
|
||||
resolve: (context: RuntimeSessionContext) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
type CredentialRefreshListener = (event: CredentialRefreshEvent) => void;
|
||||
|
||||
export class CredentialRefreshError extends Error {
|
||||
override readonly name = "CredentialRefreshError";
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
readonly code: "cancelled" | "failed" | "timeout" | "unavailable" = "failed",
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const AUTH_EXPIRY_SKEW_MS = 30_000;
|
||||
|
||||
export const isRuntimeCredentialExpired = (
|
||||
context: RuntimeSessionContext,
|
||||
now = Date.now(),
|
||||
) => {
|
||||
if (!context.tokenExpiresAt) {
|
||||
return false;
|
||||
}
|
||||
const expiresAt = Date.parse(context.tokenExpiresAt);
|
||||
return Number.isFinite(expiresAt) && now >= expiresAt - AUTH_EXPIRY_SKEW_MS;
|
||||
};
|
||||
|
||||
export class CredentialRefreshCoordinator {
|
||||
private readonly listeners = new Map<
|
||||
string,
|
||||
Set<CredentialRefreshListener>
|
||||
>();
|
||||
private readonly pending = new Map<string, PendingRefresh>();
|
||||
|
||||
constructor(private readonly timeoutMs = 30_000) {}
|
||||
|
||||
subscribe(sessionId: string, listener: CredentialRefreshListener) {
|
||||
const listeners =
|
||||
this.listeners.get(sessionId) ?? new Set<CredentialRefreshListener>();
|
||||
listeners.add(listener);
|
||||
this.listeners.set(sessionId, listeners);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) {
|
||||
this.listeners.delete(sessionId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
request(sessionId: string, reason: CredentialRefreshReason) {
|
||||
const existing = this.pending.get(sessionId);
|
||||
if (existing) {
|
||||
return existing.promise;
|
||||
}
|
||||
if (!this.listeners.get(sessionId)?.size) {
|
||||
return Promise.reject(
|
||||
new CredentialRefreshError(
|
||||
"credential refresh channel is unavailable",
|
||||
"unavailable",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const requestId = `credential-${randomUUID()}`;
|
||||
let resolvePromise!: (context: RuntimeSessionContext) => void;
|
||||
let rejectPromise!: (error: Error) => void;
|
||||
const promise = new Promise<RuntimeSessionContext>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
const timer = setTimeout(() => {
|
||||
this.fail(sessionId, requestId, "credential refresh timed out", "timeout");
|
||||
}, this.timeoutMs);
|
||||
this.pending.set(sessionId, {
|
||||
deadlineAt: Date.now() + this.timeoutMs,
|
||||
promise,
|
||||
reason,
|
||||
reject: rejectPromise,
|
||||
requestId,
|
||||
resolve: resolvePromise,
|
||||
timer,
|
||||
});
|
||||
this.emit(sessionId, {
|
||||
type: "credential_refresh_required",
|
||||
requestId,
|
||||
reason,
|
||||
timeoutMs: this.timeoutMs,
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
resolve(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
context: RuntimeSessionContext,
|
||||
) {
|
||||
const pending = this.pending.get(sessionId);
|
||||
if (!pending || pending.requestId !== requestId) {
|
||||
return false;
|
||||
}
|
||||
clearTimeout(pending.timer);
|
||||
this.pending.delete(sessionId);
|
||||
pending.resolve(context);
|
||||
this.emit(sessionId, {
|
||||
type: "credential_refreshed",
|
||||
requestId,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
fail(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
message: string,
|
||||
code: CredentialRefreshError["code"] = "failed",
|
||||
emitFailureEvent = true,
|
||||
) {
|
||||
const pending = this.pending.get(sessionId);
|
||||
if (!pending || pending.requestId !== requestId) {
|
||||
return false;
|
||||
}
|
||||
clearTimeout(pending.timer);
|
||||
this.pending.delete(sessionId);
|
||||
pending.reject(new CredentialRefreshError(message, code));
|
||||
if (emitFailureEvent) {
|
||||
this.emit(sessionId, {
|
||||
type: "credential_refresh_failed",
|
||||
requestId,
|
||||
message,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
cancelSession(sessionId: string, message = "credential refresh cancelled") {
|
||||
const pending = this.pending.get(sessionId);
|
||||
if (!pending) {
|
||||
return false;
|
||||
}
|
||||
return this.fail(
|
||||
sessionId,
|
||||
pending.requestId,
|
||||
message,
|
||||
"cancelled",
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
getPendingRequestId(sessionId: string) {
|
||||
return this.pending.get(sessionId)?.requestId;
|
||||
}
|
||||
|
||||
getPendingEvent(
|
||||
sessionId: string,
|
||||
): Extract<CredentialRefreshEvent, { type: "credential_refresh_required" }> | null {
|
||||
const pending = this.pending.get(sessionId);
|
||||
if (!pending) return null;
|
||||
return {
|
||||
type: "credential_refresh_required",
|
||||
requestId: pending.requestId,
|
||||
reason: pending.reason,
|
||||
timeoutMs: Math.max(0, pending.deadlineAt - Date.now()),
|
||||
};
|
||||
}
|
||||
|
||||
private emit(sessionId: string, event: CredentialRefreshEvent) {
|
||||
for (const listener of this.listeners.get(sessionId) ?? []) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const runWithCredentialRefresh = async <T extends { status: number }>(
|
||||
coordinator: CredentialRefreshCoordinator,
|
||||
context: RuntimeSessionContext,
|
||||
execute: (context: RuntimeSessionContext) => Promise<T>,
|
||||
) => {
|
||||
let activeContext = context;
|
||||
let refreshed = false;
|
||||
if (isRuntimeCredentialExpired(activeContext)) {
|
||||
activeContext = await coordinator.request(
|
||||
activeContext.sessionId,
|
||||
"access_token_expired",
|
||||
);
|
||||
refreshed = true;
|
||||
}
|
||||
|
||||
let result = await execute(activeContext);
|
||||
if (result.status !== 401 || refreshed) {
|
||||
return result;
|
||||
}
|
||||
activeContext = await coordinator.request(
|
||||
activeContext.sessionId,
|
||||
"access_token_rejected",
|
||||
);
|
||||
result = await execute(activeContext);
|
||||
return result;
|
||||
};
|
||||
+3
-25
@@ -41,8 +41,8 @@ const envSchema = z
|
||||
AGENT_INTERNAL_TOKEN: optionalString(),
|
||||
// Agent 前置认证调用后端 /api/v1/agent/auth/context 的超时时间(毫秒)。
|
||||
AGENT_AUTH_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),
|
||||
// opencode 运行模式:embedded 会启动本地 CLI 子进程;client 只连接现有 server。
|
||||
OPENCODE_MODE: z.enum(["embedded", "client"]).default("embedded"),
|
||||
// 当前仅支持 embedded;保留字段用于让旧 client 配置在启动时明确失败。
|
||||
OPENCODE_MODE: z.literal("embedded").default("embedded"),
|
||||
// embedded opencode server 的监听地址。
|
||||
OPENCODE_HOSTNAME: z.string().default("127.0.0.1"),
|
||||
// embedded opencode server 的监听端口。
|
||||
@@ -55,10 +55,6 @@ const envSchema = z
|
||||
OPENCODE_MODEL_OPTIONS: z.string().default(defaultAgentModelOptionsJson),
|
||||
// opencode skills 树目录;会在运行时解析为绝对路径,避免工具 cwd 偏移。
|
||||
OPENCODE_SKILLS_ROOT_DIR: z.string().default("./.opencode/skills"),
|
||||
// client 模式下,目标 opencode server 的基础地址。
|
||||
OPENCODE_CLIENT_BASE_URL: z.string().url().optional(),
|
||||
// 旧版 client 模式环境变量名,保留兼容,解析时会映射到 OPENCODE_CLIENT_BASE_URL。
|
||||
OPENCODE_BASE_URL: z.string().url().optional(),
|
||||
// tjwater-cli 可执行文件路径。
|
||||
TJWATER_CLI_PATH: z.string().default("./cli/tjwater-cli"),
|
||||
// TJWater 后端 API 的基础地址。
|
||||
@@ -117,13 +113,6 @@ const envSchema = z
|
||||
.default(3600000),
|
||||
})
|
||||
.superRefine((env, ctx) => {
|
||||
if (env.OPENCODE_MODE === "client" && !env.OPENCODE_CLIENT_BASE_URL) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["OPENCODE_CLIENT_BASE_URL"],
|
||||
message: "OPENCODE_CLIENT_BASE_URL is required when OPENCODE_MODE=client",
|
||||
});
|
||||
}
|
||||
let modelOptions;
|
||||
try {
|
||||
modelOptions = parseAgentModelOptions(env.OPENCODE_MODEL_OPTIONS);
|
||||
@@ -154,15 +143,4 @@ const envSchema = z
|
||||
|
||||
export type AppConfig = z.infer<typeof envSchema>;
|
||||
|
||||
const normalizedEnv = {
|
||||
...process.env,
|
||||
OPENCODE_MODE:
|
||||
process.env.OPENCODE_MODE ??
|
||||
(process.env.OPENCODE_CLIENT_BASE_URL || process.env.OPENCODE_BASE_URL
|
||||
? "client"
|
||||
: "embedded"),
|
||||
OPENCODE_CLIENT_BASE_URL:
|
||||
process.env.OPENCODE_CLIENT_BASE_URL ?? process.env.OPENCODE_BASE_URL,
|
||||
};
|
||||
|
||||
export const config: AppConfig = envSchema.parse(normalizedEnv);
|
||||
export const config: AppConfig = envSchema.parse(process.env);
|
||||
|
||||
@@ -246,6 +246,24 @@ register("/api/v1/agent/sessions/{session_id}/runs/current", "delete", {
|
||||
request: { params: SessionId },
|
||||
responses: { 202: jsonResponse(JsonObject), 204: { description: "No active run" } },
|
||||
});
|
||||
register(
|
||||
"/api/v1/agent/sessions/{session_id}/credential-refreshes",
|
||||
"post",
|
||||
{
|
||||
summary: "Resume a waiting agent tool call with refreshed credentials",
|
||||
request: {
|
||||
params: SessionId,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({ request_id: z.string().min(1).max(128) }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: { 202: jsonResponse(JsonObject) },
|
||||
},
|
||||
);
|
||||
register(
|
||||
"/api/v1/agent/sessions/{session_id}/permission-responses",
|
||||
"post",
|
||||
|
||||
@@ -77,12 +77,12 @@ type TurnReviewInput = {
|
||||
export class LearningOrchestrator {
|
||||
private readonly activeReviews = new Set<string>();
|
||||
private readonly sessionLearningStateStore = new SessionLearningStateStore();
|
||||
private readonly skillStore = new SkillStore();
|
||||
|
||||
constructor(
|
||||
private readonly runtime: OpencodeRuntimeAdapter,
|
||||
private readonly memoryStore: MemoryStore,
|
||||
private readonly transcriptStore: SessionTranscriptStore,
|
||||
private readonly skillStore: SkillStore,
|
||||
) {}
|
||||
|
||||
async initialize() {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { type MemoryScope, MemoryStore } from "../memory/store.js";
|
||||
import {
|
||||
setRuntimeSessionContext,
|
||||
type RuntimeSessionContext,
|
||||
} from "../runtime/sessionContext.js";
|
||||
import { SkillStore } from "../skills/store.js";
|
||||
|
||||
export type MemoryManagerInput = {
|
||||
action: "add" | "list" | "replace" | "remove";
|
||||
content?: string;
|
||||
scope: string;
|
||||
target_id?: string;
|
||||
};
|
||||
|
||||
export type SkillManagerInput = {
|
||||
action:
|
||||
| "list"
|
||||
| "write_skill"
|
||||
| "remove_skill"
|
||||
| "append_pattern"
|
||||
| "remove_pattern"
|
||||
| "write_reference"
|
||||
| "remove_reference"
|
||||
| "write_script"
|
||||
| "remove_script";
|
||||
content?: string;
|
||||
file_path?: string;
|
||||
pattern?: string;
|
||||
skill_path: string;
|
||||
target_id?: string;
|
||||
};
|
||||
|
||||
export const executeMemoryManager = async (
|
||||
memoryStore: MemoryStore,
|
||||
sessionContext: RuntimeSessionContext,
|
||||
input: MemoryManagerInput,
|
||||
) => {
|
||||
const scope: MemoryScope | null =
|
||||
input.scope === "user"
|
||||
? "user"
|
||||
: input.scope === "workspace"
|
||||
? "workspace"
|
||||
: null;
|
||||
if (!scope) {
|
||||
return rejected(
|
||||
"memory",
|
||||
`unsupported scope: ${input.scope}; use exact keyword 'user' or 'workspace'`,
|
||||
);
|
||||
}
|
||||
if (sessionContext.allowLearningWrite === false && input.action !== "list") {
|
||||
return rejected("memory", "memory writes are disabled for this session");
|
||||
}
|
||||
|
||||
const scopeKey =
|
||||
scope === "user" ? sessionContext.actorKey : sessionContext.projectKey;
|
||||
if (input.action === "list") {
|
||||
setRuntimeSessionContext({
|
||||
...sessionContext,
|
||||
memoryListReadScopes: {
|
||||
...(sessionContext.memoryListReadScopes ?? {}),
|
||||
[scope]: true,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
kind: "memory",
|
||||
decision: "accepted",
|
||||
detail: "memory listed",
|
||||
items: await memoryStore.list(scope, scopeKey),
|
||||
target: scope,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.action === "add") {
|
||||
if (sessionContext.memoryListReadScopes?.[scope] !== true) {
|
||||
return {
|
||||
...rejected(
|
||||
"memory",
|
||||
`must list ${scope} memory and review existing entries before add`,
|
||||
),
|
||||
target: scope,
|
||||
};
|
||||
}
|
||||
const result = await memoryStore.upsert(scope, scopeKey, {
|
||||
content: input.content ?? "",
|
||||
sessionId: sessionContext.clientSessionId,
|
||||
source: "tool",
|
||||
traceId: sessionContext.traceId,
|
||||
});
|
||||
if (!result.entry) {
|
||||
return rejected("memory", "content rejected by persistence policy");
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
kind: "memory",
|
||||
decision: result.changed ? "accepted" : "deduped",
|
||||
detail: result.detail,
|
||||
entry: result.entry,
|
||||
target: scope,
|
||||
};
|
||||
}
|
||||
|
||||
const result =
|
||||
input.action === "replace"
|
||||
? await memoryStore.replace(scope, scopeKey, input.target_id ?? "", {
|
||||
content: input.content ?? "",
|
||||
sessionId: sessionContext.clientSessionId,
|
||||
source: "tool",
|
||||
traceId: sessionContext.traceId,
|
||||
})
|
||||
: await memoryStore.remove(scope, scopeKey, input.target_id ?? "");
|
||||
return {
|
||||
ok: true,
|
||||
kind: "memory",
|
||||
decision: result.changed ? "accepted" : "rejected",
|
||||
detail: result.detail,
|
||||
target: scope,
|
||||
};
|
||||
};
|
||||
|
||||
export const executeSkillManager = async (
|
||||
skillStore: SkillStore,
|
||||
sessionContext: RuntimeSessionContext,
|
||||
input: SkillManagerInput,
|
||||
) => {
|
||||
if (sessionContext.allowLearningWrite === false && input.action !== "list") {
|
||||
return rejected("skill", "skill writes are disabled for this session");
|
||||
}
|
||||
if (input.action === "list") {
|
||||
const result = await skillStore.list(input.skill_path);
|
||||
if (!result) {
|
||||
return rejected(
|
||||
"skill",
|
||||
"invalid skill_path; expected a relative path under .opencode/skills",
|
||||
);
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
kind: "skill",
|
||||
decision: "accepted",
|
||||
detail: "skill listed",
|
||||
references: result.references,
|
||||
scripts: result.scripts,
|
||||
skill_path: result.skillPath,
|
||||
target: result.target,
|
||||
patterns: result.patterns,
|
||||
};
|
||||
}
|
||||
|
||||
const result =
|
||||
input.action === "write_skill"
|
||||
? await skillStore.writeSkill(input.skill_path, input.content ?? "")
|
||||
: input.action === "remove_skill"
|
||||
? await skillStore.removeSkill(input.skill_path)
|
||||
: input.action === "append_pattern"
|
||||
? await skillStore.appendPattern(input.skill_path, input.pattern ?? "")
|
||||
: input.action === "remove_pattern"
|
||||
? await skillStore.removePattern(input.skill_path, input.target_id ?? "")
|
||||
: input.action === "write_reference"
|
||||
? await skillStore.writeReference(
|
||||
input.skill_path,
|
||||
input.file_path ?? "",
|
||||
input.content ?? "",
|
||||
)
|
||||
: input.action === "remove_reference"
|
||||
? await skillStore.removeReference(
|
||||
input.skill_path,
|
||||
input.file_path ?? "",
|
||||
)
|
||||
: input.action === "write_script"
|
||||
? await skillStore.writeScript(
|
||||
input.skill_path,
|
||||
input.file_path ?? "",
|
||||
input.content ?? "",
|
||||
)
|
||||
: await skillStore.removeScript(
|
||||
input.skill_path,
|
||||
input.file_path ?? "",
|
||||
);
|
||||
return {
|
||||
ok: true,
|
||||
kind: "skill",
|
||||
decision: result.changed ? "accepted" : "rejected",
|
||||
detail: result.detail,
|
||||
target: result.target,
|
||||
};
|
||||
};
|
||||
|
||||
const rejected = (kind: "memory" | "skill", detail: string) => ({
|
||||
ok: true,
|
||||
kind,
|
||||
decision: "rejected",
|
||||
detail,
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { Router } from "express";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getAgentAuthContext } from "../auth/agentAuth.js";
|
||||
import { type CredentialRefreshCoordinator } from "../auth/credentialRefresh.js";
|
||||
import {
|
||||
agentModelOptions,
|
||||
isSupportedModel,
|
||||
@@ -121,6 +122,7 @@ export const buildChatRouter = (
|
||||
sessionTranscriptStore: SessionTranscriptStore,
|
||||
learningOrchestrator: LearningOrchestrator,
|
||||
resultReferenceResolver: ResultReferenceResolver,
|
||||
credentialRefreshCoordinator: CredentialRefreshCoordinator,
|
||||
) => {
|
||||
const chatRouter = Router();
|
||||
|
||||
@@ -295,6 +297,16 @@ export const buildChatRouter = (
|
||||
},
|
||||
};
|
||||
run.subscribers.add(subscriber);
|
||||
const pendingCredentialRefresh =
|
||||
credentialRefreshCoordinator.getPendingEvent(sessionRecord.sessionId);
|
||||
if (pendingCredentialRefresh) {
|
||||
subscriber.write(pendingCredentialRefresh.type, {
|
||||
session_id: sessionRecord.sessionId,
|
||||
request_id: pendingCredentialRefresh.requestId,
|
||||
reason: pendingCredentialRefresh.reason,
|
||||
timeout_ms: pendingCredentialRefresh.timeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
const cleanup = () => {
|
||||
run.subscribers.delete(subscriber);
|
||||
@@ -390,6 +402,7 @@ export const buildChatRouter = (
|
||||
|
||||
registerChatInteractionRoutes(chatRouter, {
|
||||
activeRuns,
|
||||
credentialRefreshCoordinator,
|
||||
runtime,
|
||||
sessionMetadataStore,
|
||||
sessionUiStateStore,
|
||||
@@ -803,6 +816,35 @@ export const buildChatRouter = (
|
||||
logger.warn({ err: error, sessionId: clientSessionId }, "failed to persist chat stream state");
|
||||
});
|
||||
};
|
||||
const unsubscribeCredentialRefresh = credentialRefreshCoordinator.subscribe(
|
||||
binding.sessionId,
|
||||
(event) => {
|
||||
publish(event.type, {
|
||||
session_id: clientSessionId,
|
||||
request_id: event.requestId,
|
||||
...(event.type === "credential_refresh_required"
|
||||
? {
|
||||
reason: event.reason,
|
||||
timeout_ms: event.timeoutMs,
|
||||
}
|
||||
: {}),
|
||||
...(event.type === "credential_refresh_failed"
|
||||
? { message: event.message }
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
const cancelCredentialRefreshOnAbort = () => {
|
||||
credentialRefreshCoordinator.cancelSession(
|
||||
binding.sessionId,
|
||||
"credential refresh cancelled because the agent run was aborted",
|
||||
);
|
||||
};
|
||||
abortController.signal.addEventListener(
|
||||
"abort",
|
||||
cancelCredentialRefreshOnAbort,
|
||||
{ once: true },
|
||||
);
|
||||
|
||||
try {
|
||||
const preparedMessage = await buildPromptWithLearningContext(
|
||||
@@ -925,6 +967,12 @@ export const buildChatRouter = (
|
||||
logger.warn({ err: error, sessionId: clientSessionId }, "failed to persist chat stream state");
|
||||
});
|
||||
sessionBridge.finalizeRequest(clientSessionId);
|
||||
abortController.signal.removeEventListener(
|
||||
"abort",
|
||||
cancelCredentialRefreshOnAbort,
|
||||
);
|
||||
credentialRefreshCoordinator.cancelSession(binding.sessionId);
|
||||
unsubscribeCredentialRefresh();
|
||||
activeRun.status = abortController.signal.aborted
|
||||
? activeRun.status === "aborted"
|
||||
? "aborted"
|
||||
|
||||
@@ -2,8 +2,13 @@ import { type Router } from "express";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getAgentAuthContext } from "../auth/agentAuth.js";
|
||||
import { type CredentialRefreshCoordinator } from "../auth/credentialRefresh.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { type OpencodeRuntimeAdapter } from "../runtime/opencode.js";
|
||||
import {
|
||||
getRuntimeSessionContext,
|
||||
setRuntimeSessionContext,
|
||||
} from "../runtime/sessionContext.js";
|
||||
import { type SessionMetadataStore } from "../sessions/metadataStore.js";
|
||||
import { type SessionUiStateStore } from "../sessions/uiStateStore.js";
|
||||
import { toActorKey, toProjectKey } from "../utils/fileStore.js";
|
||||
@@ -26,8 +31,13 @@ const questionReplyPayloadSchema = z.object({
|
||||
answers: z.array(z.array(z.string().max(2000))).default([]),
|
||||
});
|
||||
|
||||
const credentialRefreshPayloadSchema = z.object({
|
||||
request_id: z.string().min(1).max(128),
|
||||
});
|
||||
|
||||
type RegisterInteractionRoutesOptions = {
|
||||
activeRuns: Map<string, ActiveRun>;
|
||||
credentialRefreshCoordinator: CredentialRefreshCoordinator;
|
||||
runtime: OpencodeRuntimeAdapter;
|
||||
sessionMetadataStore: SessionMetadataStore;
|
||||
sessionUiStateStore: SessionUiStateStore;
|
||||
@@ -41,11 +51,73 @@ export const registerChatInteractionRoutes = (
|
||||
chatRouter: Router,
|
||||
{
|
||||
activeRuns,
|
||||
credentialRefreshCoordinator,
|
||||
runtime,
|
||||
sessionMetadataStore,
|
||||
sessionUiStateStore,
|
||||
}: RegisterInteractionRoutesOptions,
|
||||
) => {
|
||||
chatRouter.post("/sessions/:session_id/credential-refreshes", async (req, res) => {
|
||||
const parsed = credentialRefreshPayloadSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({
|
||||
message: "invalid request payload",
|
||||
detail: parsed.error.flatten(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const authContext = getAgentAuthContext(req);
|
||||
const actorKey = toActorKey(authContext.userId);
|
||||
const projectKey = toProjectKey(authContext.projectId);
|
||||
const sessionRecord = await sessionMetadataStore.get(
|
||||
{
|
||||
actorKey,
|
||||
projectId: authContext.projectId,
|
||||
projectKey,
|
||||
userId: authContext.userId,
|
||||
},
|
||||
req.params.session_id,
|
||||
);
|
||||
if (!sessionRecord) {
|
||||
res.status(404).json({ message: "session not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
const current = getRuntimeSessionContext(sessionRecord.sessionId);
|
||||
if (!current || current.actorKey !== actorKey || current.projectKey !== projectKey) {
|
||||
res.status(409).json({ message: "runtime session context unavailable" });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
credentialRefreshCoordinator.getPendingRequestId(sessionRecord.sessionId) !==
|
||||
parsed.data.request_id
|
||||
) {
|
||||
res.status(409).json({ message: "credential refresh request is no longer pending" });
|
||||
return;
|
||||
}
|
||||
const refreshedContext = {
|
||||
...current,
|
||||
accessToken: authContext.accessToken,
|
||||
authExpired: undefined,
|
||||
network: authContext.network,
|
||||
projectId: authContext.projectId,
|
||||
tokenExpiresAt: authContext.tokenExpiresAt,
|
||||
traceId: req.header("x-trace-id")?.trim() || current.traceId,
|
||||
};
|
||||
setRuntimeSessionContext(refreshedContext);
|
||||
credentialRefreshCoordinator.resolve(
|
||||
sessionRecord.sessionId,
|
||||
parsed.data.request_id,
|
||||
refreshedContext,
|
||||
);
|
||||
res.status(202).json({
|
||||
session_id: sessionRecord.sessionId,
|
||||
request_id: parsed.data.request_id,
|
||||
status: "accepted",
|
||||
});
|
||||
});
|
||||
|
||||
chatRouter.post("/sessions/:session_id/permission-responses", async (req, res) => {
|
||||
const parsed = permissionReplyPayloadSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import {
|
||||
getRuntimeSessionContext,
|
||||
setRuntimeSessionContext,
|
||||
type RuntimeSessionContext,
|
||||
} from "./sessionContext.js";
|
||||
|
||||
type FetchLike = (
|
||||
input: string | URL | Request,
|
||||
init?: RequestInit,
|
||||
) => Promise<Response>;
|
||||
|
||||
type InternalSessionContextClientOptions = {
|
||||
baseUrl?: string;
|
||||
internalToken?: string;
|
||||
fetchImpl?: FetchLike;
|
||||
};
|
||||
|
||||
type InternalSessionContextPayload = {
|
||||
actor_key: string;
|
||||
allow_learning_write?: boolean;
|
||||
client_session_id: string;
|
||||
memory_list_read_scopes?: Partial<Record<"user" | "workspace", boolean>>;
|
||||
project_key: string;
|
||||
session_id: string;
|
||||
trace_id: string;
|
||||
};
|
||||
|
||||
export const serializeRuntimeSessionContext = (
|
||||
context: RuntimeSessionContext,
|
||||
): InternalSessionContextPayload => ({
|
||||
actor_key: context.actorKey,
|
||||
allow_learning_write: context.allowLearningWrite,
|
||||
client_session_id: context.clientSessionId,
|
||||
memory_list_read_scopes: context.memoryListReadScopes,
|
||||
project_key: context.projectKey,
|
||||
session_id: context.sessionId,
|
||||
trace_id: context.traceId,
|
||||
});
|
||||
|
||||
const requireString = (
|
||||
value: unknown,
|
||||
field: keyof InternalSessionContextPayload,
|
||||
) => {
|
||||
if (typeof value !== "string" || value.length === 0) {
|
||||
throw new Error(`invalid internal session context field: ${field}`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const parseRuntimeSessionContext = (
|
||||
value: unknown,
|
||||
): RuntimeSessionContext => {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error("invalid internal session context response");
|
||||
}
|
||||
const payload = value as Record<string, unknown>;
|
||||
const readScopes = payload.memory_list_read_scopes;
|
||||
return {
|
||||
actorKey: requireString(payload.actor_key, "actor_key"),
|
||||
allowLearningWrite:
|
||||
typeof payload.allow_learning_write === "boolean"
|
||||
? payload.allow_learning_write
|
||||
: undefined,
|
||||
clientSessionId: requireString(
|
||||
payload.client_session_id,
|
||||
"client_session_id",
|
||||
),
|
||||
memoryListReadScopes:
|
||||
readScopes && typeof readScopes === "object" && !Array.isArray(readScopes)
|
||||
? (readScopes as RuntimeSessionContext["memoryListReadScopes"])
|
||||
: undefined,
|
||||
projectKey: requireString(payload.project_key, "project_key"),
|
||||
sessionId: requireString(payload.session_id, "session_id"),
|
||||
traceId: requireString(payload.trace_id, "trace_id"),
|
||||
};
|
||||
};
|
||||
|
||||
export const readBridgedRuntimeSessionContext = async (
|
||||
sessionId: string,
|
||||
options: InternalSessionContextClientOptions = {},
|
||||
) => {
|
||||
const localContext = getRuntimeSessionContext(sessionId);
|
||||
if (localContext) {
|
||||
return localContext;
|
||||
}
|
||||
|
||||
const baseUrl = (
|
||||
options.baseUrl ??
|
||||
process.env.TJWATER_AGENT_INTERNAL_BASE_URL ??
|
||||
"http://127.0.0.1:8787"
|
||||
).replace(/\/+$/, "");
|
||||
const internalToken =
|
||||
options.internalToken ?? process.env.TJWATER_AGENT_INTERNAL_TOKEN ?? "";
|
||||
const response = await (options.fetchImpl ?? fetch)(
|
||||
`${baseUrl}/internal/tools/session-context`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-agent-internal-token": internalToken,
|
||||
},
|
||||
body: JSON.stringify({ session_id: sessionId }),
|
||||
},
|
||||
);
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(text || `session context bridge failed: ${response.status}`);
|
||||
}
|
||||
|
||||
const context = parseRuntimeSessionContext(JSON.parse(text));
|
||||
if (context.sessionId !== sessionId) {
|
||||
throw new Error("internal session context id mismatch");
|
||||
}
|
||||
setRuntimeSessionContext(context);
|
||||
return context;
|
||||
};
|
||||
+1
-15
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
createOpencode,
|
||||
createOpencodeClient,
|
||||
type OpencodeClient,
|
||||
} from "@opencode-ai/sdk/v2";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
@@ -387,19 +386,6 @@ export class OpencodeRuntimeAdapter {
|
||||
}
|
||||
|
||||
private async bootstrapClient(): Promise<OpencodeClient> {
|
||||
if (config.OPENCODE_MODE === "client") {
|
||||
logger.info(
|
||||
{
|
||||
baseUrl: config.OPENCODE_CLIENT_BASE_URL,
|
||||
mode: config.OPENCODE_MODE,
|
||||
},
|
||||
"connecting to opencode server in client mode",
|
||||
);
|
||||
return createOpencodeClient({
|
||||
baseUrl: config.OPENCODE_CLIENT_BASE_URL,
|
||||
});
|
||||
}
|
||||
|
||||
// embedded 模式下,把服务内工具桥地址注入到 opencode 进程环境里,
|
||||
// 这样 .opencode/tools 下的自定义工具可以回调本服务。
|
||||
process.env.TJWATER_AGENT_INTERNAL_BASE_URL = `http://127.0.0.1:${config.PORT}`;
|
||||
@@ -430,7 +416,7 @@ export class OpencodeRuntimeAdapter {
|
||||
} catch (error) {
|
||||
if (isMissingOpencodeCli(error)) {
|
||||
throw new Error(
|
||||
"embedded mode requires the opencode CLI to be installed and available in PATH; otherwise set OPENCODE_MODE=client and provide OPENCODE_CLIENT_BASE_URL",
|
||||
"embedded mode requires the opencode CLI to be installed and available in PATH",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
|
||||
+253
-99
@@ -5,6 +5,11 @@ import express from "express";
|
||||
|
||||
import { requireAgentAuth } from "./auth/agentAuth.js";
|
||||
import { buildBackendContextHeaders } from "./auth/backendContextHeaders.js";
|
||||
import {
|
||||
CredentialRefreshError,
|
||||
CredentialRefreshCoordinator,
|
||||
runWithCredentialRefresh,
|
||||
} from "./auth/credentialRefresh.js";
|
||||
import { SessionTranscriptStore } from "./sessions/transcriptStore.js";
|
||||
import { ChatSessionBridge } from "./chat/sessionBridge.js";
|
||||
import { config } from "./config.js";
|
||||
@@ -12,6 +17,12 @@ import { SessionUiStateStore } from "./sessions/uiStateStore.js";
|
||||
import { SessionMetadataStore } from "./sessions/metadataStore.js";
|
||||
import { logger } from "./logger.js";
|
||||
import { LearningOrchestrator } from "./learning/orchestrator.js";
|
||||
import {
|
||||
executeMemoryManager,
|
||||
executeSkillManager,
|
||||
type MemoryManagerInput,
|
||||
type SkillManagerInput,
|
||||
} from "./learning/toolManagers.js";
|
||||
import { MemoryStore } from "./memory/store.js";
|
||||
import { ResultReferenceResolver } from "./results/resolver.js";
|
||||
import {
|
||||
@@ -21,12 +32,12 @@ import {
|
||||
import { buildChatRouter } from "./routes/chat.js";
|
||||
import { buildAgentPublicRouter } from "./routes/publicApi.js";
|
||||
import { opencodeRuntime } from "./runtime/opencode.js";
|
||||
import { serializeRuntimeSessionContext } from "./runtime/internalSessionContextBridge.js";
|
||||
import {
|
||||
getRuntimeSessionContext,
|
||||
markRuntimeSessionAuthExpired,
|
||||
type RuntimeSessionContext,
|
||||
} from "./runtime/sessionContext.js";
|
||||
import { SkillStore } from "./skills/store.js";
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -35,15 +46,18 @@ const sessionBridge = new ChatSessionBridge(opencodeRuntime);
|
||||
const sessionMetadataStore = new SessionMetadataStore();
|
||||
const sessionUiStateStore = new SessionUiStateStore();
|
||||
const memoryStore = new MemoryStore();
|
||||
const skillStore = new SkillStore();
|
||||
const sessionTranscriptStore = new SessionTranscriptStore();
|
||||
const learningOrchestrator = new LearningOrchestrator(
|
||||
opencodeRuntime,
|
||||
memoryStore,
|
||||
sessionTranscriptStore,
|
||||
skillStore,
|
||||
);
|
||||
const resultReferenceStore = new ResultReferenceStore();
|
||||
const resultReferenceResolver = new ResultReferenceResolver(resultReferenceStore);
|
||||
const internalToken = config.AGENT_INTERNAL_TOKEN ?? randomUUID();
|
||||
const credentialRefreshCoordinator = new CredentialRefreshCoordinator();
|
||||
|
||||
// 这个 token 只用于 OpenCode 子进程回调本服务的内部工具桥。
|
||||
process.env.TJWATER_AGENT_INTERNAL_TOKEN = internalToken;
|
||||
@@ -74,7 +88,7 @@ app.get("/health", async (_req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/internal/tools/session-context", (req, res) => {
|
||||
app.post("/internal/tools/memory-manager", async (req, res) => {
|
||||
if (req.header("x-agent-internal-token") !== internalToken) {
|
||||
res.status(403).json({ message: "forbidden" });
|
||||
return;
|
||||
@@ -90,8 +104,86 @@ app.post("/internal/tools/session-context", (req, res) => {
|
||||
});
|
||||
return;
|
||||
}
|
||||
const action = req.body?.action;
|
||||
if (
|
||||
typeof action !== "string" ||
|
||||
!["add", "list", "replace", "remove"].includes(action) ||
|
||||
typeof req.body?.scope !== "string"
|
||||
) {
|
||||
res.status(400).json({ message: "invalid memory manager request" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
res.json(
|
||||
await executeMemoryManager(memoryStore, context, {
|
||||
action: action as MemoryManagerInput["action"],
|
||||
content:
|
||||
typeof req.body?.content === "string" ? req.body.content : undefined,
|
||||
scope: req.body.scope,
|
||||
target_id:
|
||||
typeof req.body?.target_id === "string" ? req.body.target_id : undefined,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
message: "memory manager failed",
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
res.json(serializeRuntimeSessionContext(context));
|
||||
app.post("/internal/tools/skill-manager", async (req, res) => {
|
||||
if (req.header("x-agent-internal-token") !== internalToken) {
|
||||
res.status(403).json({ message: "forbidden" });
|
||||
return;
|
||||
}
|
||||
const sessionId =
|
||||
typeof req.body?.session_id === "string" ? req.body.session_id.trim() : "";
|
||||
const context = sessionId ? getRuntimeSessionContext(sessionId) : null;
|
||||
if (!context) {
|
||||
res.status(404).json({ message: "session context not found", detail: sessionId });
|
||||
return;
|
||||
}
|
||||
const action = req.body?.action;
|
||||
if (
|
||||
typeof action !== "string" ||
|
||||
![
|
||||
"list",
|
||||
"write_skill",
|
||||
"remove_skill",
|
||||
"append_pattern",
|
||||
"remove_pattern",
|
||||
"write_reference",
|
||||
"remove_reference",
|
||||
"write_script",
|
||||
"remove_script",
|
||||
].includes(action) ||
|
||||
typeof req.body?.skill_path !== "string"
|
||||
) {
|
||||
res.status(400).json({ message: "invalid skill manager request" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
res.json(
|
||||
await executeSkillManager(skillStore, context, {
|
||||
action: action as SkillManagerInput["action"],
|
||||
content:
|
||||
typeof req.body?.content === "string" ? req.body.content : undefined,
|
||||
file_path:
|
||||
typeof req.body?.file_path === "string" ? req.body.file_path : undefined,
|
||||
pattern:
|
||||
typeof req.body?.pattern === "string" ? req.body.pattern : undefined,
|
||||
skill_path: req.body.skill_path,
|
||||
target_id:
|
||||
typeof req.body?.target_id === "string" ? req.body.target_id : undefined,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
message: "skill manager failed",
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
||||
@@ -110,15 +202,6 @@ app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (isRuntimeAuthExpired(context)) {
|
||||
markAuthExpired(context, "access_token_expired");
|
||||
res.status(401).json({
|
||||
message: "access token expired; refresh chat context",
|
||||
detail: sessionId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const command = typeof req.body?.command === "string" ? req.body.command.trim() : "";
|
||||
if (!command) {
|
||||
res.status(400).json({ message: "command is required" });
|
||||
@@ -136,46 +219,35 @@ app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const authJson = JSON.stringify({
|
||||
server: config.TJWATER_API_BASE_URL,
|
||||
access_token: context.accessToken,
|
||||
project_id: context.projectId,
|
||||
});
|
||||
|
||||
const cliArgs = ["--auth-stdin", ...command.split(/\s+/).filter(Boolean)];
|
||||
|
||||
const child = spawn(config.TJWATER_CLI_PATH, cliArgs, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (data: Buffer) => {
|
||||
stdout += data.toString("utf-8");
|
||||
});
|
||||
child.stderr.on("data", (data: Buffer) => {
|
||||
stderr += data.toString("utf-8");
|
||||
});
|
||||
|
||||
child.stdin.write(authJson);
|
||||
child.stdin.end();
|
||||
|
||||
const exitCode = await new Promise<number | null>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGTERM");
|
||||
resolve(-1);
|
||||
}, timeoutSec * 1000);
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve(code);
|
||||
let result;
|
||||
try {
|
||||
result = await runWithCredentialRefresh(
|
||||
credentialRefreshCoordinator,
|
||||
context,
|
||||
(activeContext) => executeCliCommand(activeContext, command, timeoutSec),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!(error instanceof CredentialRefreshError)) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
res.status(502).json({
|
||||
message: "CLI execution failed",
|
||||
detail,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (error.code === "cancelled") {
|
||||
res.status(409).json({ message: "agent run was aborted" });
|
||||
return;
|
||||
}
|
||||
markAuthExpired(context, "access_token_expired");
|
||||
res.status(401).json({
|
||||
message: "credential refresh failed",
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
clearTimeout(timer);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (exitCode === -1) {
|
||||
if (result.status === 504) {
|
||||
res.status(504).json({
|
||||
ok: false,
|
||||
schema_version: "tjwater-cli/v1",
|
||||
@@ -189,29 +261,102 @@ app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (exitCode !== 0) {
|
||||
res.status(502).json({
|
||||
ok: false,
|
||||
exit_code: exitCode,
|
||||
stderr: stderr.slice(0, 2000),
|
||||
stdout: stdout.slice(0, 2000),
|
||||
message: `CLI exited with code ${exitCode}`,
|
||||
});
|
||||
if (result.status === 401) {
|
||||
markAuthExpired(
|
||||
getRuntimeSessionContext(sessionId) ?? context,
|
||||
"access_token_rejected",
|
||||
);
|
||||
}
|
||||
if (result.exitCode !== 0) {
|
||||
res
|
||||
.status(result.status)
|
||||
.type("application/json")
|
||||
.send(
|
||||
result.stdout ||
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
exit_code: result.exitCode,
|
||||
stderr: result.stderr.slice(0, 2000),
|
||||
message: `CLI exited with code ${result.exitCode}`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
res.json(JSON.parse(stdout));
|
||||
res.json(JSON.parse(result.stdout));
|
||||
} catch {
|
||||
res.json({
|
||||
ok: true,
|
||||
schema_version: "tjwater-cli/v1",
|
||||
raw: stdout,
|
||||
stderr: stderr || undefined,
|
||||
raw: result.stdout,
|
||||
stderr: result.stderr || undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const executeCliCommand = async (
|
||||
context: RuntimeSessionContext,
|
||||
command: string,
|
||||
timeoutSec: number,
|
||||
) => {
|
||||
const child = spawn(
|
||||
config.TJWATER_CLI_PATH,
|
||||
["--auth-stdin", ...command.split(/\s+/).filter(Boolean)],
|
||||
{ stdio: ["pipe", "pipe", "pipe"] },
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (data: Buffer) => {
|
||||
stdout += data.toString("utf-8");
|
||||
});
|
||||
child.stderr.on("data", (data: Buffer) => {
|
||||
stderr += data.toString("utf-8");
|
||||
});
|
||||
child.stdin.write(
|
||||
JSON.stringify({
|
||||
server: config.TJWATER_API_BASE_URL,
|
||||
access_token: context.accessToken,
|
||||
project_id: context.projectId,
|
||||
}),
|
||||
);
|
||||
child.stdin.end();
|
||||
|
||||
const exitCode = await new Promise<number | null>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGTERM");
|
||||
resolve(-1);
|
||||
}, timeoutSec * 1000);
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve(code);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
let errorCode = "";
|
||||
try {
|
||||
const payload = JSON.parse(stdout) as { error?: { code?: unknown } };
|
||||
errorCode =
|
||||
typeof payload.error?.code === "string" ? payload.error.code : "";
|
||||
} catch {
|
||||
errorCode = "";
|
||||
}
|
||||
const status =
|
||||
exitCode === -1
|
||||
? 504
|
||||
: errorCode === "HTTP_401" || errorCode === "UNAUTHENTICATED"
|
||||
? 401
|
||||
: errorCode === "HTTP_403"
|
||||
? 403
|
||||
: exitCode === 0
|
||||
? 200
|
||||
: 502;
|
||||
return { exitCode, status, stderr, stdout };
|
||||
};
|
||||
|
||||
app.post("/internal/tools/store-render-ref", async (req, res) => {
|
||||
if (req.header("x-agent-internal-token") !== internalToken) {
|
||||
res.status(403).json({ message: "forbidden" });
|
||||
@@ -302,39 +447,60 @@ const callBackendJson = async (
|
||||
context: RuntimeSessionContext,
|
||||
payload: unknown,
|
||||
) => {
|
||||
if (isRuntimeAuthExpired(context)) {
|
||||
try {
|
||||
const result = await runWithCredentialRefresh(
|
||||
credentialRefreshCoordinator,
|
||||
context,
|
||||
async (activeContext) => {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(
|
||||
() => controller.abort(),
|
||||
config.TJWATER_API_TIMEOUT_MS,
|
||||
);
|
||||
try {
|
||||
const response = await fetch(
|
||||
new URL(path, config.TJWATER_API_BASE_URL),
|
||||
{
|
||||
method: "POST",
|
||||
headers: buildBackendContextHeaders(activeContext),
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
text: await response.text(),
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
},
|
||||
);
|
||||
if (result.status === 401) {
|
||||
markAuthExpired(
|
||||
getRuntimeSessionContext(context.sessionId) ?? context,
|
||||
"access_token_rejected",
|
||||
);
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (!(error instanceof CredentialRefreshError)) {
|
||||
throw error;
|
||||
}
|
||||
if (error.code === "cancelled") {
|
||||
throw error;
|
||||
}
|
||||
markAuthExpired(context, "access_token_expired");
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
text: JSON.stringify({
|
||||
message: "access token expired; refresh chat context",
|
||||
message: "credential refresh failed",
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), config.TJWATER_API_TIMEOUT_MS);
|
||||
try {
|
||||
const headers = buildBackendContextHeaders(context);
|
||||
const response = await fetch(new URL(path, config.TJWATER_API_BASE_URL), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
const text = await response.text();
|
||||
if (response.status === 401) {
|
||||
markAuthExpired(context, "access_token_rejected");
|
||||
}
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
text,
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
const parseStringArray = (value: unknown) =>
|
||||
@@ -357,19 +523,6 @@ const normalizeWebSearchFreshness = (value: unknown) => {
|
||||
return webSearchFreshnessMap[value] ?? value;
|
||||
};
|
||||
|
||||
const AUTH_EXPIRY_SKEW_MS = 30_000;
|
||||
|
||||
function isRuntimeAuthExpired(context: RuntimeSessionContext) {
|
||||
if (!context.tokenExpiresAt) {
|
||||
return false;
|
||||
}
|
||||
const expiresAt = Date.parse(context.tokenExpiresAt);
|
||||
if (!Number.isFinite(expiresAt)) {
|
||||
return false;
|
||||
}
|
||||
return Date.now() >= expiresAt - AUTH_EXPIRY_SKEW_MS;
|
||||
}
|
||||
|
||||
function markAuthExpired(
|
||||
context: RuntimeSessionContext,
|
||||
reason: NonNullable<RuntimeSessionContext["authExpired"]>["reason"],
|
||||
@@ -491,6 +644,7 @@ const chatRouter = buildChatRouter(
|
||||
sessionTranscriptStore,
|
||||
learningOrchestrator,
|
||||
resultReferenceResolver,
|
||||
credentialRefreshCoordinator,
|
||||
);
|
||||
const authenticatedChatRouter = express.Router();
|
||||
authenticatedChatRouter.use(requireAgentAuth, chatRouter);
|
||||
|
||||
Reference in New Issue
Block a user