Compare commits

...

4 Commits

Author SHA1 Message Date
Akira
0d9b2758e9 日本語が発話されない件の修正案 2026-03-03 10:05:25 +09:00
Akira
1496f4a5e6 fix: Alexa TTS で locale を空にして日本語発話を修正
locale: 'ja-JP' を指定すると一瞬音が出るだけで発話されない問題を修正。
locale: '' (空文字) を使用するとデバイス設定の言語 (ja-jp) が使われ、
日本語・英語・漢字・ひらがな・カタカナ全て正常に発話される。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 19:29:47 +09:00
Akira
34107f98a2 feat: Alexa TTS API サーバーを追加
- alexa-api/: Echo デバイスに TTS を送る Node.js API サーバー
  - server.js: alexa-remote2 を使わない直接 Alexa API 実装
    - GET /api/language で CSRF トークン取得
    - GET /api/bootstrap でカスタマー ID 取得
    - POST /api/behaviors/preview で TTS 実行
  - Dockerfile + docker-compose.yml: windmill_windmill-internal ネットワーク接続
  - auth4.js: Amazon Japan OpenID フローで Cookie 取得(WORKING)
- scripts/alexa_speak.ts: Windmill から alexa-api を呼び出すスクリプト

Windmill (u/admin/alexa_speak) → alexa_api:3500/speak → Echo デバイス の
パスで日本語 TTS が動作することを確認済み。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 16:34:22 +09:00
Akira
593d13d8a1 ローカルLLMにワークフローを作らせる 2026-03-02 15:23:50 +09:00
27 changed files with 2790 additions and 1 deletions

9
.gitignore vendored
View File

@@ -3,6 +3,15 @@
variables/ variables/
resources/ resources/
# Environment / secrets
.env
.env.local
# Python
.venv/
__pycache__/
*.pyc
# wmill CLI # wmill CLI
wmill-lock.yaml wmill-lock.yaml

View File

@@ -24,7 +24,8 @@
windmill_workflow/ windmill_workflow/
├── flows/ # フロー定義JSON ├── flows/ # フロー定義JSON
│ ├── system_heartbeat.flow.json # Windmill自己診断フロー │ ├── system_heartbeat.flow.json # Windmill自己診断フロー
── shiraou_notification.flow.json # 白皇集落 変更通知フロー ── shiraou_notification.flow.json # 白皇集落 変更通知フロー
│ └── mail_filter.flow.json # メールフィルタリングフロー
├── docs/ ├── docs/
│ └── shiraou/ # 白皇集落営農組合関連ドキュメント │ └── shiraou/ # 白皇集落営農組合関連ドキュメント
│ ├── 19_windmill_通知ワークフロー連携仕様.md # API仕様書 │ ├── 19_windmill_通知ワークフロー連携仕様.md # API仕様書
@@ -43,6 +44,7 @@ windmill_workflow/
|------|------|-------------| |------|------|-------------|
| `f/app_custom/system_heartbeat` | Windmill自己診断 | なし(手動) | | `f/app_custom/system_heartbeat` | Windmill自己診断 | なし(手動) |
| `f/shiraou/shiraou_notification` | 白皇集落営農 変更通知 | 5分毎JST | | `f/shiraou/shiraou_notification` | 白皇集落営農 変更通知 | 5分毎JST |
| `f/mail/mail_filter` | メールフィルタリングIMAP→LLM→LINE | 10分毎JST予定 |
| `u/antigravity/git_sync` | Git同期 | 30分毎 | | `u/antigravity/git_sync` | Git同期 | 30分毎 |
## wm-api.sh コマンド一覧 ## wm-api.sh コマンド一覧
@@ -88,7 +90,34 @@ git push origin main
| `u/admin/LINE_CHANNEL_ACCESS_TOKEN` | ✅ | LINE Messaging APIトークン | | `u/admin/LINE_CHANNEL_ACCESS_TOKEN` | ✅ | LINE Messaging APIトークン |
| `u/admin/LINE_TO` | ✅ | LINE通知先IDユーザーまたはグループ | | `u/admin/LINE_TO` | ✅ | LINE通知先IDユーザーまたはグループ |
| `u/admin/SHIRAOU_LAST_CHECKED_AT` | ❌ | 前回確認時刻(ワークフローが自動更新) | | `u/admin/SHIRAOU_LAST_CHECKED_AT` | ❌ | 前回確認時刻(ワークフローが自動更新) |
| `u/admin/KEINASYSTEM_API_KEY` | ✅ | Keinasystem MAIL_API_KEY.envと同じ値 |
| `u/admin/KEINASYSTEM_API_URL` | ❌ | `https://keinafarm.net` |
| `u/admin/GEMINI_API_KEY` | ✅ | Google Gemini API キーLLM判定用 |
| `u/admin/GMAIL_IMAP_USER` | ✅ | GmailアカウントのIMAPユーザー名メールアドレス |
| `u/admin/GMAIL_IMAP_PASSWORD` | ✅ | GmailのアプリパスワードIMAPパスワード |
| `u/admin/MAIL_FILTER_GMAIL_LAST_UID` | ❌ | Gmail最終処理UIDワークフローが自動更新 |
| `u/admin/HOTMAIL_IMAP_USER` | ✅ | Hotmail IMAPユーザー名有効化時に登録 |
| `u/admin/HOTMAIL_IMAP_PASSWORD` | ✅ | Hotmail IMAPパスワード有効化時に登録 |
| `u/admin/MAIL_FILTER_HOTMAIL_LAST_UID` | ❌ | Hotmail最終処理UID有効化時に登録 |
| `u/admin/XSERVER_IMAP_USER` | ✅ | Xserver IMAPユーザー名有効化時に登録 |
| `u/admin/XSERVER_IMAP_PASSWORD` | ✅ | Xserver IMAPパスワード有効化時に登録 |
| `u/admin/MAIL_FILTER_XSERVER_LAST_UID` | ❌ | Xserver最終処理UID有効化時に登録 |
## マスタードキュメント ## マスタードキュメント
- [白皇集落 Windmill通知ワークフロー](docs/shiraou/20_マスタードキュメント_Windmill通知ワークフロー編.md) - [白皇集落 Windmill通知ワークフロー](docs/shiraou/20_マスタードキュメント_Windmill通知ワークフロー編.md)
## メールフィルタリング — アカウント有効化手順
Gmail → Hotmail → Xserver の順で段階的に有効化する。
### Gmail 初期設定
1. GoogleアカウントでIMAPを有効化Googleアカウント設定 → セキュリティ → アプリパスワード)
2. Windmill Variables に `GMAIL_IMAP_USER`, `GMAIL_IMAP_PASSWORD` を登録
3. フローを手動実行(初回: 既存メールスキップ、最大UIDを記録
4. スケジュール登録10分毎
### Hotmail/Xserver 追加時
1. Windmill Variables に対応する変数を登録
2. `flows/mail_filter.flow.json` の該当アカウントの `"enabled": false``true` に変更
3. フローを DELETE → POST で再デプロイ

6
alexa-api/.env.example Normal file
View File

@@ -0,0 +1,6 @@
# alexa-api/.env
# このファイルをコピーして .env を作成し、ALEXA_COOKIE に値を設定する
# .env は Git にコミットしない(.gitignore 参照)
# Amazon Cookieauth.js を実行して取得)
ALEXA_COOKIE=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

2
alexa-api/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
.env

14
alexa-api/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
FROM node:20-alpine
WORKDIR /app
# 依存パッケージのみ先にコピー(キャッシュ活用)
COPY package*.json ./
RUN npm install --omit=dev
# ソースをコピー
COPY server.js .
EXPOSE 3500
CMD ["node", "server.js"]

70
alexa-api/auth.js Normal file
View File

@@ -0,0 +1,70 @@
/**
* alexa-api/auth.js
* ローカル PC で実行して Amazon Cookie を取得するスクリプト。
*
* 使い方:
* cd alexa-api
* npm install alexa-cookie2
* node auth.js
*
* → ブラウザで http://localhost:3456 を開く
* → Amazon にログイン
* → コンソールに Cookie が表示される
* → その値を Windmill Variable "u/admin/ALEXA_COOKIE" に登録
*/
const AlexaCookie = require('alexa-cookie2');
const PROXY_PORT = 3456;
console.log('==============================================');
console.log(' Alexa Cookie 取得ツール');
console.log('==============================================');
console.log(`\n認証プロキシを起動中... (port ${PROXY_PORT})`);
console.log('\n【手順】');
console.log(` 1. ブラウザで http://localhost:${PROXY_PORT} を開く`);
console.log(' 2. Amazon アカウントにログインamazon.co.jp');
console.log(' 3. ログイン完了後、このコンソールに Cookie が表示される\n');
AlexaCookie.generateAlexaCookie(
'',
{
amazonPage: 'amazon.co.jp',
acceptLanguage: 'ja-JP',
setupProxy: true,
proxyPort: PROXY_PORT,
proxyOwnIp: '127.0.0.1',
proxyListenBind: '0.0.0.0',
logger: (msg) => {
if (!msg.includes('verbose') && !msg.includes('DEBUG')) {
console.log('[auth]', msg);
}
},
},
(err, cookie) => {
// alexa-cookie2 はブラウザを開くよう促すメッセージも err として渡してくる
if (err) {
const msg = err.message || String(err);
if (msg.includes('Please open')) {
// これは実際のエラーではなく「ブラウザで開いて」という指示
console.log('\n>>> ブラウザで http://localhost:3456/ を開いて Amazon にログインしてください <<<\n');
// プロキシを生かしたまま待機process.exit しない)
return;
}
console.error('\n[ERROR] 認証失敗:', msg);
process.exit(1);
}
console.log('\n==============================================');
console.log(' Cookie 取得成功!');
console.log('==============================================');
console.log('\n以下の値を Windmill Variable に登録してください:');
console.log(' パス: u/admin/ALEXA_COOKIE');
console.log(' Secret: ONチェックを入れる');
console.log('\n--- Cookie ---');
console.log(cookie);
console.log('--- ここまで ---\n');
process.exit(0);
}
);

76
alexa-api/auth2.js Normal file
View File

@@ -0,0 +1,76 @@
/**
* auth2.js - alexa-remote2 自身の認証フローを使う
* alexa-cookie2 より確実(ライブラリ内蔵の OAuth プロキシを使用)
*
* 使い方:
* node auth2.js
* → ブラウザで http://localhost:3001/ を開いて Amazon にログイン
* → 成功するとコンソールに Cookie が出力される → .env に保存
*/
const AlexaRemote = require('alexa-remote2');
const fs = require('fs');
const path = require('path');
const PORT = 3001;
console.log('==============================================');
console.log(' Alexa 認証ツール (alexa-remote2 内蔵プロキシ)');
console.log('==============================================');
console.log(`\nプロキシ起動中... (port ${PORT})`);
console.log(`\n【手順】ブラウザで http://localhost:${PORT}/ を開いて Amazon にログイン\n`);
const alexa = new AlexaRemote();
alexa.init(
{
cookie: null,
alexaServiceHost: 'alexa.amazon.co.jp',
amazonPage: 'amazon.co.jp',
acceptLanguage: 'ja-JP',
useWsMqtt: false,
setupProxy: true,
proxyOwnIp: '127.0.0.1',
proxyPort: PORT,
proxyListenBind: '0.0.0.0',
logger: console.log,
onSucess: (refreshedCookie) => {
// 認証成功時にリフレッシュされた Cookie を受け取る
console.log('\n[onSucess] Cookie refreshed');
},
},
(err, result) => {
if (err) {
const msg = err.message || String(err);
if (msg.includes('open') && (msg.includes('http://') || msg.includes('localhost'))) {
console.log(`\n>>> ブラウザで http://localhost:${PORT}/ を開いてください <<<\n`);
// プロキシを生かしたまま待機
return;
}
console.error('\n[ERROR]', msg);
return;
}
// 認証成功
console.log('\n==============================================');
console.log(' 認証成功!');
console.log('==============================================');
// alexa-remote2 内部の Cookie を取得
const cookie = alexa.cookie || alexa._options?.cookie;
if (cookie) {
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
console.log('\n以下を alexa-api/.env の ALEXA_COOKIE に設定してください:\n');
console.log('ALEXA_COOKIE=' + cookieStr);
// .env に自動保存
const envPath = path.join(__dirname, '.env');
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
console.log(`\n.env に自動保存しました: ${envPath}`);
} else {
console.log('Cookie を取得できませんでした。alexa オブジェクト:', Object.keys(alexa));
}
process.exit(0);
}
);

76
alexa-api/auth3.js Normal file
View File

@@ -0,0 +1,76 @@
/**
* auth3.js - メール/パスワードで直接認証2FA なしのアカウント向け)
*
* 使い方:
* AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="yourpass" node auth3.js
*
* 成功すると .env を更新して終了します。
*/
const AlexaRemote = require('alexa-remote2');
const fs = require('fs');
const path = require('path');
const email = process.env.AMAZON_EMAIL;
const password = process.env.AMAZON_PASSWORD;
if (!email || !password) {
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
console.error(' 例: AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="pass" node auth3.js');
process.exit(1);
}
console.log(`[INFO] ${email} でログイン試行中...`);
const alexa = new AlexaRemote();
alexa.init(
{
email,
password,
alexaServiceHost: 'alexa.amazon.co.jp',
amazonPage: 'amazon.co.jp',
acceptLanguage: 'ja-JP',
useWsMqtt: false,
setupProxy: false,
logger: (msg) => {
if (!msg.includes('verbose') && !msg.includes('Bearer')) {
console.log('[alexa]', msg);
}
},
onSucess: (refreshedCookie) => {
saveCookie(refreshedCookie, 'onSucess refresh');
},
},
(err) => {
if (err) {
console.error('[ERROR] 認証失敗(詳細):', err);
console.error('\n考えられる原因:');
console.error(' - パスワードが違う');
console.error(' - Amazon が CAPTCHA を要求している(後で再試行)');
console.error(' - 2FA が実際は有効になっている');
process.exit(1);
}
// 認証成功
const cookie = alexa.cookie;
saveCookie(cookie, 'init success');
process.exit(0);
}
);
function saveCookie(cookie, source) {
if (!cookie) {
console.error(`[${source}] Cookie が空です`);
return;
}
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
const envPath = path.join(__dirname, '.env');
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
console.log('\n==============================================');
console.log(' 認証成功!');
console.log('==============================================');
console.log('.env を更新しました:', envPath);
console.log('Cookie length:', cookieStr.length);
}

190
alexa-api/auth4.js Normal file
View File

@@ -0,0 +1,190 @@
/**
* auth4.js - Amazon Japan OpenID フローを正しく再現するカスタム認証スクリプト
* alexa-cookie2 の古いエンドポイント問題を回避して直接フォームを処理する
*/
const https = require('https');
const fs = require('fs');
const path = require('path');
const EMAIL = process.env.AMAZON_EMAIL;
const PASSWORD = process.env.AMAZON_PASSWORD;
if (!EMAIL || !PASSWORD) {
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
process.exit(1);
}
const ALEXA_LOGIN_URL =
'https://www.amazon.co.jp/ap/signin?' +
new URLSearchParams({
'openid.assoc_handle': 'amzn_dp_project_dee_jp',
'openid.mode': 'checkid_setup',
'openid.ns': 'http://specs.openid.net/auth/2.0',
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.return_to': 'https://alexa.amazon.co.jp/api/apps/v1/token',
'pageId': 'amzn_dp_project_dee_jp',
}).toString();
const USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
let cookieJar = {};
function setCookies(setCookieHeaders) {
if (!setCookieHeaders) return;
const headers = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders];
for (const h of headers) {
const [kv] = h.split(';');
const [k, v] = kv.trim().split('=');
if (k && v !== undefined) cookieJar[k.trim()] = v.trim();
}
}
function getCookieHeader() {
return Object.entries(cookieJar)
.map(([k, v]) => `${k}=${v}`)
.join('; ');
}
function request(url, options = {}) {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const reqOpts = {
hostname: parsed.hostname,
path: parsed.pathname + parsed.search,
method: options.method || 'GET',
headers: {
'User-Agent': USER_AGENT,
'Accept-Language': 'ja-JP,ja;q=0.9',
'Accept': 'text/html,application/xhtml+xml,*/*;q=0.8',
'Cookie': getCookieHeader(),
...(options.headers || {}),
},
};
const req = https.request(reqOpts, (res) => {
setCookies(res.headers['set-cookie']);
let body = '';
res.on('data', (d) => (body += d));
res.on('end', () => {
resolve({ status: res.statusCode, headers: res.headers, body });
});
});
req.on('error', reject);
if (options.body) req.write(options.body);
req.end();
});
}
// HTML の hidden フィールドを抽出
function extractHiddenFields(html) {
const fields = {};
const re = /<input[^>]+type=["']?hidden["']?[^>]*>/gi;
let match;
while ((match = re.exec(html)) !== null) {
const tag = match[0];
const name = (tag.match(/name=["']([^"']+)["']/) || [])[1];
const value = (tag.match(/value=["']([^"']*)["']/) || ['', ''])[1];
if (name) fields[name] = value;
}
return fields;
}
// フォームの action URL を抽出
function extractFormAction(html) {
const m = html.match(/id="ap_login_form"[^>]+action="([^"]+)"/);
if (m) return m[1].replace(/&amp;/g, '&');
const m2 = html.match(/name="signIn"[^>]+action="([^"]+)"/);
if (m2) return m2[1].replace(/&amp;/g, '&');
return null;
}
async function main() {
console.log('[1] ログインページ取得中...');
const page1 = await request(ALEXA_LOGIN_URL);
console.log(` Status: ${page1.status}, Cookies: ${Object.keys(cookieJar).join(', ')}`);
if (page1.status !== 200) {
console.error(`[ERROR] ログインページ取得失敗: ${page1.status}`);
process.exit(1);
}
// フォーム情報を抽出
const action = extractFormAction(page1.body);
const hidden = extractHiddenFields(page1.body);
if (!action) {
console.error('[ERROR] ログインフォームが見つかりません。HTMLを確認します:');
console.error(page1.body.substring(0, 500));
process.exit(1);
}
console.log(`[2] フォーム送信先: ${action}`);
console.log(` Hidden fields: ${Object.keys(hidden).join(', ')}`);
// フォームデータ構築
const formData = new URLSearchParams({
...hidden,
email: EMAIL,
password: PASSWORD,
rememberMe: 'true',
}).toString();
console.log('[3] 認証送信中...');
const page2 = await request(action, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': ALEXA_LOGIN_URL,
},
body: formData,
});
console.log(` Status: ${page2.status}`);
console.log(` Location: ${page2.headers.location || '(none)'}`);
console.log(` Cookies after login: ${Object.keys(cookieJar).join(', ')}`);
// リダイレクトをたどる
let current = page2;
let redirectCount = 0;
while (current.status >= 300 && current.status < 400 && current.headers.location && redirectCount < 10) {
const loc = current.headers.location;
const nextUrl = loc.startsWith('http') ? loc : `https://www.amazon.co.jp${loc}`;
console.log(`[${4 + redirectCount}] Redirect → ${nextUrl.substring(0, 80)}...`);
current = await request(nextUrl);
console.log(` Status: ${current.status}, New Cookies: ${Object.keys(cookieJar).join(', ')}`);
redirectCount++;
}
// 成功判定: at-acbjp または session-token が含まれているか
const cookie = getCookieHeader();
const hasAlexaToken = cookie.includes('at-acbjp') || cookie.includes('session-token');
if (!hasAlexaToken) {
console.error('[ERROR] 認証に失敗しました。取得できたCookieに認証トークンが含まれていません。');
console.error('取得済みCookieキー:', Object.keys(cookieJar).join(', '));
if (current.body.includes('captcha') || current.body.includes('CAPTCHA')) {
console.error('※ CAPTCHA が要求されています。しばらく待ってから再試行してください。');
}
if (current.body.includes('password') && current.body.includes('error')) {
console.error('※ パスワードが間違っている可能性があります。');
}
process.exit(1);
}
// .env に保存
const envPath = path.join(__dirname, '.env');
fs.writeFileSync(envPath, `ALEXA_COOKIE=${cookie}\n`);
console.log('\n==============================================');
console.log(' 認証成功!');
console.log('==============================================');
console.log(`.env を保存しました: ${envPath}`);
console.log(`Cookie 長さ: ${cookie.length} 文字`);
}
main().catch((err) => {
console.error('[FATAL]', err);
process.exit(1);
});

View File

@@ -0,0 +1,19 @@
services:
alexa-api:
build: .
container_name: alexa_api
restart: unless-stopped
env_file:
- .env
environment:
- PORT=3500
networks:
- windmill_windmill-internal
# 外部には公開しないWindmill ワーカーから内部ネットワーク経由でのみアクセス)
# デバッグ時は以下のコメントを外す:
# ports:
# - "127.0.0.1:3500:3500"
networks:
windmill_windmill-internal:
external: true

1257
alexa-api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

16
alexa-api/package.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "alexa-api",
"version": "1.0.0",
"description": "Alexa TTS API server for Windmill integration",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"alexa-cookie2": "^5.0.3",
"alexa-remote2": "^5.0.0"
}
}

210
alexa-api/server.js Normal file
View File

@@ -0,0 +1,210 @@
/**
* alexa-api/server.js
* Windmill から Echo デバイスに TTS を送る API サーバー
* 直接 Alexa API を叩く実装alexa-remote2 不使用)
*
* Endpoints:
* POST /speak { device: "デバイス名 or serial", text: "しゃべる内容" }
* GET /devices デバイス一覧取得
* GET /health ヘルスチェック
*/
const https = require('https');
const express = require('express');
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3500;
const ALEXA_HOST = 'alexa.amazon.co.jp';
const ALEXA_COOKIE = process.env.ALEXA_COOKIE;
if (!ALEXA_COOKIE) {
console.error('[ERROR] ALEXA_COOKIE 環境変数が設定されていません。');
process.exit(1);
}
// ---- キャッシュ ----
let cachedDevices = null;
let cachedCustomerId = null;
let deviceCacheExpires = 0;
// ---- HTTP ヘルパー ----
function httpsRequest(path, options, extraCookies) {
options = options || {};
extraCookies = extraCookies || '';
return new Promise(function(resolve, reject) {
var allCookies = ALEXA_COOKIE + (extraCookies ? '; ' + extraCookies : '');
var bodyBuf = options.body ? Buffer.from(options.body, 'utf8') : null;
var reqOpts = {
hostname: ALEXA_HOST,
path: path,
method: options.method || 'GET',
headers: Object.assign({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'ja-JP,ja;q=0.9',
'Cookie': allCookies,
}, bodyBuf ? { 'Content-Length': bodyBuf.length } : {}, options.headers || {}),
};
var req = https.request(reqOpts, function(res) {
var body = '';
res.on('data', function(d) { body += d; });
res.on('end', function() { resolve({ status: res.statusCode, headers: res.headers, body: body }); });
});
req.on('error', reject);
if (bodyBuf) req.write(bodyBuf);
req.end();
});
}
// ---- Alexa API ヘルパー ----
async function getCsrfToken() {
var res = await httpsRequest('/api/language');
var setCookies = res.headers['set-cookie'] || [];
var csrfCookieStr = setCookies.find(function(c) { return c.startsWith('csrf='); });
if (!csrfCookieStr) throw new Error('CSRF token not found');
return csrfCookieStr.split('=')[1].split(';')[0];
}
async function getCustomerId() {
if (cachedCustomerId) return cachedCustomerId;
var res = await httpsRequest('/api/bootstrap');
if (res.status !== 200) throw new Error('Bootstrap API failed: ' + res.status);
var data = JSON.parse(res.body);
cachedCustomerId = data.authentication && data.authentication.customerId;
if (!cachedCustomerId) throw new Error('customerId not found');
return cachedCustomerId;
}
async function getDevices(force) {
var now = Date.now();
if (!force && cachedDevices && now < deviceCacheExpires) return cachedDevices;
var res = await httpsRequest('/api/devices-v2/device?cached=false');
if (res.status !== 200) throw new Error('Devices API failed: ' + res.status);
var data = JSON.parse(res.body);
cachedDevices = data.devices || [];
deviceCacheExpires = now + 5 * 60 * 1000;
return cachedDevices;
}
function findDevice(devices, nameOrSerial) {
var bySerial = devices.find(function(d) { return d.serialNumber === nameOrSerial; });
if (bySerial) return bySerial;
var lower = nameOrSerial.toLowerCase();
var byName = devices.find(function(d) { return d.accountName && d.accountName.toLowerCase() === lower; });
if (byName) return byName;
return devices.find(function(d) { return d.accountName && d.accountName.toLowerCase().includes(lower); });
}
// ---- API エンドポイント ----
// POST /speak
app.post('/speak', async function(req, res) {
var body = req.body || {};
var device = body.device;
var text = body.text;
if (!device || !text) {
return res.status(400).json({ error: 'device と text は必須です' });
}
console.log('[SPEAK] device="' + device + '" text="' + text + '"');
try {
var results = await Promise.all([getCsrfToken(), getCustomerId(), getDevices()]);
var csrfToken = results[0];
var customerId = results[1];
var devices = results[2];
var target = findDevice(devices, device);
if (!target) {
var names = devices.map(function(d) { return d.accountName; }).join(', ');
return res.status(404).json({ error: 'デバイス "' + device + '" が見つかりません', available: names });
}
console.log(' -> ' + target.accountName + ' (type=' + target.deviceType + ', serial=' + target.serialNumber + ')');
var sequenceObj = {
'@type': 'com.amazon.alexa.behaviors.model.Sequence',
startNode: {
'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode',
type: 'Alexa.Speak',
operationPayload: {
deviceType: target.deviceType,
deviceSerialNumber: target.serialNumber,
customerId: customerId,
locale: 'ja-JP',
textToSpeak: text,
speakType: 'ssml'
},
},
};
var bodyStr = JSON.stringify({
behaviorId: 'PREVIEW',
sequenceJson: JSON.stringify(sequenceObj),
status: 'ENABLED',
});
var ttsRes = await httpsRequest('/api/behaviors/preview', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'csrf': csrfToken,
'Referer': 'https://alexa.amazon.co.jp/spa/index.html',
'Origin': 'https://alexa.amazon.co.jp',
},
body: bodyStr,
}, 'csrf=' + csrfToken);
if (ttsRes.status === 200 || ttsRes.status === 202) {
console.log(' [OK] TTS sent to ' + target.accountName);
res.json({ ok: true, device: target.accountName, text: text });
} else {
console.error(' [ERROR] TTS failed: ' + ttsRes.status + ' ' + ttsRes.body);
res.status(502).json({ error: 'Alexa API error: ' + ttsRes.status, body: ttsRes.body });
}
} catch (err) {
console.error('[ERROR] /speak:', err.message);
res.status(500).json({ error: err.message });
}
});
// GET /devices
app.get('/devices', async function(req, res) {
try {
var devices = await getDevices(true);
res.json(devices.map(function(d) {
return { name: d.accountName, type: d.deviceType, serial: d.serialNumber, online: d.online, family: d.deviceFamily };
}));
} catch (err) {
console.error('[ERROR] /devices:', err.message);
res.status(500).json({ error: err.message });
}
});
// GET /health
app.get('/health', function(req, res) {
res.json({ ok: true, cookieLength: ALEXA_COOKIE.length });
});
// ---- 起動 ----
app.listen(PORT, '0.0.0.0', async function() {
console.log('[INFO] alexa-api server listening on port ' + PORT);
try {
var customerId = await getCustomerId();
console.log('[INFO] Customer ID: ' + customerId);
var devices = await getDevices();
var echoDevices = devices.filter(function(d) {
return (d.deviceType && (d.deviceType.startsWith('A4ZXE') || d.deviceType.startsWith('ASQZWP')));
});
console.log('[INFO] Echo devices: ' + echoDevices.map(function(d) { return d.accountName; }).join(', '));
} catch (err) {
console.error('[WARN] Startup init failed:', err.message);
}
});

119
alexa-api/test_tts.js Normal file
View File

@@ -0,0 +1,119 @@
/**
* test_tts.js - TTS API テスト
* node test_tts.js
*/
const https = require('https');
const fs = require('fs');
const path = require('path');
const envContent = fs.readFileSync(path.join(__dirname, '.env'), 'utf8');
const COOKIE_STR = envContent.match(/ALEXA_COOKIE=(.+)/)[1].trim();
function makeRequest(url, options = {}, extraCookies = '') {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const allCookies = COOKIE_STR + (extraCookies ? '; ' + extraCookies : '');
const reqOpts = {
hostname: parsed.hostname,
path: parsed.pathname + parsed.search,
method: options.method || 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'ja-JP,ja;q=0.9',
'Cookie': allCookies,
...(options.headers || {}),
},
};
const req = https.request(reqOpts, (res) => {
let body = '';
res.on('data', d => body += d);
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body }));
});
req.on('error', reject);
if (options.body) req.write(options.body);
req.end();
});
}
async function main() {
// 1. CSRFトークン取得
console.log('[1] CSRF token取得...');
const langRes = await makeRequest('https://alexa.amazon.co.jp/api/language');
const setCookies = langRes.headers['set-cookie'] || [];
const csrfCookieStr = setCookies.find(c => c.startsWith('csrf='));
const csrfToken = csrfCookieStr ? csrfCookieStr.split('=')[1].split(';')[0] : null;
console.log(' CSRF token:', csrfToken);
console.log(' Status:', langRes.status);
if (!csrfToken) { console.error('CSRF token not found!'); process.exit(1); }
// 2. デバイス一覧取得
console.log('[2] デバイス一覧取得...');
const devRes = await makeRequest('https://alexa.amazon.co.jp/api/devices-v2/device?cached=false');
console.log(' Status:', devRes.status);
const devices = JSON.parse(devRes.body).devices || [];
console.log(' Device count:', devices.length);
// デバイス一覧表示
devices.filter(d => d.deviceFamily !== 'TABLET').forEach(d => {
console.log(` - ${d.accountName} (type=${d.deviceType}, serial=${d.serialNumber})`);
});
// プレハブを探す
const target = devices.find(d => d.serialNumber === 'G0922H085165007R');
console.log('\nTarget device:', target ? `${target.accountName}` : 'NOT FOUND');
if (!target) { process.exit(1); }
// 2.5. カスタマーIDを取得
const bootstrapRes = await makeRequest('https://alexa.amazon.co.jp/api/bootstrap');
const bootstrap = JSON.parse(bootstrapRes.body);
const customerId = bootstrap.authentication?.customerId;
console.log(' Customer ID:', customerId);
// 3. TTSリクエスト
const sequenceObj = {
'@type': 'com.amazon.alexa.behaviors.model.Sequence',
startNode: {
'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode',
type: 'Alexa.Speak',
operationPayload: {
deviceType: target.deviceType,
deviceSerialNumber: target.serialNumber,
customerId: customerId,
locale: 'ja-JP',
textToSpeak: 'テストです。聞こえますか',
},
},
};
const bodyObj = {
behaviorId: 'PREVIEW',
sequenceJson: JSON.stringify(sequenceObj),
status: 'ENABLED',
};
const body = JSON.stringify(bodyObj);
console.log('\n[3] TTS送信...');
const ttsRes = await makeRequest('https://alexa.amazon.co.jp/api/behaviors/preview', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'csrf': csrfToken,
'Referer': 'https://alexa.amazon.co.jp/spa/index.html',
'Origin': 'https://alexa.amazon.co.jp',
},
body,
}, `csrf=${csrfToken}`);
console.log('TTS status:', ttsRes.status);
console.log('TTS response:', ttsRes.body.substring(0, 500));
if (ttsRes.status === 200 || ttsRes.status === 202) {
console.log('\n成功エコーがしゃべるはずです。');
}
}
main().catch(console.error);

View File

@@ -0,0 +1,15 @@
# Windmill 接続設定
WINDMILL_URL=https://windmill.keinafarm.net
WINDMILL_TOKEN=your_token_here
WINDMILL_WORKSPACE=admins
# Ollama 設定
OLLAMA_URL=http://localhost:11434
OLLAMA_MODEL=qwen2.5-coder:14b
# 動作設定
DEV_PATH_PREFIX=f/dev
MAX_RETRIES=3
MAX_JSON_RETRIES=2
POLL_INTERVAL=5
POLL_MAX_COUNT=30

View File

@@ -0,0 +1,22 @@
"""設定値の一元管理。環境変数 or .env ファイルから読み込む。"""
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env")
WINDMILL_URL = os.environ.get("WINDMILL_URL", "https://windmill.keinafarm.net")
WINDMILL_TOKEN = os.environ.get("WINDMILL_TOKEN", "")
WINDMILL_WORKSPACE = os.environ.get("WINDMILL_WORKSPACE", "admins")
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434")
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5-coder:14b")
DEV_PATH_PREFIX = os.environ.get("DEV_PATH_PREFIX", "f/dev")
MAX_RETRIES = int(os.environ.get("MAX_RETRIES", "3"))
MAX_JSON_RETRIES = int(os.environ.get("MAX_JSON_RETRIES", "2"))
POLL_INTERVAL = int(os.environ.get("POLL_INTERVAL", "5"))
POLL_MAX_COUNT = int(os.environ.get("POLL_MAX_COUNT", "30"))
if not WINDMILL_TOKEN:
raise EnvironmentError("WINDMILL_TOKEN が設定されていません。.env ファイルを確認してください。")

View File

@@ -0,0 +1,148 @@
"""
自律ループ制御。全体のオーケストレーションのみを行う。
Usage:
python controller.py <flow_name> <task_description>
Example:
python controller.py hello_world "print Hello World in Python"
"""
import json
import sys
from config import DEV_PATH_PREFIX, MAX_RETRIES, MAX_JSON_RETRIES
from state_manager import State, is_duplicate, register_hash
from validator import validate
from windmill_client import create_flow, update_flow, flow_exists, run_flow
from job_poller import poll_until_done, JobTimeout
from llm_interface import generate_flow, fix_flow
def _log(prefix: str, msg: str) -> None:
print(f"{prefix} {msg}", flush=True)
def run(task_description: str, flow_name: str) -> bool:
"""
自律ループを実行する。
Returns:
True = 成功, False = 失敗
"""
# パス制限: f/dev/* のみcontroller 側で強制)
flow_path = f"{DEV_PATH_PREFIX}/{flow_name}"
state = State(retry_count=MAX_RETRIES)
is_first = True
json_fail_count = 0
_log("[START]", f"タスク: {task_description}")
_log("[START]", f"フローパス: {flow_path}")
while state.retry_count > 0:
attempt = MAX_RETRIES - state.retry_count + 1
prefix = f"[試行 {attempt}/{MAX_RETRIES}]"
# ── 1. LLM 生成 ─────────────────────────────────────────
_log(prefix, "フロー生成中...")
if is_first:
raw = generate_flow(task_description)
else:
prev_json = json.dumps(state.current_flow, ensure_ascii=False)
raw = fix_flow(prev_json, state.last_error or "")
# ── 2 & 3. JSON 検証 ─────────────────────────────────────
try:
flow_dict = validate(raw)
json_fail_count = 0
_log(prefix, "JSON検証: OK")
except ValueError as e:
_log(prefix, f"JSON検証: NG - {e}")
json_fail_count += 1
if json_fail_count >= MAX_JSON_RETRIES:
_log(prefix, f"JSON検証 {MAX_JSON_RETRIES} 回連続失敗 → リトライ消費")
state.retry_count -= 1
state.last_error = str(e)
json_fail_count = 0
is_first = False
continue
# ── 5. ハッシュ比較 ──────────────────────────────────────
if is_duplicate(state, flow_dict):
_log("[STOP]", "同一JSON検出 → 即停止")
return False
register_hash(state, flow_dict)
# ── 6. create / update ───────────────────────────────────
summary = flow_dict["summary"]
value = flow_dict["value"]
try:
if flow_exists(flow_path):
update_flow(flow_path, summary, value)
_log(prefix, f"フロー更新: {flow_path}")
else:
create_flow(flow_path, summary, value)
_log(prefix, f"フロー作成: {flow_path}")
except Exception as e:
_log(prefix, f"フロー送信エラー: {e}")
state.retry_count -= 1
state.last_error = str(e)
is_first = False
continue
# API 送信成功直後に current_flow を更新run 前・失敗時は更新しない)
state.current_flow = flow_dict
# ── 7. run ──────────────────────────────────────────────
try:
job_id = run_flow(flow_path)
state.job_id = job_id
_log(prefix, f"ジョブ実行: {job_id}")
except Exception as e:
_log(prefix, f"ジョブ起動エラー: {e}")
state.retry_count -= 1
state.last_error = str(e)
is_first = False
continue
# ── 8. ジョブ完了待ち ────────────────────────────────────
_log(prefix, "ジョブ完了待ち...")
try:
success, logs = poll_until_done(job_id)
except JobTimeout as e:
_log(prefix, f"タイムアウト: {e}")
state.retry_count -= 1
state.last_error = "タイムアウト"
state.last_logs = None
is_first = False
continue
state.last_logs = logs
# ── 9. ステータス判定 ────────────────────────────────────
if success:
_log(prefix, "実行結果: SUCCESS")
_log("[最終]", "状態: 成功")
return True
else:
excerpt = logs[:300] if logs else "(ログなし)"
_log(prefix, "実行結果: FAILURE")
_log(prefix, f"エラー内容: {excerpt}")
state.retry_count -= 1
state.last_error = logs or "不明なエラー"
is_first = False
_log("[最終]", f"状態: {MAX_RETRIES} 回失敗で停止")
return False
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python controller.py <flow_name> <task_description>")
print("Example: python controller.py hello_world 'print Hello World in Python'")
sys.exit(1)
_flow_name = sys.argv[1]
_task = " ".join(sys.argv[2:])
ok = run(_task, _flow_name)
sys.exit(0 if ok else 1)

View File

@@ -0,0 +1,48 @@
"""ジョブ完了待ちポーリング。Windmill の success フィールドで判定する。"""
import time
from windmill_client import get_job, get_job_logs
from config import POLL_INTERVAL, POLL_MAX_COUNT
class JobTimeout(Exception):
pass
def poll_until_done(job_id: str) -> tuple[bool, str]:
"""
ジョブが完了するまでポーリングする。
判定優先順位:
1. success is False → 失敗(即返却)
2. success is True → 成功(即返却)
3. それ以外 → 継続待機
ログ文字列は主判定に使わない(誤検知防止)。
Returns:
(success: bool, logs: str)
Raises:
JobTimeout: POLL_MAX_COUNT * POLL_INTERVAL 秒以内に完了しなかった場合
"""
for _ in range(POLL_MAX_COUNT):
job = get_job(job_id)
success = job.get("success")
if success is False:
logs = get_job_logs(job_id)
# result.error があればログに付加(ログが空でもエラー詳細を取得できる)
result_error = job.get("result", {}) or {}
error_detail = result_error.get("error", {}) or {}
error_msg = error_detail.get("message", "")
if error_msg and error_msg not in (logs or ""):
logs = f"{logs}\n[result.error] {error_msg}".strip()
return False, logs
if success is True:
logs = get_job_logs(job_id)
return True, logs
time.sleep(POLL_INTERVAL)
timeout_sec = POLL_MAX_COUNT * POLL_INTERVAL
raise JobTimeout(f"ジョブ {job_id}{timeout_sec} 秒以内に完了しませんでした")

View File

@@ -0,0 +1,99 @@
"""Ollama へのプロンプト送信と JSON 抽出。"""
import json
import re
import httpx
from config import OLLAMA_URL, OLLAMA_MODEL
_SYSTEM_PROMPT = """\
あなたはWindmillフロー生成AIです。
以下のルールを必ず守ってください:
- JSONのみ出力すること
- Markdownのコードブロック```)は使わない
- 説明文・コメントは一切出力しない
- フィールド順は必ず summary → value の順にすること
- 出力するJSONは必ず以下のスキーマに従うこと
{
"summary": "<タスクを一言で表す英語の説明>",
"value": {
"modules": [
{
"id": "a",
"value": {
"type": "rawscript",
"language": "python3",
"content": "<タスクを実行するPython3コード>",
"input_transforms": {}
}
}
]
}
}
【必須ルール】
- content のコードは必ず def main(): で始めることWindmillのエントリーポイント
- main() がない場合は AttributeError になるため絶対に省略しないこと
- content の内容はユーザーのタスク説明に従って書くこと(テンプレートをそのままコピーしないこと)
- content 内の改行は \\n でエスケープすること(リテラル改行を入れると JSON パースエラーになる)
- modules.id は a, b, c... の連番。追加フィールド禁止。
【出力例1】タスク: 「おはよう」と表示する
{"summary":"Print greeting","value":{"modules":[{"id":"a","value":{"type":"rawscript","language":"python3","content":"def main():\\n print('おはよう')","input_transforms":{}}}]}}
【出力例2】タスク: 1から5までの数字を表示する
{"summary":"Print numbers 1 to 5","value":{"modules":[{"id":"a","value":{"type":"rawscript","language":"python3","content":"def main():\\n for i in range(1, 6):\\n print(i)","input_transforms":{}}}]}}
【出力例3】タスク: 現在の日時を表示する
{"summary":"Display current datetime","value":{"modules":[{"id":"a","value":{"type":"rawscript","language":"python3","content":"def main():\\n from datetime import datetime\\n print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))","input_transforms":{}}}]}}\
"""
def _chat(messages: list[dict]) -> str:
resp = httpx.post(
f"{OLLAMA_URL}/api/chat",
json={
"model": OLLAMA_MODEL,
"messages": messages,
"stream": False,
"options": {"temperature": 0.1, "top_p": 0.9},
},
timeout=120,
)
resp.raise_for_status()
raw = resp.json()["message"]["content"].strip()
return _extract_json(raw)
def _extract_json(raw: str) -> str:
"""LLM がコードブロックで囲んでしまった場合でも JSON 部分を取り出す。"""
# ```json ... ``` または ``` ... ``` を除去
match = re.search(r"```(?:json)?\s*([\s\S]+?)\s*```", raw)
if match:
return match.group(1).strip()
return raw
def generate_flow(task_description: str) -> str:
"""初回生成:タスク説明からフロー JSON を生成する。"""
messages = [
{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": f"以下のフローをJSON形式で生成してください。\n要件: {task_description}"},
]
return _chat(messages)
def fix_flow(previous_flow_json: str, error_log: str) -> str:
"""リトライ生成:前回の JSON + エラーログから修正版を生成する。"""
messages = [
{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": (
"前回のフロー実行でエラーが発生しました。修正したフローをJSON形式で出力してください。\n\n"
f"--- 前回のフローJSON ---\n{previous_flow_json}\n\n"
f"--- エラーログ ---\n{error_log}\n\n"
"--- 修正指示 ---\n"
"- 前回と同一のJSONは絶対に出力しないこと\n"
"- エラーの原因箇所のみ修正すること\n"
"- スキーマは変えないこと"
)},
]
return _chat(messages)

View File

@@ -0,0 +1,3 @@
httpx
jsonschema
python-dotenv

View File

@@ -0,0 +1,81 @@
"""
GUIダイアログでフロー名とタスク説明を入力してから controller.py を起動する。
VS Code タスクから呼び出す用。
"""
import os
import sys
import tkinter as tk
from tkinter import messagebox
def main() -> None:
root = tk.Tk()
root.title("Windmill フロー生成")
root.resizable(True, True)
pad = {"padx": 12, "pady": 4}
# ── フロー名 ──────────────────────────────────
tk.Label(root, text="フロー名", anchor="w").grid(
row=0, column=0, sticky="ew", **pad
)
flow_var = tk.StringVar()
flow_entry = tk.Entry(root, textvariable=flow_var, width=46)
flow_entry.grid(row=1, column=0, sticky="ew", padx=12, pady=(0, 8))
# ── タスク説明 ────────────────────────────────
tk.Label(root, text="タスク説明", anchor="w").grid(
row=2, column=0, sticky="ew", **pad
)
task_text = tk.Text(root, width=46, height=8, wrap=tk.WORD)
task_text.grid(row=3, column=0, sticky="nsew", padx=12, pady=(0, 8))
# ── ボタン ────────────────────────────────────
btn_frame = tk.Frame(root)
btn_frame.grid(row=4, column=0, sticky="e", padx=12, pady=(4, 12))
def on_cancel():
root.destroy()
sys.exit(0)
def on_run():
flow_name = flow_var.get().strip()
task_desc = task_text.get("1.0", tk.END).strip()
if not flow_name:
messagebox.showwarning("入力エラー", "フロー名を入力してください。", parent=root)
flow_entry.focus()
return
if not task_desc:
messagebox.showwarning("入力エラー", "タスク説明を入力してください。", parent=root)
task_text.focus()
return
root.destroy()
# controller.py をカレントプロセスと置き換えて実行
# → ターミナルにそのままログが流れる
script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "controller.py")
os.execv(sys.executable, [sys.executable, script, flow_name, task_desc])
tk.Button(btn_frame, text="キャンセル", width=10, command=on_cancel).pack(
side=tk.LEFT, padx=(0, 6)
)
tk.Button(btn_frame, text="実行", width=10, command=on_run, default=tk.ACTIVE).pack(
side=tk.LEFT
)
# ── レイアウト調整 ────────────────────────────
root.columnconfigure(0, weight=1)
root.rowconfigure(3, weight=1)
# Enter キーで実行、Escape でキャンセル
root.bind("<Return>", lambda _: on_run())
root.bind("<Escape>", lambda _: on_cancel())
flow_entry.focus()
root.mainloop()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,33 @@
"""State オブジェクトの管理とハッシュ比較。"""
import json
import hashlib
from dataclasses import dataclass, field
from typing import Optional, Set
@dataclass
class State:
retry_count: int = 3
current_flow: Optional[dict] = None
last_logs: Optional[str] = None
last_error: Optional[str] = None
flow_hashes: Set[str] = field(default_factory=set)
job_id: Optional[str] = None
def _canonical(flow_dict: dict) -> str:
"""キー順を固定した JSON 文字列を返す(ハッシュ安定化)。"""
return json.dumps(flow_dict, sort_keys=True, separators=(',', ':'))
def compute_hash(flow_dict: dict) -> str:
return hashlib.sha256(_canonical(flow_dict).encode()).hexdigest()
def is_duplicate(state: State, flow_dict: dict) -> bool:
"""過去に同一の JSON を出力済みかどうかを判定する。"""
return compute_hash(flow_dict) in state.flow_hashes
def register_hash(state: State, flow_dict: dict) -> None:
state.flow_hashes.add(compute_hash(flow_dict))

View File

@@ -0,0 +1,57 @@
"""LLM 出力の JSON 構文・スキーマ検証。"""
import json
import jsonschema
# LLM が出力すべき JSON の最小スキーマ
_FLOW_SCHEMA = {
"type": "object",
"required": ["summary", "value"],
"additionalProperties": False,
"properties": {
"summary": {"type": "string", "minLength": 1},
"value": {
"type": "object",
"required": ["modules"],
"properties": {
"modules": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["id", "value"],
"properties": {
"id": {"type": "string"},
"value": {
"type": "object",
"required": ["type", "language", "content"],
"properties": {
"type": {"type": "string"},
"language": {"type": "string"},
"content": {"type": "string"},
"input_transforms": {"type": "object"},
},
},
},
},
}
},
},
},
}
def validate(raw: str) -> dict:
"""JSON 文字列を構文・スキーマ検証して dict を返す。失敗時は ValueError を投げる。"""
# 構文チェック
try:
data = json.loads(raw)
except json.JSONDecodeError as e:
raise ValueError(f"JSON構文エラー: {e}")
# スキーマチェック
try:
jsonschema.validate(data, _FLOW_SCHEMA)
except jsonschema.ValidationError as e:
raise ValueError(f"JSONスキーマ不正: {e.message}")
return data

View File

@@ -0,0 +1,50 @@
"""Windmill REST API の薄いラッパー。MCP は使わず直接 HTTPS で叩く。"""
import httpx
from config import WINDMILL_URL, WINDMILL_TOKEN, WINDMILL_WORKSPACE
def _headers() -> dict:
return {"Authorization": f"Bearer {WINDMILL_TOKEN}"}
def _api(path: str) -> str:
return f"{WINDMILL_URL}/api/w/{WINDMILL_WORKSPACE}/{path}"
def flow_exists(path: str) -> bool:
resp = httpx.get(_api(f"flows/get/{path}"), headers=_headers(), timeout=30)
return resp.status_code == 200
def create_flow(path: str, summary: str, value: dict) -> None:
payload = {"path": path, "summary": summary, "description": "", "value": value}
resp = httpx.post(_api("flows/create"), headers=_headers(), json=payload, timeout=30)
resp.raise_for_status()
def update_flow(path: str, summary: str, value: dict) -> None:
# 正しいエンドポイントは /flows/update/{path}/flows/edit/ は404になる
payload = {"path": path, "summary": summary, "description": "", "value": value}
resp = httpx.post(_api(f"flows/update/{path}"), headers=_headers(), json=payload, timeout=30)
resp.raise_for_status()
def run_flow(path: str) -> str:
"""フローを実行して job_id を返す。"""
resp = httpx.post(_api(f"jobs/run/f/{path}"), headers=_headers(), json={}, timeout=30)
resp.raise_for_status()
return resp.text.strip().strip('"')
def get_job(job_id: str) -> dict:
"""ジョブの状態を取得する。success フィールド: True=成功, False=失敗, None=実行中。"""
resp = httpx.get(_api(f"jobs_u/get/{job_id}"), headers=_headers(), timeout=30)
resp.raise_for_status()
return resp.json()
def get_job_logs(job_id: str) -> str:
resp = httpx.get(_api(f"jobs_u/getlogs/{job_id}"), headers=_headers(), timeout=30)
if resp.status_code == 200:
return resp.text
return ""

File diff suppressed because one or more lines are too long

30
scripts/alexa_speak.ts Normal file
View File

@@ -0,0 +1,30 @@
/**
* alexa_speak.ts
* 指定した Echo デバイスにテキストを読み上げさせる Windmill スクリプト
*
* パラメータ:
* device - デバイス名またはシリアル番号(例: "リビングエコー1", "プレハブ"
* text - 読み上げるテキスト
*/
export async function main(
device: string,
text: string,
): Promise<{ ok: boolean; device: string; text: string }> {
const ALEXA_API_URL = "http://alexa_api:3500";
const res = await fetch(`${ALEXA_API_URL}/speak`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ device, text }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(
`alexa-api error ${res.status}: ${JSON.stringify(body)}`
);
}
return await res.json();
}

83
test_imap.py Normal file
View File

@@ -0,0 +1,83 @@
"""
IMAP接続診断スクリプト
使い方: python test_imap.py
"""
import imaplib
import ssl
import getpass
HOST = "outlook.office365.com"
PORT = 993
USER = "akiracraftworl@infoseek.jp"
print(f"IMAP診断: {HOST}:{PORT}")
print(f"ユーザー: {USER}")
print()
# --- Step 1: SSL接続テスト認証なし---
print("[1] SSL接続テスト...")
try:
ssl_ctx = ssl.create_default_context()
mail = imaplib.IMAP4_SSL(HOST, PORT, ssl_context=ssl_ctx)
print(" ✓ SSL接続成功")
except Exception as e:
print(f" ❌ SSL接続失敗: {e}")
exit(1)
# --- Step 2: サーバーの認証方式を確認 ---
print("[2] サーバー対応認証方式を確認...")
try:
typ, caps_data = mail.capability()
caps = caps_data[0].decode() if caps_data and caps_data[0] else ""
print(f" CAPABILITY: {caps}")
if "AUTH=PLAIN" in caps or "AUTH=LOGIN" in caps:
print(" ✓ 基本認証(パスワード)が使えます")
basic_auth_supported = True
else:
basic_auth_supported = False
if "AUTH=XOAUTH2" in caps or "AUTH=OAUTHBEARER" in caps:
print(" ⚠ モダン認証OAuth2が必要な可能性があります")
if not basic_auth_supported:
print(" ❌ 基本認証は対応していません → OAuth2が必要です")
mail.logout()
exit(1)
except Exception as e:
print(f" CAPABILITY取得エラー: {e}")
# --- Step 3: ログインテスト ---
print("[3] ログインテスト...")
password = getpass.getpass(" パスワードを入力: ")
try:
mail.login(USER, password)
print(" ✓ ログイン成功!")
mail.select("INBOX")
_, data = mail.uid("SEARCH", None, "ALL")
uids = data[0].split() if data[0] else []
print(f" ✓ INBOX: {len(uids)}")
mail.logout()
print()
print("✅ 成功Windmillに登録できます。")
except imaplib.IMAP4.error as e:
err = str(e)
print(f" ❌ ログイン失敗: {err}")
print()
if "disabled" in err.lower() or "imap" in err.lower():
print(" 原因: IMAPが無効化されています")
print(" 対処: https://outlook.live.com → 設定 → メールの同期 → IMAPを有効化")
elif "AUTHENTICATE" in err or "XOAUTH" in err:
print(" 原因: モダン認証OAuth2が必要です")
else:
print(" 原因1: パスワードが間違っている")
print(" 原因2: IMAPが無効Outlook.com設定を再確認")
print(" 原因3: モダン認証が必要")
print()
print(" 確認してください:")
print(" → https://outlook.live.com にこのメアドとパスワードでログインできますか?")
except Exception as e:
print(f" ❌ エラー: {type(e).__name__}: {e}")