feat(release): prepare 1.1.0 candidate
This commit is contained in:
parent
5a34f66981
commit
5205dcdfa9
736 changed files with 115667 additions and 12203 deletions
673
apps/mobile-rn/src/features/actions/action-service.ts
Normal file
673
apps/mobile-rn/src/features/actions/action-service.ts
Normal file
|
|
@ -0,0 +1,673 @@
|
|||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import { SUPABASE_URL } from '@d3ro/core/supabase-config'
|
||||
import {
|
||||
createMeetingMemo,
|
||||
createMeetingWorkspace,
|
||||
getMeetingDetail,
|
||||
MeetingServiceError,
|
||||
} from '../meetings/meetings-service'
|
||||
import {
|
||||
KnowledgeServiceError,
|
||||
searchKnowledge,
|
||||
type KnowledgeSearchResult,
|
||||
} from '../knowledge/knowledge-service'
|
||||
|
||||
export type ParsedActionType =
|
||||
| 'create_meeting'
|
||||
| 'search_knowledge'
|
||||
| 'create_memo'
|
||||
| 'send_team_invite'
|
||||
| 'unknown'
|
||||
|
||||
export interface CreateMeetingActionArgs {
|
||||
title: string
|
||||
}
|
||||
|
||||
export interface SearchKnowledgeActionArgs {
|
||||
query: string
|
||||
}
|
||||
|
||||
export interface CreateMemoActionArgs {
|
||||
meeting_id: string
|
||||
content: string
|
||||
}
|
||||
|
||||
export interface SendTeamInviteActionArgs {
|
||||
team_id: string
|
||||
email: string
|
||||
role: 'admin' | 'member'
|
||||
}
|
||||
|
||||
export type ParsedMobileAction =
|
||||
| {
|
||||
type: 'create_meeting'
|
||||
args: CreateMeetingActionArgs
|
||||
rationale: string
|
||||
executable: true
|
||||
}
|
||||
| {
|
||||
type: 'search_knowledge'
|
||||
args: SearchKnowledgeActionArgs
|
||||
rationale: string
|
||||
executable: true
|
||||
}
|
||||
| {
|
||||
type: 'create_memo'
|
||||
args: CreateMemoActionArgs
|
||||
rationale: string
|
||||
executable: true
|
||||
}
|
||||
| {
|
||||
type: 'send_team_invite'
|
||||
args: SendTeamInviteActionArgs
|
||||
rationale: string
|
||||
executable: false
|
||||
blockReason: 'external-side-effect'
|
||||
}
|
||||
| {
|
||||
type: 'unknown'
|
||||
args: Record<string, never>
|
||||
rationale: string
|
||||
executable: false
|
||||
blockReason: 'unknown-action'
|
||||
}
|
||||
|
||||
export type ActionExecutionResult =
|
||||
| { kind: 'meeting-created'; meetingId: string; title: string }
|
||||
| { kind: 'knowledge-searched'; query: string; results: KnowledgeSearchResult[] }
|
||||
| { kind: 'memo-created'; meetingId: string; memoId: string; content: string }
|
||||
|
||||
export type ActionServiceErrorCode =
|
||||
| 'ACTION_BLOCKED'
|
||||
| 'AUTH_REQUIRED'
|
||||
| 'CANCELLED'
|
||||
| 'FORBIDDEN'
|
||||
| 'HISTORY_UNAVAILABLE'
|
||||
| 'INVALID_REQUEST'
|
||||
| 'INVALID_RESPONSE'
|
||||
| 'MODEL_NOT_ALLOWED'
|
||||
| 'NETWORK'
|
||||
| 'PROVIDER_UNAVAILABLE'
|
||||
| 'QUOTA_EXCEEDED'
|
||||
| 'SERVER_ERROR'
|
||||
| 'TIMEOUT'
|
||||
|
||||
export class ActionServiceError extends Error {
|
||||
constructor(
|
||||
public readonly code: ActionServiceErrorCode,
|
||||
public readonly retryable: boolean,
|
||||
public readonly status: number | null = null,
|
||||
public readonly historyRecorded: boolean | null = null,
|
||||
message: string = code,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ActionServiceError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface ActionHistoryRecord {
|
||||
id: string
|
||||
userId: string
|
||||
input: string
|
||||
type: ParsedActionType
|
||||
rationale: string
|
||||
args: Record<string, string>
|
||||
status: 'succeeded' | 'failed'
|
||||
result: Record<string, string | number> | null
|
||||
errorCode: ActionServiceErrorCode | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface ParseActionOptions {
|
||||
accessToken: string
|
||||
model?: string | null
|
||||
signal?: AbortSignal
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export interface ParsedActionCommandResult {
|
||||
action: ParsedMobileAction
|
||||
generationId: string
|
||||
snapshot: string
|
||||
}
|
||||
|
||||
export interface ExecuteActionOptions {
|
||||
userId: string
|
||||
accessToken: string
|
||||
input: string
|
||||
action: ParsedMobileAction
|
||||
confirmed: boolean
|
||||
nowMs?: number
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface ActionExecutionOutcome {
|
||||
result: ActionExecutionResult
|
||||
record: ActionHistoryRecord
|
||||
historyRecorded: boolean
|
||||
}
|
||||
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
const MAX_INPUT_CHARS = 4_000
|
||||
const MAX_RATIONALE_CHARS = 300
|
||||
const MAX_TITLE_CHARS = 160
|
||||
const MAX_QUERY_CHARS = 500
|
||||
const MAX_MEMO_CHARS = 4_000
|
||||
const MAX_HISTORY_RECORDS = 50
|
||||
const HISTORY_KEY_PREFIX = 'd3ro.mobile.actions.history.v1'
|
||||
|
||||
const ACTION_SYSTEM_PROMPT = `You are the D3RO Voice mobile action parser.
|
||||
Return exactly one JSON object and no markdown or prose.
|
||||
Schema: {"type":"create_meeting"|"search_knowledge"|"create_memo"|"send_team_invite"|"unknown","args":{},"rationale":"short reason"}
|
||||
Arguments:
|
||||
- create_meeting: {"title":"1-160 characters"}
|
||||
- search_knowledge: {"query":"1-500 characters"}
|
||||
- create_memo: {"meeting_id":"UUID","content":"1-4000 characters"}
|
||||
- send_team_invite: {"team_id":"UUID","email":"email","role":"admin"|"member"}
|
||||
- unknown: {}
|
||||
Do not invent missing IDs. Use unknown when required data is absent.`
|
||||
|
||||
let historySequence = 0
|
||||
let historyQueue: Promise<void> = Promise.resolve()
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizeBoundedString(value: unknown, max: number): string | null {
|
||||
if (typeof value !== 'string') return null
|
||||
const normalized = value.trim()
|
||||
return normalized.length > 0 && normalized.length <= max ? normalized : null
|
||||
}
|
||||
|
||||
function hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {
|
||||
return Object.keys(value).every((key) => allowed.includes(key))
|
||||
}
|
||||
|
||||
export function normalizeActionInput(value: string): string {
|
||||
const input = value.trim()
|
||||
if (input.length === 0 || input.length > MAX_INPUT_CHARS) {
|
||||
throw new ActionServiceError('INVALID_REQUEST', false, 400)
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
export function parseActionJson(text: string): ParsedMobileAction {
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(text.trim())
|
||||
} catch {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
if (!isRecord(value) || !hasOnlyKeys(value, ['type', 'args', 'rationale'])) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
const rationale = normalizeBoundedString(value.rationale, MAX_RATIONALE_CHARS)
|
||||
if (rationale === null || !isRecord(value.args)) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
|
||||
if (value.type === 'create_meeting') {
|
||||
const title = normalizeBoundedString(value.args.title, MAX_TITLE_CHARS)
|
||||
if (title === null || !hasOnlyKeys(value.args, ['title'])) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
return { type: value.type, args: { title }, rationale, executable: true }
|
||||
}
|
||||
if (value.type === 'search_knowledge') {
|
||||
const query = normalizeBoundedString(value.args.query, MAX_QUERY_CHARS)
|
||||
if (query === null || !hasOnlyKeys(value.args, ['query'])) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
return { type: value.type, args: { query }, rationale, executable: true }
|
||||
}
|
||||
if (value.type === 'create_memo') {
|
||||
const meetingId = normalizeBoundedString(value.args.meeting_id, 36)
|
||||
const content = normalizeBoundedString(value.args.content, MAX_MEMO_CHARS)
|
||||
if (
|
||||
meetingId === null
|
||||
|| !UUID_PATTERN.test(meetingId)
|
||||
|| content === null
|
||||
|| !hasOnlyKeys(value.args, ['meeting_id', 'content'])
|
||||
) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
return {
|
||||
type: value.type,
|
||||
args: { meeting_id: meetingId, content },
|
||||
rationale,
|
||||
executable: true,
|
||||
}
|
||||
}
|
||||
if (value.type === 'send_team_invite') {
|
||||
const teamId = normalizeBoundedString(value.args.team_id, 36)
|
||||
const email = normalizeBoundedString(value.args.email, 254)?.toLowerCase() ?? null
|
||||
const role = value.args.role === undefined ? 'member' : value.args.role
|
||||
if (
|
||||
teamId === null
|
||||
|| !UUID_PATTERN.test(teamId)
|
||||
|| email === null
|
||||
|| !EMAIL_PATTERN.test(email)
|
||||
|| (role !== 'admin' && role !== 'member')
|
||||
|| !hasOnlyKeys(value.args, ['team_id', 'email', 'role'])
|
||||
) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
return {
|
||||
type: value.type,
|
||||
args: { team_id: teamId, email, role },
|
||||
rationale,
|
||||
executable: false,
|
||||
blockReason: 'external-side-effect',
|
||||
}
|
||||
}
|
||||
if (value.type === 'unknown') {
|
||||
if (!hasOnlyKeys(value.args, [])) throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
return {
|
||||
type: value.type,
|
||||
args: {},
|
||||
rationale,
|
||||
executable: false,
|
||||
blockReason: 'unknown-action',
|
||||
}
|
||||
}
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
|
||||
function extractLlmText(value: unknown): string {
|
||||
if (!isRecord(value) || !Array.isArray(value.content)) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
const texts = value.content.map((block) => {
|
||||
if (!isRecord(block) || block.type !== 'text' || typeof block.text !== 'string') return ''
|
||||
return block.text
|
||||
}).filter((text) => text.length > 0)
|
||||
if (texts.length !== 1 || texts[0].trim().length === 0) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
return texts[0]
|
||||
}
|
||||
|
||||
function responseErrorCode(status: number, body: unknown): ActionServiceErrorCode {
|
||||
const serverCode = isRecord(body) && typeof body.error === 'string' ? body.error : ''
|
||||
if (status === 400) return 'INVALID_REQUEST'
|
||||
if (status === 401) return 'AUTH_REQUIRED'
|
||||
if (status === 403 || serverCode === 'model_not_allowed') return 'MODEL_NOT_ALLOWED'
|
||||
if (status === 429 || serverCode === 'quota_exceeded') return 'QUOTA_EXCEEDED'
|
||||
if (status === 503 || serverCode === 'provider_unavailable') return 'PROVIDER_UNAVAILABLE'
|
||||
if (status === 504 || serverCode === 'provider_timeout') return 'TIMEOUT'
|
||||
return 'SERVER_ERROR'
|
||||
}
|
||||
|
||||
export async function parseActionCommand(
|
||||
inputValue: string,
|
||||
options: ParseActionOptions,
|
||||
): Promise<ParsedActionCommandResult> {
|
||||
const input = normalizeActionInput(inputValue)
|
||||
const token = options.accessToken.trim()
|
||||
if (token.length === 0) throw new ActionServiceError('AUTH_REQUIRED', false, 401)
|
||||
const controller = new AbortController()
|
||||
let timedOut = false
|
||||
const abortFromCaller = (): void => controller.abort()
|
||||
if (options.signal?.aborted === true) controller.abort()
|
||||
else options.signal?.addEventListener('abort', abortFromCaller, { once: true })
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true
|
||||
controller.abort()
|
||||
}, options.timeoutMs ?? 45_000)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${SUPABASE_URL}/functions/v1/llm-proxy`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
'X-D3RO-Generation-Purpose': 'action_response',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
messages: [{ role: 'user', content: input }],
|
||||
system: ACTION_SYSTEM_PROMPT,
|
||||
max_tokens: 512,
|
||||
model: options.model?.trim() || undefined,
|
||||
stream: false,
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const code = responseErrorCode(response.status, body)
|
||||
throw new ActionServiceError(
|
||||
code,
|
||||
code === 'PROVIDER_UNAVAILABLE' || code === 'TIMEOUT' || code === 'SERVER_ERROR',
|
||||
response.status,
|
||||
)
|
||||
}
|
||||
const generationId = response.headers?.get('X-D3RO-Generation-Id')?.trim() ?? ''
|
||||
if (!UUID_PATTERN.test(generationId)) {
|
||||
throw new ActionServiceError('INVALID_RESPONSE', true)
|
||||
}
|
||||
const snapshot = extractLlmText(body)
|
||||
return {
|
||||
action: parseActionJson(snapshot),
|
||||
generationId: generationId.toLowerCase(),
|
||||
snapshot,
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ActionServiceError) throw error
|
||||
if (controller.signal.aborted) {
|
||||
const cancelled = options.signal?.aborted === true && !timedOut
|
||||
throw new ActionServiceError(cancelled ? 'CANCELLED' : 'TIMEOUT', !cancelled)
|
||||
}
|
||||
throw new ActionServiceError('NETWORK', true)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
options.signal?.removeEventListener('abort', abortFromCaller)
|
||||
}
|
||||
}
|
||||
|
||||
function actionHistoryKey(userId: string): string {
|
||||
if (!UUID_PATTERN.test(userId)) throw new ActionServiceError('AUTH_REQUIRED', false, 401)
|
||||
return `${HISTORY_KEY_PREFIX}.${userId}`
|
||||
}
|
||||
|
||||
function createHistoryId(nowMs: number): string {
|
||||
historySequence = (historySequence + 1) % Number.MAX_SAFE_INTEGER
|
||||
return `${nowMs.toString(36)}-${historySequence.toString(36)}`
|
||||
}
|
||||
|
||||
function isActionType(value: unknown): value is ParsedActionType {
|
||||
return value === 'create_meeting'
|
||||
|| value === 'search_knowledge'
|
||||
|| value === 'create_memo'
|
||||
|| value === 'send_team_invite'
|
||||
|| value === 'unknown'
|
||||
}
|
||||
|
||||
function isHistoryStatus(value: unknown): value is ActionHistoryRecord['status'] {
|
||||
return value === 'succeeded' || value === 'failed'
|
||||
}
|
||||
|
||||
function isActionErrorCode(value: unknown): value is ActionServiceErrorCode {
|
||||
return value === 'ACTION_BLOCKED'
|
||||
|| value === 'AUTH_REQUIRED'
|
||||
|| value === 'CANCELLED'
|
||||
|| value === 'FORBIDDEN'
|
||||
|| value === 'HISTORY_UNAVAILABLE'
|
||||
|| value === 'INVALID_REQUEST'
|
||||
|| value === 'INVALID_RESPONSE'
|
||||
|| value === 'MODEL_NOT_ALLOWED'
|
||||
|| value === 'NETWORK'
|
||||
|| value === 'PROVIDER_UNAVAILABLE'
|
||||
|| value === 'QUOTA_EXCEEDED'
|
||||
|| value === 'SERVER_ERROR'
|
||||
|| value === 'TIMEOUT'
|
||||
}
|
||||
|
||||
function parseHistoryRecord(value: unknown, expectedUserId: string): ActionHistoryRecord {
|
||||
if (!isRecord(value)) throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
if (
|
||||
typeof value.id !== 'string'
|
||||
|| value.userId !== expectedUserId
|
||||
|| typeof value.input !== 'string'
|
||||
|| value.input.length === 0
|
||||
|| value.input.length > MAX_INPUT_CHARS
|
||||
|| !isActionType(value.type)
|
||||
|| typeof value.rationale !== 'string'
|
||||
|| value.rationale.length === 0
|
||||
|| value.rationale.length > MAX_RATIONALE_CHARS
|
||||
|| !isRecord(value.args)
|
||||
|| !Object.values(value.args).every((entry) => typeof entry === 'string')
|
||||
|| !isHistoryStatus(value.status)
|
||||
|| (value.result !== null && (!isRecord(value.result)
|
||||
|| !Object.values(value.result).every((entry) => typeof entry === 'string' || typeof entry === 'number')))
|
||||
|| (value.errorCode !== null && !isActionErrorCode(value.errorCode))
|
||||
|| typeof value.createdAt !== 'string'
|
||||
|| !Number.isFinite(Date.parse(value.createdAt))
|
||||
) {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
return value as unknown as ActionHistoryRecord
|
||||
}
|
||||
|
||||
async function readActionHistoryUnlocked(userId: string): Promise<ActionHistoryRecord[]> {
|
||||
let serialized: string | null
|
||||
try {
|
||||
serialized = await AsyncStorage.getItem(actionHistoryKey(userId))
|
||||
} catch {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
if (serialized === null) return []
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(serialized)
|
||||
} catch {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
if (!Array.isArray(parsed) || parsed.length > MAX_HISTORY_RECORDS) {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
return parsed.map((record) => parseHistoryRecord(record, userId))
|
||||
}
|
||||
|
||||
export async function listActionHistory(userId: string): Promise<ActionHistoryRecord[]> {
|
||||
return readActionHistoryUnlocked(userId)
|
||||
}
|
||||
|
||||
export async function clearActionHistory(userId: string): Promise<void> {
|
||||
const key = actionHistoryKey(userId)
|
||||
const operation = historyQueue.then(async () => {
|
||||
try {
|
||||
await AsyncStorage.removeItem(key)
|
||||
} catch {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
})
|
||||
historyQueue = operation.catch(() => undefined)
|
||||
return operation
|
||||
}
|
||||
|
||||
export async function clearAllActionHistories(): Promise<void> {
|
||||
const operation = historyQueue.then(async () => {
|
||||
try {
|
||||
const keys = (await AsyncStorage.getAllKeys())
|
||||
.filter((key) => key.startsWith(`${HISTORY_KEY_PREFIX}.`))
|
||||
if (keys.length > 0) await AsyncStorage.multiRemove(keys)
|
||||
} catch {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
})
|
||||
historyQueue = operation.catch(() => undefined)
|
||||
return operation
|
||||
}
|
||||
|
||||
async function appendActionHistory(record: ActionHistoryRecord): Promise<void> {
|
||||
const operation = historyQueue.then(async () => {
|
||||
const current = await readActionHistoryUnlocked(record.userId)
|
||||
const next = [record, ...current.filter((entry) => entry.id !== record.id)]
|
||||
.slice(0, MAX_HISTORY_RECORDS)
|
||||
try {
|
||||
await AsyncStorage.setItem(actionHistoryKey(record.userId), JSON.stringify(next))
|
||||
} catch {
|
||||
throw new ActionServiceError('HISTORY_UNAVAILABLE', true)
|
||||
}
|
||||
})
|
||||
historyQueue = operation.catch(() => undefined)
|
||||
return operation
|
||||
}
|
||||
|
||||
function argsForHistory(action: ParsedMobileAction): Record<string, string> {
|
||||
if (action.type === 'create_meeting') return { title: action.args.title }
|
||||
if (action.type === 'search_knowledge') return { query: action.args.query }
|
||||
if (action.type === 'create_memo') {
|
||||
return { meeting_id: action.args.meeting_id, content: action.args.content }
|
||||
}
|
||||
if (action.type === 'send_team_invite') {
|
||||
return {
|
||||
team_id: action.args.team_id,
|
||||
email: action.args.email,
|
||||
role: action.args.role,
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
function resultForHistory(result: ActionExecutionResult): Record<string, string | number> {
|
||||
if (result.kind === 'meeting-created') {
|
||||
return { kind: result.kind, meeting_id: result.meetingId, title: result.title }
|
||||
}
|
||||
if (result.kind === 'knowledge-searched') {
|
||||
return { kind: result.kind, query: result.query, result_count: result.results.length }
|
||||
}
|
||||
return {
|
||||
kind: result.kind,
|
||||
meeting_id: result.meetingId,
|
||||
memo_id: result.memoId,
|
||||
content: result.content,
|
||||
}
|
||||
}
|
||||
|
||||
function executionError(error: unknown): ActionServiceError {
|
||||
if (error instanceof ActionServiceError) return error
|
||||
if (error instanceof KnowledgeServiceError) {
|
||||
if (error.code === 'auth') return new ActionServiceError('AUTH_REQUIRED', false, error.status)
|
||||
if (error.code === 'forbidden') return new ActionServiceError('FORBIDDEN', false, error.status)
|
||||
if (error.code === 'cancelled') return new ActionServiceError('CANCELLED', false, error.status)
|
||||
if (error.code === 'index-unavailable' || error.code === 'index-failed') {
|
||||
return new ActionServiceError('PROVIDER_UNAVAILABLE', true, error.status)
|
||||
}
|
||||
if (error.code === 'network') return new ActionServiceError('NETWORK', true, error.status)
|
||||
if (error.code === 'timeout') return new ActionServiceError('TIMEOUT', true, error.status)
|
||||
if (error.code === 'validation') return new ActionServiceError('INVALID_REQUEST', false, error.status)
|
||||
if (error.code === 'invalid-response') {
|
||||
return new ActionServiceError('INVALID_RESPONSE', true, error.status)
|
||||
}
|
||||
return new ActionServiceError('SERVER_ERROR', error.retryable, error.status)
|
||||
}
|
||||
if (error instanceof MeetingServiceError) {
|
||||
if (error.code === 'auth') return new ActionServiceError('AUTH_REQUIRED', false)
|
||||
if (error.code === 'forbidden') return new ActionServiceError('FORBIDDEN', false)
|
||||
if (error.code === 'validation' || error.code === 'conflict' || error.code === 'not-found') {
|
||||
return new ActionServiceError('INVALID_REQUEST', false)
|
||||
}
|
||||
if (error.code === 'network') return new ActionServiceError('NETWORK', true)
|
||||
return new ActionServiceError('SERVER_ERROR', true)
|
||||
}
|
||||
const message = error instanceof Error ? error.message.toLowerCase() : ''
|
||||
if (error instanceof TypeError || message.includes('network') || message.includes('fetch')) {
|
||||
return new ActionServiceError('NETWORK', true)
|
||||
}
|
||||
return new ActionServiceError('SERVER_ERROR', true)
|
||||
}
|
||||
|
||||
async function performAllowedAction(options: ExecuteActionOptions): Promise<ActionExecutionResult> {
|
||||
if (options.action.type === 'create_meeting') {
|
||||
const meeting = await createMeetingWorkspace(options.userId, options.action.args.title)
|
||||
return {
|
||||
kind: 'meeting-created',
|
||||
meetingId: meeting.id,
|
||||
title: meeting.title ?? options.action.args.title,
|
||||
}
|
||||
}
|
||||
if (options.action.type === 'search_knowledge') {
|
||||
const results = await searchKnowledge({
|
||||
accessToken: options.accessToken,
|
||||
query: options.action.args.query,
|
||||
signal: options.signal,
|
||||
})
|
||||
return { kind: 'knowledge-searched', query: options.action.args.query, results }
|
||||
}
|
||||
if (options.action.type === 'create_memo') {
|
||||
const detail = await getMeetingDetail(options.userId, options.action.args.meeting_id)
|
||||
const memo = await createMeetingMemo(
|
||||
options.userId,
|
||||
detail.meeting,
|
||||
options.action.args.content,
|
||||
options.nowMs,
|
||||
)
|
||||
return {
|
||||
kind: 'memo-created',
|
||||
meetingId: memo.meeting_id,
|
||||
memoId: memo.id,
|
||||
content: memo.content,
|
||||
}
|
||||
}
|
||||
throw new ActionServiceError('ACTION_BLOCKED', false, 403)
|
||||
}
|
||||
|
||||
export async function executeConfirmedAction(
|
||||
options: ExecuteActionOptions,
|
||||
): Promise<ActionExecutionOutcome> {
|
||||
if (!UUID_PATTERN.test(options.userId) || options.accessToken.trim().length === 0) {
|
||||
throw new ActionServiceError('AUTH_REQUIRED', false, 401)
|
||||
}
|
||||
const input = normalizeActionInput(options.input)
|
||||
let action: ParsedMobileAction
|
||||
try {
|
||||
action = parseActionJson(JSON.stringify({
|
||||
type: options.action.type,
|
||||
args: options.action.args,
|
||||
rationale: options.action.rationale,
|
||||
}))
|
||||
} catch {
|
||||
throw new ActionServiceError('INVALID_REQUEST', false, 400)
|
||||
}
|
||||
if (!options.confirmed || !action.executable) {
|
||||
throw new ActionServiceError('ACTION_BLOCKED', false, 403)
|
||||
}
|
||||
const nowMs = options.nowMs ?? Date.now()
|
||||
if (!Number.isSafeInteger(nowMs) || nowMs <= 0) {
|
||||
throw new ActionServiceError('INVALID_REQUEST', false, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const validatedOptions: ExecuteActionOptions = { ...options, action }
|
||||
const result = await performAllowedAction(validatedOptions)
|
||||
const record: ActionHistoryRecord = {
|
||||
id: createHistoryId(nowMs),
|
||||
userId: options.userId,
|
||||
input,
|
||||
type: action.type,
|
||||
rationale: action.rationale,
|
||||
args: argsForHistory(action),
|
||||
status: 'succeeded',
|
||||
result: resultForHistory(result),
|
||||
errorCode: null,
|
||||
createdAt: new Date(nowMs).toISOString(),
|
||||
}
|
||||
try {
|
||||
await appendActionHistory(record)
|
||||
return { result, record, historyRecorded: true }
|
||||
} catch {
|
||||
return { result, record, historyRecorded: false }
|
||||
}
|
||||
} catch (error) {
|
||||
const failure = executionError(error)
|
||||
const record: ActionHistoryRecord = {
|
||||
id: createHistoryId(nowMs),
|
||||
userId: options.userId,
|
||||
input,
|
||||
type: action.type,
|
||||
rationale: action.rationale,
|
||||
args: argsForHistory(action),
|
||||
status: 'failed',
|
||||
result: null,
|
||||
errorCode: failure.code,
|
||||
createdAt: new Date(nowMs).toISOString(),
|
||||
}
|
||||
let recorded = false
|
||||
try {
|
||||
await appendActionHistory(record)
|
||||
recorded = true
|
||||
} catch {
|
||||
recorded = false
|
||||
}
|
||||
throw new ActionServiceError(
|
||||
failure.code,
|
||||
failure.retryable,
|
||||
failure.status,
|
||||
recorded,
|
||||
failure.message,
|
||||
)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue